You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Fast and efficient JSON i18n translator supporting multiple AI providers (Google Gemini, OpenAI & Ollama/DeepSeek) with intelligent caching, multi-file deduplication, and MCP integration.
Features
Multiple AI Providers: Choose between Google Gemini, OpenAI (cloud) or Ollama/DeepSeek (local) for translations
Multi-File Support: Process multiple files with automatic deduplication to save API calls
Incremental Caching: Only translates new or modified strings, dramatically reducing API calls
Batch Processing: Intelligently batches translations for optimal performance
Path Preservation: Maintains exact JSON structure including nested objects and arrays
Cross-Platform: Works on Windows, macOS, and Linux with automatic cache directory detection
Developer Friendly: Built-in performance statistics and progress indicators
Cost Effective: Minimizes API usage through smart caching and deduplication
Language Detection: Automatically detect source language instead of assuming English
Multiple Target Languages: Translate to multiple languages in a single command
Translation Metadata: Optionally include translation details in output files for tracking
Dry Run Mode: Preview what would be translated without making API calls
Format Preservation: Maintains URLs, emails, dates, numbers, and template variables unchanged
Installation
Global Installation (Recommended)
npm install -g translator-ai
Local Installation
npm install translator-ai
Configuration
Option 1: Google Gemini API (Cloud)
Create a .env file in your project root or set the environment variable:
translator-ai source.json -l es -o spanish.json --provider ollama
Usage
Basic Usage
# Translate a single file translator-ai source.json -l es -o spanish.json
# Translate multiple files with deduplication translator-ai src/locales/en/*.json -l es -o "{dir}/{name}.{lang}.json"
# Use glob patterns translator-ai "src/**/*.en.json" -l fr -o "{dir}/{name}.fr.json"
Command Line Options
translator-ai [options]
Arguments: inputFiles Path(s) to source JSON file(s) or glob patterns
Options: -l, --lang Target language code(s), comma-separated for multiple -o, --output Output file path or pattern --stdout Output to stdout instead of file --stats Show detailed performance statistics --no-cache Disable incremental translation cache --cache-file Custom cache file path --provider Translation provider: gemini, openai, or ollama (default: gemini) --ollama-url Ollama API URL (default: http://localhost:11434) --ollama-model Ollama model name (default: deepseek-r1:latest) --gemini-model Gemini model name (default: gemini-2.0-flash-lite) --openai-model OpenAI model name (default: gpt-4o-mini) --list-providers List available translation providers --verbose Enable verbose output for debugging --detect-source Auto-detect source language instead of assuming English --dry-run Preview what would be translated without making API calls --preserve-formats Preserve URLs, emails, numbers, dates, and other formats --metadata Add translation metadata to output files (may break some i18n parsers) --sort-keys Sort output JSON keys alphabetically --check-keys Verify all source keys exist in output (exit with error if keys are missing) -h, --help Display help -V, --version Display version
Output Pattern Variables (for multiple files): {dir} - Original directory path {name} - Original filename without extension {lang} - Target language code
Examples
Translate a single file
translator-ai en.json -l es -o es.json
Translate multiple files with pattern
# All JSON files in a directory translator-ai locales/en/*.json -l es -o "locales/es/{name}.json"
Once configured, you can ask Claude to translate files:
{
"inputFile": "locales/en.json",
"targetLanguage": "es",
"outputFile": "locales/es.json"
}
Successfully translated! The file has been saved to locales/es.json.">Human: Can you translate my English locale file to Spanish?
Claude: I'll translate your English locale file to Spanish using translator-ai.
Successfully translated! The file has been saved to locales/es.json.
For multiple files with deduplication:
{
"pattern": "locales/en/*.json",
"targetLanguage": "de",
"outputPattern": "locales/de/{name}.json",
"showStats": true
}
Translation complete! Processed 5 files with 23% deduplication savings.">Human: Translate all my English JSON files in the locales folder to German.
Claude: I'll translate all your English JSON files to German with deduplication.
defjson_to_yaml(json_str): """Convert JSON back to YAML""" data=json.loads(json_str) returnyaml.dump(data, allow_unicode=True, default_flow_style=False)
deftranslate_yaml_file(input_yaml, target_lang, output_yaml): """Translate a YAML file using translator-ai"""
Hugo supports two translation methods: by filename (about.en.md, about.fr.md) or by content directory (content/en/, content/fr/). Here's how to automate both:
Method 1: Translation by Filename
Create hugo-translate-files.sh:
temp_frontmatter.yaml
# Convert front matter to JSON
npx js-yaml temp_frontmatter.yaml > temp_frontmatter.json
# Translate front matter
translator-ai temp_frontmatter.json -l "$lang" -o "temp_translated.json"
# Convert back to YAML
echo "---" > "$output_file"
npx js-yaml temp_translated.json >> "$output_file"
echo "---" >> "$output_file"
# Copy content (you might want to translate this too)
awk '/^---$/{p++} p==2{print}' "$file" | tail -n +2 >> "$output_file"
echo "Created $output_file"
done
# Cleanup
rm -f temp_frontmatter.yaml temp_frontmatter.json temp_translated.json
done">#!/bin/bash # Translate Hugo content files using filename convention
SOURCE_LANG="en" TARGET_LANGS=("es""fr""de""ja")
# Find all English content files find content -name "*.${SOURCE_LANG}.md"|whileread -r file;do # Extract base filename without language suffix base_name="${file%.${SOURCE_LANG}.md}"
# Translate everything .PHONY: all all: translate translate-theme
Usage:
# Translate to all languages make all
# Translate to specific language make translate-es
# Translate theme files make translate-theme
Complete Hugo Translation Workflow
Here's a comprehensive script that handles both content and i18n translations:
{
if (frontMatter[field]) {
translatable[field] = frontMatter[field];
}
});
return translatable;
}
async convertToJson(inputFile, outputFile) {
const ext = path.extname(inputFile);
const content = await fs.readFile(inputFile, 'utf8');
let data;
if (ext === '.yaml' || ext === '.yml') {
data = yaml.load(content);
} else if (ext === '.toml') {
// You'd need a TOML parser here
throw new Error('TOML support not implemented in this example');
}
await fs.writeJson(outputFile, data, { spaces: 2 });
}
async convertFromJson(inputFile, outputFile, format) {
const data = await fs.readJson(inputFile);
let content;
if (format === '.yaml' || format === '.yml') {
content = yaml.dump(data, {
indent: 2,
lineWidth: -1,
noRefs: true
});
} else if (format === '.toml') {
throw new Error('TOML support not implemented in this example');
}
await fs.writeFile(outputFile, content);
}
async updateConfig() {
console.log('\nUpdating Hugo config...');
const configFile = glob.sync('config.{yaml,yml,toml,json}')[0];
if (!configFile) return;
// This is a simplified example - you'd need to properly parse and update
console.log(' ! Remember to update your config.yaml with language settings');
}
}
// Run the translator
if (require.main === module) {
const translator = new HugoTranslator(['es', 'fr', 'de']);
translator.translateSite().catch(console.error);
}
module.exports = HugoTranslator;">#!/usr/bin/env node // hugo-complete-translator.js constfs=require('fs-extra'); constpath=require('path'); constyaml=require('js-yaml'); const{ execSync }=require('child_process'); constglob=require('glob');
if(ext==='.yaml'||ext==='.yml'){ data=yaml.load(content); }elseif(ext==='.toml'){ // You'd need a TOML parser here thrownewError('TOML support not implemented in this example'); }
if(format==='.yaml'||format==='.yml'){ content=yaml.dump(data,{ indent: 2, lineWidth: -1, noRefs: true }); }elseif(format==='.toml'){ thrownewError('TOML support not implemented in this example'); }
awaitfs.writeFile(outputFile,content); }
asyncupdateConfig(){ console.log('\nUpdating Hugo config...');
// This is a simplified example - you'd need to properly parse and update console.log(' ! Remember to update your config.yaml with language settings'); } }
// Run the translator if(require.main===module){ consttranslator=newHugoTranslator(['es','fr','de']); translator.translateSite().catch(console.error); }
module.exports=HugoTranslator;
Using with Hugo Modules
If you're using Hugo Modules, you can create a translation module:
Preserve formatting: Use js-yaml with proper options to maintain YAML structure
Handle special characters: Ensure proper encoding (UTF-8) throughout
Validate output: Some YAML features (anchors, aliases) may need special handling
Consider TOML: For Hugo, you might also need to handle TOML config files
Alternative: Direct YAML Support (Feature Request)
If you frequently work with YAML files, consider creating a wrapper script that handles conversion automatically, or request YAML support as a feature for translator-ai.
Development
Building from source
git clone https://github.com/DatanoiseTV/translator-ai.git cd translator-ai npm install npm run build
Testing locally
npm start -- test.json -l es -o output.json
License
This project requires attribution for both commercial and non-commercial use. See LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For issues, questions, or suggestions, please open an issue on GitHub.
If you find this tool useful, consider supporting the development:
About
Multi-provider AI translation tool for JSON i18n files. Features: Google Gemini & Ollama support, incremental caching, multi-file deduplication, MCP server, batch processing, and cross-platform compatibility. Ideal for developers managing multilingual applications.