如何使用translate.google.cn免费Google翻译网站翻译整篇Markdown文档, V2修改版

上篇采用分割符标记的方法进行翻译。但是后来发现,有些语言在翻译时,分割符号在翻译的过程中也被改变了。所以才想到换一种方法重新设计。

第一版存在的问题

分割符号在翻译的过程中被改变了

发现有些特定的语言,在翻译时会把分隔符改变.
尝试了不同类型分隔符 比如 01231 之类的, 翻译后其中的数字会变化,比如变成 _02231_之类,没有发现规律性, 可翻译语言有关系,甚至和翻译时间也有关系,找不到会确定不被修改的分隔符。
也可能是翻译系统的某种bug。 所以去掉了分隔符,把需要分开翻译的分成多行进行翻译,同时记录下分成的行数。

新版翻译过程

新的翻译大致分成下面的几个过程:

  1. 把不需要翻译的部分提前提取出来
  2. 把要单独翻译的项分成多行,并记录下来分成的行数
  3. 把标记好的文档,按照行分好段,每次只翻译其中的一部分,保证不超过最大长度
  4. 翻译时如果出现网络错误,重试
  5. 翻译好的结果根据行号对应到内容
  6. 翻译过程会造成部分格式缺失,重新格式化文档。

代码实现

  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
import hashlib
import codecs
import datetime
import glob
import json
import os
import re
import ssl
import time
import traceback
import urllib.parse
import urllib.request
import execjs

from cgitb import text
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

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()
        req = urllib.request.Request(url=url, headers=self.header)
        res = urllib.request.urlopen(req).read().decode("utf-8")
        response = json.loads(res)
        originalLanguageCode = response[2]
        targetText = ""
        originalText = ""
        for ds in response[0]:
            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 ... sourceTxt length=', len(sourceTxt))
        if retries > 1:
            return
        try:
            result = self.query(sourceTxt, srcLang, lang_to=targetLang)[2]
            if result is None:
                retries += 1
                print('retry ', retries)
                self.translate(sourceTxt, srcLang, targetLang, retries)
            else :
                return result
        except:
            retries += 1
            self.translate(sourceTxt, srcLang, targetLang, retries)

# 内容无需翻译
# 比如 #date: 2022-04-01
class MdTransItemReserve(object):
    def __init__(self, line):
        self.trans_buff = '  \n'
        self.value = line.strip()

    def get_trans_buff(self):
        return self.trans_buff
    
    def compose(self, translated_lines, start_pos):
        translated_lines[start_pos] = self.value + '\n'
        return translated_lines, 1

# 内容全部需翻译
# 比如MD中的正文文本块
class MdTransItemPlainText(object):
    def __init__(self, line):
        self.trans_buff = line.strip() + '\n'

    def get_trans_buff(self):
        return self.trans_buff

    def compose(self, translated_lines, start_pos):
        pass
    
# 内容为#key:value形式,value需要翻译
class MdTransItemKeyValue(object):
    def __init__(self, line):
        idx = line.index(':')
        lstr = line[0: idx + 1]
        rstr = line[idx + 1:].strip()
        self.trans_buff = rstr + '  \n'
        self.value = lstr.rstrip()

    def get_trans_buff(self):
        return self.trans_buff

    def compose(self, translated_lines, start_pos):
        translated_lines[start_pos] = self.value + ' ' + translated_lines[start_pos].rstrip().replace('"','').replace(':',' ') + '\n'

# 内容为### Title形式,Title需要翻译
class MdTransItemTitle(object):
    def __init__(self, line):
        idx = line.index(' ')
        lstr = line[0: idx + 1]
        rstr = line[idx + 1:]
        self.trans_buff = rstr.rstrip() + '  \n'
        self.value = lstr.rstrip() 

    def get_trans_buff(self):
        return self.trans_buff
    
    def compose(self, translated_lines, start_pos):
        translated_lines[start_pos] = self.value + ' ' + translated_lines[start_pos].rstrip() + '\n'

# 内容为![图片标题](01.jpg) 形式,图片标题需要翻译
class MdTransItemImg(object):
    def __init__(self, line):
        idx1 = line.index('[')
        idx2 = line.index(']')
        if idx1 == idx2 - 1:
            self.value = line[:-1]
            self.trans_buff = '  \n'
            self.type = 1
        else:
            lstr = line[0: idx1 + 1]
            mstr = line[idx1 + 1: idx2]
            rstr = line[idx2: -1]
            self.trans_buff = mstr + '  \n'
            self.value1 = lstr
            self.value2 = rstr
            self.type = 2

    def get_trans_buff(self):
        return self.trans_buff

    def compose(self, translated_lines, start_pos):
        if self.type == 1:
            translated_lines[start_pos] = self.value + '  \n'
        elif self.type == 2:
            translated_lines[start_pos] = self.value1 + translated_lines[start_pos].rstrip() + self.value2  + '  \n'
    
# 内容为#key:["values1","values2",..."valueN"]形式,value需要翻译
class MdTransItemKeyValueArray(object):
    def __init__(self, line):
        idx = line.index(':')
        lstr = line[0: idx + 1]
        self.value = lstr
        rstr = line[idx + 1:].strip()
        if rstr.startswith('['):
            self.trans_buff = ''
            items = rstr[2:-2].split('\",\"')
            for item in items:
                self.trans_buff = self.trans_buff + item + '  \n'
            self.item_cnt = len(items)
        else:
            print("Wrong format with MdTransItemKeyValueArray:", text)

    def get_trans_buff(self):
        return self.trans_buff

    def compose(self, translated_lines, start_pos):
        value_text = ''
        for idx in range(start_pos, start_pos + self.item_cnt) :
            value_text = value_text + '"' + translated_lines[idx].strip().replace('"','').rstrip('.').replace(':',' ') + '",'
        
        translated_lines[start_pos] = self.value + ' [' + value_text[:-1] + ']  \n'
        
        for idx in range(1, self.item_cnt) :
            del translated_lines[start_pos + 1]

class MdTranslater():
    langs = ['en', 'zh-tw', 'th', 'hi', 'ms', 'tl', 'id', 'vi']
        
    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_lines, src_lang, dest_lang):
        is_front_matter = False
        md_trans_items = []
        for i in range(len(src_lines)):
            line = src_lines[i]
            if line.strip() == '---':
                is_front_matter = not is_front_matter
                md_trans_items.append(MdTransItemReserve(line))
                continue

            if is_front_matter:
                if line.startswith(('title:', 'slug:', 'description:')):
                    md_trans_items.append(MdTransItemKeyValue(line))
                elif line.startswith('date:'):
                    md_trans_items.append(MdTransItemReserve(line))
                elif line.startswith(('tags:', 'categories:', 'keywords:')):
                    md_trans_items.append(MdTransItemKeyValueArray(line))
                else:
                    md_trans_items.append(MdTransItemPlainText(line))
            else:
                if len(line.strip()) == 0:  # 空行
                    md_trans_items.append(MdTransItemPlainText(line))
                elif re.match('\!\[.*\]\(.*\)', line) is not None:  # 图片
                    md_trans_items.append(MdTransItemImg(line))
                elif line.strip().startswith('#'):  # 标题
                    md_trans_items.append(MdTransItemTitle(line))
                else:  # 普通文字
                    md_trans_items.append(MdTransItemPlainText(line))

        #待翻译md文本
        src_md_text = 'BEGIN  \n' ##在首尾都要加入特定行,否则翻译后会首尾的空行去掉,造成翻译前后对应不上
        for mdTransItem in md_trans_items:
            src_md_text = src_md_text + mdTransItem.get_trans_buff()
        src_md_text = src_md_text + 'END  \n' ##在首尾都要加入特定行,否则翻译后会首尾的空行去掉,造成翻译前后对应不上
        
        #分割文本,每次翻译,发送大小不大于2000
        part_src_md_text = ""
        dest_md_text = ""
        src_lines = src_md_text.splitlines()
        # print('src_lines:', len(src_lines))
        # print('src_lines:', src_lines)
        for line in src_lines:
            part_src_md_text = part_src_md_text + line + "\n"
            if len(part_src_md_text) > 500:  #不同语言这个值不同
                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"

        translated_lines = dest_md_text.splitlines()
        start_pos = 1  #从第一行开始对应,首行为添加的无意义
        for mdTransItem in md_trans_items:
            # print(mdTransItem)
            mdTransItem.compose(translated_lines, start_pos)
            start_pos = start_pos + 1
            
        final_md_text = ''
        for dline in translated_lines[1 : -1]:
            final_md_text = final_md_text + dline.rstrip() + '  \n' 

        return final_md_text
    
    def translate_md_folder(self, src_lang, dest_lang, md_folder):
        dest_filename = md_folder + '/index.' + dest_lang + '.md'
        if os.path.exists(dest_filename):
            print('already translated ', dest_filename, ' skip.')
            return

        src_filename = md_folder + '/index.' + src_lang + '.md'
        if not os.path.exists(src_filename):
            print('src file ', src_filename, ' not exist! skip.')
            return

        #black list
        if (md_folder.endswith('000019') and dest_lang == 'my') or \
            (md_folder.endswith('000019') and dest_lang == 'hmn') :
            print(dest_filename, 'in black list, skip!')
            return

        print('translate file ', src_filename, ' to ', dest_filename)
        src_lines = ''
        with open(src_filename, encoding='utf-8') as src_filename_data:
            src_lines = src_filename_data.readlines()
            
        final_md_text = self.translate_md(src_lines, src_lang, dest_lang)
        # print('final_md_text',final_md_text)
        with open(dest_filename, 'w', encoding='utf-8') as outfile:
            outfile.write(final_md_text)

    def translate_md_folder_with_retries(self, src_lang, dest_lang, md_folder, retries=0):
        # print('translate md with retries=',  retries)
        if retries > 20:
            return
        try:
            return self.translate_md_folder(src_lang, dest_lang, md_folder)
        except Exception as e: 
            print(e)
            time.sleep(3)
            retries += 1
            self.translate_md_folder_with_retries(src_lang, dest_lang, md_folder, retries)


    def translate_all_md_folder(self, md_folder):
        print('translate_all_md_folder:', md_folder)
        files = [f for f in glob.glob(md_folder + "/**/index.zh-cn.md", recursive=True)]
        for f in files:
            d = os.path.dirname(f)
            for lang in self.langs:
                self.translate_md_folder_with_retries('zh-cn', lang, d)

    def cleanup(self, md_folder):
        print('cleanup:', md_folder)
        files = [f for f in glob.glob(md_folder + "/**/index.zh-cn.md", recursive=True)]
        for f in files:
            d = os.path.dirname(f)
            for lang in self.langs:
                dest_filename = d + '/index.' + lang + '.md'
                if os.path.exists(dest_filename):
                    print('remove ', dest_filename)
                    # os.remove(dest_filename)

参考文档

google翻译部分参考了 https://github.com/VictorZhang2014/free-google-translate

记录并分享
Built with Hugo
主题 StackJimmy 设计