Repository navigation
Expand file tree
/
Copy pathcli_manager.js
More file actions
409 lines (342 loc) · 15.8 KB
/
Copy pathcli_manager.js
File metadata and controls
409 lines (342 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const JsonAstParser = require('./json_ast_parser');
const ZhipuTranslator = require('./zhipu_translator');
const TranslationValidator = require('./translation_validator');
const IncrementalTranslator = require('./incremental_translator');
// 配置
const API_KEY = '你的智谱AI_API_KEY';
const BATCH_SIZE = 10; // 每次翻译 10 条
const MAX_RETRY = 2; // 最大重试次数
class CliManager {
constructor(baseDir = 'locales/zh', options = {}) {
this.baseDir = path.resolve(baseDir);
this.model = options.model || 'glm-4-plus'; // Default model
this.parser = new JsonAstParser();
this.translator = new ZhipuTranslator(API_KEY, { model: this.model });
this.validator = new TranslationValidator();
}
getJsonFiles() {
try {
if (!fs.existsSync(this.baseDir)) {
console.error(`Directory not found: ${this.baseDir}`);
return [];
}
const files = fs.readdirSync(this.baseDir);
return files.filter(file => file.endsWith('.json'));
} catch (error) {
console.error(`Error reading directory ${this.baseDir}:`, error.message);
return [];
}
}
/**
* 将翻译结果回填到源文件内容中
* 采用倒序替换策略,避免位置偏移
*/
applyTranslations(sourceContent, translationMap) {
// translationMap: Array of { start, end, originalText, translatedText }
// 必须按 start.row, start.column 倒序排序
// 转换成替换操作列表
const edits = translationMap.map(item => ({
start: item.start, // {row, column}
end: item.end, // {row, column}
text: JSON.stringify(item.translatedText) // 重新序列化为 JSON 字符串(带引号)
}));
// 倒序排序:行号大的在前;行号相同,列号大的在前
edits.sort((a, b) => {
if (a.start.row !== b.start.row) {
return b.start.row - a.start.row;
}
return b.start.column - a.start.column;
});
const lines = sourceContent.split('\n');
for (const edit of edits) {
const lineIdx = edit.start.row;
const line = lines[lineIdx];
// 简单处理:假设 string value 都在同一行 (JSON AST parser 提取的也是如此)
// 如果跨行字符串,需要更复杂处理,但通常 JSON value 是单行的(除非包含 \n)
// Tree-sitter 的 start/end 已经处理了跨行,但简单的字符串替换基于行切分比较麻烦
// 如果跨行,我们需要重构这部分逻辑。
// 为了安全,我们基于字符索引操作整个文件内容会更稳健
// 但是 Tree-sitter 给的是行列号。
// 让我们实现一个简单的行列号转字符索引函数。
}
// 重新实现:基于字符位置替换
// 为了避免换行符差异问题,我们先计算每行的偏移量
let buffer = sourceContent;
// 重新计算 edits 的绝对字符偏移量
// 这比较耗时,但对于一般大小文件可以接受
// 或者,我们直接在行数组上操作。
// 假设没有跨行字符串(Tree-sitter json string 只要不包含未转义换行符通常是安全的)
// 即使有跨行,start 和 end 也会跨行。
// 让我们用最稳健的方法:
// 1. 把所有行拼回去之前,先在行级别修改。
// 2. 如果一个 edit 跨越多行,我们需要替换这些行。
for (const edit of edits) {
if (edit.start.row === edit.end.row) {
// 单行替换
const line = lines[edit.start.row];
const before = line.substring(0, edit.start.column);
const after = line.substring(edit.end.column);
lines[edit.start.row] = before + edit.text + after;
} else {
// 跨行替换
// 保留 start 行的前半部分
const startLine = lines[edit.start.row].substring(0, edit.start.column);
// 保留 end 行的后半部分
const endLine = lines[edit.end.row].substring(edit.end.column);
// 中间的行全部删除
// 我们可以把 startRow 变成新内容,中间行置空,或者用 splice
lines[edit.start.row] = startLine + edit.text + endLine;
// 删除中间的行 (startRow + 1 到 endRow)
for (let i = edit.start.row + 1; i <= edit.end.row; i++) {
lines[i] = null; // 标记删除
}
}
}
return lines.filter(l => l !== null).join('\n');
}
async processFile(task) {
console.log(`\nProcessing ${task.file} -> ${task.targetLang}...`);
// 1. 解析
const astResults = this.parser.parseFile(task.filePath);
if (astResults.length === 0) {
console.log('No translatable strings found.');
return;
}
console.log(`Found ${astResults.length} strings.`);
// 2. 批量翻译(带重试机制)
const translatedItems = await this.translateWithRetry(astResults, task.targetLang);
// 3. 生成新文件内容
const sourceContent = fs.readFileSync(task.filePath, 'utf8');
const newContent = this.applyTranslations(sourceContent, translatedItems);
// 4. 写入文件
const ext = path.extname(task.file);
const name = path.basename(task.file, ext);
const newFileName = `${name}_${task.targetLang}${ext}`;
const outputDir = path.join(path.dirname(this.baseDir), task.targetLang);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const outputPath = path.join(outputDir, newFileName);
fs.writeFileSync(outputPath, newContent, 'utf8');
console.log(`Saved to ${outputPath}`);
// 5. 验证翻译质量
console.log('\nValidating translation quality...');
const validation = this.validator.validateFile(outputPath);
console.log(`Translation rate: ${validation.translationRate}`);
if (!validation.isValid) {
console.log(`⚠ Warning: ${validation.untranslatedCount} fields still contain Chinese text`);
console.log('Initiating auto-repair sequence...');
try {
// 使用较小的 batchSize (10) 进行修复,提高稳定性
const fixer = new IncrementalTranslator(API_KEY, 10);
console.log(`Auto-repairing ${task.file} -> ${task.targetLang}...`);
const repairResult = await fixer.fixTranslation(
task.filePath, // source file
outputPath, // target file (to be fixed)
task.targetLang
);
console.log('Auto-repair completed.');
console.log(` Fixed: ${repairResult.fixed} fields`);
console.log(` Final Translation Rate: ${repairResult.finalTranslationRate}`);
if (repairResult.remainingUntranslated > 0) {
console.log(`⚠ Still have ${repairResult.remainingUntranslated} untranslated fields.`);
// 保存最终验证报告
const reportPath = outputPath.replace('.json', '_validation_report.txt');
this.validator.saveReport(validation, reportPath); // 注意:这里 validation 对象可能还是旧的,最好重新验证,但 IncrementalTranslator 内部已经做过验证了
} else {
console.log('✓ All fields successfully repaired!');
}
} catch (err) {
console.error('Auto-repair failed:', err);
// 保存原始验证报告作为备份
const reportPath = outputPath.replace('.json', '_validation_report.txt');
this.validator.saveReport(validation, reportPath);
}
} else {
console.log('✓ All fields translated successfully!');
}
}
/**
* 带重试机制的批量翻译
* @param {Array} astResults
* @param {string} targetLang
* @returns {Array}
*/
async translateWithRetry(astResults, targetLang) {
const translatedItems = [];
for (let i = 0; i < astResults.length; i += BATCH_SIZE) {
const batch = astResults.slice(i, i + BATCH_SIZE);
const texts = batch.map(item => item.content);
const batchNum = Math.floor(i / BATCH_SIZE) + 1;
const totalBatches = Math.ceil(astResults.length / BATCH_SIZE);
console.log(`Translating batch ${batchNum}/${totalBatches}...`);
let translations = null;
let retryCount = 0;
// 重试机制
while (retryCount <= MAX_RETRY && !translations) {
try {
translations = await this.translator.translateBatch(texts, targetLang);
// 验证翻译结果
const validTranslations = this.validateTranslations(texts, translations);
if (validTranslations.hasIssues) {
console.log(` ⚠ Batch ${batchNum} has ${validTranslations.issueCount} untranslated fields`);
// 如果还有重试机会,重新翻译有问题的字段
if (retryCount < MAX_RETRY) {
console.log(` Retrying problematic fields (attempt ${retryCount + 1}/${MAX_RETRY})...`);
translations = await this.retryProblematicFields(
texts,
translations,
validTranslations.issues,
targetLang
);
}
}
batch.forEach((item, idx) => {
translatedItems.push({
...item,
translatedText: translations[idx]
});
});
console.log(` ✓ Batch ${batchNum} completed`);
} catch (err) {
retryCount++;
console.error(` ✗ Batch ${batchNum} failed (attempt ${retryCount}/${MAX_RETRY + 1}): ${err.message}`);
if (retryCount > MAX_RETRY) {
console.error(` Giving up on batch ${batchNum}, using original text`);
// 失败时使用原文
batch.forEach((item, idx) => {
translatedItems.push({
...item,
translatedText: texts[idx]
});
});
break;
}
// 等待一段时间后重试
await this.sleep(2000 * retryCount);
}
}
}
return translatedItems;
}
/**
* 验证翻译结果
* @param {Array} originalTexts
* @param {Array} translations
* @returns {Object}
*/
validateTranslations(originalTexts, translations) {
const issues = [];
for (let i = 0; i < translations.length; i++) {
const translation = translations[i];
// 检查是否仍包含中文(除非原文就是中文)
if (this.validator.containsChinese(translation)) {
issues.push({
index: i,
original: originalTexts[i],
translation: translation
});
}
}
return {
hasIssues: issues.length > 0,
issueCount: issues.length,
issues: issues
};
}
/**
* 重新翻译有问题的字段
* @param {Array} originalTexts
* @param {Array} translations
* @param {Array} issues
* @param {string} targetLang
* @returns {Array}
*/
async retryProblematicFields(originalTexts, translations, issues, targetLang) {
const result = [...translations];
if (issues.length === 0) return result;
// 提取需要重新翻译的文本
const textsToRetry = issues.map(issue => issue.original);
const indices = issues.map(issue => issue.index);
try {
const retryTranslations = await this.translator.translateBatch(textsToRetry, targetLang);
// 更新结果
for (let i = 0; i < indices.length; i++) {
const index = indices[i];
result[index] = retryTranslations[i];
}
} catch (err) {
console.error(` Retry failed: ${err.message}`);
}
return result;
}
/**
* 延迟函数
* @param {number} ms
* @returns {Promise}
*/
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async run() {
console.log('Welcome to JSON Translation System');
console.log('==================================');
console.log(`Current Model: ${this.model} ${this.model === 'glm-4.6' ? '(Deep Thinking Enabled)' : ''}`);
const files = this.getJsonFiles();
if (files.length === 0) {
console.log('No JSON files found in locales/zh.');
return;
}
const fileAnswer = await inquirer.prompt([
{
type: 'checkbox',
name: 'selectedFiles',
message: '请选择要翻译的文件 (按 Space 选择, Enter 确认):',
choices: files,
validate: (answer) => {
if (answer.length < 1) return 'You must choose at least one file.';
return true;
}
}
]);
const tasks = [];
for (const file of fileAnswer.selectedFiles) {
console.log(`\nConfiguration for ${file}:`);
const langAnswer = await inquirer.prompt([
{
type: 'input',
name: 'targetLang',
message: `请输入 ${file} 的目标语言代码 (如 en, ja, es):`,
default: 'en',
validate: (input) => {
if (!input || input.trim().length === 0) return 'Language code cannot be empty.';
return true;
}
}
]);
tasks.push({
file: file,
filePath: path.join(this.baseDir, file),
targetLang: langAnswer.targetLang.trim()
});
}
console.log('\nStarting tasks...');
for (const task of tasks) {
try {
await this.processFile(task);
} catch (err) {
console.error(`Failed to process ${task.file}:`, err);
}
}
console.log('\nAll tasks completed.');
}
}
// 运行入口
if (require.main === module) {
const cli = new CliManager();
cli.run().catch(err => console.error(err));
}
module.exports = CliManager;