Coverage for src/dmxfy/cli/cli.py: 49%

45 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2025-08-11 12:05 +0800

1import sys 

2from typing import NoReturn 

3 

4from dmxfy.client.client import TranslationClient 

5from dmxfy.exceptions.exceptions import DMXFYException 

6 

7 

8class CLI: 

9 """Command-line interface for DMXFY""" 

10 

11 def __init__(self) -> None: 

12 self.client = TranslationClient() 

13 self.target_lang = "英语" 

14 self.source_lang = "简体中文" 

15 self.prompt_str = "汉译英> " 

16 

17 def run(self) -> NoReturn: 

18 """Run the CLI interface""" 

19 print("Welcome to DMXFY - 大语言模型翻译器") 

20 print("Type '\\e' to switch to English-to-Chinese translation") 

21 print("Type '\\c' to switch to Chinese-to-English translation") 

22 print("Press Ctrl+C to exit") 

23 

24 while True: 

25 try: 

26 text = input(self.prompt_str) 

27 except KeyboardInterrupt: 

28 print("\nGoodbye!") 

29 sys.exit(0) 

30 except EOFError: 

31 print("Goodbye!") 

32 sys.exit(0) 

33 

34 if text.startswith("\\e"): 

35 self._switch_to_en_to_ch() 

36 elif text.startswith("\\c"): 

37 self._switch_to_ch_to_en() 

38 else: 

39 self._translate(text) 

40 

41 def _switch_to_en_to_ch(self) -> None: 

42 """Switch to English-to-Chinese translation mode""" 

43 self.target_lang = "简体中文" 

44 self.source_lang = "英语" 

45 self.prompt_str = "En2Ch> " 

46 print("Translate English to Chinese") 

47 

48 def _switch_to_ch_to_en(self) -> None: 

49 """Switch to Chinese-to-English translation mode""" 

50 self.target_lang = "英语" 

51 self.source_lang = "简体中文" 

52 self.prompt_str = "汉译英> " 

53 print("翻译成英文") 

54 

55 def _translate(self, text: str) -> None: 

56 """Translate text and print the result""" 

57 try: 

58 result = self.client.translate( 

59 text, 

60 source_lang=self.source_lang, 

61 target_lang=self.target_lang 

62 ) 

63 print(result) 

64 except DMXFYException as e: 

65 print(f"Error: {e}", file=sys.stderr)