-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathmain.py
75 lines (62 loc) · 2.16 KB
/
main.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
import argparse
import logging
from pathlib import Path
from typing import List
import polib
from googletrans import Translator
import chatgpt
from utils import refine_translations
def _get_po_paths(path: Path) -> List[Path]:
"""Find all .po files in given path"""
if not path.exists():
logging.error(f"The path '{path.absolute()}' does not exist!")
# return 1-element list if it's a file
if path.is_file():
return [path.resolve()]
# find all .po files
po_paths = [p.resolve() for p in path.glob("**/*.po")]
return po_paths
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"translator",
help="the translator to use",
choices=["google", "chatgpt"],
default="google"
)
parser.add_argument(
"path",
help="the path of a PO file or a directory containing PO files"
)
parser.add_argument(
"key",
help="api key for chatGPT use",
default=""
)
args = parser.parse_args()
po_files = _get_po_paths(Path(args.path).resolve())
errors = []
for path in po_files:
try:
pofile = polib.pofile(path)
except OSError:
errors.append(f"{path} doesn't seem to be a .po file")
continue
if args.translator == "google":
translator = Translator()
for entry in pofile.untranslated_entries()[::-1]:
translation = translator.translate(entry.msgid, src='en', dest='zh-TW')
print(
'#, fuzzy\n'
f'msgid "{repr(entry.msgid)[1:-1]}"\n'
f'msgstr "{repr(refine_translations(translation.text))[1:-1]}"\n'
)
elif args.translator == "chatgpt":
api_key = args.key
for entry in pofile.untranslated_entries()[::-1]:
translation = chatgpt.Translator(api_key, entry.msgid)
print(
'#, fuzzy\n'
f'msgid "{repr(entry.msgid)[1:-1]}"\n'
f'msgstr "{repr(refine_translations(translation.text))[1:-1]}"\n'
)