IdlecloudX commited on
Commit
20f1d29
·
verified ·
1 Parent(s): 428ecd5

Update translator.py

Browse files
Files changed (1) hide show
  1. translator.py +92 -53
translator.py CHANGED
@@ -1,76 +1,83 @@
1
- """
2
- translator.py
3
- """
4
  import hashlib, hmac, json, os, random, time
5
  from datetime import datetime
6
- from typing import List, Sequence, Optional
7
 
8
  import requests
9
 
 
 
 
 
10
  TENCENT_TRANSLATE_URL = os.environ.get("TENCENT_TRANSLATE_URL", "https://tmt.tencentcloudapi.com")
11
- BAIDU_TRANSLATE_URL = os.environ.get("BAIDU_TRANSLATE_URL", "https://fanyi-api.baidu.com/api/trans/vip/translate")
12
 
13
- _baidu_idx: int = 0
14
- def _next_baidu_cred(creds_list):
15
- global _baidu_idx
16
- if not creds_list: return None
17
- cred = creds_list[_baidu_idx]
18
- _baidu_idx = (_baidu_idx + 1) % len(creds_list)
19
- return cred
20
 
21
  def _sign(key: bytes, msg: str) -> bytes:
22
  return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
23
 
24
  def _tc3_signature(secret_key: str, date: str, service: str, string_to_sign: str) -> str:
25
- secret_date = _sign(("TC3" + secret_key).encode(), date)
26
- secret_service = _sign(secret_date, service)
27
- secret_signing = _sign(secret_service, "tc3_request")
28
  return hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
29
 
30
- def _translate_with_tencent(texts: Sequence[str], src: str, tgt: str,
31
- secret_id: Optional[str],
32
- secret_key: Optional[str]) -> Optional[List[str]]:
33
- """使用传入的密钥执行腾讯云翻译。如果密钥无效则失败。"""
34
- if not (secret_id and secret_key):
35
- return None
36
 
37
  service, host, action, version, region = "tmt", "tmt.tencentcloudapi.com", "TextTranslate", "2018-03-21", "ap-beijing"
38
- ts, date = int(time.time()), datetime.utcfromtimestamp(int(time.time())).strftime("%Y-%m-%d")
39
- algorithm = "TC3-HMAC-SHA256"
40
- payload_str = json.dumps({"SourceText": "\n".join(texts), "Source": src, "Target": tgt, "ProjectId": 0}, ensure_ascii=False)
 
 
 
 
 
 
 
41
 
42
- canonical_request = f"POST\n/\n\ncontent-type:application/json; charset=utf-8\nhost:{host}\nx-tc-action:{action.lower()}\n\ncontent-type;host;x-tc-action\n{hashlib.sha256(payload_str.encode()).hexdigest()}"
43
  credential_scope = f"{date}/{service}/tc3_request"
44
- string_to_sign = f"{algorithm}\n{ts}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode()).hexdigest()}"
 
 
45
  signature = _tc3_signature(secret_key, date, service, string_to_sign)
46
 
47
- authorization = f"{algorithm} Credential={secret_id}/{credential_scope}, SignedHeaders=content-type;host;x-tc-action, Signature={signature}"
48
- headers = {"Authorization": authorization, "Content-Type": "application/json; charset=utf-8", "Host": host, "X-TC-Action": action, "X-TC-Timestamp": str(ts), "X-TC-Version": version, "X-TC-Region": region}
 
 
 
 
 
 
49
 
50
  try:
51
  resp = requests.post(TENCENT_TRANSLATE_URL, headers=headers, data=payload_str, timeout=8)
52
  resp.raise_for_status()
53
  data = resp.json()
54
- if "Error" in data.get("Response", {}):
55
- print(f"[translator] Tencent API error: {data['Response']['Error']['Message']}")
 
 
56
  return None
57
- return data.get("Response", {}).get("TargetText", "").split("\n")
58
  except Exception as e:
59
- print(f"[translator] Tencent request error: {e}")
60
  return None
61
 
62
- def _translate_with_baidu(texts: Sequence[str], src: str, tgt: str,
63
- baidu_credentials_list: Optional[list]) -> Optional[List[str]]:
64
- if not baidu_credentials_list:
65
- return None
66
 
67
- creds = _next_baidu_cred(baidu_credentials_list)
68
- if not creds or not creds.get("app_id") or not creds.get("secret_key"):
69
- print("[translator] Baidu credentials format error.")
70
- return None
71
 
72
- app_id, secret_key = creds["app_id"], creds["secret_key"]
73
- salt, query = random.randint(32768, 65536), "\n".join(texts)
 
 
74
  sign = hashlib.md5((app_id + query + str(salt) + secret_key).encode()).hexdigest()
75
  params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
76
 
@@ -78,25 +85,57 @@ def _translate_with_baidu(texts: Sequence[str], src: str, tgt: str,
78
  resp = requests.get(BAIDU_TRANSLATE_URL, params=params, timeout=8)
79
  resp.raise_for_status()
80
  data = resp.json()
81
- if "error_code" in data:
82
- print(f"[translator] Baidu API error: {data.get('error_msg', 'Unknown error')}")
 
 
83
  return None
84
- return [item["dst"] for item in data.get("trans_result", [])]
85
  except Exception as e:
86
- print(f"[translator] Baidu request error: {e}")
87
  return None
88
 
 
89
  def translate_texts(texts: Sequence[str],
90
  src_lang: str = "auto",
91
  tgt_lang: str = "zh",
92
- tencent_secret_id: Optional[str] = None,
93
- tencent_secret_key: Optional[str] = None,
94
- baidu_credentials_list: Optional[list] = None) -> List[str]:
 
95
  if not texts:
96
  return []
97
 
98
- out = _translate_with_tencent(texts, src_lang, tgt_lang, tencent_secret_id, tencent_secret_key)
99
- if out is None:
100
- out = _translate_with_baidu(texts, src_lang, tgt_lang, baidu_credentials_list)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
- return out or list(texts)
 
 
 
 
 
 
 
1
  import hashlib, hmac, json, os, random, time
2
  from datetime import datetime
3
+ from typing import List, Sequence, Optional, Dict, Any
4
 
5
  import requests
6
 
7
+ TRANSLATOR_ACCESS_KEY = os.environ.get("TRANSLATOR_ACCESS_KEY")
8
+
9
+ TENCENT_SECRET_ID = os.environ.get("TENCENT_SECRET_ID")
10
+ TENCENT_SECRET_KEY = os.environ.get("TENCENT_SECRET_KEY")
11
  TENCENT_TRANSLATE_URL = os.environ.get("TENCENT_TRANSLATE_URL", "https://tmt.tencentcloudapi.com")
 
12
 
13
+ BAIDU_TRANSLATE_URL = os.environ.get("BAIDU_TRANSLATE_URL", "https://fanyi-api.baidu.com/api/trans/vip/translate")
14
+ try:
15
+ BAIDU_CREDENTIALS_DEFAULT = json.loads(os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
16
+ except json.JSONDecodeError:
17
+ BAIDU_CREDENTIALS_DEFAULT = []
 
 
18
 
19
  def _sign(key: bytes, msg: str) -> bytes:
20
  return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
21
 
22
  def _tc3_signature(secret_key: str, date: str, service: str, string_to_sign: str) -> str:
23
+ secret_date = _sign(("TC3" + secret_key).encode(), date)
24
+ secret_service = _sign(secret_date, service)
25
+ secret_signing = _sign(secret_service, "tc3_request")
26
  return hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
27
 
28
+ def _translate_with_tencent(texts: Sequence[str], src: str, tgt: str, secret_id: str, secret_key: str) -> Optional[List[str]]:
29
+ if not (secret_id and secret_key): return None
 
 
 
 
30
 
31
  service, host, action, version, region = "tmt", "tmt.tencentcloudapi.com", "TextTranslate", "2018-03-21", "ap-beijing"
32
+ ts = int(time.time())
33
+ date = datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d")
34
+
35
+ payload = {"SourceText": "\n".join(texts), "Source": src, "Target": tgt, "ProjectId": 0}
36
+ payload_str = json.dumps(payload, ensure_ascii=False)
37
+
38
+ canonical_request = "POST\n/\n\n" + \
39
+ f"content-type:application/json; charset=utf-8\nhost:{host}\nx-tc-action:{action.lower()}\n\n" + \
40
+ "content-type;host;x-tc-action\n" + \
41
+ hashlib.sha256(payload_str.encode()).hexdigest()
42
 
 
43
  credential_scope = f"{date}/{service}/tc3_request"
44
+ string_to_sign = "TC3-HMAC-SHA256\n" + str(ts) + "\n" + credential_scope + "\n" + \
45
+ hashlib.sha256(canonical_request.encode()).hexdigest()
46
+
47
  signature = _tc3_signature(secret_key, date, service, string_to_sign)
48
 
49
+ authorization = f"TC3-HMAC-SHA256 Credential={secret_id}/{credential_scope}, " + \
50
+ f"SignedHeaders=content-type;host;x-tc-action, Signature={signature}"
51
+
52
+ headers = {
53
+ "Authorization": authorization, "Content-Type": "application/json; charset=utf-8",
54
+ "Host": host, "X-TC-Action": action, "X-TC-Timestamp": str(ts),
55
+ "X-TC-Version": version, "X-TC-Region": region,
56
+ }
57
 
58
  try:
59
  resp = requests.post(TENCENT_TRANSLATE_URL, headers=headers, data=payload_str, timeout=8)
60
  resp.raise_for_status()
61
  data = resp.json()
62
+ if "Response" in data and "TargetText" in data["Response"]:
63
+ return data["Response"]["TargetText"].split("\n")
64
+ else:
65
+ print(f"[translator] Tencent API abnormal response: {data}")
66
  return None
 
67
  except Exception as e:
68
+ print(f"[translator] Tencent API error {e}")
69
  return None
70
 
71
+ def _translate_with_baidu(texts: Sequence[str], src: str, tgt: str, baidu_credentials: List[Dict[str, str]]) -> Optional[List[str]]:
72
+ if not baidu_credentials: return None
 
 
73
 
74
+ cred = random.choice(baidu_credentials)
75
+ app_id, secret_key = cred.get("app_id"), cred.get("secret_key")
 
 
76
 
77
+ if not (app_id and secret_key): return None
78
+
79
+ salt = random.randint(32768, 65536)
80
+ query = "\n".join(texts)
81
  sign = hashlib.md5((app_id + query + str(salt) + secret_key).encode()).hexdigest()
82
  params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
83
 
 
85
  resp = requests.get(BAIDU_TRANSLATE_URL, params=params, timeout=8)
86
  resp.raise_for_status()
87
  data = resp.json()
88
+ if "trans_result" in data:
89
+ return [item["dst"] for item in data["trans_result"]]
90
+ else:
91
+ print(f"[translator] Baidu API abnormal response: {data}")
92
  return None
 
93
  except Exception as e:
94
+ print(f"[translator] Baidu API error {e}")
95
  return None
96
 
97
+
98
  def translate_texts(texts: Sequence[str],
99
  src_lang: str = "auto",
100
  tgt_lang: str = "zh",
101
+ system_key_input: Optional[str] = None,
102
+ tencent_id: Optional[str] = None,
103
+ tencent_key: Optional[str] = None,
104
+ baidu_creds_json_str: Optional[str] = None) -> List[str]:
105
  if not texts:
106
  return []
107
 
108
+ use_tencent_id, use_tencent_key = None, None
109
+ use_baidu_creds = []
110
+
111
+ if tencent_id and tencent_key:
112
+ use_tencent_id, use_tencent_key = tencent_id, tencent_key
113
+ print("[translator] Using custom Tencent API key.")
114
+ if baidu_creds_json_str:
115
+ try:
116
+ creds = json.loads(baidu_creds_json_str)
117
+ if isinstance(creds, list) and all(isinstance(d, dict) for d in creds):
118
+ use_baidu_creds = creds
119
+ print("[translator] Using custom Baidu API key(s).")
120
+ else:
121
+ print("[translator] Warning: Custom Baidu credentials format is incorrect.")
122
+ except json.JSONDecodeError:
123
+ print("[translator] Warning: Failed to parse custom Baidu credentials JSON.")
124
+
125
+ elif TRANSLATOR_ACCESS_KEY and system_key_input == TRANSLATOR_ACCESS_KEY:
126
+ print("[translator] System access key validated. Using system-configured API keys.")
127
+ use_tencent_id, use_tencent_key = TENCENT_SECRET_ID, TENCENT_SECRET_KEY
128
+ use_baidu_creds = BAIDU_CREDENTIALS_DEFAULT
129
+
130
+ else:
131
+ print("[translator] Translation disabled: No valid API keys or system key provided.")
132
+ return list(texts)
133
+
134
+ translated_texts = None
135
+ if use_tencent_id and use_tencent_key:
136
+ translated_texts = _translate_with_tencent(texts, src_lang, tgt_lang, use_tencent_id, use_tencent_key)
137
 
138
+ if translated_texts is None and use_baidu_creds:
139
+ translated_texts = _translate_with_baidu(texts, src_lang, tgt_lang, use_baidu_creds)
140
+
141
+ return translated_texts or list(texts)