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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
|
import codecs
import datetime
import glob
import json
import os
import random
import re
import ssl
import time
import urllib.parse
import urllib.request
from cgitb import text
from datetime import datetime
from importlib.resources import contents
from sre_constants import RANGE
from typing import TYPE_CHECKING
from unittest.util import strclass
from xml.etree.ElementTree import C14NWriterTarget
import execjs
ssl._create_default_https_context = ssl._create_unverified_context
class GoogleTrans(object):
def __init__(self):
self.url = 'https://translate.google.cn/translate_a/single'
self.TKK = "434674.96463358" # 随时都有可能需要更新的TKK值
self.header = {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9",
"cookie": "NID=188=M1p_rBfweeI_Z02d1MOSQ5abYsPfZogDrFjKwIUbmAr584bc9GBZkfDwKQ80cQCQC34zwD4ZYHFMUf4F59aDQLSc79_LcmsAihnW0Rsb1MjlzLNElWihv-8KByeDBblR2V1kjTSC8KnVMe32PNSJBQbvBKvgl4CTfzvaIEgkqss",
"referer": "https://translate.google.cn/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
"x-client-data": "CJK2yQEIpLbJAQjEtskBCKmdygEIqKPKAQi5pcoBCLGnygEI4qjKAQjxqcoBCJetygEIza3KAQ==",
}
self.data = {
"client": "webapp", # 基于网页访问服务器
"sl": "zh-cn", # 源语言,auto表示由谷歌自动识别
"tl": "en", # 翻译的目标语言
"hl": "zh-cn", # 界面语言选中文,毕竟URL都是cn后缀了,就不装美国人了
# dt表示要求服务器返回的数据类型
"dt": ["at", "bd", "ex", "ld", "md", "qca", "rw", "rm", "ss", "t"],
"otf": "2",
"ssel": "0",
"tsel": "0",
"kc": "1",
"tk": "", # 谷歌服务器会核对的token
"q": "" # 待翻译的字符串
}
with open('token.js', 'r', encoding='utf-8') as f:
self.js_fun = execjs.compile(f.read())
# 构建完对象以后要同步更新一下TKK值
# self.update_TKK()
def update_TKK(self):
url = "https://translate.google.cn/"
req = urllib.request.Request(url=url, headers=self.header)
page_source = urllib.request.urlopen(req).read().decode("utf-8")
self.TKK = re.findall(r"tkk:'([0-9]+\.[0-9]+)'", page_source)[0]
def construct_url(self):
base = self.url + '?'
for key in self.data:
if isinstance(self.data[key], list):
base = base + "dt=" + "&dt=".join(self.data[key]) + "&"
else:
base = base + key + '=' + self.data[key] + '&'
base = base[:-1]
return base
def query(self, q, lang_from='zh-cn', lang_to=''):
self.data['q'] = urllib.parse.quote(q)
self.data['tk'] = self.js_fun.call('wo', q, self.TKK)
self.data['sl'] = lang_from
self.data['tl'] = lang_to
url = self.construct_url()
# print(url)
req = urllib.request.Request(url=url, headers=self.header)
res = urllib.request.urlopen(req).read().decode("utf-8")
# print("res======", res)
response = json.loads(res)
# print(response)
originalLanguageCode = response[2]
targetText = ""
originalText = ""
for ds in response[0]:
# print("-----------------")
# print(ds[0])
# print("-----------------")
# print(ds[1])
# print("-----------------")
if ds[0]:
targetText = targetText + ds[0]
if ds[1]:
originalText = originalText + ds[1]
print("翻译前:{},翻译前code:{}".format(originalText, originalLanguageCode))
print("翻译后:{}, 翻译后code:{}".format(targetText, lang_to))
return originalText, originalLanguageCode, targetText, lang_to
def translate(self, sourceTxt, srcLang, targetLang, retries=0):
print('translate retries=', retries)
if retries > 20:
return
try:
result = self.query(sourceTxt, srcLang, lang_to=targetLang)[2]
print(result)
if result is None:
retries += 1
self.translate(sourceTxt, srcLang, targetLang, retries)
else:
return result
except:
retries += 1
self.translate(sourceTxt, srcLang, targetLang, retries)
class MdTransItem(object):
def __init__(self, i):
self.delimiter = '_{:05d}_'.format(i)
# 内容无需翻译
# 比如 #date: 2022-04-01
class MdTransItemReserve(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
self.trans_buff = self.delimiter + '\n'
self.value = text
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
return translated_md_text.replace(self.trans_buff, self.value)
# 内容全部需翻译
# 比如MD中的正文文本块
class MdTransItemPlainText(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
self.trans_buff = text
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
return translated_md_text
# 内容为#key:value形式,value需要翻译
# 比如 #title: 这是文章标题
class MdTransItemKeyValue(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
# print(text)
idx = text.index(':')
# print(idx)
lstr = text[0: idx + 1]
rstr = text[idx + 1:].strip()
# print(rstr)
self.trans_buff = self.delimiter + ' \n' + \
rstr + ' \n' + self.delimiter + ' \n'
self.value = lstr.rstrip()
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
# return translated_md_text.replace(self.delimiter, self.value)
print('self.delimiter:', self.delimiter)
print(translated_md_text)
result_md_text = ''
dlen = len(self.delimiter)
idx1 = translated_md_text.index(self.delimiter)
idx2 = translated_md_text.index(self.delimiter, idx1 + 1)
lstr = translated_md_text[0: idx1]
mstr = translated_md_text[idx1 + dlen + 1: idx2]
rstr = translated_md_text[idx2 + dlen + 1:]
rstr = rstr.lstrip()
result_md_text = lstr + self.value + ' ' + mstr.strip() + '\n' + rstr
return result_md_text
# 内容为### Title形式,Title需要翻译
# 比如 ### MD标题
class MdTransItemTitle(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
idx = text.index(' ')
lstr = text[0: idx + 1]
rstr = text[idx + 1:]
# print(rstr)
self.trans_buff = self.delimiter + ' \n' + \
rstr + ' \n' + self.delimiter + ' \n'
self.value = lstr.rstrip()
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
# return translated_md_text.replace(self.delimiter, self.value)
print('self.delimiter:', self.delimiter)
print(translated_md_text)
result_md_text = ''
dlen = len(self.delimiter)
idx1 = translated_md_text.index(self.delimiter)
idx2 = translated_md_text.index(self.delimiter, idx1 + 1)
lstr = translated_md_text[0: idx1]
mstr = translated_md_text[idx1 + dlen + 1: idx2]
rstr = translated_md_text[idx2 + dlen + 1:]
rstr = rstr.lstrip()
result_md_text = lstr + self.value + ' ' + mstr.strip() + '\n' + rstr
return result_md_text
# 内容为![图片标题](01.jpg) 形式,图片标题需要翻译
# 比如 ![图片名称](01.jpg)
class MdTransItemImg(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
idx1 = text.index('[')
idx2 = text.index(']')
if idx1 == idx2 - 1:
self.value = text[:-1]
self.trans_buff = self.delimiter + '\n'
self.type = 1
else:
lstr = text[0: idx1 + 1]
mstr = text[idx1 + 1: idx2]
rstr = text[idx2: -1]
self.trans_buff = self.delimiter + '_B ' + mstr + ' ' + self.delimiter + '_E\n'
self.value1 = lstr
self.value2 = rstr
self.type = 2
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
if self.type == 1:
translated_md_text = translated_md_text.replace(
self.delimiter, self.value)
elif self.type == 2:
translated_md_text = translated_md_text.replace(
self.delimiter + '_B', self.value1)
translated_md_text = translated_md_text.replace(
self.delimiter + '_E', self.value2)
return translated_md_text
# 内容为#key:["values1","values2",..."valueN"]形式,value需要翻译
# 比如 keywords: ["关键词1","关键词2","关键词3"]
class MdTransItemKeyValueArray(MdTransItem):
def __init__(self, text, i):
MdTransItem.__init__(self, i)
idx = text.index(':')
# print(idx)
lstr = text[0: idx + 1]
self.value = lstr
rstr = text[idx + 1:].strip()
# print(rstr)
# 列表内容
if rstr.startswith('['):
self.trans_buff = ''
self.trans_buff = self.trans_buff + self.delimiter + ' \n'
# print('strat with [')
trans_str = ''
items = rstr[2:-2].split('\",\"')
for item in items:
self.trans_buff = self.trans_buff + item + '\n'
self.trans_buff = self.trans_buff + self.delimiter + ' \n'
else:
print("Wrong format with MdTransItemKeyValueArray:", text)
def get_trans_buff(self):
return self.trans_buff
def compose(self, translated_md_text):
print('self.delimiter:', self.delimiter)
print(translated_md_text)
result_md_text = ''
dlen = len(self.delimiter)
idx1 = translated_md_text.index(self.delimiter)
idx2 = translated_md_text.index(self.delimiter, idx1 + 1)
lstr = translated_md_text[0: idx1]
mstr = translated_md_text[idx1 + dlen + 1: idx2]
rstr = translated_md_text[idx2 + dlen + 1:]
rstr = rstr.lstrip()
result_md_text = lstr
result_md_text = result_md_text + self.value + ' ['
mstr_array = mstr.strip().split('\n')
for m in mstr_array:
if m.endswith('.'):
m = m[0:-1]
result_md_text = result_md_text + '"' + m + '",'
if result_md_text.endswith(','):
result_md_text = result_md_text[0: len(result_md_text) - 1]
result_md_text = result_md_text + ']\n'
result_md_text = result_md_text + rstr
return result_md_text
class MdTranslater(object):
langs = ['en', 'zh-tw', 'th', 'hi', 'ms', 'tl', 'id', 'vi']
def cleanup(self, md_folder):
for lang in self.langs:
dest_filename = md_folder + '/index.' + lang + '.md'
if os.path.exists(dest_filename):
print('remove ', dest_filename)
os.remove(dest_filename)
def check_missing(self, md_folder):
for lang in self.langs:
dest_filename = md_folder + '/index.' + lang + '.md'
if not os.path.exists(dest_filename):
print('lack ', dest_filename)
def replace_useless_char(self, tstr):
return tstr
def translate_md(self, src_lang, dest_lang, md_file):
dest_filename = md_file.replace(src_lang, dest_lang)
if os.path.exists(dest_filename):
print('already translated ', dest_filename, ' skip.')
return
src_filename = md_file
if not os.path.exists(src_filename):
print('src file ', src_filename, ' not exist! skip.')
return
src_md_lines = ''
with open(src_filename, encoding='utf-8') as src_filename_data:
src_md_lines = src_filename_data.readlines()
print('translate ', dest_filename, ' ...')
is_front_matter = False
md_trans_items = []
for i in range(len(src_md_lines)):
line = src_md_lines[i]
line = self.replace_useless_char(line)
if line.strip() == '---':
is_front_matter = not is_front_matter
md_trans_items.append(MdTransItemReserve(line, i))
continue
if is_front_matter:
if line.startswith(('title:', 'slug:', 'description:')):
md_trans_items.append(MdTransItemKeyValue(line, i))
elif line.startswith('date:'):
md_trans_items.append(MdTransItemReserve(line, i))
elif line.startswith(('tags:', 'categories:', 'keywords:')):
md_trans_items.append(MdTransItemKeyValueArray(line, i))
else:
md_trans_items.append(MdTransItemPlainText(line, i))
else:
if len(line.strip()) == 0: # 空行
md_trans_items.append(MdTransItemPlainText(line, i))
elif re.match('\!\[.*\]\(.*\)', line) is not None: # 图片
md_trans_items.append(MdTransItemImg(line, i))
elif line.strip().startswith('#'): # 标题
md_trans_items.append(MdTransItemTitle(line, i))
else: # 普通文字
md_trans_items.append(MdTransItemPlainText(line, i))
# 待翻译md文本
src_md_text = ''
for mdTransItem in md_trans_items:
src_md_text = src_md_text + mdTransItem.get_trans_buff()
# 分割文本,每次翻译,发送大小不大于1000
part_src_md_text = ""
dest_md_text = ""
for line in src_md_text.splitlines():
part_src_md_text = part_src_md_text + line + "\n"
if len(part_src_md_text) > 1000:
dest_md_text = dest_md_text + GoogleTrans().translate(part_src_md_text,
src_lang, dest_lang) + "\n"
part_src_md_text = ""
if len(part_src_md_text) > 0:
dest_md_text = dest_md_text + GoogleTrans().translate(part_src_md_text,
src_lang, dest_lang) + "\n"
for mdTransItem in md_trans_items:
print(mdTransItem)
dest_md_text = mdTransItem.compose(dest_md_text)
final_md_text = ''
for dline in dest_md_text.splitlines():
final_md_text = final_md_text + dline + ' \n'
with open(dest_filename, 'w', encoding='utf-8') as outfile:
outfile.write(final_md_text)
def translate_md_with_retries(self, src_lang, dest_lang, md_folder, retries=0):
print('translate md with retries=', retries)
if retries > 20:
return
try:
time.sleep(1)
return self.translate_md(src_lang, dest_lang, md_folder)
except:
time.sleep(5)
retries += 1
self.translate_md_with_retries(
src_lang, dest_lang, md_folder, retries)
def translate_all_md(self, md_folder):
print('translate_all_md:', md_folder)
files = [f for f in glob.glob(
md_folder + "/**/*.zh-cn.md", recursive=True)]
for f in files:
for lang in self.langs:
self.translate_md_with_retries('zh-cn', lang, f)
|