[tools] Add a command for translating into a new language

Signed-off-by: Roman Tsisyk <roman@tsisyk.com>
This commit is contained in:
Roman Tsisyk 2024-01-07 18:09:52 +02:00
parent ec59fa8dda
commit 732baca186
2 changed files with 39 additions and 0 deletions

View file

@ -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

View file

@ -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:')