如何使用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
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
Theme Stack designed by Jimmy