cherry-studio/scripts/update-i18n.ts
Phantom 52c087fd22
chore(i18n): improve i18n translation scripts (#8441)
* refactor(i18n): 迁移i18n脚本至TypeScript并添加进度条

- 将check-i18n.js和sync-i18n.js迁移为TypeScript版本
- 添加cli-progress依赖以显示翻译进度条
- 更新package.json中的i18n相关脚本
- 移除不再使用的sort.js工具文件

* refactor(i18n): 重构翻译同步脚本以支持多目录

将翻译文件目录变量重命名为更清晰的名称,并添加对translate目录的支持
优化文件路径处理逻辑,使用path.basename获取文件名

* chore: update i18n

* docs(i18n): 更新翻译目录的README说明

更新README文件以更清晰地说明翻译文件的生成方式和使用注意事项

* style(DMXAPISettings): 添加关于国际化的FIXME注释

在PlatformOptions上方添加注释,提醒此处需要国际化处理
2025-07-24 10:21:48 +08:00

148 lines
6.1 KiB
TypeScript

/**
* 使用 OpenAI 兼容的模型生成 i18n 文本,并更新到 translate 目录
*
* API_KEY=sk-xxxx BASE_URL=xxxx MODEL=xxxx ts-node scripts/update-i18n.ts
*/
import cliProgress from 'cli-progress'
import fs from 'fs'
import OpenAI from 'openai'
type I18NValue = string | { [key: string]: I18NValue }
type I18N = { [key: string]: I18NValue }
const API_KEY = process.env.API_KEY
const BASE_URL = process.env.BASE_URL || 'https://dashscope.aliyuncs.com/compatible-mode/v1/'
const MODEL = process.env.MODEL || 'qwen-plus-latest'
const INDEX = [
// 语言的名称代码用来翻译的模型
{ name: 'France', code: 'fr-fr', model: MODEL },
{ name: 'Spanish', code: 'es-es', model: MODEL },
{ name: 'Portuguese', code: 'pt-pt', model: MODEL },
{ name: 'Greek', code: 'el-gr', model: MODEL }
]
const zh = JSON.parse(fs.readFileSync('src/renderer/src/i18n/locales/zh-cn.json', 'utf8')) as I18N
const openai = new OpenAI({
apiKey: API_KEY,
baseURL: BASE_URL
})
// 递归遍历翻译
async function translate(baseObj: I18N, targetObj: I18N, targetLang: string, model: string, updateFile) {
const toTranslateTexts: { [key: string]: string } = {}
for (const key in baseObj) {
if (typeof baseObj[key] == 'object') {
// 遍历下一层
if (!targetObj[key] || typeof targetObj[key] != 'object') targetObj[key] = {}
await translate(baseObj[key], targetObj[key], targetLang, model, updateFile)
} else if (
!targetObj[key] ||
typeof targetObj[key] != 'string' ||
(typeof targetObj[key] === 'string' && targetObj[key].startsWith('[to be translated]'))
) {
// 加入到本层待翻译列表
toTranslateTexts[key] = baseObj[key]
}
}
if (Object.keys(toTranslateTexts).length > 0) {
const completion = await openai.chat.completions.create({
model: model,
response_format: { type: 'json_object' },
messages: [
{
role: 'user',
content: `
You are a robot specifically designed for translation tasks. As a model that has been extensively fine-tuned on Russian language corpora, you are proficient in using the Russian language.
Now, please output the translation based on the input content. The input will include both Chinese and English key values, and you should output the corresponding key values in the Russian language.
When translating, ensure that no key value is omitted, and maintain the accuracy and fluency of the translation. Pay attention to the capitalization rules in the output to match the source text, and especially pay attention to whether to capitalize the first letter of each word except for prepositions. For strings containing \`{{value}}\`, ensure that the format is not disrupted.
Output in JSON.
######################################################
INPUT
######################################################
${JSON.stringify({
confirm: '确定要备份数据吗?',
select_model: '选择模型',
title: '文件',
deeply_thought: '已深度思考(用时 {{secounds}} 秒)'
})}
######################################################
MAKE SURE TO OUTPUT IN Russian. DO NOT OUTPUT IN UNSPECIFIED LANGUAGE.
######################################################
`
},
{
role: 'assistant',
content: JSON.stringify({
confirm: 'Подтвердите резервное копирование данных?',
select_model: 'Выберите Модель',
title: 'Файл',
deeply_thought: 'Глубоко продумано (заняло {{seconds}} секунд)'
})
},
{
role: 'user',
content: `
You are a robot specifically designed for translation tasks. As a model that has been extensively fine-tuned on ${targetLang} language corpora, you are proficient in using the ${targetLang} language.
Now, please output the translation based on the input content. The input will include both Chinese and English key values, and you should output the corresponding key values in the ${targetLang} language.
When translating, ensure that no key value is omitted, and maintain the accuracy and fluency of the translation. Pay attention to the capitalization rules in the output to match the source text, and especially pay attention to whether to capitalize the first letter of each word except for prepositions. For strings containing \`{{value}}\`, ensure that the format is not disrupted.
Output in JSON.
######################################################
INPUT
######################################################
${JSON.stringify(toTranslateTexts)}
######################################################
MAKE SURE TO OUTPUT IN ${targetLang}. DO NOT OUTPUT IN UNSPECIFIED LANGUAGE.
######################################################
`
}
]
})
// 添加翻译后的键值,并打印错译漏译内容
try {
const result = JSON.parse(completion.choices[0].message.content!)
// console.debug('result', result)
for (const e in toTranslateTexts) {
if (result[e] && typeof result[e] === 'string') {
targetObj[e] = result[e]
} else {
console.warn(`missing value "${e}" in ${targetLang} translation`)
}
}
} catch (e) {
console.error(e)
for (const e in toTranslateTexts) {
console.warn(`missing value "${e}" in ${targetLang} translation`)
}
}
}
// 删除多余的键值
for (const e in targetObj) {
if (!baseObj[e]) {
delete targetObj[e]
}
}
// 更新文件
updateFile()
}
let count = 0
;(async () => {
const bar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic)
bar.start(INDEX.length, 0)
for (const { name, code, model } of INDEX) {
const obj = fs.existsSync(`src/renderer/src/i18n/translate/${code}.json`)
? (JSON.parse(fs.readFileSync(`src/renderer/src/i18n/translate/${code}.json`, 'utf8')) as I18N)
: {}
await translate(zh, obj, name, model, () => {
fs.writeFileSync(`src/renderer/src/i18n/translate/${code}.json`, JSON.stringify(obj, null, 2), 'utf8')
})
count += 1
bar.update(count)
}
bar.stop()
})()