Blame view

query/translator.py 7.61 KB
be52af70   tangwang   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  """
  Translation service for multi-language query support.
  
  Supports DeepL API for high-quality translations.
  """
  
  import requests
  from typing import Dict, List, Optional
  from utils.cache import DictCache
  
  
  class Translator:
      """Multi-language translator using DeepL API."""
  
16c42787   tangwang   feat: implement r...
15
      DEEPL_API_URL = "https://api.deepl.com/v2/translate"  # Pro tier
be52af70   tangwang   first commit
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  
      # Language code mapping
      LANG_CODE_MAP = {
          'zh': 'ZH',
          'en': 'EN',
          'ru': 'RU',
          'ar': 'AR',
          'ja': 'JA',
          'es': 'ES',
          'de': 'DE',
          'fr': 'FR',
          'it': 'IT',
          'pt': 'PT',
      }
  
      def __init__(
          self,
          api_key: Optional[str] = None,
          use_cache: bool = True,
          timeout: int = 10
      ):
          """
          Initialize translator.
  
          Args:
d79810d5   tangwang   first commit
41
              api_key: DeepL API key (or None to use from config/env)
be52af70   tangwang   first commit
42
43
44
              use_cache: Whether to cache translations
              timeout: Request timeout in seconds
          """
d79810d5   tangwang   first commit
45
46
47
48
49
50
51
52
          # Get API key from config if not provided
          if api_key is None:
              try:
                  from config.env_config import get_deepl_key
                  api_key = get_deepl_key()
              except ImportError:
                  pass
  
be52af70   tangwang   first commit
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
          self.api_key = api_key
          self.timeout = timeout
          self.use_cache = use_cache
  
          if use_cache:
              self.cache = DictCache(".cache/translations.json")
          else:
              self.cache = None
  
      def translate(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None
      ) -> Optional[str]:
          """
          Translate text to target language.
  
          Args:
              text: Text to translate
              target_lang: Target language code ('zh', 'en', 'ru', etc.)
              source_lang: Source language code (optional, auto-detect if None)
  
          Returns:
              Translated text or None if translation fails
          """
          if not text or not text.strip():
              return text
  
          # Normalize language codes
          target_lang = target_lang.lower()
          if source_lang:
              source_lang = source_lang.lower()
  
          # Check cache
          if self.use_cache:
              cache_key = f"{source_lang or 'auto'}:{target_lang}:{text}"
              cached = self.cache.get(cache_key, category="translations")
              if cached:
                  return cached
  
          # If no API key, return mock translation (for testing)
          if not self.api_key:
              print(f"[Translator] No API key, returning original text (mock mode)")
              return text
  
16c42787   tangwang   feat: implement r...
99
          # Translate using DeepL with fallback
be52af70   tangwang   first commit
100
101
          result = self._translate_deepl(text, target_lang, source_lang)
  
16c42787   tangwang   feat: implement r...
102
103
104
105
106
107
108
109
110
111
          # If translation failed, try fallback to free API
          if result is None and "api.deepl.com" in self.DEEPL_API_URL:
              print(f"[Translator] Pro API failed, trying free API...")
              result = self._translate_deepl_free(text, target_lang, source_lang)
  
          # If still failed, return original text with warning
          if result is None:
              print(f"[Translator] Translation failed, returning original text")
              result = text
  
be52af70   tangwang   first commit
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
          # Cache result
          if result and self.use_cache:
              cache_key = f"{source_lang or 'auto'}:{target_lang}:{text}"
              self.cache.set(cache_key, result, category="translations")
  
          return result
  
      def _translate_deepl(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str]
      ) -> Optional[str]:
          """Translate using DeepL API."""
          # Map to DeepL language codes
          target_code = self.LANG_CODE_MAP.get(target_lang, target_lang.upper())
  
          headers = {
              "Authorization": f"DeepL-Auth-Key {self.api_key}",
              "Content-Type": "application/json",
          }
  
          payload = {
              "text": [text],
              "target_lang": target_code,
          }
  
          if source_lang:
              source_code = self.LANG_CODE_MAP.get(source_lang, source_lang.upper())
              payload["source_lang"] = source_code
  
          try:
              response = requests.post(
                  self.DEEPL_API_URL,
                  headers=headers,
                  json=payload,
                  timeout=self.timeout
              )
  
              if response.status_code == 200:
                  data = response.json()
                  if "translations" in data and len(data["translations"]) > 0:
                      return data["translations"][0]["text"]
              else:
                  print(f"[Translator] DeepL API error: {response.status_code} - {response.text}")
                  return None
  
          except requests.Timeout:
              print(f"[Translator] Translation request timed out")
              return None
          except Exception as e:
              print(f"[Translator] Translation failed: {e}")
              return None
  
16c42787   tangwang   feat: implement r...
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
      def _translate_deepl_free(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str]
      ) -> Optional[str]:
          """Translate using DeepL Free API."""
          # Map to DeepL language codes
          target_code = self.LANG_CODE_MAP.get(target_lang, target_lang.upper())
  
          headers = {
              "Authorization": f"DeepL-Auth-Key {self.api_key}",
              "Content-Type": "application/json",
          }
  
          payload = {
              "text": [text],
              "target_lang": target_code,
          }
  
          if source_lang:
              source_code = self.LANG_CODE_MAP.get(source_lang, source_lang.upper())
              payload["source_lang"] = source_code
  
          try:
              response = requests.post(
                  "https://api-free.deepl.com/v2/translate",
                  headers=headers,
                  json=payload,
                  timeout=self.timeout
              )
  
              if response.status_code == 200:
                  data = response.json()
                  if "translations" in data and len(data["translations"]) > 0:
                      return data["translations"][0]["text"]
              else:
                  print(f"[Translator] DeepL Free API error: {response.status_code} - {response.text}")
                  return None
  
          except requests.Timeout:
              print(f"[Translator] Free API request timed out")
              return None
          except Exception as e:
              print(f"[Translator] Free API translation failed: {e}")
              return None
  
be52af70   tangwang   first commit
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
      def translate_multi(
          self,
          text: str,
          target_langs: List[str],
          source_lang: Optional[str] = None
      ) -> Dict[str, Optional[str]]:
          """
          Translate text to multiple target languages.
  
          Args:
              text: Text to translate
              target_langs: List of target language codes
              source_lang: Source language code (optional)
  
          Returns:
              Dictionary mapping language code to translated text
          """
          results = {}
          for lang in target_langs:
              results[lang] = self.translate(text, lang, source_lang)
          return results
  
      def get_translation_needs(
          self,
          detected_lang: str,
          supported_langs: List[str]
      ) -> List[str]:
          """
          Determine which languages need translation.
  
          Args:
              detected_lang: Detected query language
              supported_langs: List of supported languages
  
          Returns:
              List of language codes to translate to
          """
          # If detected language is in supported list, translate to others
          if detected_lang in supported_langs:
              return [lang for lang in supported_langs if lang != detected_lang]
  
          # Otherwise, translate to all supported languages
          return supported_langs