diff --git a/tools/python/strings_utils.py b/tools/python/strings_utils.py index 10ba27427d..0b33798227 100755 --- a/tools/python/strings_utils.py +++ b/tools/python/strings_utils.py @@ -484,6 +484,15 @@ class StringsTxt: self.print_strings_with_wrong_placeholders(langs=args.langs) return not self.validation_errors + def translate(self, source_language, target_language): + from translate import translate_one + self._print_header(f"Translating from {source_language} to {target_language}...") + for key, source in self.translations_by_language[source_language].items(): + if key in self.translations_by_language[target_language]: + continue + translation = translate_one(source, source_language, target_language) + print(f'{source} -> {translation}') + self.add_translation(translation, key, target_language) def find_project_root(): my_path = abspath(__file__) @@ -585,6 +594,14 @@ def get_args(): before punctuation, etc; exit with error if not valid""" ) + parser.add_argument( + "-tr", "--translate", + nargs=2, + dest="translate", + metavar=('source_lang', 'target_lang'), + help="""translate SOURCE_LANG into TARGET_LANG""" + ) + return parser.parse_args() @@ -630,6 +647,11 @@ if __name__ == "__main__": print("\n\033[0;31mThe file is not valid, terminating\033[0m") sys.exit(1) + if args.translate: + if not args.output: + args.output = True + strings.translate(args.translate[0], args.translate[1]) + if args.output: if args.output == True: args.output = args.input diff --git a/tools/python/translate.py b/tools/python/translate.py index 75b076c5de..179be34028 100755 --- a/tools/python/translate.py +++ b/tools/python/translate.py @@ -100,6 +100,15 @@ def google_translate(text, source_language): print(lang + ' = ' + line) return translations +def google_translate_one(text, source_language, target_language): + fromTo = source_language.lower() + ':' + target_language.lower() + res = subprocess.run([TRANS_CMD, '-b', '-no-bidi', fromTo, text], text=True, capture_output=True) + if res.returncode != 0: + print(f'Error running {TRANS_CMD} program:') + print(res.stderr) + exit(1) + return res.stdout.splitlines()[0] + def deepl_translate_one(text, source_language, target_language): url = 'https://api-free.deepl.com/v2/translate' payload = { @@ -114,6 +123,14 @@ def deepl_translate_one(text, source_language, target_language): json = response.json() return json['translations'][0]['text'] +def translate_one(text, source_language, target_language): + if target_language in DEEPL_TARGET_LANGUAGES: + return deepl_translate_one(text, source_language, target_language) + elif target_language in GOOGLE_TARGET_LANGUAGES: + return google_translate_one(text, source_language, target_language) + else: + raise ValueError(f'Unsupported target language {target_language}') + def deepl_translate(text, source_language): translations = {} print('Deepl translations:')