当前位置: 首页 > news >正文

i18n-ai-translate开源程序,可以使用DeepSeek等模型将您的 i18nJSON翻译成任何语言

一、软件介绍

文末提供程序和源码下载

       i18n-ai-translate开源程序使用 DeepSeek等模型可以将您的 i18n JSON 翻译成任何语言。 无缝翻译本地化文件。支持嵌套翻译文件的目录。需要i18next样式的JSON 文件(文末一并提供下载)。

二、模式

CSV 模式

三个提示链接在一起,以确保每个翻译格式正确。

  1. 翻译提示尝试翻译
  2. 翻译验证提示使用单独的上下文来验证翻译
  3. 样式验证提示使用另一个上下文来验证翻译的格式是否与源一致

JSON 模式

​翻译和验证分两个单独的步骤完成。

  1. 翻译提示尝试翻译整个文件
  2. 翻译验证提示会验证/修复并再次验证每一行。
  3. 在两次调用之间保留历史记录,以确保翻译整个文件时的一致性。

​三、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 generationPrompttranslationVerificationPrompt, 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 文件,将上述提示替换为您自己的提示,该文件至少包含 generationPrompttranslationVerificationPrompt 或 stylingVerificationPrompt 中的至少一个键。然后,将其作为参数传递。 --override-prompt <path to file> 请务必在提示符中包含模板化参数,例如 ${inputLanguage}

软件下载

夸克网盘分享

本文信息来源于GitHub作者地址:https://github.com/taahamahdi/i18n-ai-translate

相关文章:

  • PyTorch作为深度学习框架在建筑行业的应用
  • pymongo功能整理与基础操作类
  • 力扣面试150题--合并两个有序链表和随机链表的复制
  • SpringBoot物资管理系统 | JavaWeb项目设计与实现
  • 04-谷粒商城笔记
  • 测试用例的设计
  • 迷宫问题演示
  • ShaderToy学习笔记 03.多个形状和旋转
  • ‌C/C++对时间的处理
  • Scratch——第19课 正话反说问题
  • 线程池(四):并发编程常见问题解析
  • QT6 源(52)篇二:存储 c 语言字符串的类 QByteArray 的使用举例,
  • 中美艺术教育深度融合,Glowstar与ACSDA在尔湾签署战略合作协议推动艺术发展
  • ShaderToy学习笔记 02.圆
  • JAVA多线程(8.0)
  • Pygame核心概念解析:Surface、Clock与事件循环
  • C++学习-入门到精通-【2】类、对象和字符串的介绍
  • 2025.04.26-饿了么春招笔试题-第二题
  • leetcode 26和80
  • DIY 3D打印机 原理及步骤概况
  • 国家统计局:一季度规模以上工业企业利润延续持续恢复态势
  • 金正恩出席朝鲜人民军海军驱逐舰入水仪式
  • 观察|上海算力生态蓬勃发展,如何助力千行百业数智化转型升级
  • 经济日报:AI时代如何寻找“你的赛道”
  • 东北财大“一把手”调整:方红星任校党委书记,汪旭晖任校长
  • 韩国京畿道骊州市市长率团访问菏泽:想和菏泽一起办牡丹节