### Install translate-json package Source: https://github.com/yxor/translate-json/blob/main/README.md Install the package via pip. ```sh pip install translate-json ``` -------------------------------- ### Install translate-json Package Source: https://context7.com/yxor/translate-json/llms.txt Install the package using pip and set your Google Cloud Translate API key as an environment variable or in a .env file. ```bash pip install translate-json ``` ```bash export GOOGLE_TRANSLATE_TOKEN=your_google_translate_api_key ``` ```bash echo "GOOGLE_TRANSLATE_TOKEN=your_google_translate_api_key" > .env ``` -------------------------------- ### Define source JSON file Source: https://github.com/yxor/translate-json/blob/main/README.md Example input JSON file structure containing strings and nested objects. ```JSON { "title": "Hello World", "tags": { "lara": ["Video games", "swimming", "Interrupt routines"], "david": [ { "value": "Baseball", "count": 5 }, "Climbing trees" ] }, "example": { "title": "This will be translated", "ok": true } } ``` -------------------------------- ### View translated JSON output Source: https://github.com/yxor/translate-json/blob/main/README.md Example output files generated by the translation process. ```JSON { "title": "Bonjour le monde", "tags": { "lara": [ "Jeux vidéo", "la natation", "Routines d'interruption" ], "david": [ { "value": "Base-ball", "count": 5 }, "Grimper aux arbres" ] }, "example": { "title": "Cela sera traduit", "ok": true } } ``` ```JSON { "title": "Hallo Wereld", "tags": { "lara": [ "Computerspellen", "zwemmen", "Routines onderbreken" ], "david": [ { "value": "Basketbal", "count": 5 }, "Bomen klimmen" ] }, "example": { "title": "Dit wordt vertaald", "ok": true } } ``` -------------------------------- ### View CLI help and usage Source: https://github.com/yxor/translate-json/blob/main/README.md Display the command line interface help menu and argument definitions. ```text usage: translate-json [-h] -f FILE -s SOURCE_LANGUAGE [-o OUT] -l LANGS [LANGS ...] -k KEY Translate all string values in a JSON file to multiple languages using the google translate API. optional arguments: -h, --help show this help message and exit -f FILE, --file FILE The input file path -s SOURCE_LANGUAGE, --source-language SOURCE_LANGUAGE The source language code -o OUT, --out OUT The output directory path, will contain the created translation files -l LANGS [LANGS ...], --langs LANGS [LANGS ...] List of target languages you want to translate the file to -k KEY, --key KEY Google translate API key, don't set this if you already have a key set as the environement variable "GOOGLE_TRANSLATE_TOKEN" ``` -------------------------------- ### Import and use library in Python Source: https://github.com/yxor/translate-json/blob/main/README.md Programmatic usage of the library. Ensure the Google Cloud Translate API key is set as an environment variable. ```python from translate_json.translate import translate_all if __name__=="__main__": # you must set the google cloud translate API key as an environment variable before running this program translate_all('source.json', 'en', ['nl', 'de', 'fr'], './dist/') ``` -------------------------------- ### Utility Functions Source: https://context7.com/yxor/translate-json/llms.txt Helper functions for JSON file I/O and translation file path management. ```APIDOC ## Utility Functions ### open_json(path) - **Description**: Loads a JSON file into a dictionary. - **Parameters**: path (str) - Path to the JSON file. ### save_json(o, path) - **Description**: Saves a dictionary to a JSON file with UTF-8 encoding. - **Parameters**: - o (dict) - The data to save. - path (str) - The destination file path. ### translation_path(original_path, lang_code) - **Description**: Generates a translation filename using the convention {name}.{lang_code}.json. - **Parameters**: - original_path (str) - The base filename. - lang_code (str) - The target language code. ``` -------------------------------- ### Execute CLI translation Source: https://github.com/yxor/translate-json/blob/main/README.md Run the translation command to process the source file into Dutch and French. ```sh translate-json -f source.json -s en -o ./translations/ -l nl fr -k YOUR_API_KEY ``` -------------------------------- ### JSON File I/O and Translation Path Utilities Source: https://context7.com/yxor/translate-json/llms.txt Provides utility functions for loading JSON files into dictionaries, saving dictionaries to JSON files (preserving UTF-8), and generating language-specific translation filenames. The `translation_path` function creates filenames in the format 'basename.lang.ext'. ```python from translate_json.utils import open_json, save_json, translation_path # Load a JSON file into a dictionary data = open_json('locales/en.json') # Returns: {"key": "value", ...} # Save a dictionary to a JSON file (UTF-8, non-ASCII characters preserved) save_json( o={"greeting": "Bonjour le monde"}, path='locales/fr.json' ) # Generate a translation filename filename = translation_path('locales/messages.json', 'de') print(filename) # Output: "messages.de.json" # Full workflow example import os source = open_json('source.json') # ... perform translations ... output_path = os.path.join('./output/', translation_path('source.json', 'es')) save_json(translated_data, output_path) # Creates: ./output/source.es.json ``` -------------------------------- ### translate() Source: https://context7.com/yxor/translate-json/llms.txt Performs a single string translation using the Google Cloud Translate API. ```APIDOC ## translate(value, source, target) ### Description Translates a single string from a source language to a target language using the Google Cloud Translate API. ### Parameters - **value** (str) - Required - The text string to translate. - **source** (str) - Required - The language code of the source text. - **target** (str) - Required - The language code to translate into. ### Response - **Returns** (str) - The translated text. - **Raises** (TranslationError) - If the API call fails due to invalid keys or unsupported language codes. ``` -------------------------------- ### Exception Classes Source: https://context7.com/yxor/translate-json/llms.txt Custom exceptions for handling translation and argument errors. ```APIDOC ## Exception Classes ### TranslationError - **Description**: Raised when the Google Cloud Translate API fails (e.g., invalid API key, network issues). ### BadArgumentException - **Description**: Raised for invalid CLI arguments, such as missing files, invalid language codes, or incorrect output paths. ``` -------------------------------- ### Handling Translation API and Argument Exceptions Source: https://context7.com/yxor/translate-json/llms.txt Demonstrates the use of custom exception classes: `TranslationError` for Google Translate API failures and `BadArgumentException` for invalid command-line arguments. The `TranslationError` catch block provides a sample error message. ```python from translate_json.utils import TranslationError, BadArgumentException from translate_json.translate import translate import os os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_api_key" # TranslationError: raised when Google Translate API fails try: result = translate("Hello", "en", "invalid_lang_code") except TranslationError as e: print(f"API Error: {e}") # "Error getting the data from google translate API, # make sure you are using valid API key and language codes" # BadArgumentException: raised for invalid CLI arguments # This is used internally by ConsoleManager for validation: # - Invalid or non-existent input file # - Missing source language # - Empty target languages list # - Invalid output directory path ``` -------------------------------- ### Translate JSON File via CLI Source: https://context7.com/yxor/translate-json/llms.txt Use the translate-json command to translate a JSON file to specified languages. Output files are named with the pattern {filename}.{lang}.json. The API key can be provided directly or via an environment variable. ```bash translate-json -f source.json -s en -o ./translations/ -l nl fr -k YOUR_API_KEY ``` ```bash export GOOGLE_TRANSLATE_TOKEN=YOUR_API_KEY translate-json -f source.json -s en -o ./translations/ -l nl fr de es ``` ```bash translate-json -f locales/en.json -s en -l ja zh ko ``` -------------------------------- ### CLI Usage: translate-json Source: https://context7.com/yxor/translate-json/llms.txt Command-line interface for translating JSON files. It supports specifying source and target languages, input files, and output directories. API key can be provided directly or via environment variable. ```APIDOC ## CLI Usage: translate-json ### Description The `translate-json` command translates a JSON file to one or more target languages, outputting separate files for each language with the naming pattern `{filename}.{lang}.json`. ### Method CLI Command ### Endpoint N/A (Command-line tool) ### Parameters #### Command-line Arguments - **-f, --file** (string) - Required - Path to the source JSON file. - **-s, --source** (string) - Required - ISO 639-1 source language code. - **-o, --output** (string) - Optional - Output directory for translated files. Defaults to the current directory. - **-l, --languages** (string) - Required - Comma-separated list of target ISO 639-1 language codes. - **-k, --key** (string) - Optional - Google Cloud Translate API key. If not provided, it looks for the `GOOGLE_TRANSLATE_TOKEN` environment variable. ### Request Example ```bash # Basic usage: translate source.json from English to Dutch and French translate-json -f source.json -s en -o ./translations/ -l nl fr -k YOUR_API_KEY # Using environment variable for API key (recommended) export GOOGLE_TRANSLATE_TOKEN=YOUR_API_KEY translate-json -f source.json -s en -o ./translations/ -l nl fr de es # Output to current directory (default when -o is omitted) translate-json -f locales/en.json -s en -l ja zh ko ``` ### Response #### Output Files (200) - Files are generated in the specified output directory (or current directory) with the pattern `{filename}.{lang}.json` for each target language. - Non-string values (numbers, booleans, nulls) are preserved unchanged. ### Response Example ```json # Example input file (source.json): # { # "title": "Hello World", # "tags": { # "lara": ["Video games", "swimming", "Interrupt routines"], # "david": [ # {"value": "Baseball", "count": 5}, # "Climbing trees" # ] # }, # "example": {"title": "This will be translated", "ok": true} # } # Output files created in ./translations/ directory: # translations/source.nl.json # translations/source.fr.json ``` ``` -------------------------------- ### Batch Translate JSON File Programmatically Source: https://context7.com/yxor/translate-json/llms.txt The translate_all function translates a source JSON file to multiple target languages and saves each translation to a separate file in the specified output directory. Ensure the API key is set via the environment variable. ```python from translate_json.translate import translate_all import os os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_google_translate_api_key" translate_all( input_path='locales/en.json', source_language='en', target_languages=['nl', 'de', 'fr'], output_dir='./dist/' ) ``` -------------------------------- ### translate_all() Function Source: https://context7.com/yxor/translate-json/llms.txt Python function for batch translation of JSON files. It reads a source JSON, translates it to specified target languages, and saves each translation to a separate file. ```APIDOC ## translate_all() ### Description The `translate_all` function is the primary programmatic interface for batch translation. It reads a source JSON file, translates it to all specified target languages, and saves each translation to a separate output file. ### Method Python Function ### Endpoint N/A (Python library function) ### Parameters #### Function Parameters - **input_path** (string) - Required - Path to the source JSON file. - **source_language** (string) - Required - ISO 639-1 source language code. - **target_languages** (list of strings) - Required - List of target ISO 639-1 language codes. - **output_dir** (string) - Optional - Output directory for translated files. Defaults to the current directory. - **api_key** (string) - Optional - Google Cloud Translate API key. If not provided, it looks for the `GOOGLE_TRANSLATE_TOKEN` environment variable. ### Request Example ```python from translate_json.translate import translate_all import os # Set API key via environment variable (recommended) os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_google_translate_api_key" # Translate a JSON file to multiple languages translate_all( input_path='locales/en.json', # Source JSON file path source_language='en', # ISO 639-1 source language code target_languages=['nl', 'de', 'fr'], # List of target language codes output_dir='./dist/' # Output directory for translated files ) ``` ### Response #### Output Files (200) - Separate JSON files are created in the specified `output_dir` for each target language. - File naming convention: `{input_filename_without_extension}.{target_language_code}.json`. ### Response Example ```python # Output files created in ./dist/ directory: # - dist/en.nl.json (Dutch) # - dist/en.de.json (German) # - dist/en.fr.json (French) ``` ``` -------------------------------- ### Translate Single String with Google Cloud API Source: https://context7.com/yxor/translate-json/llms.txt Performs a single string translation using the Google Cloud Translate API. Ensure the GOOGLE_TRANSLATE_TOKEN environment variable is set with your API key. Handles TranslationError for API failures. ```python from translate_json.translate import translate from translate_json.utils import TranslationError import os os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_google_translate_api_key" try: # Translate a single string from English to German result = translate( value="Hello, how are you?", source="en", target="de" ) print(result) # Output: "Hallo, wie geht es dir?" # Translate to Japanese japanese = translate("Welcome to our application", "en", "ja") print(japanese) # Output: "私たちのアプリケーションへようこそ" except TranslationError as e: # Handle API errors (invalid key, unsupported language, etc.) print(f"Translation failed: {e}") ``` -------------------------------- ### Translate Dictionary Object Programmatically Source: https://context7.com/yxor/translate-json/llms.txt The translate_object function recursively translates string values within a dictionary, preserving nested structures and non-string data types. The API key must be set in the environment. ```python from translate_json.translate import translate_object import os os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_google_translate_api_key" source_data = { "greeting": "Hello World", "count": 42, "active": True, "items": ["Apple", "Banana"], "nested": { "message": "Welcome back", "code": 200 } } translated = translate_object(source_data, source='en', target='es') ``` -------------------------------- ### translate_object() Function Source: https://context7.com/yxor/translate-json/llms.txt Python function to recursively translate string values within a dictionary, preserving the original JSON structure and non-string data types. ```APIDOC ## translate_object() ### Description The `translate_object` function recursively translates all string values within a dictionary, preserving the structure and non-string values. It handles nested objects and arrays automatically. ### Method Python Function ### Endpoint N/A (Python library function) ### Parameters #### Function Parameters - **data** (dict) - Required - The dictionary (JSON object) to translate. - **source** (string) - Required - ISO 639-1 source language code. - **target** (string) - Required - ISO 639-1 target language code. - **api_key** (string) - Optional - Google Cloud Translate API key. If not provided, it looks for the `GOOGLE_TRANSLATE_TOKEN` environment variable. ### Request Example ```python from translate_json.translate import translate_object import os os.environ["GOOGLE_TRANSLATE_TOKEN"] = "your_google_translate_api_key" # Source dictionary with nested structures source_data = { "greeting": "Hello World", "count": 42, # Numbers preserved "active": True, # Booleans preserved "items": ["Apple", "Banana"], # Arrays translated "nested": { "message": "Welcome back", "code": 200 } } # Translate from English to Spanish translated = translate_object(source_data, source='en', target='es') ``` ### Response #### Translated Object (200) - Returns a new dictionary with all string values translated to the target language. - Non-string values (numbers, booleans, nulls) and the original structure are preserved. ### Response Example ```python # Result: # { # "greeting": "Hola Mundo", # "count": 42, # "active": True, # "items": ["Manzana", "Plátano"], # "nested": { # "message": "Bienvenido de nuevo", # "code": 200 # } # } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.