Last active
December 7, 2016 21:28
-
-
Save Ceda/626f9997e86f28830d1e562321053dff to your computer and use it in GitHub Desktop.
Translate a yaml file with Yandex Translation API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse; | |
import json; | |
import yaml; | |
import urllib.parse; | |
import urllib.request; | |
## | |
# Translation URI | |
## | |
uri = 'https://translate.yandex.net/api/v1.5/tr.json/translate?text=%s&lang=%s-%s&format=html&key=YANDEX-KEY'; | |
## | |
# Functions | |
## | |
def translate (string): | |
response = json.loads(urllib.request.urlopen(urllib.request.Request(uri % (urllib.parse.quote(string), args.source_locale, args.target_locale))).read().decode()); | |
return response['text'][0] if response['code'] == 200 else string; | |
def process (input): | |
output = {}; | |
for (k, v) in input.items(): | |
output[k] = process(v) if type(v) is dict else translate(v); | |
return output; | |
def read (): | |
with open(args.source, 'r') as stream: | |
try: | |
return yaml.safe_load(stream); | |
except yaml.YAMLError as exc: | |
print(exc); | |
def write(data): | |
with open(args.target, 'w') as stream: | |
try: | |
yaml.dump(data, stream, default_flow_style = False, allow_unicode = True, width = float('inf')) | |
except yaml.YAMLError as exc: | |
print(exc); | |
## | |
# Input Handling | |
## | |
parser = argparse.ArgumentParser(description = 'Translate the contents of a yaml file'); | |
parser.add_argument('source', help = 'The source yaml file you wish to translate'); | |
parser.add_argument('source_locale', help = 'The source file locale'); | |
parser.add_argument('target', help = 'The target yaml file you wish to translate'); | |
parser.add_argument('target_locale', help = 'The target file locale'); | |
args = parser.parse_args(); | |
write(process(read())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment