IdlecloudX commited on
Commit
efcb14c
·
verified ·
1 Parent(s): c01b9a5

Update translator.py

Browse files
Files changed (1) hide show
  1. translator.py +102 -99
translator.py CHANGED
@@ -1,57 +1,21 @@
 
 
 
1
  import hashlib, hmac, json, os, random, time
2
  from datetime import datetime
3
- from typing import List, Sequence, Optional
4
- import requests
5
- import threading
6
-
7
- APP_TENCENT_SECRET_ID = os.environ.get("TENCENT_SECRET_ID")
8
- APP_TENCENT_SECRET_KEY = os.environ.get("TENCENT_SECRET_KEY")
9
- APP_BAIDU_CREDENTIALS = json.loads(os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
10
- APP_ACCESS_KEY = os.environ.get("TRANSLATOR_ACCESS_KEY")
11
 
12
- TENCENT_TRANSLATE_URL = os.environ.get("TENCENT_TRANSLATE_URL", "https://tmt.tencentcloudapi.com")
13
- BAIDU_TRANSLATE_URL = os.environ.get("BAIDU_TRANSLATE_URL", "https://fanyi-api.baidu.com/api/trans/vip/translate")
14
 
15
- _user_keys = threading.local()
 
 
16
 
17
- def set_user_provided_keys(tencent_id, tencent_key, baidu_json_str):
18
- _user_keys.tencent_id = tencent_id if tencent_id else None
19
- _user_keys.tencent_key = tencent_key if tencent_key else None
20
- try:
21
- _user_keys.baidu_credentials = json.loads(baidu_json_str) if baidu_json_str else []
22
- except json.JSONDecodeError:
23
- _user_keys.baidu_credentials = []
24
-
25
- def clear_user_provided_keys():
26
- if hasattr(_user_keys, 'tencent_id'): del _user_keys.tencent_id
27
- if hasattr(_user_keys, 'tencent_key'): del _user_keys.tencent_key
28
- if hasattr(_user_keys, 'baidu_credentials'): del _user_keys.baidu_credentials
29
-
30
- def _get_tencent_credentials():
31
- user_id = getattr(_user_keys, 'tencent_id', None)
32
- user_key = getattr(_user_keys, 'tencent_key', None)
33
- if user_id and user_key:
34
- # print("DEBUG: Using user-provided Tencent keys.")
35
- return user_id, user_key
36
- # print("DEBUG: Using app-level Tencent keys.")
37
- return APP_TENCENT_SECRET_ID, APP_TENCENT_SECRET_KEY
38
-
39
- def _get_baidu_credentials():
40
- user_creds = getattr(_user_keys, 'baidu_credentials', [])
41
- if user_creds:
42
- # print("DEBUG: Using user-provided Baidu credentials.")
43
- return user_creds
44
- # print("DEBUG: Using app-level Baidu credentials.")
45
- return APP_BAIDU_CREDENTIALS
46
- _baidu_idx = 0
47
- def _next_baidu_cred():
48
- global _baidu_idx
49
- creds_list = _get_baidu_credentials()
50
- if not creds_list:
51
- return None
52
- cred = creds_list[_baidu_idx]
53
- _baidu_idx = (_baidu_idx + 1) % len(creds_list)
54
- return cred
55
 
56
  def _sign(key: bytes, msg: str) -> bytes:
57
  return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
@@ -62,11 +26,16 @@ def _tc3_signature(secret_key: str, date: str, service: str, string_to_sign: str
62
  secret_signing = _sign(secret_service, "tc3_request")
63
  return hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
64
 
65
- def _translate_with_tencent(texts: Sequence[str], src="auto", tgt="zh") -> Optional[List[str]]:
66
- secret_id, secret_key = _get_tencent_credentials()
 
 
 
 
 
 
67
  if not (secret_id and secret_key):
68
  return None
69
-
70
  service, host, action, version, region = "tmt", "tmt.tencentcloudapi.com", "TextTranslate", "2018-03-21", "ap-beijing"
71
  ts = int(time.time())
72
  date = datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d")
@@ -74,78 +43,112 @@ def _translate_with_tencent(texts: Sequence[str], src="auto", tgt="zh") -> Optio
74
 
75
  payload = {"SourceText": "\n".join(texts), "Source": src, "Target": tgt, "ProjectId": 0}
76
  payload_str = json.dumps(payload, ensure_ascii=False)
77
- hashed_request_payload = hashlib.sha256(payload_str.encode()).hexdigest()
78
 
79
- canonical_headers = f"content-type:application/json; charset=utf-8\nhost:{host}\nx-tc-action:{action.lower()}\n"
80
- signed_headers = "content-type;host;x-tc-action"
81
- canonical_request = f"POST\n/\n\n{canonical_headers}\n{signed_headers}\n{hashed_request_payload}"
82
-
83
  credential_scope = f"{date}/{service}/tc3_request"
84
- string_to_sign = f"{algorithm}\n{ts}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode()).hexdigest()}"
85
-
 
86
  signature = _tc3_signature(secret_key, date, service, string_to_sign)
87
- authorization = f"{algorithm} Credential={secret_id}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
88
-
 
 
89
  headers = {
90
- "Authorization": authorization, "Content-Type": "application/json; charset=utf-8",
91
- "Host": host, "X-TC-Action": action, "X-TC-Timestamp": str(ts),
92
- "X-TC-Version": version, "X-TC-Region": region,
93
  }
94
 
95
  try:
96
- resp = requests.post(TENCENT_TRANSLATE_URL, headers=headers, data=payload_str, timeout=8)
97
  resp.raise_for_status()
98
  data = resp.json()
99
- if "Error" in data.get("Response", {}):
100
- print(f"[translator] Tencent API returned error: {data['Response']['Error']['Message']}")
101
- return None
102
  return data["Response"]["TargetText"].split("\n")
103
  except Exception as e:
104
- print(f"[translator] Tencent API request failed → {e}")
105
  return None
106
 
107
- def _translate_with_baidu(texts: Sequence[str], src="auto", tgt="zh") -> Optional[List[str]]:
108
- creds = _next_baidu_cred()
109
- if not creds:
 
 
 
 
 
 
 
 
 
 
110
  return None
111
- app_id, secret_key = creds["app_id"], creds["secret_key"]
112
- salt = random.randint(32768, 65536)
113
  query = "\n".join(texts)
114
- sign = hashlib.md5((app_id + query + str(salt) + secret_key).encode()).hexdigest()
115
  params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
116
-
117
  try:
118
- resp = requests.get(BAIDU_TRANSLATE_URL, params=params, timeout=8)
119
  resp.raise_for_status()
120
  data = resp.json()
121
- if "error_code" in data:
122
- print(f"[translator] Baidu API returned error: {data['error_msg']} (code: {data['error_code']})")
 
 
123
  return None
124
- return [item["dst"] for item in data["trans_result"]]
125
  except Exception as e:
126
- print(f"[translator] Baidu API request failed → {e}")
127
  return None
128
 
129
- def translate_texts(texts: Sequence[str],
130
- src_lang: str = "auto",
131
- tgt_lang: str = "zh",
132
- access_key: str = None) -> List[str]:
 
 
 
 
 
 
 
133
  if not texts:
134
  return []
135
 
136
- has_user_tencent = getattr(_user_keys, 'tencent_id', None) and getattr(_user_keys, 'tencent_key', None)
137
- has_user_baidu = bool(getattr(_user_keys, 'baidu_credentials', []))
138
-
139
- can_use_app_keys = False
140
- if not (has_user_tencent or has_user_baidu):
141
- if not APP_ACCESS_KEY:
142
- can_use_app_keys = True
143
- elif access_key and access_key == APP_ACCESS_KEY:
144
- can_use_app_keys = True
145
- if has_user_tencent or has_user_baidu or can_use_app_keys:
146
- out = _translate_with_tencent(texts, src_lang, tgt_lang)
147
- if out is None:
148
- out = _translate_with_baidu(texts, src_lang, tgt_lang)
149
  if out is not None:
150
  return out
151
- return list(texts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Dict, Any
 
 
 
 
 
 
 
7
 
8
+ import requests
 
9
 
10
+ DEFAULT_TENCENT_SECRET_ID = os.environ.get("TENCENT_SECRET_ID")
11
+ DEFAULT_TENCENT_SECRET_KEY = os.environ.get("TENCENT_SECRET_KEY")
12
+ DEFAULT_TENCENT_URL = os.environ.get("TENCENT_TRANSLATE_URL", "https://tmt.tencentcloudapi.com")
13
 
14
+ DEFAULT_BAIDU_URL = os.environ.get("BAIDU_TRANSLATE_URL", "https://fanyi-api.baidu.com/api/trans/vip/translate")
15
+ try:
16
+ DEFAULT_BAIDU_CREDENTIALS = json.loads(os.environ.get("BAIDU_CREDENTIALS_JSON", "[]"))
17
+ except json.JSONDecodeError:
18
+ DEFAULT_BAIDU_CREDENTIALS = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def _sign(key: bytes, msg: str) -> bytes:
21
  return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
 
26
  secret_signing = _sign(secret_service, "tc3_request")
27
  return hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
28
 
29
+ def _translate_with_tencent_dynamic(
30
+ texts: Sequence[str],
31
+ secret_id: str,
32
+ secret_key: str,
33
+ url: str,
34
+ src="auto",
35
+ tgt="zh"
36
+ ) -> Optional[List[str]]:
37
  if not (secret_id and secret_key):
38
  return None
 
39
  service, host, action, version, region = "tmt", "tmt.tencentcloudapi.com", "TextTranslate", "2018-03-21", "ap-beijing"
40
  ts = int(time.time())
41
  date = datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d")
 
43
 
44
  payload = {"SourceText": "\n".join(texts), "Source": src, "Target": tgt, "ProjectId": 0}
45
  payload_str = json.dumps(payload, ensure_ascii=False)
 
46
 
47
+ canonical_request = "\n".join([
48
+ "POST", "/", "", f"content-type:application/json; charset=utf-8\nhost:{host}\nx-tc-action:{action.lower()}\n",
49
+ "content-type;host;x-tc-action", hashlib.sha256(payload_str.encode()).hexdigest(),
50
+ ])
51
  credential_scope = f"{date}/{service}/tc3_request"
52
+ string_to_sign = "\n".join([
53
+ algorithm, str(ts), credential_scope, hashlib.sha256(canonical_request.encode()).hexdigest(),
54
+ ])
55
  signature = _tc3_signature(secret_key, date, service, string_to_sign)
56
+ authorization = (
57
+ f"{algorithm} Credential={secret_id}/{credential_scope}, "
58
+ f"SignedHeaders=content-type;host;x-tc-action, Signature={signature}"
59
+ )
60
  headers = {
61
+ "Authorization": authorization, "Content-Type": "application/json; charset=utf-8", "Host": host,
62
+ "X-TC-Action": action, "X-TC-Timestamp": str(ts), "X-TC-Version": version, "X-TC-Region": region,
 
63
  }
64
 
65
  try:
66
+ resp = requests.post(url, headers=headers, data=payload_str, timeout=8)
67
  resp.raise_for_status()
68
  data = resp.json()
 
 
 
69
  return data["Response"]["TargetText"].split("\n")
70
  except Exception as e:
71
+ print(f"[translator] Dynamic Tencent API error → {e}")
72
  return None
73
 
74
+ def _translate_with_baidu_dynamic(
75
+ texts: Sequence[str],
76
+ baidu_creds_list: List[Dict[str, str]],
77
+ url: str,
78
+ src="auto",
79
+ tgt="zh"
80
+ ) -> Optional[List[str]]:
81
+ if not baidu_creds_list:
82
+ return None
83
+
84
+ cred = random.choice(baidu_creds_list)
85
+ app_id, secret_key = cred.get("app_id"), cred.get("secret_key")
86
+ if not (app_id and secret_key):
87
  return None
88
+
89
+ salt = random.randint(32768, 65536)
90
  query = "\n".join(texts)
91
+ sign = hashlib.md5((app_id + query + str(salt) + secret_key).encode()).hexdigest()
92
  params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
 
93
  try:
94
+ resp = requests.get(url, params=params, timeout=8)
95
  resp.raise_for_status()
96
  data = resp.json()
97
+ if "trans_result" in data:
98
+ return [item["dst"] for item in data["trans_result"]]
99
+ else:
100
+ print(f"[translator] Baidu API returned error: {data.get('error_msg', 'Unknown error')}")
101
  return None
 
102
  except Exception as e:
103
+ print(f"[translator] Dynamic Baidu API error → {e}")
104
  return None
105
 
106
+ def translate_texts_with_dynamic_keys(
107
+ texts: Sequence[str],
108
+ tencent_id: str,
109
+ tencent_key: str,
110
+ baidu_json_str: str,
111
+ src_lang: str = "auto",
112
+ tgt_lang: str = "zh"
113
+ ) -> List[str]:
114
+ """
115
+ 使用传入的密钥进行翻译。
116
+ """
117
  if not texts:
118
  return []
119
 
120
+ if tencent_id and tencent_key:
121
+ out = _translate_with_tencent_dynamic(texts, tencent_id, tencent_key, DEFAULT_TENCENT_URL, src_lang, tgt_lang)
 
 
 
 
 
 
 
 
 
 
 
122
  if out is not None:
123
  return out
124
+
125
+ baidu_creds = []
126
+ if baidu_json_str:
127
+ try:
128
+ baidu_creds = json.loads(baidu_json_str)
129
+ if not isinstance(baidu_creds, list): baidu_creds = []
130
+ except json.JSONDecodeError:
131
+ print("[translator] Invalid Baidu JSON provided by user.")
132
+ baidu_creds = []
133
+
134
+ if baidu_creds:
135
+ out = _translate_with_baidu_dynamic(texts, baidu_creds, DEFAULT_BAIDU_URL, src_lang, tgt_lang)
136
+ if out is not None:
137
+ return out
138
+
139
+ return list(texts)
140
+
141
+ def translate_texts(texts: Sequence[str],
142
+ src_lang: str = "auto",
143
+ tgt_lang: str = "zh") -> List[str]:
144
+ """
145
+ (供所有者使用) 封装了对动态密钥函数的调用,使用环境变量中的默认凭证。
146
+ """
147
+ return translate_texts_with_dynamic_keys(
148
+ texts,
149
+ DEFAULT_TENCENT_SECRET_ID,
150
+ DEFAULT_TENCENT_SECRET_KEY,
151
+ json.dumps(DEFAULT_BAIDU_CREDENTIALS),
152
+ src_lang,
153
+ tgt_lang
154
+ )