i18n-ai-translate开源程序,可以使用DeepSeek等模型将您的 i18nJSON翻译成任何语言
一、软件介绍
文末提供程序和源码下载
i18n-ai-translate开源程序使用 DeepSeek等模型可以将您的 i18n JSON 翻译成任何语言。 无缝翻译本地化文件。支持嵌套翻译文件的目录。需要i18next样式的JSON 文件(文末一并提供下载)。
二、模式
CSV 模式
三个提示链接在一起,以确保每个翻译格式正确。
- 翻译提示尝试翻译
- 翻译验证提示使用单独的上下文来验证翻译
- 样式验证提示使用另一个上下文来验证翻译的格式是否与源一致
JSON 模式
翻译和验证分两个单独的步骤完成。
- 翻译提示尝试翻译整个文件
- 翻译验证提示会验证/修复并再次验证每一行。
- 在两次调用之间保留历史记录,以确保翻译整个文件时的一致性。
三、Usage 用法
Quick-start 快速启动
GitHub Actions GitHub 作
使用 GitHub Action 将其合并到您的 CI 中,以将每个拉取请求的密钥自动转换为新提交。所有可配置选项均以 action.yml 形式提供。
下面翻译了 i18n/en.json
被修改的每个 PR:
name: i18n-ai-translateon:pull_request:# Only trigger when en.json has been modifiedpaths:- "i18n/en.json"jobs:build:runs-on: ubuntu-lateststeps:- name: i18n-ai-translateuses: taahamahdi/i18n-ai-translate@masterwith:json-file-path: i18n/en.jsonapi-key: ${{ secrets.OPENAI_API_KEY }}
四、Running directly 直接运行
git clone git@github.com:taahamahdi/i18n-ai-translate.git cd i18n-ai-translate yarn cp /home/en.json jsons/# Generate French translations npm run i18n-ai-translate -- translate -i en.json -o fr.json --engine chatgpt --model gpt-4o --api-key <openai_key>
Running as a script in your own project在您自己的项目中作为脚本运行
yarn add i18n-ai-translate# Generate French translations npx i18n-ai-translate translate -i en.json -o fr.json --engine gemini --model gemini-2.0-flash-exp --api-key <gemini_key># Or, assuming you already have other translations in the current directory npx i18n-ai-translate diff --before en-before.json --after en.json --input-language English --engine claude --model claude-3-5-sonnet-latest --api-key <anthropic_key>
Running as a library 作为库运行
import { translate } from "i18n-ai-translate"; ... const englishJSON = {"welcomeMessage": "Welcome, {{name}}!","messages": {"notifications_one": "You have one notification","notifications_other": "You have {{count}} notifications","delete": "Would you like to delete the \"{{name}}\" category?"} };const frenchTranslation = await translate({inputJSON: englishJSON,inputLanguage: "English",outputLanguage: "French",... });console.log(frenchTranslation);
{"welcomeMessage": "Bienvenue, {{name}} !","messages": {"notifications_one": "Vous avez une notification","notifications_other": "Vous avez {{count}} notifications","delete": "Voulez-vous supprimer la catégorie « {{name}} » ?"} }
Script 脚本
Use i18n-ai-translate translate
to convert a local i18n JSON file to any language. Relative paths begin from the jsons/
directory.
使用 i18n-ai-translate translate 将
本地 i18n JSON 文件转换为任何语言。相对路径从 jsons/
目录开始。
Use i18n-ai-translate diff
to find the differences between two versions of a source language file, and apply them to all language files in the same directory.
使用 i18n-ai-translate diff
查找源语言文件的两个版本之间的差异,并将它们应用于同一目录中的所有语言文件。
Create a .env
file with an entry for your API key, or pass the --api-key
flag.
创建一个包含 API 密钥条目的 .env
文件,或传递 --api-key
标志。
GEMINI_API_KEY=<your Gemini API key>
OPENAI_API_KEY=<your OpenAI API key>
ANTHROPIC_API_KEY=<your Anthropic API key>
For Ollama, create an entry for your host, use the --host
flag to set a custom host and path (Defaults to localhost:11434
).
对于 Ollama,为您的主机创建一个条目,使用 --host
标志设置自定义主机和路径(默认为 localhost:11434
)。
OLLAMA_HOSTNAME=<the server and port number running Ollama>
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>Usage: i18n-ai-translate [options] [command]Use ChatGPT or Gemini to translate your i18n JSON to any languageOptions:-V, --version output the version number-h, --help display help for commandCommands:translate [options]diff [options]help [command] display help for command
</code></span></span></span></span>
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>Usage: i18n-ai-translate translate [options]Options:-i, --input <input> Source i18n file or path of source language, in the jsons/ directory if a relative path is given-o, --output-languages [language codes...] A list of languages to translate to-e, --engine <engine> Engine to use (chatgpt, gemini, ollama, or claude)-m, --model <model> Model to use (e.g. gpt-4o, gemini-2.0-flash-exp, llama3.3, claude-3-5-sonnet-latest)-r, --rate-limit-ms <rateLimitMs> How many milliseconds between requests (defaults to 1s for Gemini, 120ms (at 500RPM) for ChatGPT, 1200msfor Claude)-f, --force-language-name <language name> Force output language name-A, --all-languages Translate to all supported languages-p, --templated-string-prefix <prefix> Prefix for templated strings (default: "{{")-s, --templated-string-suffix <suffix> Suffix for templated strings (default: "}}")-k, --api-key <API key> API key-h, --host <hostIP:port> The host and port number serving Ollama. 11434 is the default port number.--ensure-changed-translation Each generated translation key must differ from the input (for keys longer than 4) (default: false)-n, --batch-size <batchSize> How many keys to process at a time (default: "32")--skip-translation-verification Skip validating the resulting translation through another query (default: false)--skip-styling-verification Skip validating the resulting translation's formatting through another query (default: false)--override-prompt <path to JSON file> Use the prompts from the given JSON file, containing keys for at least one of generationPrompt,translationVerificationPrompt, stylingVerificationPrompt--prompt-mode <prompt-mode> Chose between 'csv' mode for better performance and 'json' mode for better compatibility,--batch-max-tokens <batch-max-tokens> For json mode only, maximum size of a single request in tokens--verbose Print logs about progress (default: false)--help display help for command
</code></span></span></span></span>
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>Usage: i18n-ai-translate diff [options]Options:-b, --before <fileOrDirectoryBefore> Source i18n file or directory before changes, in the jsons/ directory if a relative path is given-a, --after <fileOrDirectoryAfter> Source i18n file or directory after changes, in the jsons/ directory if a relative path is given-l, --input-language <inputLanguageCode> The input language's code, in ISO6391 (e.g. en, fr)-e, --engine <engine> Engine to use (chatgpt, gemini, ollama, or claude)-m, --model <model> Model to use (e.g. gpt-4o, gemini-2.0-flash-exp, llama3.3, claude-3-5-sonnet-latest)-r, --rate-limit-ms <rateLimitMs> How many milliseconds between requests (defaults to 1s for Gemini, 120ms (at 500RPM) for ChatGPT, 1200ms forClaude)-k, --api-key <API key> API key-h, --host <hostIP:port> The host and port number serving Ollama. 11434 is the default port number.--ensure-changed-translation Each generated translation key must differ from the input (for keys longer than 4) (default: false)-p, --templated-string-prefix <prefix> Prefix for templated strings (default: "{{")-s, --templated-string-suffix <suffix> Suffix for templated strings (default: "}}")-n, --batch-size <batchSize> How many keys to process at a time (default: "32")--skip-translation-verification Skip validating the resulting translation through another query (default: false)--skip-styling-verification Skip validating the resulting translation's formatting through another query (default: false)--override-prompt <path to JSON file> Use the prompts from the given JSON file, containing keys for at least one of generationPrompt,translationVerificationPrompt, stylingVerificationPrompt--prompt-mode <prompt-mode> Chose between 'csv' mode for better performance and 'json' mode for better compatibility,--batch-max-tokens <batch-max-tokens> For json mode only, maximum size of a single request in tokens--verbose Print logs about progress (default: false)--help display help for command
</code></span></span></span></span>
Example usage 用法示例
npx i18n-ai-translate translate -i en.json -o fr
- Translate the
en.json
file injsons/
to French, and save the output infr.json
将jsons/
中的en.json
文件翻译成法语,并将输出保存在fr.json
中
npx i18n-ai-translate translate -i en.json -o es de nl --engine gemini
- Translate the
en.json
file injsons/
to Spanish, German, and Dutch, and save each file injsons/
, using Google Gemini
使用 Google Gemini 将jsons/
中的en.json
文件翻译成西班牙语、德语和荷兰语,并将每个文件保存在jsons/
中
npx i18n-ai-translate diff -b en.json -a en-after.json -l English --verbose --engine ollama --host my-olllama-server.com:12345
- Translate the keys that have changed between
en.json
anden-after.json
for all files in theen.json
directory, with logging enabled using Ollama running onmy-ollama-server.com:12345
转换en.json
目录中所有文件的en.json
和en-after.json
之间更改的键,并使用在my-ollama-server.com:12345
上运行的 Ollama 启用日志记录
npx i18n-ai-translate translate -i en.json -A --engine chatgpt --model gpt-4-turbo --api-key <my_key> --rate-limit-ms 150 -n 64
- Translate the
en.json
file injsons/
to 200+ languages, save each file injsons/
, using the GPT-4 Turbo model of ChatGPT, with the given key, a rate limit of 150ms between requests, and 64 keys sent in each batch
将jsons/
的en.json
文件翻译成 200+ 种语言,使用 ChatGPT 的 GPT-4 Turbo 模型,使用给定的 key,请求之间的限速为 150ms,每批发送 64 个 key
npx i18n-ai-translate diff -b en -a en-after --engine claude
- Translate the keys that have changed between
en/
anden-after/
for all JSON files in both directories using Claude
使用 Claude 翻译两个目录中所有 JSON 文件的en/
和en-after/
之间更改的键
五、As a library 作为库
或者,导入此项目并使用它通过 translate() 即时转换 JSON,或者在源 i18n 文件发生更改时使用 translateDiff() 获取已修改键的更新。
import { translate, translateDiff } from "i18n-ai-translate";...const translation = await translate({apiKey, // OpenAI/Gemini/Anthropic API keybatchMaxTokens, // Maximum amount of tokens for one requestbatchSize, // How many keys to process at a timechatParams, // Additional configuration to pass to the modelengine, // ChatGPT, Gemini, Ollama, or ClaudeensureChangedTranslation, // Every key longer than 4 characters must be different than the inputhost, // The host and port number running OllamainputJSON, // JSON to translateinputLanguage, // Language of inputJSONmodel, // Model to use (e.g. gpt-4o, gemini-2.0-flash-exp, llama3.3, claude-3-5-sonnet-latest)outputLanguage, // Targeted language (e.g. French, Spanish, etc.)overridePrompt, // Set custom prompts for generation or verificationpromptMode, // Chose between 'csv' mode and 'json' moderateLimitMs, // How many milliseconds between requestsskipStylingVerification, // Whether to skip an additional query to see whether the text formatting remained consistentskipTranslationVerification, // Whether to skip an additional query to see whether the resultant translation makes sensetemplatedStringPrefix, // The start of inline variables; defaults to "{{"templatedStringSuffix, // The end of inline variables; defaults to "}}"verbose, // Print status of conversion to stdout/stderr});const translations = await translateDiff({apiKey, // OpenAI/Gemini/Anthropic API keybatchMaxTokens, // Maximum amount of tokens for one requestbatchSize, // How many keys to process at a timechatParams, // Additional configuration to pass to the modelengine, // ChatGPT, Gemini, Ollama, or ClaudeensureChangedTranslation, // Every key longer than 4 characters must be different than the inputhost, // The host and port number running OllamainputJSONAfter, // The source translation after a changeinputJSONBefore, // The source translation before a changeinputLanguage, // Language of inputJSONBefore/Aftermodel, // Model to use (e.g. gpt-4o, gemini-2.0-flash-exp, llama3.3, claude-3-5-sonnet-latest)overridePrompt, // Set custom prompts for generation or verificationpromptMode, // Chose between 'csv' mode and 'json' moderateLimitMs, // How many milliseconds between requestsskipStylingVerification, // Whether to skip an additional query to see whether the text formatting remained consistentskipTranslationVerification, // Whether to skip an additional query to see whether the resultant translation makes sensetemplatedStringPrefix, // The start of inline variables; defaults to "{{"templatedStringSuffix, // The end of inline variables; defaults to "}}"toUpdateJSONs, // An object of language codes to their translationsverbose, // Print status of conversion to stdout/stderr });
六、CSV Mode CSV 模式
Translation prompt 翻译提示
Batches of the i18n input are passed in. Each call is checked to ensure no keys are lost, all templated strings are retained, and no translations were skipped.
传入 i18n 输入的批次。检查每个调用以确保没有键丢失,所有模板化字符串都被保留,并且没有跳过任何翻译。
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>You are a professional translator.Translate each line from ${inputLanguage} to ${outputLanguage}.Return translations in the same text formatting.Maintain case sensitivity and whitespacing.Output only the translations.All lines should start and end with an ASCII quotation mark (").${input}
</code></span></span></span></span>
Translation verification prompt
翻译验证提示
The output of the translation is sent back to ensure the model is okay with the translation. If this fails, the translation is re-generated.
将翻译的输出发回以确保模型对翻译没有问题。如果失败,则会重新生成转换。
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>Given a translation from ${inputLanguage} to ${outputLanguage} in CSV form, reply with NAK if _any_ of the translations are poorly translated.Otherwise, reply with ACK.Only reply with ACK/NAK.
</code></span></span></span></span>
Styling verification prompt
样式验证提示
Formatting from the input should be retained where possible. If punctuation, capitalization, or whitespaces differ between the source and the translation, the translation is re-generated.
应尽可能保留输入中的格式。如果源和翻译之间的标点符号、大小写或空格不同,则会重新生成翻译。
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>Given text from ${inputLanguage} to ${outputLanguage} in CSV form, reply with NAK if _any_ of the translations do not match the formatting of the original.Check for differing capitalization, punctuation, or whitespaces.Otherwise, reply with ACK.Only reply with ACK/NAK.
</code></span></span></span></span>
JSON Mode JSON 模式
Translation prompt json 翻译提示 json
Batches of the i18n input are passed in. Each call is checked to ensure no keys are lost, all templated strings are retained, and no translations are skipped.
传入 i18n 输入的批次。检查每个调用以确保没有键丢失,保留所有模板化字符串,并且不会跳过任何翻译。
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>You are a professional translator.Translate from ${inputLanguage} to ${outputLanguage}.- Translate each object in the array.
- 'original' is the text to be translated.
- 'translated' must not be empty.
- 'context' is additional info if needed.
- 'failure' explains why the previous translation failed.
- Preserve text formatting, case sensitivity, and whitespace.Special Instructions:
- Treat anything in the format {{variableName}} as a placeholder. Never translate or modify its content.
- Do not add your own variables
- The number of variables like {{timeLeft}} must be the same in the translated text.
- Do not convert {{NEWLINE}} to \\n.Return the translation as JSON.
\`\`\`json
${input}
\`\`\`
</code></span></span></span></span>
Translation verification prompt json
翻译验证提示 json
The output of the translation is sent back to ensure the model is okay with the translation/formatting. If this fails, the translation is re-generated.
将翻译的输出发回,以确保模型对翻译/格式设置没有问题。如果失败,则会重新生成转换。
<span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><span style="color:#1f2328"><span style="color:var(--fgColor-default, var(--color-fg-default))"><span style="background-color:var(--bgColor-muted, var(--color-canvas-subtle))"><code>You are a professional translator.Check translations from ${inputLanguage} to ${outputLanguage}.- Verify each object in the array.
- 'original' is the text to be translated.
- 'translated' is the translated text.
- 'context' is additional info if needed.
- 'failure' explains why the previous translation failed.
- check for Accuracy (meaning, tone, grammar), Formatting (case, whitespace, punctuation).If correct, return 'valid' as 'true' and leave 'fixedTranslation' and 'issue' empty.
If incorrect, return 'valid' as 'false' and put the fixed translation in 'fixedTranslation' and explain what is 'issue'.Special Instructions:
- Treat anything in the format {{variableName}} as a placeholder. Never translate or modify its content.
- Do not add your own variables
- The number of variables like {{timeLeft}} must be the same in the translated text.
- Do not convert {{NEWLINE}} to \\n.Allow minor grammar, phrasing, and formatting differences if meaning is clear.
Flag only significant issues affecting accuracy or readability.Return the verified as JSON.
\`\`\`json
${input}
\`\`\`
</code></span></span></span></span>
Prompt overriding 提示覆盖
Replace the aforementioned prompts with your own by creating a JSON file containing keys of at least one of generationPrompt
, translationVerificationPrompt
, or stylingVerificationPrompt
. Then, pass it as an argument with --override-prompt <path to file>
. Be sure to include templated arguments like ${inputLanguage}
as part of the prompt.
通过创建一个 JSON 文件,将上述提示替换为您自己的提示,该文件至少包含 generationPrompt
、translationVerificationPrompt
或 stylingVerificationPrompt
中的至少一个键。然后,将其作为参数传递。 --override-prompt <path to file>
请务必在提示符中包含模板化参数,例如 ${inputLanguage}
。
软件下载
夸克网盘分享
本文信息来源于GitHub作者地址:https://github.com/taahamahdi/i18n-ai-translate