Skip to content

Commit 0fe7fe7

Browse files
committed
pycon_sprints_add_chatgpt
1 parent 149fc0b commit 0fe7fe7

File tree

2 files changed

+56
-8
lines changed

2 files changed

+56
-8
lines changed

.scripts/google_translate/chatgpt.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import json
2+
import requests
3+
4+
def translate(api_key, ipt):
5+
prompt = f'假設你是一位python工程師,請將下列文件翻譯為繁體中文 “{ipt}”'
6+
response = requests.post(
7+
'https://api.openai.com/v1/completions',
8+
headers = {
9+
'Content-Type': 'application/json',
10+
'Authorization': f'Bearer {api_key}'
11+
},
12+
json = {
13+
'model': 'text-davinci-003',
14+
'prompt': prompt,
15+
'temperature': 0.4,
16+
'max_tokens': 1000
17+
}
18+
)
19+
return response
20+
21+
def Translator(ipt, api_key):
22+
response = translate(api_key, ipt)
23+
opt = json.loads(response.text)['choices'][0]['text']
24+
print(opt)

.scripts/google_translate/main.py

+32-8
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import polib
77
from googletrans import Translator
8+
import chatgpt
89

910
from utils import refine_translations
1011

@@ -25,13 +26,23 @@ def _get_po_paths(path: Path) -> List[Path]:
2526

2627
if __name__ == '__main__':
2728
parser = argparse.ArgumentParser()
29+
parser.add_argument(
30+
"translator",
31+
help="the translator to use",
32+
choices=["google", "chatgpt"],
33+
default="google"
34+
)
2835
parser.add_argument(
2936
"path",
3037
help="the path of a PO file or a directory containing PO files"
3138
)
39+
parser.add_argument(
40+
"key",
41+
help="api key for chatGPT use",
42+
default=""
43+
)
3244
args = parser.parse_args()
3345

34-
translator = Translator()
3546
po_files = _get_po_paths(Path(args.path).resolve())
3647
errors = []
3748
for path in po_files:
@@ -41,11 +52,24 @@ def _get_po_paths(path: Path) -> List[Path]:
4152
errors.append(f"{path} doesn't seem to be a .po file")
4253
continue
4354

44-
for entry in pofile.untranslated_entries()[::-1]:
45-
translation = translator.translate(entry.msgid, src='en', dest='zh-TW')
55+
if args.translator == "google":
56+
translator = Translator()
57+
for entry in pofile.untranslated_entries()[::-1]:
58+
translation = translator.translate(entry.msgid, src='en', dest='zh-TW')
59+
60+
print(
61+
'#, fuzzy\n'
62+
f'msgid "{repr(entry.msgid)[1:-1]}"\n'
63+
f'msgstr "{repr(refine_translations(translation.text))[1:-1]}"\n'
64+
)
65+
66+
elif args.translator == "chatgpt":
67+
api_key = args.key
68+
for entry in pofile.untranslated_entries()[::-1]:
69+
translation = chatgpt.Translator(api_key, entry.msgid)
4670

47-
print(
48-
'#, fuzzy\n'
49-
f'msgid "{repr(entry.msgid)[1:-1]}"\n'
50-
f'msgstr "{repr(refine_translations(translation.text))[1:-1]}"\n'
51-
)
71+
print(
72+
'#, fuzzy\n'
73+
f'msgid "{repr(entry.msgid)[1:-1]}"\n'
74+
f'msgstr "{repr(refine_translations(translation.text))[1:-1]}"\n'
75+
)

0 commit comments

Comments
 (0)