-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.py
More file actions
183 lines (144 loc) · 5.39 KB
/
Copy pathtranslator.py
File metadata and controls
183 lines (144 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
翻译模块
支持百度翻译和 Google 免费翻译
"""
import requests
import hashlib
import random
import log
import db
# ──────────────────────────────────────────────
# Configuration
# ──────────────────────────────────────────────
def get_config():
"""从数据库读取翻译配置"""
config = db.get_all_system_config()
enabled = config.get("TRANSLATION_ENABLED", "0") == "1"
engine = config.get("TRANSLATION_ENGINE", "google_free").lower()
baidu_app_id = config.get("BAIDU_APP_ID", "").strip()
baidu_app_key = config.get("BAIDU_APP_KEY", "").strip()
return enabled, engine, baidu_app_id, baidu_app_key
# ──────────────────────────────────────────────
# Google Free Translation
# ──────────────────────────────────────────────
def translate_google_free(text, target_lang="zh-CN"):
"""Google 免费翻译(无需 API key)
Args:
text: 待翻译文本
target_lang: 目标语言(默认中文)
Returns:
str: 翻译后的文本
"""
if not text:
return text
url = "https://translate.googleapis.com/translate_a/single"
params = {
"client": "gtx",
"sl": "auto",
"tl": target_lang,
"dt": "t",
"q": text
}
try:
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
# 解析结果
translated = ""
if data and data[0]:
for segment in data[0]:
if segment[0]:
translated += segment[0]
return translated
except Exception as e:
log.logger.warning(f"Google Free translation failed: {e}")
return text
# ──────────────────────────────────────────────
# Baidu Translation
# ──────────────────────────────────────────────
def translate_baidu(text, app_id, app_key, target_lang="zh"):
"""百度翻译
Args:
text: 待翻译文本
app_id: 百度翻译 App ID
app_key: 百度翻译 App Key
target_lang: 目标语言(默认中文)
Returns:
str: 翻译后的文本
"""
if not text:
return text
url = "https://api.fanyi.baidu.com/api/trans/vip/translate"
# 生成随机盐
salt = str(random.randint(32768, 65536))
# 计算签名
sign_str = app_id + text + salt + app_key
sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
params = {
"q": text,
"from": "auto",
"to": target_lang,
"appid": app_id,
"salt": salt,
"sign": sign
}
try:
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
if "trans_result" in data:
translated = ""
for item in data["trans_result"]:
if "dst" in item:
translated += item["dst"]
return translated
else:
error_code = data.get("error_code", "unknown")
error_msg = data.get("error_msg", "unknown")
log.logger.warning(f"Baidu translation error: {error_code} - {error_msg}")
return text
except Exception as e:
log.logger.warning(f"Baidu translation failed: {e}")
return text
# ──────────────────────────────────────────────
# High-level Translate
# ──────────────────────────────────────────────
def translate(text):
"""翻译文本(根据配置自动选择引擎)
Args:
text: 待翻译文本
Returns:
str: 翻译后的文本(如果翻译失败则返回原文)
"""
enabled, engine, baidu_app_id, baidu_app_key = get_config()
if not enabled:
return text
if engine == "baidu":
if not baidu_app_id or not baidu_app_key:
log.logger.warning("Baidu translation enabled but App ID/Key not configured")
return text
return translate_baidu(text, baidu_app_id, baidu_app_key)
else:
# 默认 Google Free
return translate_google_free(text)
def translate_movie_data(detail):
"""翻译影片数据(标题 + 简介)
Args:
detail: MetaTube 返回的影片详情 dict
Returns:
dict: 翻译后的影片详情
"""
if not detail:
return detail
enabled, _, _, _ = get_config()
if not enabled:
return detail
# 翻译标题
if detail.get("title"):
detail["title"] = translate(detail["title"])
# 翻译简介
if detail.get("summary"):
detail["summary"] = translate(detail["summary"])
return detail