Blame view

query/translator.py 37.7 KB
be52af70   tangwang   first commit
1
2
3
  """
  Translation service for multi-language query support.
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
4
5
6
  Supports multiple translation models:
  - Qwen (default): Alibaba Cloud DashScope API using qwen-mt-flash model
  - DeepL: DeepL API for high-quality translations
0064e946   tangwang   feat: 增量索引服务、租户配置...
7
  
985752f5   tangwang   1. 前端调试功能
8
9
10
11
12
  重要说明(Qwen 机翻限速):
  - 当前默认使用的 `qwen-mt-flash` 为云端机翻模型,**官方限速较低,约 RPM=60(每分钟约 60 请求)**
  - 在高并发场景必须依赖 Redis 翻译缓存与批量预热,避免在用户实时请求路径上直接打满 DashScope 限流
  - 若业务侧存在大规模离线翻译或更高吞吐需求,建议评估 DeepL 或自建翻译后端
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
13
  使用方法 (Usage):
0064e946   tangwang   feat: 增量索引服务、租户配置...
14
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
15
  ```python
a0a173ae   tangwang   last
16
  from query.qwen_mt_translate import Translator
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  
  # 使用默认的 qwen 模型(推荐)
  translator = Translator()  # 默认使用 qwen 模型
  
  # 或显式指定模型
  translator = Translator(model='qwen')  # 使用 qwen 模型
  translator = Translator(model='deepl')  # 使用 DeepL 模型
  
  # 翻译文本
  result = translator.translate(
      text="我看到这个视频后没有笑",
      target_lang="en",
      source_lang="auto"  # 自动检测源语言
  )
  ```
  
  配置说明 (Configuration):
  - Qwen 模型需要设置 DASHSCOPE_API_KEY 环境变量(在 .env 文件中)
  - DeepL 模型需要设置 DEEPL_AUTH_KEY 环境变量(在 .env 文件中)
0064e946   tangwang   feat: 增量索引服务、租户配置...
36
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
37
38
39
  Qwen 模型参考文档:
  - 官方文档:https://help.aliyun.com/zh/model-studio/get-api-key
  - 模型:qwen-mt-flash(快速翻译模型)
0064e946   tangwang   feat: 增量索引服务、租户配置...
40
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
41
42
  DeepL 官方文档:
  https://developers.deepl.com/api-reference/translate/request-translation
be52af70   tangwang   first commit
43
44
  """
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
45
  import os
be52af70   tangwang   first commit
46
  import requests
a5a6bab8   tangwang   多语言查询优化
47
  import re
453992a8   tangwang   需求:
48
  import redis
3ec5bfe6   tangwang   1. get_translatio...
49
  from concurrent.futures import ThreadPoolExecutor, Future
453992a8   tangwang   需求:
50
  from datetime import timedelta
3ec5bfe6   tangwang   1. get_translatio...
51
  from typing import Dict, List, Optional, Union
6e0e310c   tangwang   1. Translator 类增强
52
  import logging
d90e7428   tangwang   补充重排
53
  import time
6e0e310c   tangwang   1. Translator 类增强
54
55
  
  logger = logging.getLogger(__name__)
be52af70   tangwang   first commit
56
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
57
58
  from config.env_config import DEEPL_AUTH_KEY, DASHSCOPE_API_KEY, REDIS_CONFIG
  from openai import OpenAI
325eec03   tangwang   1. 日志、配置基础设施,使用优化
59
  
be52af70   tangwang   first commit
60
61
  
  class Translator:
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
62
63
64
65
66
      """
      Multi-language translator supporting Qwen and DeepL APIs.
      
      Default model is 'qwen' which uses Alibaba Cloud DashScope API.
      """
cc11ae04   tangwang   cnclip
67
68
69
  # 华北2(北京):https://dashscope.aliyuncs.com/compatible-mode/v1
  # 新加坡:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
  # 美国(弗吉尼亚):https://dashscope-us.aliyuncs.com/compatible-mode/v1
be52af70   tangwang   first commit
70
  
16c42787   tangwang   feat: implement r...
71
      DEEPL_API_URL = "https://api.deepl.com/v2/translate"  # Pro tier
cc11ae04   tangwang   cnclip
72
      QWEN_BASE_URL = "https://dashscope-us.aliyuncs.com/compatible-mode/v1"  # 北京地域
3b84605d   tangwang   docs
73
      # QWEN_BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"  # 新加坡
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
74
75
      # 如果使用新加坡地域的模型,需要将base_url替换为:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
      QWEN_MODEL = "qwen-mt-flash"  # 快速翻译模型
be52af70   tangwang   first commit
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
  
      # 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,
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
93
          model: str = "qwen",
be52af70   tangwang   first commit
94
95
          api_key: Optional[str] = None,
          use_cache: bool = True,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
96
97
98
          timeout: int = 10,
          glossary_id: Optional[str] = None,
          translation_context: Optional[str] = None
be52af70   tangwang   first commit
99
100
101
102
103
      ):
          """
          Initialize translator.
  
          Args:
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
104
105
              model: Translation model to use. Options: 'qwen' (default) or 'deepl'
              api_key: API key for the selected model (or None to use from config/env)
be52af70   tangwang   first commit
106
107
              use_cache: Whether to cache translations
              timeout: Request timeout in seconds
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
108
              glossary_id: DeepL glossary ID for custom terminology (optional, only for DeepL)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
109
              translation_context: Context hint for translation (e.g., "e-commerce", "product search")
be52af70   tangwang   first commit
110
          """
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
111
112
113
114
          self.model = model.lower()
          if self.model not in ['qwen', 'deepl']:
              raise ValueError(f"Unsupported model: {model}. Supported models: 'qwen', 'deepl'")
          
d79810d5   tangwang   first commit
115
          # Get API key from config if not provided
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
116
117
118
119
120
          if api_key is None:
              if self.model == 'qwen':
                  api_key = DASHSCOPE_API_KEY or os.getenv("DASHSCOPE_API_KEY")
              else:  # deepl
                  api_key = DEEPL_AUTH_KEY or os.getenv("DEEPL_AUTH_KEY")
d79810d5   tangwang   first commit
121
  
be52af70   tangwang   first commit
122
123
124
          self.api_key = api_key
          self.timeout = timeout
          self.use_cache = use_cache
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
125
126
          self.glossary_id = glossary_id
          self.translation_context = translation_context or "e-commerce product search"
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
127
128
129
130
131
132
133
134
135
136
137
          
          # Initialize OpenAI client for Qwen if needed
          self.qwen_client = None
          if self.model == 'qwen':
              if not self.api_key:
                  logger.warning("DASHSCOPE_API_KEY not set. Qwen translation will not work.")
              else:
                  self.qwen_client = OpenAI(
                      api_key=self.api_key,
                      base_url=self.QWEN_BASE_URL,
                  )
be52af70   tangwang   first commit
138
  
453992a8   tangwang   需求:
139
          # Initialize Redis cache if enabled
be52af70   tangwang   first commit
140
          if use_cache:
453992a8   tangwang   需求:
141
142
143
144
145
146
147
148
149
150
151
152
153
              try:
                  self.redis_client = redis.Redis(
                      host=REDIS_CONFIG.get('host', 'localhost'),
                      port=REDIS_CONFIG.get('port', 6479),
                      password=REDIS_CONFIG.get('password'),
                      decode_responses=True,  # Return str instead of bytes
                      socket_timeout=REDIS_CONFIG.get('socket_timeout', 1),
                      socket_connect_timeout=REDIS_CONFIG.get('socket_connect_timeout', 1),
                      retry_on_timeout=REDIS_CONFIG.get('retry_on_timeout', False),
                      health_check_interval=10,  # 避免复用坏连接
                  )
                  # Test connection
                  self.redis_client.ping()
a866b688   tangwang   翻译接口
154
155
156
                  expire_days = REDIS_CONFIG.get('translation_cache_expire_days', 360)
                  self.expire_time = timedelta(days=expire_days)
                  self.expire_seconds = int(self.expire_time.total_seconds())  # Redis 需要秒数
453992a8   tangwang   需求:
157
158
159
160
161
162
                  self.cache_prefix = REDIS_CONFIG.get('translation_cache_prefix', 'trans')
                  logger.info("Redis cache initialized for translations")
              except Exception as e:
                  logger.warning(f"Failed to initialize Redis cache: {e}, falling back to no cache")
                  self.redis_client = None
                  self.cache = None
be52af70   tangwang   first commit
163
          else:
453992a8   tangwang   需求:
164
              self.redis_client = None
be52af70   tangwang   first commit
165
              self.cache = None
6e0e310c   tangwang   1. Translator 类增强
166
167
168
          
          # Thread pool for async translation
          self.executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="translator")
be52af70   tangwang   first commit
169
170
171
172
173
  
      def translate(
          self,
          text: str,
          target_lang: str,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
174
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
175
176
          context: Optional[str] = None,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
177
178
      ) -> Optional[str]:
          """
0064e946   tangwang   feat: 增量索引服务、租户配置...
179
          Translate text to target language (synchronous mode).
be52af70   tangwang   first commit
180
181
182
183
  
          Args:
              text: Text to translate
              target_lang: Target language code ('zh', 'en', 'ru', etc.)
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
184
              source_lang: Source language code (option al, auto-detect if None)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
185
              context: Additional context for translation (overrides default context)
0064e946   tangwang   feat: 增量索引服务、租户配置...
186
              prompt: Translation prompt/instruction (optional, for better translation quality)
be52af70   tangwang   first commit
187
188
189
190
191
192
193
194
195
196
197
198
  
          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   多语言查询优化
199
200
          # Optimization: Skip translation if not needed
          if target_lang == 'en' and self._is_english_text(text):
3652f85f   tangwang   trans for index
201
              logger.info(f"[Translator] Text is already English, skipping translation: '{text[:50]}...'")
a5a6bab8   tangwang   多语言查询优化
202
203
204
              return text
          
          if target_lang == 'zh' and (self._contains_chinese(text) or self._is_pure_number(text)):
70dab99f   tangwang   add logs
205
206
207
208
              logger.info(
                  f"[Translator] Translation request | Original text: '{text}' | Target language: {target_lang} | "
                  f"Source language: {source_lang or 'auto'} | Result: Skip translation (contains Chinese or pure number)"
              )
a5a6bab8   tangwang   多语言查询优化
209
210
              return text
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
211
212
          # Use provided context or default context
          translation_context = context or self.translation_context
0064e946   tangwang   feat: 增量索引服务、租户配置...
213
214
215
216
217
218
219
220
221
          
          # 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)
453992a8   tangwang   需求:
222
223
          if self.use_cache and self.redis_client:
              cached = self._get_cached_translation_redis(text, target_lang, source_lang, translation_context, prompt)
be52af70   tangwang   first commit
224
              if cached:
3652f85f   tangwang   trans for index
225
                  logger.info(
70dab99f   tangwang   add logs
226
227
                      f"[Translator] Translation request | Original text: '{text}' | Target language: {target_lang} | "
                      f"Source language: {source_lang or 'auto'} | Result: '{cached}' | Source: Cache hit"
3652f85f   tangwang   trans for index
228
                  )
be52af70   tangwang   first commit
229
230
231
232
                  return cached
  
          # If no API key, return mock translation (for testing)
          if not self.api_key:
70dab99f   tangwang   add logs
233
234
235
236
              logger.info(
                  f"[Translator] Translation request | Original text: '{text}' | Target language: {target_lang} | "
                  f"Source language: {source_lang or 'auto'} | Result: '{text}' | Source: Mock mode (no API key)"
              )
be52af70   tangwang   first commit
237
238
              return text
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
239
          # Translate using selected model
3652f85f   tangwang   trans for index
240
          logger.info(
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
241
              f"[Translator] Translation request | Model: {self.model} | Original text: '{text}' | Target language: {target_lang} | "
70dab99f   tangwang   add logs
242
243
              f"Source language: {source_lang or 'auto'} | Context: {translation_context} | "
              f"Prompt: {'yes' if prompt else 'no'} | Status: Starting translation"
3652f85f   tangwang   trans for index
244
          )
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
245
246
247
248
249
          
          if self.model == 'qwen':
              result = self._translate_qwen(text, target_lang, source_lang, translation_context, prompt)
          else:  # deepl
              result = self._translate_deepl(text, target_lang, source_lang, translation_context, prompt)
be52af70   tangwang   first commit
250
  
a7bb846c   tangwang   monitor
251
252
          # Surface translation failure to the caller instead of silently
          # masquerading the source text as a successful translation.
16c42787   tangwang   feat: implement r...
253
          if result is None:
70dab99f   tangwang   add logs
254
255
              logger.warning(
                  f"[Translator] Translation request | Original text: '{text}' | Target language: {target_lang} | "
a7bb846c   tangwang   monitor
256
                  f"Source language: {source_lang or 'auto'} | Status: Translation failed"
70dab99f   tangwang   add logs
257
              )
70dab99f   tangwang   add logs
258
259
260
261
262
          else:
              logger.info(
                  f"[Translator] Translation request | Original text: '{text}' | Target language: {target_lang} | "
                  f"Source language: {source_lang or 'auto'} | Result: '{result}' | Status: Translation successful"
              )
3652f85f   tangwang   trans for index
263
  
a7bb846c   tangwang   monitor
264
265
266
          # Cache only successful translations. Failed attempts must not poison
          # Redis with the original text.
          if result is not None and self.use_cache and self.redis_client:
453992a8   tangwang   需求:
267
              self._set_cached_translation_redis(text, target_lang, result, source_lang, translation_context, prompt)
be52af70   tangwang   first commit
268
269
270
  
          return result
  
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
      def _translate_qwen(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str],
          context: Optional[str] = None,
          prompt: Optional[str] = None
      ) -> Optional[str]:
          """
          Translate using Qwen MT Flash model via Alibaba Cloud DashScope API.
          
          Args:
              text: Text to translate
              target_lang: Target language code ('zh', 'en', 'ru', etc.)
              source_lang: Source language code (optional, 'auto' if None)
              context: Context hint for translation (optional)
              prompt: Translation prompt/instruction (optional)
              
          Returns:
              Translated text or None if translation fails
          """
          if not self.qwen_client:
              logger.error("[Translator] Qwen client not initialized. Check DASHSCOPE_API_KEY.")
              return None
          
          # Qwen (qwen-mt-plus/flash/turbo) supported languages mapping
          # 标准来自:你提供的“语言 / 英文名 / 代码”表
          qwen_lang_map = {
              "en": "English",
              "zh": "Chinese",
              "zh_tw": "Traditional Chinese",
              "ru": "Russian",
              "ja": "Japanese",
              "ko": "Korean",
              "es": "Spanish",
              "fr": "French",
              "pt": "Portuguese",
              "de": "German",
              "it": "Italian",
              "th": "Thai",
              "vi": "Vietnamese",
              "id": "Indonesian",
              "ms": "Malay",
              "ar": "Arabic",
              "hi": "Hindi",
              "he": "Hebrew",
              "my": "Burmese",
              "ta": "Tamil",
              "ur": "Urdu",
              "bn": "Bengali",
              "pl": "Polish",
              "nl": "Dutch",
              "ro": "Romanian",
              "tr": "Turkish",
              "km": "Khmer",
              "lo": "Lao",
              "yue": "Cantonese",
              "cs": "Czech",
              "el": "Greek",
              "sv": "Swedish",
              "hu": "Hungarian",
              "da": "Danish",
              "fi": "Finnish",
              "uk": "Ukrainian",
              "bg": "Bulgarian",
          }
          
          # Convert target language
          target_lang_normalized = target_lang.lower()
          target_lang_qwen = qwen_lang_map.get(target_lang_normalized, target_lang.capitalize())
  
          # Convert source language
          source_lang_normalized = (source_lang or "").strip().lower()
          if not source_lang_normalized or source_lang_normalized == "auto":
              source_lang_qwen = "auto"
          else:
              source_lang_qwen = qwen_lang_map.get(source_lang_normalized, source_lang.capitalize())
          
          # Prepare translation options
          translation_options = {
              "source_lang": source_lang_qwen,
              "target_lang": target_lang_qwen,
          }
          
          # Prepare messages
          messages = [
              {
                  "role": "user",
                  "content": text
              }
          ]
          
d90e7428   tangwang   补充重排
363
          start_time = time.time()
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
364
365
366
367
368
369
370
371
372
373
          try:
              completion = self.qwen_client.chat.completions.create(
                  model=self.QWEN_MODEL,
                  messages=messages,
                  extra_body={
                      "translation_options": translation_options
                  }
              )
              
              translated_text = completion.choices[0].message.content.strip()
d90e7428   tangwang   补充重排
374
              duration_ms = (time.time() - start_time) * 1000
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
375
              
d90e7428   tangwang   补充重排
376
              logger.info(
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
377
                  f"[Translator] Qwen API response success | Original text: '{text}' | Target language: {target_lang_qwen} | "
d90e7428   tangwang   补充重排
378
                  f"Translation result: '{translated_text}' | Duration: {duration_ms:.2f} ms"
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
379
380
381
382
              )
              return translated_text
              
          except Exception as e:
d90e7428   tangwang   补充重排
383
              duration_ms = (time.time() - start_time) * 1000
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
384
385
              logger.error(
                  f"[Translator] Qwen API request exception | Original text: '{text}' | Target language: {target_lang_qwen} | "
d90e7428   tangwang   补充重排
386
                  f"Duration: {duration_ms:.2f} ms | Error: {e}", exc_info=True
3cd09b3b   tangwang   翻译接口改为调用qwen-mt-f...
387
388
389
              )
              return None
  
be52af70   tangwang   first commit
390
391
392
393
      def _translate_deepl(
          self,
          text: str,
          target_lang: str,
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
394
          source_lang: Optional[str],
0064e946   tangwang   feat: 增量索引服务、租户配置...
395
396
          context: Optional[str] = None,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
397
      ) -> Optional[str]:
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
398
399
400
401
402
403
404
405
406
          """
          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
407
408
409
410
411
412
413
414
          # 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: 增量索引服务、租户配置...
415
416
417
418
419
          # 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添...
420
421
          # 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: 增量索引服务、租户配置...
422
          text_to_translate, needs_extraction = self._add_ecommerce_context(text, source_lang, api_context)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
423
  
be52af70   tangwang   first commit
424
          payload = {
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
425
              "text": [text_to_translate],
be52af70   tangwang   first commit
426
427
428
429
430
431
432
              "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: 增量索引服务、租户配置...
433
434
435
436
437
          # 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添...
438
439
440
441
          # Add glossary if configured
          if self.glossary_id:
              payload["glossary_id"] = self.glossary_id
  
0064e946   tangwang   feat: 增量索引服务、租户配置...
442
443
444
          # 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添...
445
  
be52af70   tangwang   first commit
446
447
448
449
450
451
452
453
454
455
456
          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添...
457
458
459
460
461
462
                      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
                          )
70dab99f   tangwang   add logs
463
464
465
466
                      logger.debug(
                          f"[Translator] DeepL API response success | Original text: '{text}' | Target language: {target_code} | "
                          f"Translation result: '{translated_text}'"
                      )
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
467
                      return translated_text
be52af70   tangwang   first commit
468
              else:
70dab99f   tangwang   add logs
469
470
471
472
                  logger.error(
                      f"[Translator] DeepL API error | Original text: '{text}' | Target language: {target_code} | "
                      f"Status code: {response.status_code} | Error message: {response.text}"
                  )
be52af70   tangwang   first commit
473
474
475
                  return None
  
          except requests.Timeout:
70dab99f   tangwang   add logs
476
477
478
479
              logger.warning(
                  f"[Translator] DeepL API request timeout | Original text: '{text}' | Target language: {target_code} | "
                  f"Timeout: {self.timeout}s"
              )
be52af70   tangwang   first commit
480
481
              return None
          except Exception as e:
70dab99f   tangwang   add logs
482
483
484
485
              logger.error(
                  f"[Translator] DeepL API request exception | Original text: '{text}' | Target language: {target_code} | "
                  f"Error: {e}", exc_info=True
              )
be52af70   tangwang   first commit
486
487
              return None
  
3652f85f   tangwang   trans for index
488
489
490
      # NOTE: _translate_deepl_free is intentionally not implemented.
      # We do not support automatic fallback to the free endpoint, to avoid
      # mixing Pro keys with https://api-free.deepl.com and related 403 errors.
16c42787   tangwang   feat: implement r...
491
  
be52af70   tangwang   first commit
492
493
494
495
      def translate_multi(
          self,
          text: str,
          target_langs: List[str],
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
496
          source_lang: Optional[str] = None,
6e0e310c   tangwang   1. Translator 类增强
497
          context: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
498
499
          async_mode: bool = True,
          prompt: Optional[str] = None
be52af70   tangwang   first commit
500
501
502
      ) -> Dict[str, Optional[str]]:
          """
          Translate text to multiple target languages.
6e0e310c   tangwang   1. Translator 类增强
503
504
505
          
          In async_mode=True (default):
          - Returns cached translations immediately if available
a5a6bab8   tangwang   多语言查询优化
506
507
508
509
          - 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 类增强
510
511
512
          
          In async_mode=False:
          - Waits for all translations to complete (blocking)
be52af70   tangwang   first commit
513
514
515
516
517
  
          Args:
              text: Text to translate
              target_langs: List of target language codes
              source_lang: Source language code (optional)
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
518
              context: Context hint for translation (optional)
6e0e310c   tangwang   1. Translator 类增强
519
              async_mode: If True, return cached results immediately and translate missing ones async
0064e946   tangwang   feat: 增量索引服务、租户配置...
520
              prompt: Translation prompt/instruction (optional)
be52af70   tangwang   first commit
521
522
  
          Returns:
6e0e310c   tangwang   1. Translator 类增强
523
              Dictionary mapping language code to translated text (only cached results in async mode)
be52af70   tangwang   first commit
524
525
          """
          results = {}
6e0e310c   tangwang   1. Translator 类增强
526
          missing_langs = []
a5a6bab8   tangwang   多语言查询优化
527
          async_langs = []
6e0e310c   tangwang   1. Translator 类增强
528
529
          
          # First, get cached translations
be52af70   tangwang   first commit
530
          for lang in target_langs:
0064e946   tangwang   feat: 增量索引服务、租户配置...
531
              cached = self._get_cached_translation(text, lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
532
533
534
535
536
              if cached is not None:
                  results[lang] = cached
              else:
                  missing_langs.append(lang)
          
a5a6bab8   tangwang   多语言查询优化
537
          # If async mode and there are missing translations
6e0e310c   tangwang   1. Translator 类增强
538
          if async_mode and missing_langs:
a5a6bab8   tangwang   多语言查询优化
539
              # Check if translation can be optimized (immediate return)
6e0e310c   tangwang   1. Translator 类增强
540
              for lang in missing_langs:
a5a6bab8   tangwang   多语言查询优化
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
                  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 类增强
563
564
565
          else:
              # Synchronous mode: wait for all translations
              for lang in missing_langs:
0064e946   tangwang   feat: 增量索引服务、租户配置...
566
                  results[lang] = self.translate(text, lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
567
          
be52af70   tangwang   first commit
568
          return results
6e0e310c   tangwang   1. Translator 类增强
569
      
3ec5bfe6   tangwang   1. get_translatio...
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
      def translate_multi_async(
          self,
          text: str,
          target_langs: List[str],
          source_lang: Optional[str] = None,
          context: Optional[str] = None,
          prompt: Optional[str] = None
      ) -> Dict[str, Union[str, Future]]:
          """
          Translate text to multiple target languages asynchronously, returning Futures that can be awaited.
          
          This method returns a dictionary where:
          - If translation is cached, the value is the translation string (immediate)
          - If translation needs to be done, the value is a Future object that can be awaited
          
          Args:
              text: Text to translate
              target_langs: List of target language codes
              source_lang: Source language code (optional)
              context: Context hint for translation (optional)
              prompt: Translation prompt/instruction (optional)
  
          Returns:
              Dictionary mapping language code to either translation string (cached) or Future object
          """
          results = {}
          missing_langs = []
          
          # First, get cached translations
          for lang in target_langs:
              cached = self._get_cached_translation(text, lang, source_lang, context, prompt)
              if cached is not None:
                  results[lang] = cached
              else:
                  missing_langs.append(lang)
          
          # For missing translations, submit async tasks and return Futures
          for lang in missing_langs:
              future = self.executor.submit(
                  self.translate,
                  text,
                  lang,
                  source_lang,
                  context,
                  prompt
              )
              results[lang] = future
          
          return results
      
6e0e310c   tangwang   1. Translator 类增强
620
621
622
623
624
      def _get_cached_translation(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
625
626
          context: Optional[str] = None,
          prompt: Optional[str] = None
6e0e310c   tangwang   1. Translator 类增强
627
628
      ) -> Optional[str]:
          """Get translation from cache if available."""
453992a8   tangwang   需求:
629
630
631
632
633
634
635
636
637
638
639
640
          if not self.redis_client:
              return None
          return self._get_cached_translation_redis(text, target_lang, source_lang, context, prompt)
      
      def _get_cached_translation_redis(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
          context: Optional[str] = None,
          prompt: Optional[str] = None
      ) -> Optional[str]:
a866b688   tangwang   翻译接口
641
642
643
644
645
646
647
          """
          Get translation from Redis cache with sliding expiration.
          
          滑动过期机制:每次访问缓存时,重置过期时间为配置的过期时间(默认720天)。
          这样缓存会在最后一次访问后的720天才过期,而不是写入后的720天。
          这确保了常用的翻译缓存不会被过早删除。
          """
453992a8   tangwang   需求:
648
          if not self.redis_client:
6e0e310c   tangwang   1. Translator 类增强
649
650
              return None
          
453992a8   tangwang   需求:
651
652
653
654
655
656
657
658
          try:
              # Build cache key: prefix:target_lang:text
              # For simplicity, we use target_lang and text as key
              # Context and prompt are not included in key to maximize cache hits
              cache_key = f"{self.cache_prefix}:{target_lang.upper()}:{text}"
              value = self.redis_client.get(cache_key)
              if value:
                  # Sliding expiration: reset expiration time on access
a866b688   tangwang   翻译接口
659
660
661
662
663
664
665
666
667
                  # 每次读取缓存时,重置过期时间为配置的过期时间(最后一次访问后的N天才过期)
                  try:
                      self.redis_client.expire(cache_key, self.expire_seconds)
                  except Exception as expire_error:
                      # 即使 expire 失败,也返回缓存值(不影响功能)
                      logger.warning(
                          f"[Translator] Failed to update cache expiration for key {cache_key}: {expire_error}"
                      )
                  
70dab99f   tangwang   add logs
668
669
                  logger.debug(
                      f"[Translator] Redis cache hit | Original text: '{text}' | Target language: {target_lang} | "
a866b688   tangwang   翻译接口
670
                      f"Cache key: {cache_key} | Translation result: '{value}' | TTL reset to {self.expire_seconds}s"
3652f85f   tangwang   trans for index
671
                  )
453992a8   tangwang   需求:
672
                  return value
70dab99f   tangwang   add logs
673
674
675
676
              logger.debug(
                  f"[Translator] Redis cache miss | Original text: '{text}' | Target language: {target_lang} | "
                  f"Cache key: {cache_key}"
              )
453992a8   tangwang   需求:
677
678
              return None
          except Exception as e:
70dab99f   tangwang   add logs
679
              logger.error(f"[Translator] Redis error during get translation cache | Original text: '{text}' | Target language: {target_lang} | Error: {e}")
453992a8   tangwang   需求:
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
              return None
      
      def _set_cached_translation_redis(
          self,
          text: str,
          target_lang: str,
          translation: str,
          source_lang: Optional[str] = None,
          context: Optional[str] = None,
          prompt: Optional[str] = None
      ) -> None:
          """Store translation in Redis cache."""
          if not self.redis_client:
              return
          
          try:
              cache_key = f"{self.cache_prefix}:{target_lang.upper()}:{text}"
a866b688   tangwang   翻译接口
697
              self.redis_client.setex(cache_key, self.expire_seconds, translation)
153a592e   tangwang   redis统计脚本
698
              logger.info(
70dab99f   tangwang   add logs
699
700
                  f"[Translator] Redis cache write | Original text: '{text}' | Target language: {target_lang} | "
                  f"Cache key: {cache_key} | Translation result: '{translation}'"
3652f85f   tangwang   trans for index
701
              )
453992a8   tangwang   需求:
702
          except Exception as e:
70dab99f   tangwang   add logs
703
704
705
706
              logger.error(
                  f"[Translator] Redis cache write failed | Original text: '{text}' | Target language: {target_lang} | "
                  f"Error: {e}"
              )
6e0e310c   tangwang   1. Translator 类增强
707
708
709
710
711
712
      
      def _translate_async(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
0064e946   tangwang   feat: 增量索引服务、租户配置...
713
714
          context: Optional[str] = None,
          prompt: Optional[str] = None
6e0e310c   tangwang   1. Translator 类增强
715
716
717
718
      ):
          """Launch async translation task."""
          def _do_translate():
              try:
0064e946   tangwang   feat: 增量索引服务、租户配置...
719
                  result = self.translate(text, target_lang, source_lang, context, prompt)
6e0e310c   tangwang   1. Translator 类增强
720
721
722
723
724
725
                  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
726
  
522a3964   tangwang   多语言搜索翻译的优化(deepL添...
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
      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
  
038e4e2f   tangwang   refactor(i18n): t...
809
810
811
812
813
814
815
816
817
818
819
820
      def _shop_lang_matches(self, shop_lang_lower: str, lang_code: str) -> bool:
          """True if shop language matches index language (use source, no translate)."""
          if not shop_lang_lower or not lang_code:
              return False
          if shop_lang_lower == lang_code:
              return True
          if lang_code == "zh" and "zh" in shop_lang_lower:
              return True
          if lang_code == "en" and "en" in shop_lang_lower:
              return True
          return False
  
453992a8   tangwang   需求:
821
822
823
824
825
826
      def translate_for_indexing(
          self,
          text: str,
          shop_language: str,
          source_lang: Optional[str] = None,
          context: Optional[str] = None,
345d960b   tangwang   1. 删除全局 enable_tr...
827
          prompt: Optional[str] = None,
038e4e2f   tangwang   refactor(i18n): t...
828
          index_languages: Optional[List[str]] = None,
453992a8   tangwang   需求:
829
830
      ) -> Dict[str, Optional[str]]:
          """
038e4e2f   tangwang   refactor(i18n): t...
831
832
833
834
835
          Translate text for indexing based on shop language and tenant index_languages.
  
          For each language in index_languages: use source text if shop language matches,
          otherwise translate to that language.
  
453992a8   tangwang   需求:
836
837
          Args:
              text: Text to translate
038e4e2f   tangwang   refactor(i18n): t...
838
839
              shop_language: Shop primary language (e.g. 'zh', 'en', 'ru')
              source_lang: Source language code (optional)
453992a8   tangwang   需求:
840
              context: Additional context for translation (optional)
038e4e2f   tangwang   refactor(i18n): t...
841
842
843
              prompt: Translation prompt (optional)
              index_languages: Languages to index (from tenant_config). Default ["en", "zh"].
  
453992a8   tangwang   需求:
844
          Returns:
038e4e2f   tangwang   refactor(i18n): t...
845
              Dict keyed by each index_language with translated or source text (or None).
453992a8   tangwang   需求:
846
          """
038e4e2f   tangwang   refactor(i18n): t...
847
848
          langs = index_languages if index_languages else ["en", "zh"]
          results = {lang: None for lang in langs}
453992a8   tangwang   需求:
849
          if not text or not text.strip():
038e4e2f   tangwang   refactor(i18n): t...
850
              return results
453992a8   tangwang   需求:
851
852
          if re.match(r'^[\d\s_-]+$', text):
              logger.info(f"[Translator] Skip translation for symbol-only query: '{text}'")
453992a8   tangwang   需求:
853
              return results
038e4e2f   tangwang   refactor(i18n): t...
854
855
856
857
858
859
860
861
862
  
          shop_lang_lower = (shop_language or "").strip().lower()
          targets = []
          for lang in langs:
              if self._shop_lang_matches(shop_lang_lower, lang):
                  results[lang] = text
              else:
                  targets.append(lang)
  
453992a8   tangwang   需求:
863
          for target_lang in targets:
453992a8   tangwang   需求:
864
865
866
867
868
              cached = self._get_cached_translation_redis(text, target_lang, source_lang, context, prompt)
              if cached:
                  results[target_lang] = cached
                  logger.debug(f"[Translator] Cache hit for indexing: '{text}' -> {target_lang}: {cached}")
                  continue
453992a8   tangwang   需求:
869
870
871
872
873
              translated = self.translate(
                  text,
                  target_lang=target_lang,
                  source_lang=source_lang or shop_language,
                  context=context,
038e4e2f   tangwang   refactor(i18n): t...
874
                  prompt=prompt,
453992a8   tangwang   需求:
875
876
              )
              results[target_lang] = translated
453992a8   tangwang   需求:
877
878
          return results
  
be52af70   tangwang   first commit
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
      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:
453992a8   tangwang   需求:
896
              return [lang for lang in supported_langs if detected_lang != lang]
be52af70   tangwang   first commit
897
898
899
  
          # Otherwise, translate to all supported languages
          return supported_langs
a5a6bab8   tangwang   多语言查询优化
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
      
      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()