llm.py
12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""LLM-based translation backend."""
from __future__ import annotations
import logging
import re
import time
from typing import List, Optional, Sequence, Union
from openai import OpenAI
from translation.languages import LANGUAGE_LABELS
from translation.prompts import BATCH_TRANSLATION_PROMPTS, TRANSLATION_PROMPTS
from translation.scenes import normalize_scene_name
logger = logging.getLogger(__name__)
_NUMBERED_LINE_RE = re.compile(r"^\s*(\d+)[\.\uFF0E]\s*(.*)\s*$")
def _resolve_prompt_template(
prompt_groups: dict[str, dict[str, str]],
*,
target_lang: str,
scene: Optional[str],
) -> tuple[str, str, str]:
tgt = str(target_lang or "").strip().lower()
normalized_scene = normalize_scene_name(scene)
group = prompt_groups[normalized_scene]
template = group.get(tgt) or group.get("en")
if template is None:
raise ValueError(f"Missing llm translation prompt for scene='{normalized_scene}' target_lang='{tgt}'")
return tgt, normalized_scene, template
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,
)
source_lang_label = LANGUAGE_LABELS.get(src, src)
target_lang_label = LANGUAGE_LABELS.get(tgt, tgt)
return template.format(
source_lang=source_lang_label,
src_lang_code=src,
target_lang=target_lang_label,
tgt_lang_code=tgt,
text=text,
)
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)]
class LLMTranslationBackend:
def __init__(
self,
*,
capability_name: str,
model: str,
timeout_sec: float,
base_url: str,
api_key: Optional[str],
) -> None:
self.capability_name = capability_name
self.model = model
self.timeout_sec = float(timeout_sec)
self.base_url = base_url
self.api_key = api_key
self.client = self._create_client()
@property
def supports_batch(self) -> bool:
return True
def _create_client(self) -> Optional[OpenAI]:
if not self.api_key:
logger.warning("DASHSCOPE_API_KEY not set; llm translation unavailable")
return None
try:
return OpenAI(api_key=self.api_key, base_url=self.base_url)
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,
scene: Optional[str] = None,
) -> Optional[str]:
if not text or not str(text).strip():
return text
if not self.client:
return None
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(
text=text,
source_lang=src,
target_lang=tgt,
scene=normalized_scene,
)
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
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
def translate(
self,
text: Union[str, Sequence[str]],
target_lang: str,
source_lang: Optional[str] = None,
scene: Optional[str] = None,
) -> Union[Optional[str], List[Optional[str]]]:
if isinstance(text, (list, tuple)):
return self._translate_batch(
text,
target_lang=target_lang,
source_lang=source_lang,
scene=scene,
)
return self._translate_single(
text=str(text),
target_lang=target_lang,
source_lang=source_lang,
scene=scene,
)