Spaces:
Running
Running
Update translator.py
Browse files- translator.py +91 -41
translator.py
CHANGED
|
@@ -1,19 +1,54 @@
|
|
| 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 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
global _baidu_idx
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
cred = creds_list[_baidu_idx]
|
| 18 |
_baidu_idx = (_baidu_idx + 1) % len(creds_list)
|
| 19 |
return cred
|
|
@@ -27,75 +62,90 @@ def _tc3_signature(secret_key: str, date: str, service: str, string_to_sign: str
|
|
| 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
|
| 31 |
-
|
| 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
|
|
|
|
| 38 |
algorithm = "TC3-HMAC-SHA256"
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 57 |
except Exception as e:
|
| 58 |
-
print(f"[translator] Tencent request
|
| 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 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
return None
|
| 70 |
-
|
| 71 |
app_id, secret_key = creds["app_id"], creds["secret_key"]
|
| 72 |
-
salt
|
|
|
|
| 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
|
| 82 |
return None
|
| 83 |
-
return [item["dst"] for item in data
|
| 84 |
except Exception as e:
|
| 85 |
-
print(f"[translator] Baidu request
|
| 86 |
return None
|
| 87 |
|
| 88 |
def translate_texts(texts: Sequence[str],
|
| 89 |
src_lang: str = "auto",
|
| 90 |
tgt_lang: str = "zh",
|
| 91 |
-
|
| 92 |
-
tencent_secret_key: Optional[str] = None,
|
| 93 |
-
baidu_credentials_list: Optional[list] = None) -> List[str]:
|
| 94 |
if not texts:
|
| 95 |
return []
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
| 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")
|
| 73 |
algorithm = "TC3-HMAC-SHA256"
|
| 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)
|