Blame view

translation/backends/llm.py 12.2 KB
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
1
2
3
4
5
  """LLM-based translation backend."""
  
  from __future__ import annotations
  
  import logging
1e370dc9   tangwang   1. 翻译性能优化
6
  import re
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
7
8
9
10
11
  import time
  from typing import List, Optional, Sequence, Union
  
  from openai import OpenAI
  
0fd2f875   tangwang   translate
12
  from translation.languages import LANGUAGE_LABELS
1e370dc9   tangwang   1. 翻译性能优化
13
  from translation.prompts import BATCH_TRANSLATION_PROMPTS, TRANSLATION_PROMPTS
0fd2f875   tangwang   translate
14
  from translation.scenes import normalize_scene_name
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
15
16
  
  logger = logging.getLogger(__name__)
1e370dc9   tangwang   1. 翻译性能优化
17
  _NUMBERED_LINE_RE = re.compile(r"^\s*(\d+)[\.\uFF0E]\s*(.*)\s*$")
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
18
  
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
19
  
1e370dc9   tangwang   1. 翻译性能优化
20
21
  def _resolve_prompt_template(
      prompt_groups: dict[str, dict[str, str]],
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
22
      *,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
23
24
      target_lang: str,
      scene: Optional[str],
1e370dc9   tangwang   1. 翻译性能优化
25
  ) -> tuple[str, str, str]:
0fd2f875   tangwang   translate
26
      tgt = str(target_lang or "").strip().lower()
0fd2f875   tangwang   translate
27
      normalized_scene = normalize_scene_name(scene)
1e370dc9   tangwang   1. 翻译性能优化
28
      group = prompt_groups[normalized_scene]
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
29
      template = group.get(tgt) or group.get("en")
0fd2f875   tangwang   translate
30
31
      if template is None:
          raise ValueError(f"Missing llm translation prompt for scene='{normalized_scene}' target_lang='{tgt}'")
1e370dc9   tangwang   1. 翻译性能优化
32
33
      return tgt, normalized_scene, template
  
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
34
  
1e370dc9   tangwang   1. 翻译性能优化
35
36
37
38
39
40
41
42
43
44
45
46
47
  def _build_prompt(
      text: str,
      *,
      source_lang: Optional[str],
      target_lang: str,
      scene: Optional[str],
  ) -> str:
      src = str(source_lang or "auto").strip().lower() or "auto"
      tgt, _normalized_scene, template = _resolve_prompt_template(
          TRANSLATION_PROMPTS,
          target_lang=target_lang,
          scene=scene,
      )
0fd2f875   tangwang   translate
48
49
      source_lang_label = LANGUAGE_LABELS.get(src, src)
      target_lang_label = LANGUAGE_LABELS.get(tgt, tgt)
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
50
51
52
53
54
55
56
57
58
59
  
      return template.format(
          source_lang=source_lang_label,
          src_lang_code=src,
          target_lang=target_lang_label,
          tgt_lang_code=tgt,
          text=text,
      )
  
  
1e370dc9   tangwang   1. 翻译性能优化
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
  def _build_batch_prompt(
      texts: Sequence[str],
      *,
      source_lang: Optional[str],
      target_lang: str,
      scene: Optional[str],
  ) -> str:
      src = str(source_lang or "auto").strip().lower() or "auto"
      tgt, _normalized_scene, template = _resolve_prompt_template(
          BATCH_TRANSLATION_PROMPTS,
          target_lang=target_lang,
          scene=scene,
      )
      source_lang_label = LANGUAGE_LABELS.get(src, src)
      target_lang_label = LANGUAGE_LABELS.get(tgt, tgt)
      numbered_input = "\n".join(f"{idx}. {item}" for idx, item in enumerate(texts, start=1))
      format_example = "\n".join(f"{idx}. translation" for idx in range(1, len(texts) + 1))
  
      return template.format(
          source_lang=source_lang_label,
          src_lang_code=src,
          target_lang=target_lang_label,
          tgt_lang_code=tgt,
          item_count=len(texts),
          format_example=format_example,
          text=numbered_input,
      )
  
  
  def _parse_batch_translation_output(content: str, *, expected_count: int) -> Optional[List[str]]:
      numbered_lines: dict[int, str] = {}
      for raw_line in content.splitlines():
          stripped = raw_line.strip()
          if not stripped or stripped.startswith("```"):
              continue
          match = _NUMBERED_LINE_RE.match(stripped)
          if match is None:
              logger.warning("[llm] Invalid batch line format | line=%s", raw_line)
              return None
          index = int(match.group(1))
          if index in numbered_lines:
              logger.warning("[llm] Duplicate batch line index | index=%s", index)
              return None
          numbered_lines[index] = match.group(2).strip()
  
      expected_indices = set(range(1, expected_count + 1))
      actual_indices = set(numbered_lines.keys())
      if actual_indices != expected_indices:
          logger.warning(
              "[llm] Batch line indices mismatch | expected=%s actual=%s",
              sorted(expected_indices),
              sorted(actual_indices),
          )
          return None
      return [numbered_lines[idx] for idx in range(1, expected_count + 1)]
  
  
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
117
118
119
120
  class LLMTranslationBackend:
      def __init__(
          self,
          *,
0fd2f875   tangwang   translate
121
122
123
124
          capability_name: str,
          model: str,
          timeout_sec: float,
          base_url: str,
86d8358b   tangwang   config optimize
125
          api_key: Optional[str],
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
126
      ) -> None:
0fd2f875   tangwang   translate
127
128
129
130
          self.capability_name = capability_name
          self.model = model
          self.timeout_sec = float(timeout_sec)
          self.base_url = base_url
86d8358b   tangwang   config optimize
131
          self.api_key = api_key
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
132
133
134
135
136
137
138
          self.client = self._create_client()
  
      @property
      def supports_batch(self) -> bool:
          return True
  
      def _create_client(self) -> Optional[OpenAI]:
86d8358b   tangwang   config optimize
139
          if not self.api_key:
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
140
141
142
              logger.warning("DASHSCOPE_API_KEY not set; llm translation unavailable")
              return None
          try:
86d8358b   tangwang   config optimize
143
              return OpenAI(api_key=self.api_key, base_url=self.base_url)
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
144
145
146
147
148
149
150
151
152
          except Exception as exc:
              logger.error("Failed to initialize llm translation client: %s", exc, exc_info=True)
              return None
  
      def _translate_single(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
0fd2f875   tangwang   translate
153
          scene: Optional[str] = None,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
154
155
156
157
158
159
      ) -> Optional[str]:
          if not text or not str(text).strip():
              return text
          if not self.client:
              return None
  
0fd2f875   tangwang   translate
160
161
162
163
164
165
          tgt = str(target_lang or "").strip().lower()
          src = str(source_lang or "auto").strip().lower() or "auto"
          if scene is None:
              raise ValueError("llm translation scene is required")
          normalized_scene = normalize_scene_name(scene)
          user_prompt = _build_prompt(
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
166
167
168
              text=text,
              source_lang=src,
              target_lang=tgt,
0fd2f875   tangwang   translate
169
              scene=normalized_scene,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
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
          )
          start = time.time()
          try:
              logger.info(
                  "[llm] Request | src=%s tgt=%s model=%s prompt=%s",
                  src,
                  tgt,
                  self.model,
                  user_prompt,
              )
              completion = self.client.chat.completions.create(
                  model=self.model,
                  messages=[{"role": "user", "content": user_prompt}],
                  timeout=self.timeout_sec,
              )
              content = (completion.choices[0].message.content or "").strip()
              latency_ms = (time.time() - start) * 1000
              if not content:
                  logger.warning("[llm] Empty result | src=%s tgt=%s latency=%.1fms", src, tgt, latency_ms)
                  return None
              logger.info(
                  "[llm] Success | src=%s tgt=%s src_text=%s response=%s latency=%.1fms",
                  src,
                  tgt,
                  text,
                  content,
                  latency_ms,
              )
              return content
          except Exception as exc:
              latency_ms = (time.time() - start) * 1000
              logger.warning(
                  "[llm] Failed | src=%s tgt=%s latency=%.1fms error=%s",
                  src,
                  tgt,
                  latency_ms,
                  exc,
                  exc_info=True,
              )
              return None
  
1e370dc9   tangwang   1. 翻译性能优化
211
212
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
      def _translate_batch_serial_fallback(
          self,
          texts: Sequence[Optional[str]],
          target_lang: str,
          source_lang: Optional[str] = None,
          scene: Optional[str] = None,
      ) -> List[Optional[str]]:
          results: List[Optional[str]] = []
          for item in texts:
              if item is None:
                  results.append(None)
                  continue
              normalized = str(item)
              if not normalized.strip():
                  results.append(normalized)
                  continue
              results.append(
                  self._translate_single(
                      text=normalized,
                      target_lang=target_lang,
                      source_lang=source_lang,
                      scene=scene,
                  )
              )
          return results
  
      def _translate_batch(
          self,
          texts: Sequence[Optional[str]],
          target_lang: str,
          source_lang: Optional[str] = None,
          scene: Optional[str] = None,
      ) -> List[Optional[str]]:
          results: List[Optional[str]] = [None] * len(texts)
          prompt_texts: List[str] = []
          prompt_positions: List[int] = []
  
          for idx, item in enumerate(texts):
              if item is None:
                  continue
              normalized = str(item)
              if not normalized.strip():
                  results[idx] = normalized
                  continue
              if "\n" in normalized or "\r" in normalized:
                  logger.info("[llm] Batch fallback to serial | reason=multiline_input item_index=%s", idx)
                  return self._translate_batch_serial_fallback(
                      texts=texts,
                      target_lang=target_lang,
                      source_lang=source_lang,
                      scene=scene,
                  )
              prompt_texts.append(normalized)
              prompt_positions.append(idx)
  
          if not prompt_texts:
              return results
          if not self.client:
              return results
  
          tgt = str(target_lang or "").strip().lower()
          src = str(source_lang or "auto").strip().lower() or "auto"
          if scene is None:
              raise ValueError("llm translation scene is required")
          normalized_scene = normalize_scene_name(scene)
          user_prompt = _build_batch_prompt(
              texts=prompt_texts,
              source_lang=src,
              target_lang=tgt,
              scene=normalized_scene,
          )
  
          start = time.time()
          try:
              logger.info(
                  "[llm] Batch request | src=%s tgt=%s model=%s item_count=%s prompt=%s",
                  src,
                  tgt,
                  self.model,
                  len(prompt_texts),
                  user_prompt,
              )
              completion = self.client.chat.completions.create(
                  model=self.model,
                  messages=[{"role": "user", "content": user_prompt}],
                  timeout=self.timeout_sec,
              )
              content = (completion.choices[0].message.content or "").strip()
              latency_ms = (time.time() - start) * 1000
              if not content:
                  logger.warning(
                      "[llm] Empty batch result | src=%s tgt=%s item_count=%s latency=%.1fms",
                      src,
                      tgt,
                      len(prompt_texts),
                      latency_ms,
                  )
                  return self._translate_batch_serial_fallback(
                      texts=texts,
                      target_lang=target_lang,
                      source_lang=source_lang,
                      scene=scene,
                  )
  
              parsed = _parse_batch_translation_output(content, expected_count=len(prompt_texts))
              if parsed is None:
                  logger.warning(
                      "[llm] Batch parse failed, fallback to serial | src=%s tgt=%s item_count=%s response=%s",
                      src,
                      tgt,
                      len(prompt_texts),
                      content,
                  )
                  return self._translate_batch_serial_fallback(
                      texts=texts,
                      target_lang=target_lang,
                      source_lang=source_lang,
                      scene=scene,
                  )
  
              for position, translated in zip(prompt_positions, parsed):
                  results[position] = translated
              logger.info(
                  "[llm] Batch success | src=%s tgt=%s item_count=%s response=%s latency=%.1fms",
                  src,
                  tgt,
                  len(prompt_texts),
                  content,
                  latency_ms,
              )
              return results
          except Exception as exc:
              latency_ms = (time.time() - start) * 1000
              logger.warning(
                  "[llm] Batch failed | src=%s tgt=%s item_count=%s latency=%.1fms error=%s",
                  src,
                  tgt,
                  len(prompt_texts),
                  latency_ms,
                  exc,
                  exc_info=True,
              )
              return results
  
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
355
356
357
358
359
      def translate(
          self,
          text: Union[str, Sequence[str]],
          target_lang: str,
          source_lang: Optional[str] = None,
0fd2f875   tangwang   translate
360
          scene: Optional[str] = None,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
361
362
      ) -> Union[Optional[str], List[Optional[str]]]:
          if isinstance(text, (list, tuple)):
1e370dc9   tangwang   1. 翻译性能优化
363
364
365
366
367
368
              return self._translate_batch(
                  text,
                  target_lang=target_lang,
                  source_lang=source_lang,
                  scene=scene,
              )
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
369
370
371
372
373
  
          return self._translate_single(
              text=str(text),
              target_lang=target_lang,
              source_lang=source_lang,
0fd2f875   tangwang   translate
374
              scene=scene,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
375
          )