cc-translate 1.2.2 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -7,16 +7,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import path from "path";
11
22
  import fs from "fs";
12
23
  import colors from "ansi-colors";
13
24
  import { OpenAI } from "openai";
14
25
  import cliProgress from "cli-progress";
15
26
  import { getRandomNumber, notExistsToCreateFile, readFileOfDirSync, readJsonFileSync, runWithConcurrencyLimit, sleep, } from "./lib/utils.js";
16
- import { getCacheFileSync, registerLanguageCacheFile, translateJSONDiffToJson, } from "./lib/cache/index.js";
27
+ import { getCacheFileSync, readReferenceCache, registerLanguageCacheFile, translateJSONDiffToJson, writeReferenceCache, } from "./lib/cache/index.js";
17
28
  import { logErrorToFile } from "./lib/log/index.js";
18
29
  import { SUPPORT_LANGUAGE_MAP } from "./lib/support.js";
30
+ import { isProtectedText, protectTerms, readProtectedTerms, readTranslationMetadata, } from "./lib/translation-metadata.js";
31
+ import { TranslationReferencePlugin } from "./lib/translation-reference.js";
32
+ import { readTranslationResponse } from "./lib/translation-response.js";
19
33
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
34
+ export { TranslationReferencePlugin };
20
35
  const DEFAULT_CHAT_COMPLETION_CREATE_PARAMS = {
21
36
  model: "gpt-4o",
22
37
  };
@@ -37,8 +52,13 @@ export class I18nTranslateAgent {
37
52
  /**
38
53
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
39
54
  */
40
- this.translate = () => __awaiter(this, void 0, void 0, function* () {
41
- fs.writeFileSync("error.log", "", "utf8");
55
+ this.translate = (referencePlugins) => __awaiter(this, void 0, void 0, function* () {
56
+ var _a, _b, _c, _d;
57
+ const plugins = referencePlugins && "prepare" in referencePlugins
58
+ ? [referencePlugins]
59
+ : referencePlugins !== null && referencePlugins !== void 0 ? referencePlugins : [];
60
+ if (plugins.length === 0)
61
+ fs.writeFileSync("error.log", "", "utf8");
42
62
  console.log("🚀 Start translation");
43
63
  console.log(`🚀 Using model: ${this.chatCompletionCreateParams.model} 🚀`);
44
64
  console.log(`🚀 Fine-tuning: ${this.fineTune.join(",")} 🚀`);
@@ -47,66 +67,177 @@ export class I18nTranslateAgent {
47
67
  // 翻译源语言问价夹下的所有json文件
48
68
  const translateFolders = yield readFileOfDirSync(translateFolderPath);
49
69
  console.log("🚀 ~ files to translate:", translateFolders, translateFolderPath);
50
- // 创建进度条
51
- const multiBar = new cliProgress.MultiBar({
52
- clearOnComplete: false,
53
- hideCursor: true,
54
- format: colors.cyan("{bar}") +
55
- "| {percentage}% || {filename} {value}/{total} ",
56
- }, cliProgress.Presets.legacy);
57
- const taskList = [];
70
+ const tasks = [];
58
71
  const skippedNoContent = [];
59
- for (const item of this.supportLanguages) {
60
- // 源语言不翻译
61
- if (item.code === this.SOURCE_LANGUAGE)
62
- continue;
63
- for (const fileName of translateFolders) {
64
- const translateJson = yield this.getTranslateContent(item.code, fileName);
65
- if (!translateJson) {
66
- skippedNoContent.push(`${item.code}:${fileName}`);
67
- continue;
72
+ const emptyFiles = [];
73
+ const referenceLanguages = new Set(plugins.map(({ language }) => language));
74
+ const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && !referenceLanguages.has(code));
75
+ const sourceFiles = new Map();
76
+ for (const fileName of translateFolders) {
77
+ const _e = (_a = (yield readJsonFileSync(path.join(translateFolderPath, fileName)))) !== null && _a !== void 0 ? _a : {}, { _meta } = _e, entries = __rest(_e, ["_meta"]);
78
+ sourceFiles.set(fileName, { entries, metadata: readTranslationMetadata(_meta) });
79
+ }
80
+ const writableDirectories = targetLanguages.flatMap(({ code }) => [
81
+ path.join(this.outputPath, code),
82
+ path.join(this.CACHE_ROOT_PATH, code),
83
+ path.join(this.CACHE_ROOT_PATH, code, ".references"),
84
+ ]);
85
+ const loadedReferences = plugins.map((plugin) => ({
86
+ plugin,
87
+ identity: JSON.stringify([plugin.language, plugin.directory]),
88
+ files: plugin.readFiles(sourceFiles.keys(), writableDirectories),
89
+ }));
90
+ // 用本次匹配和发送给模型的参考译文建立快照,避免两次读取之间发生变化。
91
+ const referenceSnapshots = new Map();
92
+ if (loadedReferences.length) {
93
+ for (const [fileName, { entries, metadata }] of sourceFiles) {
94
+ const snapshots = new Map();
95
+ for (const [key, source] of Object.entries(entries)) {
96
+ if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate))
97
+ continue;
98
+ snapshots.set(key, Object.fromEntries(loadedReferences.map(({ identity, files }) => {
99
+ var _a, _b;
100
+ return [
101
+ identity,
102
+ (_b = (_a = files.get(fileName)) === null || _a === void 0 ? void 0 : _a.get(key)) !== null && _b !== void 0 ? _b : null,
103
+ ];
104
+ })));
68
105
  }
69
- taskList.push(() => __awaiter(this, void 0, void 0, function* () {
70
- let attempt = 0;
71
- while (attempt <= this.maxTaskRetries) {
72
- try {
73
- yield this.singleTranslate({
74
- language: item.code,
75
- fileName,
76
- multiBar,
77
- translateJson,
78
- });
79
- attempt = this.maxTaskRetries + 1;
80
- return;
106
+ referenceSnapshots.set(fileName, snapshots);
107
+ }
108
+ }
109
+ const baselines = [];
110
+ for (const item of targetLanguages) {
111
+ for (const [fileName, { entries, metadata }] of sourceFiles) {
112
+ const translateJson = (_b = (yield this.getTranslateContent(item.code, fileName, plugins.length ? emptyFiles : undefined, entries))) !== null && _b !== void 0 ? _b : {};
113
+ const current = referenceSnapshots.get(fileName);
114
+ let referenceCache;
115
+ if (current === null || current === void 0 ? void 0 : current.size) {
116
+ const filePath = path.join(this.CACHE_ROOT_PATH, item.code, ".references", fileName);
117
+ const observed = readReferenceCache(filePath);
118
+ referenceCache = { filePath, observed, current };
119
+ let addedBaseline = false;
120
+ for (const [key, snapshot] of current) {
121
+ if (Object.prototype.hasOwnProperty.call(translateJson, key))
122
+ continue;
123
+ const previous = (_c = observed.get(key)) !== null && _c !== void 0 ? _c : {};
124
+ const values = Object.entries(snapshot);
125
+ // 参考译文被清空或删除时,保留已有译文。
126
+ if (values.some(([id, value]) => value !== null && previous[id] !== undefined && previous[id] !== value)) {
127
+ translateJson[key] = entries[key];
128
+ continue;
81
129
  }
82
- catch (error) {
83
- attempt++;
84
- if (attempt > this.maxTaskRetries) {
85
- throw error;
86
- }
87
- const waitMs = this.taskRetryBaseDelayMs * attempt;
88
- console.warn(`${colors.yellow("Task retry")} ${item.code}:${fileName} (${attempt}/${this.maxTaskRetries})`);
89
- yield sleep(waitMs);
130
+ // 旧缓存只记录源文案。首次遇到未记录的参考时建立比对基准,不回填旧译文。
131
+ const untracked = values.filter(([id]) => previous[id] === undefined);
132
+ if (untracked.length) {
133
+ observed.set(key, Object.assign(Object.assign({}, previous), Object.fromEntries(untracked)));
134
+ addedBaseline = true;
90
135
  }
91
136
  }
92
- }));
137
+ if (addedBaseline)
138
+ baselines.push(referenceCache);
139
+ }
140
+ if (Object.keys(translateJson).length === 0) {
141
+ skippedNoContent.push(`${item.code}:${fileName}`);
142
+ continue;
143
+ }
144
+ tasks.push({ language: item.code, fileName, translateJson, metadata, referenceCache });
145
+ }
146
+ }
147
+ if (plugins.length) {
148
+ const prepared = [];
149
+ for (const { plugin, files } of loadedReferences) {
150
+ const matches = yield plugin.prepare(tasks, writableDirectories, this.noTranslate, files);
151
+ if (!matches)
152
+ return;
153
+ prepared.push({ plugin, matches });
154
+ }
155
+ fs.writeFileSync("error.log", "", "utf8");
156
+ // 所有参考匹配预览通过后,才写入比对基准。
157
+ for (const baseline of baselines)
158
+ writeReferenceCache(baseline);
159
+ const blockedByFile = new Map();
160
+ for (const { plugin, matches } of prepared) {
161
+ if (plugin.checkConflicts) {
162
+ yield this.reviewReferences(matches, plugin.language, blockedByFile);
163
+ }
164
+ }
165
+ for (const task of tasks) {
166
+ const fileReferences = prepared.flatMap(({ plugin, matches }) => {
167
+ const fileMatches = matches.get(task.fileName);
168
+ return fileMatches
169
+ ? [{ language: plugin.language, matches: fileMatches }]
170
+ : [];
171
+ });
172
+ if (fileReferences.length === 1)
173
+ task.reference = fileReferences[0];
174
+ else if (fileReferences.length > 1)
175
+ task.references = fileReferences;
176
+ task.blockedKeys = blockedByFile.get(task.fileName);
177
+ for (const key of (_d = task.blockedKeys) !== null && _d !== void 0 ? _d : []) {
178
+ delete task.translateJson[key];
179
+ }
180
+ }
181
+ for (const emptyFile of emptyFiles) {
182
+ yield this.outputLanguageFile(emptyFile);
93
183
  }
94
184
  }
95
185
  if (skippedNoContent.length > 0) {
96
186
  const summary = skippedNoContent.length <= 5
97
187
  ? skippedNoContent.join(", ")
98
188
  : `${skippedNoContent.slice(0, 3).join(", ")} ... +${skippedNoContent.length - 3} more`;
99
- console.log(`${colors.dim("Skipped (no content to translate):")} ${skippedNoContent.length} items${skippedNoContent.length <= 5 ? ` (${summary})` : ` — e.g. ${summary}`}`);
189
+ console.log(`Skipped (no content to translate): ${skippedNoContent.length} items${skippedNoContent.length <= 5 ? ` (${summary})` : ` — e.g. ${summary}`}`);
100
190
  }
101
- // 并发队列:同时最多 concurrency 个任务,完成一个即从队列取下一个,避免长任务拖慢整批
102
- const results = yield runWithConcurrencyLimit(taskList, this.concurrency);
103
- multiBar.stop();
104
- const errorLength = results.filter((item) => item.status === "rejected").length;
105
- if (errorLength > 0) {
106
- console.log(`${colors.red("Translation failed")}: ${errorLength} tasks`);
107
- }
108
- console.log(`${colors.green("Translation completed")}: ${results.length} tasks`);
109
- console.log(`${colors.green("Translation successful")}: ${results.length - errorLength} tasks`);
191
+ const readyTasks = tasks.filter(({ translateJson }) => Object.keys(translateJson).length > 0);
192
+ const multiBar = process.stderr.isTTY && !process.env.CI && readyTasks.length > 0
193
+ ? new cliProgress.MultiBar({
194
+ clearOnComplete: false,
195
+ hideCursor: true,
196
+ format: colors.cyan("{bar}") +
197
+ "| {percentage}% || {filename} {value}/{total} ",
198
+ }, cliProgress.Presets.legacy)
199
+ : undefined;
200
+ const totalBar = multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(readyTasks.length, 0, {
201
+ filename: "Total tasks finished",
202
+ });
203
+ const warnTask = (message) => {
204
+ if (multiBar)
205
+ multiBar.log(`${message}\n`);
206
+ else
207
+ console.warn(message);
208
+ };
209
+ const taskList = readyTasks.map((task) => () => __awaiter(this, void 0, void 0, function* () {
210
+ const filename = `${task.language}:${task.fileName}`;
211
+ const progressBar = multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(Object.keys(task.translateJson).length, 0, { filename });
212
+ try {
213
+ for (let attempt = 0;; attempt++) {
214
+ try {
215
+ yield this.singleTranslate(Object.assign(Object.assign({}, task), { progressBar }));
216
+ if (!multiBar)
217
+ console.log(`Task successful: ${filename}`);
218
+ return;
219
+ }
220
+ catch (error) {
221
+ if (attempt >= this.maxTaskRetries) {
222
+ warnTask(`Task failed: ${filename}`);
223
+ throw error;
224
+ }
225
+ const retry = attempt + 1;
226
+ warnTask(`Task retry: ${filename} (${retry}/${this.maxTaskRetries})`);
227
+ yield sleep(this.taskRetryBaseDelayMs * retry);
228
+ }
229
+ }
230
+ }
231
+ finally {
232
+ totalBar === null || totalBar === void 0 ? void 0 : totalBar.increment();
233
+ if (progressBar)
234
+ multiBar === null || multiBar === void 0 ? void 0 : multiBar.remove(progressBar);
235
+ }
236
+ }));
237
+ const results = yield runWithConcurrencyLimit(taskList, this.concurrency).finally(() => multiBar === null || multiBar === void 0 ? void 0 : multiBar.stop());
238
+ const failed = results.filter((item) => item.status === "rejected").length;
239
+ const successful = results.filter((item) => item.status === "fulfilled").length;
240
+ console.log(`Translation summary: ${successful} successful, ${failed} failed, ${skippedNoContent.length} skipped`);
110
241
  });
111
242
  /**
112
243
  * 翻译单个文件
@@ -118,28 +249,46 @@ export class I18nTranslateAgent {
118
249
  /** 待翻译的语言 */
119
250
  language,
120
251
  /** 待翻译的文件名 */
121
- fileName, translateJson, multiBar, callback, } = params;
252
+ fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, references, blockedKeys, metadata, referenceCache, } = params;
122
253
  try {
254
+ const fileReferences = references !== null && references !== void 0 ? references : (reference ? [reference] : []);
123
255
  // 生成chat循环代码
124
- const promiseList = Object.entries(translateJson).map(([key, value], index) => () => this.translateChat({
125
- key,
126
- value,
127
- language,
128
- index,
129
- fileName,
130
- }));
131
- const progressBar = multiBar.create(promiseList.length, 0);
256
+ const promiseList = Object.entries(translateJson).map(([key, value], index) => () => {
257
+ const matched = fileReferences.flatMap(({ language, matches }) => {
258
+ const match = matches.get(key);
259
+ return match ? [{ language, value: match.translation }] : [];
260
+ });
261
+ return this.translateChat({
262
+ key,
263
+ value,
264
+ language,
265
+ index,
266
+ fileName,
267
+ reference: matched.length === 1 ? matched[0] : undefined,
268
+ references: matched.length > 1 ? matched : undefined,
269
+ metadata,
270
+ });
271
+ });
272
+ const progressBar = taskProgressBar !== null && taskProgressBar !== void 0 ? taskProgressBar : multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(promiseList.length, 0, {
273
+ filename: `${language}:${fileName}`,
274
+ });
132
275
  for (const fn of promiseList) {
133
276
  const result = yield fn();
134
277
  yield this.outputLanguageFile({
135
278
  jsonMap: { [result.key]: result.value },
136
279
  folderName: language,
137
280
  fileName,
281
+ blockedKeys,
138
282
  });
283
+ // 译文写入成功后才更新参考快照,失败或跳过的词条留待下次处理。
284
+ const snapshot = referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.current.get(result.key);
285
+ if (referenceCache && snapshot) {
286
+ const previous = referenceCache.observed.get(result.key);
287
+ referenceCache.observed.set(result.key, Object.assign(Object.assign({}, previous), snapshot));
288
+ writeReferenceCache(referenceCache);
289
+ }
139
290
  delete translateJson[result.key];
140
- progressBar.update(result.index + 1, {
141
- filename: `${language}:${fileName}`,
142
- });
291
+ progressBar === null || progressBar === void 0 ? void 0 : progressBar.increment();
143
292
  }
144
293
  callback && callback();
145
294
  }
@@ -162,11 +311,9 @@ export class I18nTranslateAgent {
162
311
  * @returns
163
312
  */
164
313
  this.translateChat = (params) => __awaiter(this, void 0, void 0, function* () {
165
- var _a, _b, _c;
166
- const { key, value, language, index, fileName } = params;
314
+ var _a, _b;
315
+ const { key, value, language, index, fileName, reference, references, metadata } = params;
167
316
  try {
168
- if (!this.client)
169
- throw new Error("Connection failed");
170
317
  const targetLanguage = this.searchLanguage(language);
171
318
  const originLanguage = this.searchLanguage(this.SOURCE_LANGUAGE);
172
319
  if (!targetLanguage) {
@@ -175,28 +322,72 @@ export class I18nTranslateAgent {
175
322
  if (!originLanguage) {
176
323
  throw new Error(`Unsupported language:${this.SOURCE_LANGUAGE}`);
177
324
  }
325
+ if (isProtectedText(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate)) {
326
+ return { key, value, index };
327
+ }
328
+ if (!this.client)
329
+ throw new Error("Connection failed");
330
+ const protectedText = protectTerms(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate);
331
+ const source = (_a = protectedText === null || protectedText === void 0 ? void 0 : protectedText.text) !== null && _a !== void 0 ? _a : value;
332
+ const referenceEntries = (references !== null && references !== void 0 ? references : (reference ? [reference] : [])).map(({ language, value }) => {
333
+ var _a, _b;
334
+ return ({
335
+ referenceLanguage: (_b = (_a = SUPPORT_LANGUAGE_MAP[language]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : language,
336
+ reference: value,
337
+ });
338
+ });
339
+ let input = source;
340
+ let referenceInstruction = "";
341
+ if (referenceEntries.length > 0) {
342
+ referenceInstruction =
343
+ ". For ambiguous words, abbreviations, and short UI labels, use the reviewed reference to determine the intended product meaning before interpreting or rewriting the source. " +
344
+ "Translate that meaning using the established terminology of the target language and domain.";
345
+ if (referenceEntries.length === 1) {
346
+ input = JSON.stringify(Object.assign({ source }, referenceEntries[0]));
347
+ }
348
+ else {
349
+ input = JSON.stringify({ source, references: referenceEntries });
350
+ referenceInstruction += " Consider the references in the given order.";
351
+ }
352
+ }
353
+ const instructions = [
354
+ `Please translate ${originLanguage.name} to ${targetLanguage.name}${referenceInstruction}`,
355
+ ];
356
+ if (metadata === null || metadata === void 0 ? void 0 : metadata.context) {
357
+ instructions.push(`Business context for this file: ${metadata.context}`);
358
+ }
359
+ if (protectedText) {
360
+ instructions.push("Copy each {__CC_PROTECTED_...} placeholder exactly once. Translate the surrounding text normally.");
361
+ }
178
362
  yield sleep(getRandomNumber(200, 300));
179
- const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
363
+ const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_b = this.chatCompletionCreateParams.model) !== null && _b !== void 0 ? _b : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
180
364
  ...this.fineTune.map((val) => ({
181
365
  role: "system",
182
366
  content: val,
183
367
  })),
184
368
  {
185
369
  role: "system",
186
- content: `Please translate ${originLanguage.name} to ${targetLanguage.name}`,
370
+ content: instructions.join("\n"),
187
371
  },
188
372
  {
189
373
  role: "system",
190
- content: `After translation is complete, directly output the corresponding meaning without any irrelevant content`,
374
+ content: "Return only the translated text in the requested language. " +
375
+ "Do not add the source text, response labels, JSON or Markdown wrappers, or explanations. " +
376
+ "Preserve JSON examples that are part of the source text.",
191
377
  },
192
378
  {
193
379
  role: "user",
194
- content: value,
380
+ content: input,
195
381
  },
196
382
  ] }));
383
+ const choice = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0];
384
+ if ((choice === null || choice === void 0 ? void 0 : choice.message.refusal) || ((choice === null || choice === void 0 ? void 0 : choice.finish_reason) && choice.finish_reason !== "stop")) {
385
+ throw new Error("The model did not complete the translation");
386
+ }
387
+ const translation = readTranslationResponse(choice === null || choice === void 0 ? void 0 : choice.message.content, source);
197
388
  return {
198
389
  key,
199
- value: (_c = (_b = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) !== null && _c !== void 0 ? _c : value,
390
+ value: protectedText ? protectedText.restore(translation) : translation,
200
391
  index,
201
392
  };
202
393
  }
@@ -216,7 +407,8 @@ export class I18nTranslateAgent {
216
407
  * @param fileName
217
408
  * @returns
218
409
  */
219
- this.getTranslateContent = (language, fileName) => __awaiter(this, void 0, void 0, function* () {
410
+ this.getTranslateContent = (language, fileName, deferredEmptyFiles, sourceEntries) => __awaiter(this, void 0, void 0, function* () {
411
+ var _a;
220
412
  const translateFilePath = path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName);
221
413
  /** 缓存文件路径 */
222
414
  const cacheFilePath = path.join(this.CACHE_ROOT_PATH, language, fileName);
@@ -224,16 +416,20 @@ export class I18nTranslateAgent {
224
416
  console.dir(`File not found: ${translateFilePath}`);
225
417
  return;
226
418
  }
227
- const translateFileObject = yield readJsonFileSync(translateFilePath);
419
+ const _b = (_a = sourceEntries !== null && sourceEntries !== void 0 ? sourceEntries : (yield readJsonFileSync(translateFilePath))) !== null && _a !== void 0 ? _a : {}, { _meta } = _b, translateFileObject = __rest(_b, ["_meta"]);
228
420
  const cacheObject = yield getCacheFileSync(cacheFilePath);
229
421
  const diffObject = translateJSONDiffToJson(cacheObject, translateFileObject);
230
422
  if (Object.values(diffObject).length === 0) {
231
423
  if (Object.keys(translateFileObject).length === 0) {
232
- this.outputLanguageFile({
424
+ const emptyFile = {
233
425
  jsonMap: {},
234
426
  folderName: language,
235
427
  fileName,
236
- });
428
+ };
429
+ if (deferredEmptyFiles)
430
+ deferredEmptyFiles.push(emptyFile);
431
+ else
432
+ yield this.outputLanguageFile(emptyFile);
237
433
  }
238
434
  return;
239
435
  }
@@ -244,7 +440,7 @@ export class I18nTranslateAgent {
244
440
  * @param {Object} jsonMap
245
441
  */
246
442
  this.outputLanguageFile = (params) => __awaiter(this, void 0, void 0, function* () {
247
- const { folderName, fileName, jsonMap } = params;
443
+ const { folderName, fileName, jsonMap, blockedKeys } = params;
248
444
  const outputFilePath = path.join(this.outputPath, folderName, fileName);
249
445
  //创建输出文件夹
250
446
  notExistsToCreateFile(this.outputPath);
@@ -252,14 +448,20 @@ export class I18nTranslateAgent {
252
448
  notExistsToCreateFile(`${this.outputPath}/${folderName}`);
253
449
  let oldJsonData = "";
254
450
  // 检查是否存在文件
255
- if (!fs.existsSync(outputFilePath)) {
451
+ const hasOutputFile = fs.existsSync(outputFilePath);
452
+ if (!hasOutputFile) {
256
453
  oldJsonData = yield fs.readFileSync(path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName), "utf8");
257
454
  }
258
455
  else {
259
456
  oldJsonData = yield fs.readFileSync(outputFilePath, "utf8");
260
457
  }
261
458
  const oldJsonMap = JSON.parse(oldJsonData);
459
+ if (!hasOutputFile && blockedKeys) {
460
+ for (const key of blockedKeys)
461
+ delete oldJsonMap[key];
462
+ }
262
463
  const newJsonMap = Object.assign(oldJsonMap, jsonMap);
464
+ delete newJsonMap._meta;
263
465
  yield fs.writeFileSync(path.resolve(outputFilePath), JSON.stringify(newJsonMap, null, 2), "utf8");
264
466
  // 注册缓存
265
467
  yield registerLanguageCacheFile({
@@ -285,6 +487,7 @@ export class I18nTranslateAgent {
285
487
  this.OUTPUT_ROOT_PATH = params.outputRootPath;
286
488
  /** 微调模型 */
287
489
  this.fineTune = (_d = params.fineTune) !== null && _d !== void 0 ? _d : [];
490
+ this.noTranslate = readProtectedTerms(params.noTranslate);
288
491
  /** 需要翻译的语言列表 */
289
492
  this.languages = (_e = params.languages) !== null && _e !== void 0 ? _e : [];
290
493
  /** 翻译任务并发数(队列长度),完成一个即取下一个 */
@@ -311,4 +514,103 @@ export class I18nTranslateAgent {
311
514
  searchLanguage(code) {
312
515
  return this.supportLanguages.find((item) => item.code === code);
313
516
  }
517
+ reviewReferences(matches, language, blocked) {
518
+ return __awaiter(this, void 0, void 0, function* () {
519
+ var _a, _b, _c, _d, _e;
520
+ let skipped = 0;
521
+ const sourceLanguage = (_b = (_a = SUPPORT_LANGUAGE_MAP[this.SOURCE_LANGUAGE]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.SOURCE_LANGUAGE;
522
+ const referenceLanguage = (_d = (_c = SUPPORT_LANGUAGE_MAP[language]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : language;
523
+ const timeout = (_e = this.openaiClientConfig.timeout) !== null && _e !== void 0 ? _e : 30000;
524
+ const checks = Array.from(matches).flatMap(([fileName, entries]) => {
525
+ const blockedKeys = blocked.get(fileName);
526
+ const pending = Array.from(entries).filter(([key]) => !(blockedKeys === null || blockedKeys === void 0 ? void 0 : blockedKeys.has(key)));
527
+ return pending.map(([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
528
+ var _a, _b, _c;
529
+ let issue;
530
+ for (let attempt = 0;; attempt++) {
531
+ const deadline = new AbortController();
532
+ const timer = setTimeout(() => deadline.abort(), timeout);
533
+ try {
534
+ if (!this.client)
535
+ throw new Error("Connection failed");
536
+ const response = yield this.client.chat.completions.create({
537
+ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o",
538
+ messages: [
539
+ {
540
+ role: "system",
541
+ content: "Compare the source UI text and its reference translation. " +
542
+ "Reply CONFLICT only when they clearly express incompatible product meanings. " +
543
+ "A reference that clarifies an ambiguous source or adds compatible detail is not a conflict. " +
544
+ "Reply COMPATIBLE in all other cases. Output exactly one label.",
545
+ },
546
+ {
547
+ role: "user",
548
+ content: JSON.stringify({
549
+ sourceLanguage,
550
+ source,
551
+ referenceLanguage,
552
+ reference: translation,
553
+ }),
554
+ },
555
+ ],
556
+ }, { signal: deadline.signal, timeout, maxRetries: 0 });
557
+ const verdict = (_c = (_b = response.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) === null || _c === void 0 ? void 0 : _c.trim();
558
+ if (verdict === "COMPATIBLE")
559
+ return;
560
+ if (verdict !== "CONFLICT")
561
+ throw new Error("Invalid reference verdict");
562
+ issue = new Error("Reference conflict");
563
+ break;
564
+ }
565
+ catch (error) {
566
+ if (attempt >= this.maxTaskRetries) {
567
+ const reason = deadline.signal.aborted
568
+ ? `request timed out after ${timeout} ms`
569
+ : error;
570
+ issue = new Error(`Reference judgment failed: ${reason}`);
571
+ break;
572
+ }
573
+ }
574
+ finally {
575
+ clearTimeout(timer);
576
+ }
577
+ yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
578
+ }
579
+ let keys = blocked.get(fileName);
580
+ if (!keys) {
581
+ keys = new Set();
582
+ blocked.set(fileName, keys);
583
+ }
584
+ keys.add(key);
585
+ skipped++;
586
+ yield logErrorToFile({ error: issue, fileName, key, language });
587
+ }));
588
+ });
589
+ if (checks.length === 0)
590
+ return;
591
+ let completed = 0;
592
+ const reportProgress = () => {
593
+ console.log(`Reference checks: ${completed}/${checks.length} completed`);
594
+ };
595
+ console.log(`Checking ${checks.length} reference entries before translation...`);
596
+ const progressTimer = setInterval(reportProgress, 10000);
597
+ try {
598
+ yield runWithConcurrencyLimit(checks.map((check) => () => __awaiter(this, void 0, void 0, function* () {
599
+ try {
600
+ yield check();
601
+ }
602
+ finally {
603
+ completed++;
604
+ }
605
+ })), this.concurrency);
606
+ }
607
+ finally {
608
+ clearInterval(progressTimer);
609
+ }
610
+ reportProgress();
611
+ if (skipped) {
612
+ console.warn(`Skipped ${skipped} reference entries. See error.log for details.`);
613
+ }
614
+ });
615
+ }
314
616
  }
@@ -1,4 +1,4 @@
1
- import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile } from "../../types";
1
+ import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile, ReferenceCacheState, ReferenceSnapshot } from "../../types/index.js";
2
2
  /**
3
3
  * 和翻译缓存json文件对比 返回存在更改的json文件
4
4
  * @param {object} cacheObject 已经缓存的对象
@@ -12,6 +12,8 @@ export declare const translateJSONDiffToJson: (cacheObject: IJson, translateObje
12
12
  * @returns {Promise<{key:value}>}
13
13
  */
14
14
  export declare const getCacheFileSync: (filePath: string) => Promise<IJson>;
15
+ export declare const readReferenceCache: (filePath: string) => Map<string, ReferenceSnapshot>;
16
+ export declare const writeReferenceCache: ({ filePath, observed }: ReferenceCacheState) => void;
15
17
  /**
16
18
  * 注册语言缓存文件
17
19
  * @param {string} language
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAEL,wBAAwB,EACxB,oBAAoB,EACpB,KAAK,EACL,0BAA0B,EAC3B,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,gBACrB,KAAK,mBACD,KAAK,UAiBvB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,aAAoB,MAAM,KAAG,OAAO,CAAC,KAAK,CAMtE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAC5B,0BAA0B,kBAmBnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,WAAkB,oBAAoB,kBAwC/D,CAAC;AAwCF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WAAY,wBAAwB,SA8BhE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,wBAAwB,EACxB,oBAAoB,EACpB,KAAK,EACL,0BAA0B,EAC1B,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAE9B;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,gBACrB,KAAK,mBACD,KAAK,UAiBvB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,aAAoB,MAAM,KAAG,OAAO,CAAC,KAAK,CAMtE,CAAC;AAGF,eAAO,MAAM,kBAAkB,aAAc,MAAM,KAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAGpE,CAAC;AAEhB,eAAO,MAAM,mBAAmB,2BAA4B,mBAAmB,SAS9E,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAC5B,0BAA0B,kBAoBnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,WAAkB,oBAAoB,kBAwC/D,CAAC;AAwCF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WAAY,wBAAwB,SA8BhE,CAAC"}