Blame view

translation/client.py 3.24 KB
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
1
2
3
4
5
6
7
8
  """HTTP client for the translation service."""
  
  from __future__ import annotations
  
  import logging
  from typing import List, Optional, Sequence, Union
  
  import requests
d6c29734   tangwang   translation optim...
9
  from requests.adapters import HTTPAdapter
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
10
  
86d8358b   tangwang   config optimize
11
  from config.loader import get_app_config
0fd2f875   tangwang   translate
12
  from translation.settings import normalize_translation_model, normalize_translation_scene
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
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:
86d8358b   tangwang   config optimize
28
          cfg = get_app_config().services.translation.as_dict()
0fd2f875   tangwang   translate
29
30
31
32
          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)
d6c29734   tangwang   translation optim...
33
34
35
          self._session = requests.Session()
          self._session.mount("http://", HTTPAdapter(pool_connections=32, pool_maxsize=32, max_retries=0))
          self._session.mount("https://", HTTPAdapter(pool_connections=32, pool_maxsize=32, max_retries=0))
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  
      @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   翻译架构按“一个翻译服务 +
50
          scene: Optional[str] = None,
0fd2f875   tangwang   translate
51
          model: Optional[str] = None,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
52
53
54
55
56
57
      ) -> Union[Optional[str], List[Optional[str]]]:
          if isinstance(text, tuple):
              text = list(text)
          payload = {
              "text": text,
              "target_lang": target_lang,
0fd2f875   tangwang   translate
58
              "source_lang": source_lang,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
59
              "model": (model or self.default_model),
0fd2f875   tangwang   translate
60
              "scene": self.default_scene if scene is None else scene,
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
61
          }
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
62
          try:
d6c29734   tangwang   translation optim...
63
              response = self._session.post(
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
64
65
                  f"{self.base_url}/translate",
                  json=payload,
d6c29734   tangwang   translation optim...
66
                  timeout=(2.0, self.timeout_sec),
5e4dc8e4   tangwang   翻译架构按“一个翻译服务 +
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
              )
              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
88
89
90
91
92
  
  
  def create_translation_client() -> TranslationServiceClient:
      """Create the business-side translation client."""
      return TranslationServiceClient()