GoldenDict添加文本翻译

近期为了更好的阅读文献,使用zotero的翻译插件添加了各种词典,已经申请了腾讯、百度、小牛等翻译帐号,总体试用下来都还可以,不过最终小牛胜出。在完成这些配置之后,发现可以使用PythonGoldenDict也具备翻译句子的功能!于是一百度还找到了对应的Python脚本,而且有些还是官方给出的脚本,然而通过【免费开源词典软件】GoldenDict 使用指南(详、附句段翻译) 找到了一个多合一版本的translatorGD.py, 因为之前我配置了一个基于文本的baidu.py, 而这个具有多合一的脚本却支持html显示效果更好,所以专门开此博客来记录此脚本,同时准备基于其他翻译api不断优化和增加该脚本功能。

translatorGD.py
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
#! /usr/bin/env python3
# vim:fenc=utf-8
import json
import requests
import random
from hashlib import md5
import time
import sys
import io
import threading
caiyunxiaoyiKey=""
baiduKey={"id":"YourID","secret":"YourSecret"}
xiaoniuKey="YourKey"
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
originalText = sys.argv[1]
css = """<style type="text/css">
.engine {
font-family: "MiSansVF";
font-size: 18px;
color: #578bc5;
}
.originalText {
font-size: 120%;
font-family: "MiSansVF";
font-weight: 600;
display: inline-block;
margin: 0rem 0rem 0rem 0rem;
color: #2a5598;
margin-bottom: 0.6rem;
}
.frame {
margin: 1rem 0.5rem 0.5rem 0;
padding: 0.7rem 0.5rem 0.5rem 0;
border-top: 3px dashed #eaeef6;
}
definition {
font-family: "MiSansVF";
color: #2a5598;
height: 120px;
padding: 0.05em;
font-weight: 500;
font-size: 16px;
}
</style>"""
print(css)
print( '<div class="originalText">' + originalText + '</div>')
print('<br><br>')
def output(engineName:str,definition:str):
print('<span class="engine">' + engineName + "</span>")
print('<div class="frame">')
print('<definition>' + definition + '</definition>')
print("</div>")
print("<br>")
def Youdao():
global originalText
headers = {
'authority': 'aidemo.youdao.com',
'accept': 'application/json, text/javascript, */*; q=0.01',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'origin': 'https://ai.youdao.com',
'referer': 'https://ai.youdao.com/',
'sec-ch-ua': \
'"Chromium";v="106",\
"Microsoft Edge";v="106",\
"Not;A=Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'user-agent': \
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)\
AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.47',
}
data = {
'q': originalText,
'from': 'Auto',
'to': 'Auto',
}
try:
output("有道翻译",
requests.post('https://aidemo.youdao.com/trans',
headers=headers, data=data).json()["translation"][0])
except:
output("有道翻译","错误")
def Google():
global originalText
definition=""
try:
for x in requests.get("https://translate.googleapis.com/translate_a/single?\
client=gtx&sl=auto&tl=&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&\
dt=rm&dt=ss&dt=t&q="+originalText,\
headers={"user-agent":\
"Mozilla/5.0 (Windows NT 10.0;\
Win64; x64; rv:59.0)"}).json()[0]:
if x[0]:
definition += x[0]
output("谷歌翻译",definition)
except:
output("谷歌翻译","错误")
def Caiyun():
global originalText
global caiyunxiaoyiKey
payload = {
"source": originalText,
"trans_type": "auto2zh",
"request_id": "demo",
"detect": True,
}
headers = {
"content-type": "application/json",
"x-authorization": "token " + caiyunxiaoyiKey,
}
try:
output("彩云小译",
json.loads(requests.post(
"http://api.interpreter.caiyunai.com/v1/translator",
data=json.dumps(payload), headers=headers).text)["target"])
except Exception as e:
output("彩云小译","错误:"+str(e))
def Baidu():
global originalText
global baiduKey
salt = random.randint(32768, 65536)
s=baiduKey["id"] + originalText + str(salt) + baiduKey["secret"]
sign = md5(s.encode('utf-8')).hexdigest()
try:
output("百度翻译",
requests.post(
'http://api.fanyi.baidu.com/api/trans/vip/translate',
params={'appid': baiduKey["id"],
'q': originalText, 'from': 'auto', 'to': 'zh',
'salt': salt, 'sign': sign}
).json()["trans_result"][0]["dst"])
except Exception as e:
output("百度翻译","错误"+str(e))
def Xiaoniu():
global originalText
global xiaoniuKey
try:
output("小牛翻译",
json.loads(requests.post(
"http://api.niutrans.com/NiuTransServer/translation?",
data={"from": 'en', "to": 'zh',\
"apikey": xiaoniuKey,\
"src_text": originalText}).text)['tgt_text'])
except Exception as e:
output("小牛翻译","错误"+str(e))
threads=[]
# threads.append(threading.Thread(target=Caiyun))
# threads.append(threading.Thread(target=Google))
threads.append(threading.Thread(target=Xiaoniu))
threads.append(threading.Thread(target=Baidu))
threads.append(threading.Thread(target=Youdao))
for t in threads:
t.start()

使用dtx文件管理脚本,实现程序与注释彻底分离,上述即是无注释版,同时今天也添加了小牛翻译,去除了YoudaoPulbicBackup

彩云文本翻译 xiaoyi.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
tee xiaoyi.sh << END
DIRECTION=\$1
SOURCE=\$2

if test -f \$HOME/.xiaoyi ; then
. \$HOME/.xiaoyi
else
echo "Please input your token: "
read TOKEN
echo "TOKEN=\$TOKEN" > \$HOME/.xiaoyi
fi

BODY='{"source": ["'\$SOURCE'"], "trans_type": "'\$DIRECTION'", "replaced": true, "media": "text", "request_id": "demo" }'

export PYTHONIOENCODING=utf8
curl -s -X POST http://api.interpreter.caiyunai.com/v1/translator\
-H 'Content-Type: application/json'\
-H "X-Authorization: token \$TOKEN"\
-d "\$BODY" | python -c "import sys, json; print json.load(sys.stdin)['target']"
END
再按照下面的方式执行 xiaoyi.sh 就会得到翻译结果
执行xiaoyi.sh
1
2
3
4
sh xiaoyi.sh en2zh "You know some birds are not meant to be caged, their feathers are just too bright."
# 你知道有些鸟不应该被关在笼子里,它们的羽毛太亮了。
sh xiaoyi.sh ja2zh "薄紅の秋の実に"
# 淡红色的秋天的果实

备注:第一次执行 xiaoyi.sh 时会要求输入访问令牌 Token 。

彩云Python调用
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
import json

import requests


def tranlate(source, direction):
url = "http://api.interpreter.caiyunai.com/v1/translator"

# WARNING, this token is a test token for new developers,
# and it should be replaced by your token
token = "YOUR_TOKEN"

payload = {
"source": source,
"trans_type": direction,
"request_id": "demo",
"detect": True,
}

headers = {
"content-type": "application/json",
"x-authorization": "token " + token,
}

response = requests.request("POST", url, data=json.dumps(payload), headers=headers)

return json.loads(response.text)["target"]


source = ["Lingocloud is the best translation service.", "彩云小译は最高の翻訳サービスです"]
target = tranlate(source, "auto2zh")

print(target)

请把 YOUR_TOKEN 设置为你的 token,并发请求的速度会是逐个请求的数倍,如有可能,请将长度类似的 20-40 个句子打包请求,下面是实例代码。 虽然彩云小译提供了官方的脚本,但是感觉还是免费的用的更方便,把代码放在此处仅供不时这需。

xiaoniu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import json
import requests
apikey="3ca7eb8b8ad0f8fe04a96fc3d52bfc11"
lines=["hello","How are you?"]
def translate(sentence, src_lan, tgt_lan):
url = 'http://api.niutrans.com/NiuTransServer/translation?'
data = {"from": src_lan, "to": tgt_lan, "apikey": apikey, "src_text": sentence}
res = requests.post(url, data = data)
res_dict = json.loads(res.text)
if "tgt_text" in res_dict:
result = res_dict['tgt_text']
else:
result = res
return result
if __name__ == "__main__":
for line in lines:
try:
trans = translate(line, 'auto', 'zh')
print(trans)
except Exception as exc:
print(exc)

注意:上述代码源自于:Python调用小牛机器翻译API进行文本批量翻译 , 官方文档为 小牛翻译API服务, 这部分有待于加入到多合一脚本。

脚本赖于pythonrequests模块,所以要安装这个模块

1
sudo pacman -S python-requests

translatorGD脚本配置方法

  • 在使用脚本前,请输入申请到的百度帐号和密钥,小牛的密钥

  • Linux中配置

    命令行
    1
    python "/home/feng/软件/goldendict/translatorGD.py" %GDWORD%

  • Windows配置

    命令行
    1
    python "D:\goldendict\translatorGD.py" %GDWORD%

Windows下translatorGD配置方法