Blame view

query/translator.py 21.6 KB
be52af70   tangwang   first commit
1
2
3
4
  """
  Translation service for multi-language query support.
  
  Supports DeepL API for high-quality translations.
0064e946   tangwang   feat: 增量索引服务、租户配置...
5
6
7
8
9
10
11
  
  
  #### 官方文档:
  https://developers.deepl.com/api-reference/translate/request-translation
  #####
  
  
be52af70   tangwang   first commit
12
13
14
  """
  
  import requests
a5a6bab8   tangwang   多语言查询优化
15
  import re
6e0e310c   tangwang   1. Translator 类增强
16
  from concurrent.futures import ThreadPoolExecutor
be52af70   tangwang   first commit
17
18
  from typing import Dict, List, Optional
  from utils.cache import DictCache
6e0e310c   tangwang   1. Translator 类增强
19
20
21
  import logging
  
  logger = logging.getLogger(__name__)
be52af70   tangwang   first commit
22
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
23
24
25
26
27
28
  # Try to import DEEPL_AUTH_KEY, but allow import to fail
  try:
      from config.env_config import DEEPL_AUTH_KEY
  except ImportError:
      DEEPL_AUTH_KEY = None
  
be52af70   tangwang   first commit
29
30
31
32
  
  class Translator:
      """Multi-language translator using DeepL API."""
  
16c42787   tangwang   feat: implement r...
33
      DEEPL_API_URL = "https://api.deepl.com/v2/translate"  # Pro tier
be52af70   tangwang   first commit
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  
      # 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,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
53
54
55
          timeout: int = 10,
          glossary_id: Optional[str] = None,
          translation_context: Optional[str] = None
be52af70   tangwang   first commit
56
57
58
59
60
      ):
          """
          Initialize translator.
  
          Args:
d79810d5   tangwang   first commit
61
              api_key: DeepL API key (or None to use from config/env)
be52af70   tangwang   first commit
62
63
              use_cache: Whether to cache translations
              timeout: Request timeout in seconds
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
64
65
              glossary_id: DeepL glossary ID for custom terminology (optional)
              translation_context: Context hint for translation (e.g., "e-commerce", "product search")
be52af70   tangwang   first commit
66
          """
d79810d5   tangwang   first commit
67
          # Get API key from config if not provided
325eec03   tangwang   1. 日志、配置基础设施,使用优化
68
69
          if api_key is None and DEEPL_AUTH_KEY:
              api_key = DEEPL_AUTH_KEY
d79810d5   tangwang   first commit
70
  
be52af70   tangwang   first commit
71
72
73
          self.api_key = api_key
          self.timeout = timeout
          self.use_cache = use_cache
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
74
75
          self.glossary_id = glossary_id
          self.translation_context = translation_context or "e-commerce product search"
be52af70   tangwang   first commit
76
77
78
79
80
  
          if use_cache:
              self.cache = DictCache(".cache/translations.json")
          else:
              self.cache = None
6e0e310c   tangwang   1. Translator 类增强
81
82
83
          
          # Thread pool for async translation
          self.executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="translator")
be52af70   tangwang   first commit
84
85
86
87
88
  
      def translate(
          self,
          text: str,
          target_lang: str,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
89
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
90
91
          context: Optional[str] = None,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
92
93
      ) -> Optional[str]:
          """
0064e946   tangwang   feat: 增量索引服务、租户配置...
94
          Translate text to target language (synchronous mode).
be52af70   tangwang   first commit
95
96
97
98
99
  
          Args:
              text: Text to translate
              target_lang: Target language code ('zh', 'en', 'ru', etc.)
              source_lang: Source language code (optional, auto-detect if None)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
100
              context: Additional context for translation (overrides default context)
0064e946   tangwang   feat: 增量索引服务、租户配置...
101
              prompt: Translation prompt/instruction (optional, for better translation quality)
be52af70   tangwang   first commit
102
103
104
105
106
107
108
109
110
111
112
113
  
          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()
  
a5a6bab8   tangwang   多语言查询优化
114
115
116
117
118
119
120
121
122
          # Optimization: Skip translation if not needed
          if target_lang == 'en' and self._is_english_text(text):
              logger.debug(f"[Translator] Text is already English, skipping translation: '{text[:50]}...'")
              return text
          
          if target_lang == 'zh' and (self._contains_chinese(text) or self._is_pure_number(text)):
              logger.debug(f"[Translator] Text contains Chinese or is pure number, skipping translation: '{text[:50]}...'")
              return text
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
123
124
          # Use provided context or default context
          translation_context = context or self.translation_context
0064e946   tangwang   feat: 增量索引服务、租户配置...
125
126
127
128
129
130
131
132
133
          
          # Build cache key (include prompt in cache key if provided)
          cache_key_parts = [source_lang or 'auto', target_lang, translation_context]
          if prompt:
              cache_key_parts.append(prompt)
          cache_key_parts.append(text)
          cache_key = ':'.join(cache_key_parts)
  
          # Check cache (include context and prompt in cache key for accuracy)
be52af70   tangwang   first commit
134
          if self.use_cache:
be52af70   tangwang   first commit
135
136
137
138
139
140
              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:
0064e946   tangwang   feat: 增量索引服务、租户配置...
141
              logger.debug(f"[Translator] No API key, returning original text (mock mode)")
be52af70   tangwang   first commit
142
143
              return text
  
16c42787   tangwang   feat: implement r...
144
          # Translate using DeepL with fallback
0064e946   tangwang   feat: 增量索引服务、租户配置...
145
          result = self._translate_deepl(text, target_lang, source_lang, translation_context, prompt)
be52af70   tangwang   first commit
146
  
16c42787   tangwang   feat: implement r...
147
148
          # If translation failed, try fallback to free API
          if result is None and "api.deepl.com" in self.DEEPL_API_URL:
0064e946   tangwang   feat: 增量索引服务、租户配置...
149
150
              logger.debug(f"[Translator] Pro API failed, trying free API...")
              result = self._translate_deepl_free(text, target_lang, source_lang, translation_context, prompt)
16c42787   tangwang   feat: implement r...
151
152
153
  
          # If still failed, return original text with warning
          if result is None:
0064e946   tangwang   feat: 增量索引服务、租户配置...
154
              logger.warning(f"[Translator] Translation failed for '{text[:50]}...', returning original text")
16c42787   tangwang   feat: implement r...
155
156
              result = text
  
be52af70   tangwang   first commit
157
158
          # Cache result
          if result and self.use_cache:
be52af70   tangwang   first commit
159
160
161
162
163
164
165
166
              self.cache.set(cache_key, result, category="translations")
  
          return result
  
      def _translate_deepl(
          self,
          text: str,
          target_lang: str,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
167
          source_lang: Optional[str],
0064e946   tangwang   feat: 增量索引服务、租户配置...
168
169
          context: Optional[str] = None,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
170
      ) -> Optional[str]:
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
171
172
173
174
175
176
177
178
179
          """
          Translate using DeepL API with context and glossary support.
          
          Args:
              text: Text to translate
              target_lang: Target language code
              source_lang: Source language code (optional)
              context: Context hint for translation (e.g., "e-commerce product search")
          """
be52af70   tangwang   first commit
180
181
182
183
184
185
186
187
          # 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",
          }
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
188
189
190
191
192
          # Use prompt as context parameter for DeepL API (not as text prefix)
          # According to DeepL API: context is "Additional context that can influence a translation but is not translated itself"
          # If prompt is provided, use it as context; otherwise use the default context
          api_context = prompt if prompt else context
          
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
193
194
          # For e-commerce, add context words to help DeepL understand the domain
          # This is especially important for single-word ambiguous terms like "车" (car vs rook)
0064e946   tangwang   feat: 增量索引服务、租户配置...
195
          text_to_translate, needs_extraction = self._add_ecommerce_context(text, source_lang, api_context)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
196
  
be52af70   tangwang   first commit
197
          payload = {
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
198
              "text": [text_to_translate],
be52af70   tangwang   first commit
199
200
201
202
203
204
205
              "target_lang": target_code,
          }
  
          if source_lang:
              source_code = self.LANG_CODE_MAP.get(source_lang, source_lang.upper())
              payload["source_lang"] = source_code
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
206
207
208
209
210
          # Add context parameter (prompt or default context)
          # Context influences translation but is not translated itself
          if api_context:
              payload["context"] = api_context
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
211
212
213
214
          # Add glossary if configured
          if self.glossary_id:
              payload["glossary_id"] = self.glossary_id
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
215
216
217
          # Note: DeepL API v2 supports "context" parameter for additional context
          # that influences translation but is not translated itself.
          # We use prompt as context parameter when provided.
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
218
  
be52af70   tangwang   first commit
219
220
221
222
223
224
225
226
227
228
229
          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:
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
230
231
232
233
234
235
236
                      translated_text = data["translations"][0]["text"]
                      # If we added context, extract just the term from the result
                      if needs_extraction:
                          translated_text = self._extract_term_from_translation(
                              translated_text, text, target_code
                          )
                      return translated_text
be52af70   tangwang   first commit
237
              else:
0064e946   tangwang   feat: 增量索引服务、租户配置...
238
                  logger.error(f"[Translator] DeepL API error: {response.status_code} - {response.text}")
be52af70   tangwang   first commit
239
240
241
                  return None
  
          except requests.Timeout:
0064e946   tangwang   feat: 增量索引服务、租户配置...
242
              logger.warning(f"[Translator] Translation request timed out")
be52af70   tangwang   first commit
243
244
              return None
          except Exception as e:
0064e946   tangwang   feat: 增量索引服务、租户配置...
245
              logger.error(f"[Translator] Translation failed: {e}", exc_info=True)
be52af70   tangwang   first commit
246
247
              return None
  
16c42787   tangwang   feat: implement r...
248
249
250
251
      def _translate_deepl_free(
          self,
          text: str,
          target_lang: str,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
252
          source_lang: Optional[str],
0064e946   tangwang   feat: 增量索引服务、租户配置...
253
254
          context: Optional[str] = None,
          prompt: Optional[str] = None
16c42787   tangwang   feat: implement r...
255
      ) -> Optional[str]:
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
256
257
258
259
260
          """
          Translate using DeepL Free API.
          
          Note: Free API may not support glossary_id parameter.
          """
16c42787   tangwang   feat: implement r...
261
262
263
264
265
266
267
268
          # 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",
          }
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
269
270
271
          # Use prompt as context parameter for DeepL API
          api_context = prompt if prompt else context
          
16c42787   tangwang   feat: implement r...
272
273
274
275
276
277
278
279
280
          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
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
281
282
283
284
          # Add context parameter
          if api_context:
              payload["context"] = api_context
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
285
286
287
          # Note: Free API typically doesn't support glossary_id
          # But we can still use context hints in the text
  
16c42787   tangwang   feat: implement r...
288
289
290
291
292
293
294
295
296
297
298
299
300
          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:
0064e946   tangwang   feat: 增量索引服务、租户配置...
301
                  logger.error(f"[Translator] DeepL Free API error: {response.status_code} - {response.text}")
16c42787   tangwang   feat: implement r...
302
303
304
                  return None
  
          except requests.Timeout:
0064e946   tangwang   feat: 增量索引服务、租户配置...
305
              logger.warning(f"[Translator] Free API request timed out")
16c42787   tangwang   feat: implement r...
306
307
              return None
          except Exception as e:
0064e946   tangwang   feat: 增量索引服务、租户配置...
308
              logger.error(f"[Translator] Free API translation failed: {e}", exc_info=True)
16c42787   tangwang   feat: implement r...
309
310
              return None
  
be52af70   tangwang   first commit
311
312
313
314
      def translate_multi(
          self,
          text: str,
          target_langs: List[str],
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
315
          source_lang: Optional[str] = None,
6e0e310c   tangwang   1. Translator 类增强
316
          context: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
317
318
          async_mode: bool = True,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
319
320
321
      ) -> Dict[str, Optional[str]]:
          """
          Translate text to multiple target languages.
6e0e310c   tangwang   1. Translator 类增强
322
323
324
          
          In async_mode=True (default):
          - Returns cached translations immediately if available
a5a6bab8   tangwang   多语言查询优化
325
326
327
328
          - For translations that can be optimized (e.g., pure numbers, already in target language),
            returns result immediately via synchronous call
          - Launches async tasks for other missing translations (non-blocking)
          - Returns None for missing translations that require async processing
6e0e310c   tangwang   1. Translator 类增强
329
330
331
          
          In async_mode=False:
          - Waits for all translations to complete (blocking)
be52af70   tangwang   first commit
332
333
334
335
336
  
          Args:
              text: Text to translate
              target_langs: List of target language codes
              source_lang: Source language code (optional)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
337
              context: Context hint for translation (optional)
6e0e310c   tangwang   1. Translator 类增强
338
              async_mode: If True, return cached results immediately and translate missing ones async
0064e946   tangwang   feat: 增量索引服务、租户配置...
339
              prompt: Translation prompt/instruction (optional)
be52af70   tangwang   first commit
340
341
  
          Returns:
6e0e310c   tangwang   1. Translator 类增强
342
              Dictionary mapping language code to translated text (only cached results in async mode)
be52af70   tangwang   first commit
343
344
          """
          results = {}
6e0e310c   tangwang   1. Translator 类增强
345
          missing_langs = []
a5a6bab8   tangwang   多语言查询优化
346
          async_langs = []
6e0e310c   tangwang   1. Translator 类增强
347
348
          
          # First, get cached translations
be52af70   tangwang   first commit
349
          for lang in target_langs:
0064e946   tangwang   feat: 增量索引服务、租户配置...
350
              cached = self._get_cached_translation(text, lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
351
352
353
354
355
              if cached is not None:
                  results[lang] = cached
              else:
                  missing_langs.append(lang)
          
a5a6bab8   tangwang   多语言查询优化
356
          # If async mode and there are missing translations
6e0e310c   tangwang   1. Translator 类增强
357
          if async_mode and missing_langs:
a5a6bab8   tangwang   多语言查询优化
358
              # Check if translation can be optimized (immediate return)
6e0e310c   tangwang   1. Translator 类增强
359
              for lang in missing_langs:
a5a6bab8   tangwang   多语言查询优化
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
                  target_lang = lang.lower()
                  # Check optimization conditions (same as in translate method)
                  can_optimize = False
                  if target_lang == 'en' and self._is_english_text(text):
                      can_optimize = True
                  elif target_lang == 'zh' and (self._contains_chinese(text) or self._is_pure_number(text)):
                      can_optimize = True
                  
                  if can_optimize:
                      # Can be optimized, call translate synchronously for immediate result
                      results[lang] = self.translate(text, lang, source_lang, context, prompt)
                  else:
                      # Requires actual translation, add to async list
                      async_langs.append(lang)
              
              # Launch async tasks for translations that require actual API calls
              if async_langs:
                  for lang in async_langs:
                      self._translate_async(text, lang, source_lang, context, prompt)
                  # Return None for async translations
                  for lang in async_langs:
                      results[lang] = None
6e0e310c   tangwang   1. Translator 类增强
382
383
384
          else:
              # Synchronous mode: wait for all translations
              for lang in missing_langs:
0064e946   tangwang   feat: 增量索引服务、租户配置...
385
                  results[lang] = self.translate(text, lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
386
          
be52af70   tangwang   first commit
387
          return results
6e0e310c   tangwang   1. Translator 类增强
388
389
390
391
392
393
      
      def _get_cached_translation(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
394
395
          context: Optional[str] = None,
          prompt: Optional[str] = None
6e0e310c   tangwang   1. Translator 类增强
396
397
398
399
400
401
      ) -> Optional[str]:
          """Get translation from cache if available."""
          if not self.cache:
              return None
          
          translation_context = context or self.translation_context
0064e946   tangwang   feat: 增量索引服务、租户配置...
402
403
404
405
406
          cache_key_parts = [source_lang or 'auto', target_lang, translation_context]
          if prompt:
              cache_key_parts.append(prompt)
          cache_key_parts.append(text)
          cache_key = ':'.join(cache_key_parts)
6e0e310c   tangwang   1. Translator 类增强
407
408
409
410
411
412
413
          return self.cache.get(cache_key, category="translations")
      
      def _translate_async(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
414
415
          context: Optional[str] = None,
          prompt: Optional[str] = None
6e0e310c   tangwang   1. Translator 类增强
416
417
418
419
      ):
          """Launch async translation task."""
          def _do_translate():
              try:
0064e946   tangwang   feat: 增量索引服务、租户配置...
420
                  result = self.translate(text, target_lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
421
422
423
424
425
426
                  if result:
                      logger.debug(f"Async translation completed: {text} -> {target_lang}: {result}")
              except Exception as e:
                  logger.warning(f"Async translation failed: {text} -> {target_lang}: {e}")
          
          self.executor.submit(_do_translate)
be52af70   tangwang   first commit
427
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
      def _add_ecommerce_context(
          self,
          text: str,
          source_lang: Optional[str],
          context: Optional[str]
      ) -> tuple:
          """
          Add e-commerce context to text for better disambiguation.
          
          For single-word ambiguous Chinese terms, we add context words that help
          DeepL understand this is an e-commerce/product search context.
          
          Args:
              text: Original text to translate
              source_lang: Source language code
              context: Context hint
              
          Returns:
              Tuple of (text_with_context, needs_extraction)
              - text_with_context: Text to send to DeepL
              - needs_extraction: Whether we need to extract the term from the result
          """
          # Only apply for e-commerce context and Chinese source
          if not context or "e-commerce" not in context.lower():
              return text, False
              
          if not source_lang or source_lang.lower() != 'zh':
              return text, False
              
          # For single-word queries, add context to help disambiguation
          text_stripped = text.strip()
          if len(text_stripped.split()) == 1 and len(text_stripped) <= 2:
              # Common ambiguous Chinese e-commerce terms like "车" (car vs rook)
              # We add a context phrase: "购买 [term]" (buy [term]) or "商品 [term]" (product [term])
              # This helps DeepL understand the e-commerce context
              # We'll need to extract just the term from the translation result
              context_phrase = f"购买 {text_stripped}"
              return context_phrase, True
          
          # For multi-word queries, DeepL usually has enough context
          return text, False
  
      def _extract_term_from_translation(
          self,
          translated_text: str,
          original_text: str,
          target_lang_code: str
      ) -> str:
          """
          Extract the actual term from a translation that included context.
          
          For example, if we translated "购买 车" (buy car) and got "buy car",
          we want to extract just "car".
          
          Args:
              translated_text: Full translation result
              original_text: Original single-word query
              target_lang_code: Target language code (EN, ZH, etc.)
              
          Returns:
              Extracted term or original translation if extraction fails
          """
          # For English target, try to extract the last word (the actual term)
          if target_lang_code == "EN":
              words = translated_text.strip().split()
              if len(words) > 1:
                  # Usually the last word is the term we want
                  # But we need to be smart - if it's "buy car", we want "car"
                  # Common context words to skip: buy, purchase, product, item, etc.
                  context_words = {"buy", "purchase", "product", "item", "commodity", "goods"}
                  # Try to find the term (not a context word)
                  for word in reversed(words):
                      word_lower = word.lower().rstrip('.,!?;:')
                      if word_lower not in context_words:
                          return word_lower
                  # If all words are context words, return the last one
                  return words[-1].lower().rstrip('.,!?;:')
          
          # For other languages or if extraction fails, return as-is
          # The user can configure a glossary for better results
          return translated_text
  
be52af70   tangwang   first commit
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
      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
a5a6bab8   tangwang   多语言查询优化
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
      
      def _is_english_text(self, text: str) -> bool:
          """
          Check if text is primarily English (ASCII letters, numbers, common punctuation).
          
          Args:
              text: Text to check
              
          Returns:
              True if text appears to be English
          """
          if not text or not text.strip():
              return True
          
          # Remove whitespace and common punctuation
          text_clean = re.sub(r'[\s\.,!?;:\-\'\"\(\)\[\]{}]', '', text)
          if not text_clean:
              return True
          
          # Check if all remaining characters are ASCII (letters, numbers)
          # This is a simple heuristic: if most characters are ASCII, it's likely English
          ascii_count = sum(1 for c in text_clean if ord(c) < 128)
          ratio = ascii_count / len(text_clean) if text_clean else 0
          
          # If more than 80% are ASCII characters, consider it English
          return ratio > 0.8
      
      def _contains_chinese(self, text: str) -> bool:
          """
          Check if text contains Chinese characters (Han characters).
          
          Args:
              text: Text to check
              
          Returns:
              True if text contains Chinese characters
          """
          if not text:
              return False
          
          # Check for Chinese characters (Unicode range: \u4e00-\u9fff)
          chinese_pattern = re.compile(r'[\u4e00-\u9fff]')
          return bool(chinese_pattern.search(text))
      
      def _is_pure_number(self, text: str) -> bool:
          """
          Check if text is purely numeric (digits, possibly with spaces, dots, commas).
          
          Args:
              text: Text to check
              
          Returns:
              True if text is purely numeric
          """
          if not text or not text.strip():
              return False
          
          # Remove whitespace, dots, commas (common number separators)
          text_clean = re.sub(r'[\s\.,]', '', text.strip())
          if not text_clean:
              return False
          
          # Check if all remaining characters are digits
          return text_clean.isdigit()