MCPcopy Create free account
hub / github.com/Simsys/qhexedit2 / Translate

Class Translate

python/translate.py:13–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11 exit(1)
12
13class Translate:
14 def __init__(self, pro_file):
15 self._dir_path = os.path.dirname(os.path.realpath(pro_file))
16 self._translator = Translator()
17
18 with open(pro_file) as f:
19 splits = re.split(' |\n|=', f.read())
20
21 self._ts_files = []
22 for split in splits:
23 if len(split) > 3:
24 if ".ts" == split[-3:]:
25 ts_path = os.path.join(self._dir_path, split)
26 with open(ts_path) as f:
27 content = f.read()
28 todo = content.count('<translation type="unfinished"></translation>')
29 if todo > 0:
30 self._ts_files.append(ts_path)
31
32 async def runner(self):
33 tasks = []
34
35 for ts_path in self._ts_files:
36 task = asyncio.create_task(self._translate_file(ts_path))
37 tasks.append(task)
38
39 await asyncio.gather(*tasks)
40 print()
41
42 async def _translate_file(self, ts_path):
43 file_name = os.path.basename(ts_path)
44 print(f"Translating '{file_name}'")
45 target_lang = ts_path.split('.')[0].split('_')[1]
46 ts_write_path = ts_path + '~'
47
48 with open(ts_path) as f:
49 content = f.read()
50
51 with open(ts_write_path, 'wt') as fw:
52 for frag in content.split("</translation>"):
53 if "source>" in frag:
54 if frag[-31:] == '<translation type="unfinished">':
55 splits = frag.split('source>')
56 to_translate = splits[1][:-2]
57 translated = await self._translate_frag(to_translate, target_lang)
58 frag = frag[:-31] + "<translation>" + translated
59 print('.', end='', flush=True)
60 frag += "</translation>"
61 fw.write(frag)
62
63 shutil.move(ts_write_path, ts_path)
64
65 async def _translate_frag(self, to_translate, target_lang):
66 s = to_translate.replace("&quot;", "\"").replace("&apos;", "\&#x27;").replace("&lt;", "<") \
67 .replace("&gt;", ">").replace("&amp;", "\&").replace("&", "")
68
69 result = await self._translator.translate(s, src='en', dest=target_lang)
70 return result.text

Callers 1

translate.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected