i18n-translate-agent
Version:
An intelligent i18n translation agent powered by OpenAI, supporting automatic translation of JSON files with caching and progress tracking
245 lines (189 loc) β’ 7.49 kB
Markdown
# i18n-translate-agent
π An intelligent i18n translation agent powered by OpenAI, supporting automatic translation of JSON files with caching and progress tracking.
## β¨ Features
- **Multi-language Support**: Translate from one source language to multiple target languages
- **AI-Powered**: Uses OpenAI's GPT models (default: gpt-4o) for high-quality translations
- **Smart Caching**: Intelligent caching system to avoid re-translating unchanged content
- **Progress Tracking**: Real-time progress bars for translation tasks
- **Fine-tuning Support**: Customize translation context for domain-specific accuracy
- **JSON File Processing**: Automatically processes JSON internationalization files
- **Error Handling**: Comprehensive error logging and recovery
- **Batch Processing**: Efficient batch translation with configurable concurrency
## π¦ Installation
```bash
# Using npm
npm install i18n-translate-agent
# Using yarn
yarn add i18n-translate-agent
# Using pnpm
pnpm add i18n-translate-agent
```
## π Quick Start
```javascript
import { CwalletTranslate } from "i18n-translate-agent";
import path from "path";
// Get current directory
const __dirname = import.meta.dirname;
// Create translation instance
const translator = new CwalletTranslate({
key: "your-openai-api-key",
sourceLanguage: "en",
// Cache file path for optimized re-runs
cacheFileRootPath: path.resolve(__dirname, "./cache"),
// Source translation files path
fileRootPath: path.resolve(__dirname, "./locales"),
// Fine-tune translation context for better accuracy
fineTune: [
"We are blockchain developers",
"This is a cryptocurrency wallet application",
"Technical terms should be kept consistent",
],
// Target languages to translate to
languages: [
"zh-CN", // Simplified Chinese
"zh-TW", // Traditional Chinese
"ja", // Japanese
"ko", // Korean
"fr", // French
"de", // German
"es", // Spanish
"pt", // Portuguese
"ru", // Russian
"ar", // Arabic
],
// Output directory for translated files
outputRootPath: path.resolve(__dirname, "./locales"),
// Optional: Custom OpenAI configuration
openaiClientConfig: {
apiKey: "your-openai-api-key",
baseURL: "https://api.openai.com/v1", // Optional: custom endpoint
},
// Optional: Custom chat completion parameters
chatCompletionCreateParams: {
model: "gpt-4o",
temperature: 0.3,
max_tokens: 1000,
},
});
// Start translation
await translator.translate();
```
## π File Structure
Your project should have the following structure:
```
your-project/
βββ locales/
β βββ en/ # Source language folder
β βββ common.json
β βββ auth.json
β βββ dashboard.json
βββ cache/ # Generated cache files
β βββ zh-CN/
β βββ ja/
β βββ ...
βββ translate.js # Your translation script
```
### Example JSON Files
**locales/en/common.json**
```json
{
"welcome": "Welcome",
"loading": "Loading...",
"error": "An error occurred",
"save": "Save",
"cancel": "Cancel"
}
```
After translation, you'll get:
**locales/zh-CN/common.json**
```json
{
"welcome": "ζ¬’θΏ",
"loading": "ε θ½½δΈ...",
"error": "εηιθ――",
"save": "δΏε",
"cancel": "εζΆ"
}
```
## βοΈ Configuration Options
| Option | Type | Required | Description |
| ---------------------------- | ---------------------------- | -------- | ----------------------------------------------- |
| `key` | `string` | β
| OpenAI API key |
| `sourceLanguage` | `string` | β | Source language code (default: 'en') |
| `languages` | `string[]` | β
| Target language codes to translate to |
| `fileRootPath` | `string` | β
| Path to source translation files |
| `cacheFileRootPath` | `string` | β
| Path for cache files |
| `outputRootPath` | `string` | β | Output path (default: same as fileRootPath) |
| `fineTune` | `string[]` | β | Context strings for better translation accuracy |
| `openaiClientConfig` | `ClientOptions` | β | Custom OpenAI client configuration |
| `chatCompletionCreateParams` | `ChatCompletionCreateParams` | β | Custom chat completion parameters |
## π Supported Languages
The agent supports all major languages. Use standard language codes:
- `en` - English
- `zh-CN` - Simplified Chinese
- `zh-TW` - Traditional Chinese
- `ja` - Japanese
- `ko` - Korean
- `fr` - French
- `de` - German
- `es` - Spanish
- `pt` - Portuguese
- `ru` - Russian
- `ar` - Arabic
- `hi` - Hindi
- `th` - Thai
- `vi` - Vietnamese
- And many more...
## π οΈ Advanced Usage
### Custom Fine-tuning
```javascript
const translator = new CwalletTranslate({
// ... other options
fineTune: [
"This is a financial application",
"Cryptocurrency and blockchain terminology should be preserved",
"Keep technical terms in English when appropriate",
"Maintain formal tone throughout",
],
});
```
### Error Handling
```javascript
try {
await translator.translate();
console.log("Translation completed successfully!");
} catch (error) {
console.error("Translation failed:", error);
}
```
### Cache Management
```javascript
import { generateCache, deleteBatchCache } from "i18n-translate-agent";
// Generate cache for specific languages
await generateCache(["zh-CN", "ja"], "/path/to/cache");
// Clear cache for specific languages
await deleteBatchCache(["zh-CN", "ja"], "/path/to/cache");
```
## π Progress Tracking
The agent provides real-time progress tracking:
```
π Starting translation
π Model being used: gpt-4o π
π Fine-tuning: ['Technical context...'] π
π ~ Files to be translated: ['common.json', 'auth.json']
ββββββββββββββββββββββββββββββββββββββββ 100% | zh-CN:common.json 25/25
ββββββββββββββββββββββββββββββββββββββββ 100% | zh-CN:auth.json 30/30
ββββββββββββββββββββββββββββββββββββββββ 100% | ja:common.json 25/25
ββββββββββββββββββββββββββββββββββββββββ 100% | ja:auth.json 30/30
π Translation completed
```
## π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## π License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## πββοΈ Support
If you have any questions or need help, please [open an issue](https://github.com/victorLee11/i18n-translate-agent/issues).
## π Links
- [GitHub Repository](https://github.com/victorLee11/i18n-translate-agent)
- [NPM Package](https://www.npmjs.com/package/i18n-translate-agent)
- [OpenAI API Documentation](https://platform.openai.com/docs)