Spaces:
Running
Running
Update translator.py
Browse files- translator.py +54 -101
translator.py
CHANGED
|
@@ -3,19 +3,20 @@ 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 |
-
|
| 11 |
-
|
| 12 |
-
DEFAULT_TENCENT_URL = os.environ.get("TENCENT_TRANSLATE_URL", "https://tmt.tencentcloudapi.com")
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
def _sign(key: bytes, msg: str) -> bytes:
|
| 21 |
return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()
|
|
@@ -26,123 +27,75 @@ def _tc3_signature(secret_key: str, date: str, service: str, string_to_sign: str
|
|
| 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
|
| 30 |
-
|
| 31 |
-
|
| 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")
|
| 42 |
algorithm = "TC3-HMAC-SHA256"
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 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
|
| 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 |
-
|
| 57 |
-
|
| 58 |
-
|
| 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(
|
| 67 |
resp.raise_for_status()
|
| 68 |
data = resp.json()
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
except Exception as e:
|
| 71 |
-
print(f"[translator]
|
| 72 |
return None
|
| 73 |
|
| 74 |
-
def
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
url: str,
|
| 78 |
-
src="auto",
|
| 79 |
-
tgt="zh"
|
| 80 |
-
) -> Optional[List[str]]:
|
| 81 |
-
if not baidu_creds_list:
|
| 82 |
return None
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
return None
|
| 88 |
|
| 89 |
-
|
| 90 |
-
query = "\n".join(texts)
|
| 91 |
-
sign
|
| 92 |
params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
|
|
|
|
| 93 |
try:
|
| 94 |
-
resp = requests.get(
|
| 95 |
resp.raise_for_status()
|
| 96 |
data = resp.json()
|
| 97 |
-
if "
|
| 98 |
-
|
| 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]
|
| 104 |
return None
|
| 105 |
|
| 106 |
-
def
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
tgt_lang: str = "zh"
|
| 113 |
-
) -> List[str]:
|
| 114 |
if not texts:
|
| 115 |
return []
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
return out
|
| 121 |
|
| 122 |
-
|
| 123 |
-
if baidu_json_str:
|
| 124 |
-
try:
|
| 125 |
-
baidu_creds = json.loads(baidu_json_str)
|
| 126 |
-
if not isinstance(baidu_creds, list): baidu_creds = []
|
| 127 |
-
except json.JSONDecodeError:
|
| 128 |
-
print("[translator] Invalid Baidu JSON provided by user.")
|
| 129 |
-
baidu_creds = []
|
| 130 |
-
|
| 131 |
-
if baidu_creds:
|
| 132 |
-
out = _translate_with_baidu_dynamic(texts, baidu_creds, DEFAULT_BAIDU_URL, src_lang, tgt_lang)
|
| 133 |
-
if out is not None:
|
| 134 |
-
return out
|
| 135 |
-
|
| 136 |
-
return list(texts)
|
| 137 |
-
|
| 138 |
-
def translate_texts(texts: Sequence[str],
|
| 139 |
-
src_lang: str = "auto",
|
| 140 |
-
tgt_lang: str = "zh") -> List[str]:
|
| 141 |
-
return translate_texts_with_dynamic_keys(
|
| 142 |
-
texts,
|
| 143 |
-
DEFAULT_TENCENT_SECRET_ID,
|
| 144 |
-
DEFAULT_TENCENT_SECRET_KEY,
|
| 145 |
-
json.dumps(DEFAULT_BAIDU_CREDENTIALS), # 转换回 JSON 字符串以匹配接口
|
| 146 |
-
src_lang,
|
| 147 |
-
tgt_lang
|
| 148 |
-
)
|
|
|
|
| 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()
|
|
|
|
| 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 |
if not (secret_id and secret_key):
|
| 34 |
return None
|
| 35 |
+
|
| 36 |
service, host, action, version, region = "tmt", "tmt.tencentcloudapi.com", "TextTranslate", "2018-03-21", "ap-beijing"
|
| 37 |
+
ts, date = int(time.time()), datetime.utcfromtimestamp(int(time.time())).strftime("%Y-%m-%d")
|
|
|
|
| 38 |
algorithm = "TC3-HMAC-SHA256"
|
| 39 |
+
payload_str = json.dumps({"SourceText": "\n".join(texts), "Source": src, "Target": tgt, "ProjectId": 0}, ensure_ascii=False)
|
| 40 |
+
|
| 41 |
+
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()}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
credential_scope = f"{date}/{service}/tc3_request"
|
| 43 |
+
string_to_sign = f"{algorithm}\n{ts}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode()).hexdigest()}"
|
|
|
|
|
|
|
| 44 |
signature = _tc3_signature(secret_key, date, service, string_to_sign)
|
| 45 |
+
|
| 46 |
+
authorization = f"{algorithm} Credential={secret_id}/{credential_scope}, SignedHeaders=content-type;host;x-tc-action, Signature={signature}"
|
| 47 |
+
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}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
try:
|
| 50 |
+
resp = requests.post(TENCENT_TRANSLATE_URL, headers=headers, data=payload_str, timeout=8)
|
| 51 |
resp.raise_for_status()
|
| 52 |
data = resp.json()
|
| 53 |
+
if "Error" in data.get("Response", {}):
|
| 54 |
+
print(f"[translator] Tencent API error: {data['Response']['Error']['Message']}")
|
| 55 |
+
return None
|
| 56 |
+
return data.get("Response", {}).get("TargetText", "").split("\n")
|
| 57 |
except Exception as e:
|
| 58 |
+
print(f"[translator] Tencent request error: {e}")
|
| 59 |
return None
|
| 60 |
|
| 61 |
+
def _translate_with_baidu(texts: Sequence[str], src: str, tgt: str,
|
| 62 |
+
baidu_credentials_list: Optional[list]) -> Optional[List[str]]:
|
| 63 |
+
if not baidu_credentials_list:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
return None
|
| 65 |
+
|
| 66 |
+
creds = _next_baidu_cred(baidu_credentials_list)
|
| 67 |
+
if not creds or not creds.get("app_id") or not creds.get("secret_key"):
|
| 68 |
+
print("[translator] Baidu credentials format error.")
|
| 69 |
return None
|
| 70 |
|
| 71 |
+
app_id, secret_key = creds["app_id"], creds["secret_key"]
|
| 72 |
+
salt, query = random.randint(32768, 65536), "\n".join(texts)
|
| 73 |
+
sign = hashlib.md5((app_id + query + str(salt) + secret_key).encode()).hexdigest()
|
| 74 |
params = {"q": query, "from": src, "to": tgt, "appid": app_id, "salt": salt, "sign": sign}
|
| 75 |
+
|
| 76 |
try:
|
| 77 |
+
resp = requests.get(BAIDU_TRANSLATE_URL, params=params, timeout=8)
|
| 78 |
resp.raise_for_status()
|
| 79 |
data = resp.json()
|
| 80 |
+
if "error_code" in data:
|
| 81 |
+
print(f"[translator] Baidu API error: {data.get('error_msg', 'Unknown error')}")
|
|
|
|
|
|
|
| 82 |
return None
|
| 83 |
+
return [item["dst"] for item in data.get("trans_result", [])]
|
| 84 |
except Exception as e:
|
| 85 |
+
print(f"[translator] Baidu request error: {e}")
|
| 86 |
return None
|
| 87 |
|
| 88 |
+
def translate_texts(texts: Sequence[str],
|
| 89 |
+
src_lang: str = "auto",
|
| 90 |
+
tgt_lang: str = "zh",
|
| 91 |
+
tencent_secret_id: Optional[str] = None,
|
| 92 |
+
tencent_secret_key: Optional[str] = None,
|
| 93 |
+
baidu_credentials_list: Optional[list] = None) -> List[str]:
|
|
|
|
|
|
|
| 94 |
if not texts:
|
| 95 |
return []
|
| 96 |
|
| 97 |
+
out = _translate_with_tencent(texts, src_lang, tgt_lang, tencent_secret_id, tencent_secret_key)
|
| 98 |
+
if out is None:
|
| 99 |
+
out = _translate_with_baidu(texts, src_lang, tgt_lang, baidu_credentials_list)
|
|
|
|
| 100 |
|
| 101 |
+
return out or list(texts)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|