一、軟件介紹
文末提供程序和源碼下載
? ? ? ?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 in?jsons/
?to French, and save the output in?fr.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 in?jsons/
?to Spanish, German, and Dutch, and save each file in?jsons/
, 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
?and?en-after.json
?for all files in the?en.json
?directory, with logging enabled using Ollama running on?my-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 in?jsons/
?to 200+ languages, save each file in?jsons/
, 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/
?and?en-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