5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
1
2
3
4
5
6
7
8
9
10
|
"""HTTP client for the translation service."""
from __future__ import annotations
import logging
from typing import List, Optional, Sequence, Union
import requests
from config.services_config import get_translation_config
|
0fd2f875
tangwang
translate
|
11
|
from translation.settings import normalize_translation_model, normalize_translation_scene
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
logger = logging.getLogger(__name__)
class TranslationServiceClient:
"""Business-side translation client that talks to the translator service."""
def __init__(
self,
*,
base_url: Optional[str] = None,
default_model: Optional[str] = None,
default_scene: Optional[str] = None,
timeout_sec: Optional[float] = None,
) -> None:
cfg = get_translation_config()
|
0fd2f875
tangwang
translate
|
28
29
30
31
|
self.base_url = str(base_url or cfg["service_url"]).rstrip("/")
self.default_model = normalize_translation_model(cfg, default_model or cfg["default_model"])
self.default_scene = normalize_translation_scene(cfg, default_scene or cfg["default_scene"])
self.timeout_sec = float(cfg["timeout_sec"] if timeout_sec is None else timeout_sec)
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
@property
def model(self) -> str:
return self.default_model
@property
def supports_batch(self) -> bool:
return True
def translate(
self,
text: Union[str, Sequence[str]],
target_lang: str,
source_lang: Optional[str] = None,
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
46
|
scene: Optional[str] = None,
|
0fd2f875
tangwang
translate
|
47
|
model: Optional[str] = None,
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
48
49
50
51
52
53
|
) -> Union[Optional[str], List[Optional[str]]]:
if isinstance(text, tuple):
text = list(text)
payload = {
"text": text,
"target_lang": target_lang,
|
0fd2f875
tangwang
translate
|
54
|
"source_lang": source_lang,
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
55
|
"model": (model or self.default_model),
|
0fd2f875
tangwang
translate
|
56
|
"scene": self.default_scene if scene is None else scene,
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
57
|
}
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
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
|
try:
response = requests.post(
f"{self.base_url}/translate",
json=payload,
timeout=self.timeout_sec,
)
if response.status_code != 200:
logger.warning(
"Translation service request failed: status=%s body=%s",
response.status_code,
(response.text or "")[:300],
)
return self._empty_result_for(text)
data = response.json()
return data.get("translated_text")
except Exception as exc:
logger.warning("Translation service request error: %s", exc, exc_info=True)
return self._empty_result_for(text)
@staticmethod
def _empty_result_for(
text: Union[str, Sequence[str]],
) -> Union[Optional[str], List[Optional[str]]]:
if isinstance(text, (list, tuple)):
return [None for _ in text]
return None
|
0fd2f875
tangwang
translate
|
84
85
86
87
88
|
def create_translation_client() -> TranslationServiceClient:
"""Create the business-side translation client."""
return TranslationServiceClient()
|