Skip to content

Instantly share code, notes, and snippets.

@Reyuu
Created June 10, 2020 23:27
Show Gist options
  • Save Reyuu/11c789f94d370b26459992adc9327c1b to your computer and use it in GitHub Desktop.
Save Reyuu/11c789f94d370b26459992adc9327c1b to your computer and use it in GitHub Desktop.
MT PO file with Google translate. Generates PO file that has targets filled with machine translation. Requires googletrans and polib to be installed.
import googletrans
import polib
import sys
import shutil
import argparse
parser = argparse.ArgumentParser(description="MT PO file with Google translate. Requires googletrans and polib to be installed.")
parser.add_argument("input_pot", help="input POT file")
parser.add_argument("-t", "--target", help="target language in lowercase ISO 3166-1 alpha-2")
parser.add_argument("-s", "--source", help="source language in lowercase ISO 3166-1 alpha-2", default="en")
args = parser.parse_args()
new_file = f"{args.target}.po"
shutil.copy(args.input_pot, new_file)
translator = googletrans.Translator()
po = polib.pofile(new_file)
po_entries = [p.msgid for p in po.untranslated_entries()]
translations = translator.translate(po_entries, dest=args.target, src=args.source)
mapped_translations = {t.origin: t.text for t in translations}
for entry in po:
entry.msgstr = mapped_translations[entry.msgid]
po.save(new_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment