|
| 1 | +import os |
| 2 | +import json |
| 3 | +from glob import glob |
| 4 | +from openai import OpenAI |
| 5 | + |
| 6 | +client = OpenAI( |
| 7 | + # This is the default and can be omitted |
| 8 | + api_key=os.environ.get("OPENAI_API_KEY") |
| 9 | +) |
| 10 | + |
| 11 | +# Keys to translate. If this is empty, all keys are translated. |
| 12 | +KEYS = [] |
| 13 | + |
| 14 | +DEFAULT_LANG = "en.json" |
| 15 | +DIR = os.path.normpath(os.path.join( |
| 16 | + os.path.dirname(os.path.abspath(__file__)), "../i18n")) |
| 17 | +BASE = json.loads(open(os.path.join(DIR, DEFAULT_LANG), "r").read()) |
| 18 | + |
| 19 | + |
| 20 | +def translate(data, lang): |
| 21 | + completion = client.chat.completions.create( |
| 22 | + model="gpt-3.5-turbo-16k", |
| 23 | + messages=[ |
| 24 | + {"role": "system", "content": "You are an i18n language pack translator for listmonk, a mailing list manager. Remember that context when translating."}, |
| 25 | + {"role": "user", |
| 26 | + "content": "Translate the untranslated English strings in the following JSON language map to {}. Retain any technical terms or acronyms.".format(lang)}, |
| 27 | + {"role": "user", "content": json.dumps(data)} |
| 28 | + # {"role": "user", "content": "Hello world good morning!"} |
| 29 | + ] |
| 30 | + ) |
| 31 | + |
| 32 | + return json.loads(str(completion.choices[0].message.content)) |
| 33 | + |
| 34 | + |
| 35 | +# Go through every i18n file. |
| 36 | +for f in glob(os.path.join(DIR, "*.json")): |
| 37 | + if os.path.basename(f) == DEFAULT_LANG: |
| 38 | + continue |
| 39 | + |
| 40 | + print(os.path.basename(f)) |
| 41 | + |
| 42 | + data = json.loads(open(f, "r").read()) |
| 43 | + |
| 44 | + # Diff the entire file or only given keys. |
| 45 | + if KEYS: |
| 46 | + diff = {k: BASE[k] for k in KEYS} |
| 47 | + else: |
| 48 | + diff = {k: v for k, v in data.items() if BASE.get(k) == v} |
| 49 | + |
| 50 | + new = translate(diff, data["_.name"]) |
| 51 | + data.update(new) |
| 52 | + |
| 53 | + with open(f, "w") as o: |
| 54 | + o.write(json.dumps(data, sort_keys=True, |
| 55 | + indent=4, ensure_ascii=False) + "\n") |
0 commit comments