JustPaste.it
User avatar
@anonymous · Nov 19, 2023
import os
import yaml
from googletrans import Translator

def translate_recursive(obj, translator, source_language='tr', target_language='ku'):
    if isinstance(obj, str):
        # Translate the text
        translation = translator.translate(obj, src=source_language, dest=target_language).text
        return translation
    elif isinstance(obj, dict):
        # Iterate through the dictionary and translate each value
        return {key: translate_recursive(value, translator) for key, value in obj.items()}
    elif isinstance(obj, list):
        # Iterate through the list and translate each item
        return [translate_recursive(item, translator) for item in obj]
    else:
        # Leave other data types as they are
        return obj

def translate_yaml_file(input_file, output_file, translator):
    # Read the YAML file
    with open(input_file, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)

    # Apply translation
    translated_data = translate_recursive(data, translator)

    # Write translated data to a new YAML file
    with open(output_file, 'w', encoding='utf-8') as file:
        yaml.dump(translated_data, file, default_flow_style=False, allow_unicode=True)

def main():
    # Create a Translator object for Google Translate API
    translator = Translator()

    # Input and output folders
    input_folder = "locale"
    output_folder = "locale1"

    # Create the output folder if it doesn't exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # Iterate through all YAML files in the input folder
    for filename in os.listdir(input_folder):
        if filename.endswith(".yaml"):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename)

            # Translate YAML file and print the file name
            translate_yaml_file(input_path, output_path, translator)
            print(f"Translated: {filename}")

    # List untranslated files
    untranslated_files = [filename for filename in os.listdir(input_folder) if filename.endswith(".yaml")]
    if untranslated_files:
        print("\nUntranslated files:")
        for filename in untranslated_files:
            print(filename)

if __name__ == "__main__":
    main()