Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pricklywiggles/dfd50d4b2fc64e465b88754e372f0c9e to your computer and use it in GitHub Desktop.
Save pricklywiggles/dfd50d4b2fc64e465b88754e372f0c9e to your computer and use it in GitHub Desktop.
Google cloud translate script for YML files
import yaml
import sys
import os
from google.cloud import translate_v2 as translate
def translate_text(text, target_language):
if isinstance(text, str):
result = translate_client.translate(text, target_language=target_language)
return result['translatedText']
elif isinstance(text, list):
return [translate_text(item, target_language) for item in text]
elif isinstance(text, dict):
return {key: translate_text(value, target_language) for key, value in text.items()}
else:
return text
def translate_and_save(yaml_content, target_language, output_file):
original_key = list(yaml_content.keys())[0]
content_to_translate = yaml_content[original_key]
translated_content = translate_text(content_to_translate, target_language)
yaml_content_translated = {target_language: translated_content}
# Create the output directory if it doesn't exist
os.makedirs(os.path.dirname(output_file), exist_ok=True)
# Write the translated content back to a new YAML file
with open(output_file, 'w') as file:
yaml.dump(yaml_content_translated, file, allow_unicode=True, default_flow_style=False)
print(f"Translation to '{target_language}' complete. Check '{output_file}'.")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python translate_yaml.py input_file [target_language_code]")
sys.exit(1)
input_file = sys.argv[1]
target_languages = sys.argv[2:]
if not target_languages:
target_languages = [
"af", "am", "ar", "az", "be", "bn", "bs", "cs", "da", "de", "el", "es", "et",
"fa", "fi", "fr", "hi", "hr", "hu", "hy", "id", "is", "it", "ja", "ka", "kk",
"km", "ko", "lb", "lo", "lt", "mk", "mn", "mt", "my", "ne", "nl", "no", "ny",
"pa", "pl", "ps", "pt", "ro", "ru", "si", "sk", "sl", "sm", "so", "sq", "sr",
"su", "sv", "sw", "ta", "tg", "th", "tk", "tl", "tr", "uk", "ur", "uz", "vi",
"xh", "zh", "zh-TW", "zu"
]
# Initialize the translate client
translate_client = translate.Client()
# Read the YAML file
with open(input_file, 'r') as file:
yaml_content = yaml.safe_load(file)
base_name = os.path.splitext(os.path.basename(input_file))[0]
for target_language in target_languages:
output_file = f"output/{base_name}.{target_language}.yml"
translate_and_save(yaml_content, target_language, output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment