@publishpress/potomatic 0.0.0-stage → 1.4.5
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/CHANGELOG.md +127 -0
- package/LICENSE.md +20 -0
- package/README.md +470 -2
- package/config/openai-pricing.json +112 -0
- package/config/po-header.json +10 -0
- package/config/prompt.md +23 -0
- package/package.json +84 -5
- package/potomatic +103 -0
- package/src/config/index.js +497 -0
- package/src/logging/index.js +362 -0
- package/src/orchestrator/index.js +1031 -0
- package/src/processors/batchProcessor.js +171 -0
- package/src/processors/languageProcessor.js +1464 -0
- package/src/providers/ProviderFactory.js +124 -0
- package/src/providers/base/Provider.js +198 -0
- package/src/providers/openai/OpenAIProvider.js +805 -0
- package/src/providers/openai/modelCapabilities.js +256 -0
- package/src/reporters/ConsoleReporter.js +256 -0
- package/src/reporters/JsonReporter.js +254 -0
- package/src/reporters/ReporterFactory.js +218 -0
- package/src/reporters/base/BaseReporter.js +124 -0
- package/src/utils/colorUtils.js +93 -0
- package/src/utils/costCalculations.js +245 -0
- package/src/utils/costTracker.js +277 -0
- package/src/utils/dictionaryUtils.js +211 -0
- package/src/utils/languageMapping.js +1113 -0
- package/src/utils/pluralization.js +39 -0
- package/src/utils/poFileUtils.js +599 -0
- package/src/utils/promptLoader.js +115 -0
- package/src/utils/reportingUtils.js +417 -0
- package/src/utils/validationStats.js +110 -0
- package/src/utils/xmlTranslation.js +532 -0
|
@@ -0,0 +1,1464 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { prepareBatches } from './batchProcessor.js';
|
|
4
|
+
import { parsePotFile, countUntranslatedStrings, mergePoData, compilePoFile, initializePluralForms, getPluralForms, extractPluralCount, countRealTranslations } from '../utils/poFileUtils.js';
|
|
5
|
+
import { createCostAccumulator } from '../utils/costTracker.js';
|
|
6
|
+
import { buildSystemPrompt, getPromptTokenCount } from '../utils/promptLoader.js';
|
|
7
|
+
import { formatCost, formatNumber, formatDuration } from '../utils/costCalculations.js';
|
|
8
|
+
import { getFileNamingLocale, normalizeLanguageInput, getLanguageName } from '../utils/languageMapping.js';
|
|
9
|
+
import { buildXmlPrompt, buildDictionaryResponse } from '../utils/xmlTranslation.js';
|
|
10
|
+
import { loadDictionary, findDictionaryMatches } from '../utils/dictionaryUtils.js';
|
|
11
|
+
import { createEmptyValidationStats, accumulateValidationStats, getTotalValidationIssues, formatValidationBreakdown } from '../utils/validationStats.js';
|
|
12
|
+
|
|
13
|
+
// Cost threshold for determining when to show budget-related skip messages.
|
|
14
|
+
// When cost reaches 80% of remaining budget, we show explanatory messages.
|
|
15
|
+
const BUDGET_WARNING_THRESHOLD = 0.8;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Handles the complete translation workflow for a single language.
|
|
19
|
+
* Manages POT parsing, existing translation merging, batch processing, and PO file compilation.
|
|
20
|
+
*
|
|
21
|
+
* @since 1.0.0
|
|
22
|
+
*/
|
|
23
|
+
export class LanguageProcessor {
|
|
24
|
+
/**
|
|
25
|
+
* Creates a new LanguageProcessor instance.
|
|
26
|
+
*
|
|
27
|
+
* @since 1.0.0
|
|
28
|
+
*
|
|
29
|
+
* @param {Object} config - Configuration object.
|
|
30
|
+
* @param {Provider} provider - AI provider instance.
|
|
31
|
+
* @param {Object} logger - Logger instance for this language.
|
|
32
|
+
*/
|
|
33
|
+
constructor(config, provider, logger) {
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.provider = provider;
|
|
36
|
+
this.logger = logger;
|
|
37
|
+
this.costAccumulator = createCostAccumulator();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Processes translation for a single language with complete workflow.
|
|
42
|
+
* Handles POT parsing, merging, batch translation, and progress tracking.
|
|
43
|
+
*
|
|
44
|
+
* @since 1.0.0
|
|
45
|
+
*
|
|
46
|
+
* @param {string} language - Target language code (e.g., 'fr_FR', 'ja').
|
|
47
|
+
* @param {Function|null} progressCallback - Optional callback for progress updates.
|
|
48
|
+
*
|
|
49
|
+
* @throws {Error} When critical errors occur during processing.
|
|
50
|
+
*
|
|
51
|
+
* @return {Object} Statistics object containing translation results and counts.
|
|
52
|
+
*/
|
|
53
|
+
async processLanguage(language, progressCallback = null) {
|
|
54
|
+
const stats = this._initializeStats(language);
|
|
55
|
+
|
|
56
|
+
this.stats = stats;
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
this.logger.info(`Processing language: ${language}`);
|
|
60
|
+
|
|
61
|
+
const normalizedTarget = normalizeLanguageInput(language);
|
|
62
|
+
const normalizedSource = normalizeLanguageInput(this.config.sourceLanguage);
|
|
63
|
+
const targetBaseCode = normalizedTarget.split(/[_-]/)[0];
|
|
64
|
+
const sourceBaseCode = normalizedSource.split(/[_-]/)[0];
|
|
65
|
+
|
|
66
|
+
if (targetBaseCode === sourceBaseCode) {
|
|
67
|
+
return await this._processSameLanguage(language, stats);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const outputFile = this._getOutputFilePath(language);
|
|
71
|
+
|
|
72
|
+
stats.outputFile = outputFile;
|
|
73
|
+
|
|
74
|
+
this.logger.info(`Output .po file will be: ${outputFile}`);
|
|
75
|
+
|
|
76
|
+
const potData = await this._loadPotFile();
|
|
77
|
+
|
|
78
|
+
this.potData = potData;
|
|
79
|
+
stats.totalStringsInPot = countUntranslatedStrings(potData);
|
|
80
|
+
|
|
81
|
+
const { outputPoData, mergedStringsCount } = await this._mergeExistingTranslations(potData, language);
|
|
82
|
+
|
|
83
|
+
this.outputPoData = outputPoData;
|
|
84
|
+
stats.mergedFromExisting = mergedStringsCount;
|
|
85
|
+
|
|
86
|
+
const batches = await this._prepareBatches(outputPoData);
|
|
87
|
+
const totalStringsToTranslate = batches.reduce((sum, batch) => sum + batch.length, 0);
|
|
88
|
+
|
|
89
|
+
stats.alreadyTranslated = countRealTranslations(outputPoData);
|
|
90
|
+
|
|
91
|
+
const totalUntranslatedStrings = countUntranslatedStrings(outputPoData);
|
|
92
|
+
|
|
93
|
+
stats.skippedDueToLimits = Math.max(0, totalUntranslatedStrings - totalStringsToTranslate);
|
|
94
|
+
|
|
95
|
+
if (totalStringsToTranslate === 0) {
|
|
96
|
+
this.logger.info(`No strings to translate for ${language}. Saving existing/merged .po file.`);
|
|
97
|
+
|
|
98
|
+
await this._savePoFile(outputPoData, language, outputFile);
|
|
99
|
+
|
|
100
|
+
return stats;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const { successCount, failedCount, skippedDueToBudget, validationStats } = await this._processBatches(batches, outputPoData, language, outputFile, progressCallback);
|
|
104
|
+
|
|
105
|
+
stats.translatedInRun = successCount;
|
|
106
|
+
stats.failedInRun = failedCount;
|
|
107
|
+
stats.skippedDueToBudget = skippedDueToBudget;
|
|
108
|
+
|
|
109
|
+
this.logger.success(`All batches for ${language} processed successfully.`);
|
|
110
|
+
|
|
111
|
+
stats.costData = this.costAccumulator.getTotals();
|
|
112
|
+
stats.validationStats = validationStats;
|
|
113
|
+
|
|
114
|
+
return stats;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
this.logger.error(`Critical error processing ${language}: ${error.message}`);
|
|
117
|
+
stats.error = error.message;
|
|
118
|
+
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Initializes the statistics object for language processing.
|
|
125
|
+
*
|
|
126
|
+
* @private
|
|
127
|
+
*
|
|
128
|
+
* @since 1.0.0
|
|
129
|
+
*
|
|
130
|
+
* @param {string} language - Target language code.
|
|
131
|
+
*
|
|
132
|
+
* @return {Object} Initialized statistics object.
|
|
133
|
+
*/
|
|
134
|
+
_initializeStats(language) {
|
|
135
|
+
return {
|
|
136
|
+
language,
|
|
137
|
+
totalStringsInPot: 0,
|
|
138
|
+
mergedFromExisting: 0,
|
|
139
|
+
translatedInRun: 0,
|
|
140
|
+
failedInRun: 0,
|
|
141
|
+
skippedDueToBudget: 0,
|
|
142
|
+
skippedDueToLimits: 0,
|
|
143
|
+
alreadyTranslated: 0,
|
|
144
|
+
method: 'api_translation',
|
|
145
|
+
outputFile: null,
|
|
146
|
+
costData: null,
|
|
147
|
+
error: null,
|
|
148
|
+
validationStats: createEmptyValidationStats(),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Processes same-language translation by copying source strings directly.
|
|
154
|
+
* Used when target language matches source language to avoid unnecessary API calls.
|
|
155
|
+
*
|
|
156
|
+
* @private
|
|
157
|
+
*
|
|
158
|
+
* @since 1.0.0
|
|
159
|
+
*
|
|
160
|
+
* @param {string} language - Target language code (same as source).
|
|
161
|
+
* @param {Object} stats - Statistics object to populate.
|
|
162
|
+
*
|
|
163
|
+
* @return {Promise<Object>} Updated statistics object.
|
|
164
|
+
*/
|
|
165
|
+
async _processSameLanguage(language, stats) {
|
|
166
|
+
this.logger.info(`Target language '${language}' matches source language '${this.config.sourceLanguage}' - copying strings directly`);
|
|
167
|
+
|
|
168
|
+
const outputFile = this._getOutputFilePath(language);
|
|
169
|
+
|
|
170
|
+
stats.outputFile = outputFile;
|
|
171
|
+
|
|
172
|
+
const potData = await this._loadPotFile();
|
|
173
|
+
|
|
174
|
+
stats.totalStringsInPot = countUntranslatedStrings(potData);
|
|
175
|
+
|
|
176
|
+
const outputPoData = JSON.parse(JSON.stringify(potData));
|
|
177
|
+
const copiedCount = this._copySourceStringsToTarget(outputPoData);
|
|
178
|
+
|
|
179
|
+
await this._savePoFile(outputPoData, language, outputFile);
|
|
180
|
+
|
|
181
|
+
stats.translatedInRun = copiedCount;
|
|
182
|
+
stats.mergedFromExisting = 0;
|
|
183
|
+
stats.failedInRun = 0;
|
|
184
|
+
stats.method = 'source_copy';
|
|
185
|
+
|
|
186
|
+
const formattedCount = formatNumber(copiedCount);
|
|
187
|
+
|
|
188
|
+
this.logger.success(`Copied ${formattedCount} strings from source language to ${language}.po`);
|
|
189
|
+
|
|
190
|
+
return stats;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Copies source strings to target strings for same-language processing.
|
|
195
|
+
*
|
|
196
|
+
* @private
|
|
197
|
+
*
|
|
198
|
+
* @since 1.0.0
|
|
199
|
+
*
|
|
200
|
+
* @param {Object} outputPoData - PO data structure to modify.
|
|
201
|
+
*
|
|
202
|
+
* @return {number} Number of strings copied.
|
|
203
|
+
*/
|
|
204
|
+
_copySourceStringsToTarget(outputPoData) {
|
|
205
|
+
let copiedCount = 0;
|
|
206
|
+
|
|
207
|
+
for (const [, contextData] of Object.entries(outputPoData.translations)) {
|
|
208
|
+
for (const [msgid, translation] of Object.entries(contextData)) {
|
|
209
|
+
if (!msgid || msgid === '') {
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (translation.msgstr && Array.isArray(translation.msgstr)) {
|
|
214
|
+
translation.msgstr = [msgid];
|
|
215
|
+
} else {
|
|
216
|
+
translation.msgstr = msgid;
|
|
217
|
+
}
|
|
218
|
+
copiedCount++;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return copiedCount;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Generates the output file path for a given language.
|
|
227
|
+
* Combines configured prefix, language code, and output directory.
|
|
228
|
+
* Uses the configured locale format for file naming.
|
|
229
|
+
*
|
|
230
|
+
* @private
|
|
231
|
+
*
|
|
232
|
+
* @since 1.0.0
|
|
233
|
+
*
|
|
234
|
+
* @param {string} language - Target language code.
|
|
235
|
+
*
|
|
236
|
+
* @return {string} Full path to output .po file.
|
|
237
|
+
*/
|
|
238
|
+
_getOutputFilePath(language) {
|
|
239
|
+
const fileNamingLocale = getFileNamingLocale(language, this.config.localeFormat);
|
|
240
|
+
const fileName = `${this.config.poFilePrefix}${fileNamingLocale}.po`;
|
|
241
|
+
|
|
242
|
+
return path.join(this.config.outputDir, fileName);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Loads and parses the POT file specified in configuration.
|
|
247
|
+
* Validates file existence and POT data structure before returning.
|
|
248
|
+
*
|
|
249
|
+
* @private
|
|
250
|
+
*
|
|
251
|
+
* @since 1.0.0
|
|
252
|
+
*
|
|
253
|
+
* @throws {Error} If POT file cannot be loaded or parsed.
|
|
254
|
+
*
|
|
255
|
+
* @return {Promise<Object>} Parsed POT data structure.
|
|
256
|
+
*/
|
|
257
|
+
async _loadPotFile() {
|
|
258
|
+
try {
|
|
259
|
+
const potData = await parsePotFile(this.config.potFilePath, this.logger);
|
|
260
|
+
|
|
261
|
+
if (!potData || !potData.translations) {
|
|
262
|
+
throw new Error(`Parsed .pot file is empty or invalid: ${this.config.potFilePath}`);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return potData;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
this.logger.error(`Could not load or parse POT file ${this.config.potFilePath}. Error: ${error.message}`);
|
|
268
|
+
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Merges existing translations with POT data to preserve completed work.
|
|
275
|
+
* Handles force translate mode and missing existing files gracefully.
|
|
276
|
+
*
|
|
277
|
+
* @private
|
|
278
|
+
*
|
|
279
|
+
* @since 1.0.0
|
|
280
|
+
*
|
|
281
|
+
* @param {Object} potData - Parsed POT data structure.
|
|
282
|
+
* @param {string} language - Target language code.
|
|
283
|
+
*
|
|
284
|
+
* @return {Promise<Object>} Object containing outputPoData and mergedStringsCount.
|
|
285
|
+
*/
|
|
286
|
+
async _mergeExistingTranslations(potData, language) {
|
|
287
|
+
// Initialize plural forms for the target language.
|
|
288
|
+
let outputPoData = initializePluralForms(potData, language, this.logger);
|
|
289
|
+
let mergedStringsCount = 0;
|
|
290
|
+
|
|
291
|
+
if (this.config.forceTranslate) {
|
|
292
|
+
this.logger.info(`Force translate enabled for ${language}: Starting with a clean slate from the .pot file.`);
|
|
293
|
+
|
|
294
|
+
return { outputPoData, mergedStringsCount };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Check for specific input PO path first, then conventional output path
|
|
298
|
+
let existingPoPath = null;
|
|
299
|
+
|
|
300
|
+
if (this.config.inputPoPath && fs.existsSync(this.config.inputPoPath)) {
|
|
301
|
+
existingPoPath = this.config.inputPoPath;
|
|
302
|
+
|
|
303
|
+
this.logger.info(`Using specific input .po file: ${existingPoPath}`);
|
|
304
|
+
} else {
|
|
305
|
+
const outputFile = this._getOutputFilePath(language);
|
|
306
|
+
|
|
307
|
+
if (fs.existsSync(outputFile)) {
|
|
308
|
+
existingPoPath = outputFile;
|
|
309
|
+
this.logger.info(`Found existing .po file at conventional path: ${existingPoPath}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (!existingPoPath) {
|
|
314
|
+
this.logger.info(`No existing .po file found for ${language}. Starting fresh translation.`);
|
|
315
|
+
|
|
316
|
+
return { outputPoData, mergedStringsCount };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
this.logger.info(`Attempting to merge translations from: ${existingPoPath}`);
|
|
321
|
+
|
|
322
|
+
const existingPoData = await parsePotFile(existingPoPath, this.logger);
|
|
323
|
+
|
|
324
|
+
if (existingPoData) {
|
|
325
|
+
const mergeResult = mergePoData(outputPoData, existingPoData, this.logger, language);
|
|
326
|
+
|
|
327
|
+
outputPoData = mergeResult.outputPoData;
|
|
328
|
+
mergedStringsCount = mergeResult.mergedStringsCount;
|
|
329
|
+
|
|
330
|
+
this.logger.info(`Merge complete. ${formatNumber(mergedStringsCount)} strings were merged.`);
|
|
331
|
+
}
|
|
332
|
+
} catch (error) {
|
|
333
|
+
this.logger.warn(`Could not parse existing .po file ${existingPoPath}. Proceeding without merging. Error: ${error.message}`);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return { outputPoData, mergedStringsCount };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Prepares translation batches from PO data.
|
|
341
|
+
* Delegates to the batch processor with configured batch size and string limits.
|
|
342
|
+
*
|
|
343
|
+
* @private
|
|
344
|
+
*
|
|
345
|
+
* @since 1.0.0
|
|
346
|
+
*
|
|
347
|
+
* @param {Object} outputPoData - PO data structure to prepare batches from.
|
|
348
|
+
*
|
|
349
|
+
* @return {Promise<Array>} Array of batches ready for translation.
|
|
350
|
+
*/
|
|
351
|
+
async _prepareBatches(outputPoData) {
|
|
352
|
+
return prepareBatches(outputPoData, this.config.batchSize, this.logger, this.config.maxStrings);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Processes all translation batches sequentially with error handling and progress tracking.
|
|
357
|
+
* Handles dry run mode, cost tracking, and automatic file saving after each batch.
|
|
358
|
+
*
|
|
359
|
+
* @private
|
|
360
|
+
*
|
|
361
|
+
* @since 1.0.0
|
|
362
|
+
*
|
|
363
|
+
* @param {Array} batches - Array of translation batches to process.
|
|
364
|
+
* @param {Object} outputPoData - PO data structure to update with translations.
|
|
365
|
+
* @param {string} language - Target language code.
|
|
366
|
+
* @param {string} outputFile - Path to output .po file.
|
|
367
|
+
* @param {Function|null} progressCallback - Optional callback for progress updates.
|
|
368
|
+
*
|
|
369
|
+
* @throws {Error} If critical errors occur during batch processing.
|
|
370
|
+
*
|
|
371
|
+
* @return {Promise<Object>} Object containing successCount, failedCount, and skippedDueToBudget.
|
|
372
|
+
*/
|
|
373
|
+
async _processBatches(batches, outputPoData, language, outputFile, progressCallback) {
|
|
374
|
+
const skippedDueToLimitsCount = 0;
|
|
375
|
+
const totalStringsToTranslate = batches.reduce((sum, batch) => sum + batch.length, 0);
|
|
376
|
+
const processStartTime = Date.now();
|
|
377
|
+
let successfullyTranslatedCount = 0;
|
|
378
|
+
let actuallyFailedCount = 0;
|
|
379
|
+
let skippedDueToBudgetCount = 0;
|
|
380
|
+
let processedStringsCount = 0;
|
|
381
|
+
let previousBatchDuration = null;
|
|
382
|
+
|
|
383
|
+
// Accumulate validation stats across all batches.
|
|
384
|
+
const accumulatedValidationStats = createEmptyValidationStats();
|
|
385
|
+
|
|
386
|
+
for (let i = 0; i < batches.length; i++) {
|
|
387
|
+
const batch = batches[i];
|
|
388
|
+
const batchNumber = i + 1;
|
|
389
|
+
const batchStartTime = Date.now();
|
|
390
|
+
|
|
391
|
+
this.logger.info(`Processing batch ${batchNumber} of ${batches.length} (${formatNumber(batch.length || 0)} strings)…`);
|
|
392
|
+
|
|
393
|
+
this._updateProgressCallback(progressCallback, processedStringsCount, totalStringsToTranslate, language, batchNumber, batches.length, previousBatchDuration, processStartTime, '');
|
|
394
|
+
|
|
395
|
+
try {
|
|
396
|
+
let translatedBatchItems;
|
|
397
|
+
|
|
398
|
+
if (this.config.dryRun) {
|
|
399
|
+
const dryRunResult = await this._processDryRunBatch(batch, batchNumber, batches.length, language);
|
|
400
|
+
|
|
401
|
+
translatedBatchItems = dryRunResult.translatedBatchItems;
|
|
402
|
+
|
|
403
|
+
if (this._shouldStopDueToCostLimit(batches, i, skippedDueToBudgetCount, processedStringsCount, language)) {
|
|
404
|
+
const remainingBatches = batches.slice(i + 1);
|
|
405
|
+
|
|
406
|
+
skippedDueToBudgetCount = remainingBatches.reduce((sum, batch) => sum + batch.length, 0);
|
|
407
|
+
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
if (this._shouldStopBeforeBatch(batch, batchNumber, batches, i, skippedDueToBudgetCount, processedStringsCount, language)) {
|
|
412
|
+
const remainingBatches = batches.slice(i);
|
|
413
|
+
|
|
414
|
+
skippedDueToBudgetCount = remainingBatches.reduce((sum, batch) => sum + batch.length, 0);
|
|
415
|
+
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const batchResult = await this._processActualBatch(batch, language, batchNumber, batches.length, progressCallback, processedStringsCount, totalStringsToTranslate, processStartTime);
|
|
420
|
+
|
|
421
|
+
translatedBatchItems = batchResult.translatedBatchItems;
|
|
422
|
+
|
|
423
|
+
if (!batchResult.success) {
|
|
424
|
+
const failureResult = await this._handleBatchFailure(batchResult, batch, batchNumber, batches, i, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount);
|
|
425
|
+
|
|
426
|
+
if (failureResult.shouldStop) {
|
|
427
|
+
if (failureResult.shouldThrow) {
|
|
428
|
+
throw new Error(failureResult.errorMessage);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
successfullyTranslatedCount = failureResult.successfullyTranslatedCount;
|
|
432
|
+
actuallyFailedCount = failureResult.actuallyFailedCount;
|
|
433
|
+
processedStringsCount = failureResult.processedStringsCount;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
if (this.config.stopOnMaxRetriesFailure || this.config.skipJobOnMaxRetriesFailure) {
|
|
438
|
+
successfullyTranslatedCount = failureResult.successfullyTranslatedCount;
|
|
439
|
+
actuallyFailedCount = failureResult.actuallyFailedCount;
|
|
440
|
+
processedStringsCount = failureResult.processedStringsCount;
|
|
441
|
+
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (batchResult.cost) {
|
|
447
|
+
this.costAccumulator.addCost(batchResult.cost);
|
|
448
|
+
|
|
449
|
+
if (this._shouldStopAfterBatch(batches, i, skippedDueToBudgetCount, processedStringsCount, language)) {
|
|
450
|
+
break;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Accumulate validation stats from this batch.
|
|
455
|
+
if (batchResult.validationStats) {
|
|
456
|
+
accumulateValidationStats(accumulatedValidationStats, batchResult.validationStats);
|
|
457
|
+
|
|
458
|
+
// Debug: log validation stats.
|
|
459
|
+
this.logger.debug(`Batch ${batchNumber} validation stats:`, JSON.stringify(batchResult.validationStats));
|
|
460
|
+
} else {
|
|
461
|
+
this.logger.debug(`Batch ${batchNumber} has no validationStats`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
this._updatePoDataWithBatch(outputPoData, translatedBatchItems);
|
|
466
|
+
|
|
467
|
+
const { batchSuccessCount, batchFailedCount, errorSummary } = this._countBatchResults(translatedBatchItems);
|
|
468
|
+
|
|
469
|
+
successfullyTranslatedCount += batchSuccessCount;
|
|
470
|
+
actuallyFailedCount += batchFailedCount;
|
|
471
|
+
processedStringsCount += batch.length;
|
|
472
|
+
|
|
473
|
+
const batchEndTime = Date.now();
|
|
474
|
+
|
|
475
|
+
previousBatchDuration = batchEndTime - batchStartTime;
|
|
476
|
+
|
|
477
|
+
this.logger.success(`Batch ${batchNumber} processed. Success: ${batchSuccessCount}, Failed: ${batchFailedCount}.`);
|
|
478
|
+
|
|
479
|
+
if (batchFailedCount > 0 && errorSummary) {
|
|
480
|
+
this.logger.warn(`Batch ${batchNumber} errors: ${errorSummary}`);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
await this._savePoFile(outputPoData, language, outputFile);
|
|
484
|
+
|
|
485
|
+
this.logger.info(`Batch ${batchNumber}/${batches.length} data saved to ${outputFile}.`);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
this.logger.error(`Critical error during translation of batch ${batchNumber}: ${error.message}`);
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
this._logFinalSummary(language, successfullyTranslatedCount, batches, skippedDueToBudgetCount, outputFile);
|
|
493
|
+
|
|
494
|
+
// Display validation summary at verbosity level 2+ in detailed logs.
|
|
495
|
+
const totalValidationIssues = getTotalValidationIssues(accumulatedValidationStats);
|
|
496
|
+
|
|
497
|
+
this.logger.debug(`Total validation issues: ${totalValidationIssues}`, JSON.stringify(accumulatedValidationStats));
|
|
498
|
+
this.logger.debug(`Verbose level: ${this.config.verboseLevel || 1}`);
|
|
499
|
+
|
|
500
|
+
if (totalValidationIssues > 0) {
|
|
501
|
+
const breakdown = formatValidationBreakdown(accumulatedValidationStats);
|
|
502
|
+
|
|
503
|
+
this.logger.warn(`Validation: ${breakdown}`);
|
|
504
|
+
|
|
505
|
+
const blanked = accumulatedValidationStats.blankedStrings || [];
|
|
506
|
+
|
|
507
|
+
if (blanked.length > 0) {
|
|
508
|
+
this.logger.warn(`Blanked ${blanked.length} translation(s) due to placeholder mismatch:`);
|
|
509
|
+
|
|
510
|
+
for (const b of blanked) {
|
|
511
|
+
this.logger.warn(` "${b.msgid}" [form ${b.form}]: expected [${b.expected}], got [${b.got}]`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
return {
|
|
517
|
+
successCount: successfullyTranslatedCount,
|
|
518
|
+
failedCount: actuallyFailedCount,
|
|
519
|
+
skippedDueToBudget: skippedDueToBudgetCount,
|
|
520
|
+
skippedDueToLimits: skippedDueToLimitsCount,
|
|
521
|
+
validationStats: accumulatedValidationStats,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Updates progress callback with current translation status.
|
|
527
|
+
*
|
|
528
|
+
* @private
|
|
529
|
+
*
|
|
530
|
+
* @since 1.0.0
|
|
531
|
+
*
|
|
532
|
+
* @param {Function|null} progressCallback - Optional callback for progress updates.
|
|
533
|
+
* @param {number} processedStringsCount - Number of strings processed so far.
|
|
534
|
+
* @param {number} totalStringsToTranslate - Total number of strings to translate.
|
|
535
|
+
* @param {string} language - Target language code.
|
|
536
|
+
* @param {number} batchNumber - Current batch number.
|
|
537
|
+
* @param {number} totalBatches - Total number of batches.
|
|
538
|
+
* @param {number|null} previousBatchDuration - Duration of previous batch in milliseconds.
|
|
539
|
+
* @param {number|null} processStartTime - Start time of the entire process in milliseconds.
|
|
540
|
+
* @param {string} retryStatus - Retry status string to append to the first line.
|
|
541
|
+
*/
|
|
542
|
+
_updateProgressCallback(progressCallback, processedStringsCount, totalStringsToTranslate, language, batchNumber, totalBatches, previousBatchDuration, processStartTime = null, retryStatus = '') {
|
|
543
|
+
if (!progressCallback) return;
|
|
544
|
+
|
|
545
|
+
const languageDisplayName = getLanguageName(language);
|
|
546
|
+
const currentCost = this.costAccumulator.getTotals().totalCost;
|
|
547
|
+
const currentTokens = this.costAccumulator.getTotals().totalTokens;
|
|
548
|
+
|
|
549
|
+
// Get POT stats - use consistent data source.
|
|
550
|
+
// Show original POT counts (before plural expansion) to avoid user confusion.
|
|
551
|
+
const potStats = this.potData
|
|
552
|
+
? {
|
|
553
|
+
total: this._countAllPotEntries(this.potData),
|
|
554
|
+
merged: this.stats ? this.stats.mergedFromExisting : 0,
|
|
555
|
+
// Calculate untranslated based on original POT count, not expanded plural forms
|
|
556
|
+
untranslated: this._countAllPotEntries(this.potData) - (this.stats ? this.stats.mergedFromExisting : 0),
|
|
557
|
+
}
|
|
558
|
+
: { total: 0, merged: 0, untranslated: 0 };
|
|
559
|
+
|
|
560
|
+
// Calculate batch progress.
|
|
561
|
+
const batchSize = this.config.batchSize;
|
|
562
|
+
const currentBatchProgress = Math.min(processedStringsCount, totalStringsToTranslate);
|
|
563
|
+
const progressPercentage = totalStringsToTranslate > 0 ? Math.round((currentBatchProgress / totalStringsToTranslate) * 100) : 0;
|
|
564
|
+
|
|
565
|
+
// Format cost display
|
|
566
|
+
const costDisplay = this.config.maxCost ? `$${currentCost.toFixed(6)}/$${this.config.maxCost.toFixed(6)}` : `$${currentCost.toFixed(6)}`;
|
|
567
|
+
|
|
568
|
+
// Build limit display - only show when there are actual limits.
|
|
569
|
+
let limitDisplay = '';
|
|
570
|
+
const limits = [];
|
|
571
|
+
|
|
572
|
+
if (this.config.maxStrings) {
|
|
573
|
+
limits.push(`${this.config.maxStrings} strings`);
|
|
574
|
+
}
|
|
575
|
+
if (this.config.maxStringsTotal) {
|
|
576
|
+
limits.push(`${this.config.maxStringsTotal} total strings`);
|
|
577
|
+
}
|
|
578
|
+
if (this.config.maxCost) {
|
|
579
|
+
limits.push(`$${this.config.maxCost.toFixed(6)} cost`);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if (limits.length > 0) {
|
|
583
|
+
limitDisplay = ` | Limit: ${limits.join(', ')}`;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// Calculate execution time if start time is provided.
|
|
587
|
+
let timeText = '';
|
|
588
|
+
|
|
589
|
+
if (processStartTime) {
|
|
590
|
+
const elapsedMs = Date.now() - processStartTime;
|
|
591
|
+
timeText = formatDuration(elapsedMs);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const batchSizeText = timeText ? `📦 Batch Size: ${batchSize} | Progress: ${currentBatchProgress}/${totalStringsToTranslate} (${progressPercentage}%) | Time: ${timeText}` : `📦 Batch Size: ${batchSize} | Progress: ${currentBatchProgress}/${totalStringsToTranslate} (${progressPercentage}%)`;
|
|
595
|
+
|
|
596
|
+
const progressLines = [
|
|
597
|
+
`⠼ Language: ${language} (${languageDisplayName}) | Batch ${batchNumber} of ${totalBatches}${limitDisplay}${retryStatus}`,
|
|
598
|
+
`📊 POT Stats: ${potStats.total} strings, ${potStats.merged} merged, ${potStats.untranslated} strings to translate`,
|
|
599
|
+
batchSizeText,
|
|
600
|
+
`💰 Cost: ${costDisplay} | Tokens: ${formatNumber(currentTokens)}`,
|
|
601
|
+
];
|
|
602
|
+
|
|
603
|
+
const progressText = progressLines.join('\n');
|
|
604
|
+
|
|
605
|
+
progressCallback(progressText);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Processes a batch in dry run mode with cost estimation.
|
|
610
|
+
*
|
|
611
|
+
* @private
|
|
612
|
+
*
|
|
613
|
+
* @since 1.0.0
|
|
614
|
+
*
|
|
615
|
+
* @param {Array} batch - Translation batch to process.
|
|
616
|
+
* @param {number} batchNumber - Current batch number.
|
|
617
|
+
* @param {number} totalBatches - Total number of batches.
|
|
618
|
+
* @param {string} language - Target language code.
|
|
619
|
+
*
|
|
620
|
+
* @return {Promise<Object>} Object containing translatedBatchItems.
|
|
621
|
+
*/
|
|
622
|
+
async _processDryRunBatch(batch, batchNumber, totalBatches, language) {
|
|
623
|
+
this.logger.info(`[Batch ${batchNumber}/${totalBatches}] DRY RUN: Analyzing ${formatNumber(batch.length || 0)} strings for translation`);
|
|
624
|
+
|
|
625
|
+
const systemPrompt = buildSystemPrompt(language, this.config.sourceLanguage, this.config.promptFilePath, this.config.extraPromptPath);
|
|
626
|
+
const costData = this._calculateDryRunCosts(batch, systemPrompt, language);
|
|
627
|
+
|
|
628
|
+
// Log dictionary usage if enabled.
|
|
629
|
+
if (this.config.useDictionary && costData.dictionaryInfo.matches > 0) {
|
|
630
|
+
this.logger.info(`Dictionary: ${costData.dictionaryInfo.matches} matching terms found (+${costData.dictionaryInfo.additionalTokens} tokens)`);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (this.config.verboseLevel >= 2) {
|
|
634
|
+
// Calculate prompt components to show what would be sent to AI.
|
|
635
|
+
const pluralFormsString = getPluralForms(language, this.logger);
|
|
636
|
+
const pluralCount = extractPluralCount(pluralFormsString);
|
|
637
|
+
|
|
638
|
+
// Load dictionary if enabled.
|
|
639
|
+
let dictionaryMatches = [];
|
|
640
|
+
|
|
641
|
+
if (this.config.useDictionary) {
|
|
642
|
+
const dictionary = loadDictionary(this.config.dictionaryPath, language, this.logger);
|
|
643
|
+
|
|
644
|
+
dictionaryMatches = findDictionaryMatches(batch, dictionary);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Build the actual XML prompt that would be sent.
|
|
648
|
+
const promptResult = buildXmlPrompt(batch, language, pluralCount, dictionaryMatches);
|
|
649
|
+
|
|
650
|
+
this.logger.info(`=== DRY RUN: SYSTEM MESSAGE ===`);
|
|
651
|
+
this.logger.info(systemPrompt);
|
|
652
|
+
this.logger.info(`=== END SYSTEM MESSAGE ===`);
|
|
653
|
+
this.logger.info(`=== DRY RUN: USER MESSAGE (XML) ===`);
|
|
654
|
+
this.logger.info(promptResult.xmlPrompt);
|
|
655
|
+
this.logger.info(`=== END USER MESSAGE ===`);
|
|
656
|
+
|
|
657
|
+
// Show dictionary response if there are matches
|
|
658
|
+
if (dictionaryMatches.length > 0) {
|
|
659
|
+
const dictionaryResponse = buildDictionaryResponse(dictionaryMatches);
|
|
660
|
+
|
|
661
|
+
this.logger.info(`=== DRY RUN: DICTIONARY EXAMPLES ===`);
|
|
662
|
+
this.logger.info(dictionaryResponse);
|
|
663
|
+
this.logger.info(`=== END DICTIONARY EXAMPLES ===`);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
this._logDryRunSamples(batch, batchNumber);
|
|
668
|
+
|
|
669
|
+
const { estimatedCost, totalEstimatedTokens, inputTokens, estimatedOutputTokens } = costData;
|
|
670
|
+
|
|
671
|
+
this.logger.info(`[Batch ${batchNumber}] Estimated tokens: ${formatNumber(totalEstimatedTokens || 0)} (input: ${formatNumber(inputTokens || 0)}, estimated output: ${formatNumber(estimatedOutputTokens || 0)}), Estimated cost: $${formatCost(estimatedCost)}`);
|
|
672
|
+
|
|
673
|
+
const translatedBatchItems = batch.map((item) => ({
|
|
674
|
+
...item,
|
|
675
|
+
msgstr: [`[DRY RUN] Would translate: "${item.msgid.substring(0, 50)}${item.msgid.length > 50 ? '…' : ''}"`],
|
|
676
|
+
dryRun: true,
|
|
677
|
+
}));
|
|
678
|
+
|
|
679
|
+
const estimatedCostData = {
|
|
680
|
+
totalCost: estimatedCost,
|
|
681
|
+
totalTokens: totalEstimatedTokens,
|
|
682
|
+
inputTokens,
|
|
683
|
+
outputTokens: estimatedOutputTokens,
|
|
684
|
+
model: this.config.model,
|
|
685
|
+
estimated: true,
|
|
686
|
+
isDryRun: true,
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
this.costAccumulator.addCost(estimatedCostData);
|
|
690
|
+
|
|
691
|
+
return { translatedBatchItems };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Logs sample strings for dry run batches based on verbosity level.
|
|
696
|
+
*
|
|
697
|
+
* @private
|
|
698
|
+
*
|
|
699
|
+
* @since 1.0.0
|
|
700
|
+
*
|
|
701
|
+
* @param {Array} batch - Translation batch.
|
|
702
|
+
* @param {number} batchNumber - Current batch number.
|
|
703
|
+
*/
|
|
704
|
+
_logDryRunSamples(batch, batchNumber) {
|
|
705
|
+
if (this.config.verboseLevel >= 2) {
|
|
706
|
+
this.logger.info(`Sample strings from batch ${batchNumber}:`);
|
|
707
|
+
|
|
708
|
+
const sampleCount = Math.min(3, batch.length);
|
|
709
|
+
|
|
710
|
+
for (let j = 0; j < sampleCount; j++) {
|
|
711
|
+
const item = batch[j];
|
|
712
|
+
const preview = item.msgid.length > 80 ? item.msgid.substring(0, 80) + '…' : item.msgid;
|
|
713
|
+
|
|
714
|
+
this.logger.info(` [${j + 1}] "${preview}"`);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
if (batch.length > sampleCount) {
|
|
718
|
+
this.logger.info(` … and ${batch.length - sampleCount} more strings`);
|
|
719
|
+
}
|
|
720
|
+
} else if (this.config.verboseLevel >= 1) {
|
|
721
|
+
this.logger.info(`Sample strings: "${batch[0].msgid.substring(0, 60)}${batch[0].msgid.length > 60 ? '…' : ''}"${batch.length > 1 ? ` and ${batch.length - 1} more` : ''}`);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* Calculates estimated costs for dry run batch processing.
|
|
727
|
+
*
|
|
728
|
+
* @private
|
|
729
|
+
*
|
|
730
|
+
* @since 1.0.0
|
|
731
|
+
*
|
|
732
|
+
* @param {Array} batch - Translation batch.
|
|
733
|
+
* @param {string} systemPrompt - System prompt for translation.
|
|
734
|
+
* @param {string} language - Target language code.
|
|
735
|
+
*
|
|
736
|
+
* @return {Object} Object containing cost calculations.
|
|
737
|
+
*/
|
|
738
|
+
_calculateDryRunCosts(batch, systemPrompt, language) {
|
|
739
|
+
const systemPromptTokens = getPromptTokenCount(systemPrompt, this.config.model);
|
|
740
|
+
|
|
741
|
+
// Calculate plural count for target language
|
|
742
|
+
const pluralFormsString = getPluralForms(language, this.logger);
|
|
743
|
+
const pluralCount = extractPluralCount(pluralFormsString);
|
|
744
|
+
|
|
745
|
+
// Load dictionary if enabled to get accurate prompt size.
|
|
746
|
+
let dictionaryMatches = [];
|
|
747
|
+
|
|
748
|
+
if (this.config.useDictionary) {
|
|
749
|
+
const dictionary = loadDictionary(this.config.dictionaryPath, language, this.logger);
|
|
750
|
+
|
|
751
|
+
dictionaryMatches = findDictionaryMatches(batch, dictionary);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Use XML prompt format with dictionary for accurate cost estimation.
|
|
755
|
+
const promptResult = buildXmlPrompt(batch, language, pluralCount, dictionaryMatches);
|
|
756
|
+
const userMessageTokens = getPromptTokenCount(promptResult.xmlPrompt, this.config.model);
|
|
757
|
+
|
|
758
|
+
// Account for additional dictionary assistant response and follow-up.
|
|
759
|
+
let dictionaryResponseTokens = 0;
|
|
760
|
+
|
|
761
|
+
if (dictionaryMatches.length > 0) {
|
|
762
|
+
const dictionaryResponse = dictionaryMatches.map((match, index) => `<t i="${index + 1}">${match.target}</t>`).join('\n');
|
|
763
|
+
|
|
764
|
+
dictionaryResponseTokens = getPromptTokenCount(dictionaryResponse, this.config.model);
|
|
765
|
+
|
|
766
|
+
// Add tokens for the follow-up user message
|
|
767
|
+
const followUpTokens = getPromptTokenCount('<!-- Now translate the actual strings -->', this.config.model);
|
|
768
|
+
|
|
769
|
+
dictionaryResponseTokens += followUpTokens;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const inputTokens = systemPromptTokens + userMessageTokens + dictionaryResponseTokens;
|
|
773
|
+
const estimatedOutputTokens = Math.round(userMessageTokens * 1.4);
|
|
774
|
+
const totalEstimatedTokens = inputTokens + estimatedOutputTokens;
|
|
775
|
+
|
|
776
|
+
const pricing = this.provider.getModelPricing(this.config.model);
|
|
777
|
+
const inputCost = (inputTokens / 1000) * pricing.prompt;
|
|
778
|
+
const outputCost = (estimatedOutputTokens / 1000) * pricing.completion;
|
|
779
|
+
const estimatedCost = inputCost + outputCost;
|
|
780
|
+
|
|
781
|
+
return {
|
|
782
|
+
estimatedCost,
|
|
783
|
+
totalEstimatedTokens,
|
|
784
|
+
inputTokens,
|
|
785
|
+
estimatedOutputTokens,
|
|
786
|
+
dictionaryInfo: {
|
|
787
|
+
matches: dictionaryMatches.length,
|
|
788
|
+
additionalTokens: dictionaryResponseTokens,
|
|
789
|
+
},
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Checks if processing should stop due to cost limit in dry run mode.
|
|
795
|
+
*
|
|
796
|
+
* @private
|
|
797
|
+
*
|
|
798
|
+
* @since 1.0.0
|
|
799
|
+
*
|
|
800
|
+
* @param {Array} batches - All translation batches.
|
|
801
|
+
* @param {number} currentIndex - Current batch index.
|
|
802
|
+
* @param {number} skippedDueToBudgetCount - Current count of skipped strings.
|
|
803
|
+
* @param {number} processedStringsCount - Current count of processed strings.
|
|
804
|
+
* @param {string} language - Target language code.
|
|
805
|
+
*
|
|
806
|
+
* @return {boolean} True if processing should stop.
|
|
807
|
+
*/
|
|
808
|
+
_shouldStopDueToCostLimit(batches, currentIndex, skippedDueToBudgetCount, processedStringsCount, language) {
|
|
809
|
+
if (this.config.maxCostRemaining === undefined || this.config.maxCostRemaining === null || this.costAccumulator.getTotals().totalCost < this.config.maxCostRemaining) {
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
this.logger.info(`DRY RUN: Estimated cost limit approaching. Estimated cost: ${formatCost(this.costAccumulator.getTotals().totalCost)}, Limit: ${formatCost(this.config.maxCostRemaining)}`);
|
|
814
|
+
this.logger.info(`DRY RUN: Would stop translation for ${language} to avoid exceeding budget.`);
|
|
815
|
+
|
|
816
|
+
const remainingBatches = batches.length - (currentIndex + 1);
|
|
817
|
+
|
|
818
|
+
if (remainingBatches > 0) {
|
|
819
|
+
const remainingStrings = batches.slice(currentIndex + 1).reduce((sum, batch) => sum + batch.length, 0);
|
|
820
|
+
|
|
821
|
+
this.logger.info(`DRY RUN: Would skip ${remainingBatches} remaining batches (${formatNumber(remainingStrings || 0)} strings) due to cost limit.`);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Checks if processing should stop before processing a batch due to cost limits.
|
|
829
|
+
*
|
|
830
|
+
* @private
|
|
831
|
+
*
|
|
832
|
+
* @since 1.0.0
|
|
833
|
+
*
|
|
834
|
+
* @param {Array} batch - Current translation batch.
|
|
835
|
+
* @param {number} batchNumber - Current batch number.
|
|
836
|
+
* @param {Array} batches - All translation batches.
|
|
837
|
+
* @param {number} currentIndex - Current batch index.
|
|
838
|
+
* @param {number} skippedDueToBudgetCount - Current count of skipped strings.
|
|
839
|
+
* @param {number} processedStringsCount - Current count of processed strings.
|
|
840
|
+
* @param {string} language - Target language code.
|
|
841
|
+
*
|
|
842
|
+
* @return {boolean} True if processing should stop.
|
|
843
|
+
*/
|
|
844
|
+
_shouldStopBeforeBatch(batch, batchNumber, batches, currentIndex, skippedDueToBudgetCount, processedStringsCount, language) {
|
|
845
|
+
if (this.config.maxCostRemaining === undefined || this.config.maxCostRemaining === null) {
|
|
846
|
+
return false;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const currentCost = this.costAccumulator.getTotals().totalCost;
|
|
850
|
+
const limit = this.config.maxCostRemaining;
|
|
851
|
+
|
|
852
|
+
// Stop if we've already reached or exceeded the limit.
|
|
853
|
+
if (currentCost >= limit) {
|
|
854
|
+
this.logger.info(`Cost limit reached before batch ${batchNumber}. Current cost: ${formatCost(currentCost)}, Limit: ${formatCost(limit)}`);
|
|
855
|
+
this.logger.info(`Stopping translation for ${language} to avoid exceeding budget.`);
|
|
856
|
+
|
|
857
|
+
this._logRemainingBatchesSkipped(batches, currentIndex, language);
|
|
858
|
+
|
|
859
|
+
return true;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// Check if this batch would exceed the limit.
|
|
863
|
+
const estimatedBatchCost = this._estimateBatchCost(batch, language);
|
|
864
|
+
|
|
865
|
+
// Use a smarter threshold that works better with small remaining budgets
|
|
866
|
+
// For small budgets (< $.0.001), use a small absolute safety margin
|
|
867
|
+
// For larger budgets, use a percentage-based approach.
|
|
868
|
+
let safetyThreshold;
|
|
869
|
+
|
|
870
|
+
if (limit < 0.001) {
|
|
871
|
+
// For small budgets, use a small absolute margin (.e.g., $0.00005).
|
|
872
|
+
safetyThreshold = Math.max(limit - 0.00005, limit * 0.9);
|
|
873
|
+
} else {
|
|
874
|
+
// For larger budgets, use 95% threshold.
|
|
875
|
+
safetyThreshold = limit * 0.95;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
if (currentCost + estimatedBatchCost > safetyThreshold) {
|
|
879
|
+
this.logger.info(`Cost limit would be exceeded by batch ${batchNumber}:`);
|
|
880
|
+
this.logger.info(` Current cost: ${formatCost(currentCost)}`);
|
|
881
|
+
this.logger.info(` Estimated batch cost: ${formatCost(estimatedBatchCost)} (${formatNumber(batch.length || 0)} strings)`);
|
|
882
|
+
this.logger.info(` Total would be: ${formatCost(currentCost + estimatedBatchCost)} (exceeds safety threshold: ${formatCost(safetyThreshold)})`);
|
|
883
|
+
this.logger.info(` Remaining budget: ${formatCost(limit)}`);
|
|
884
|
+
this.logger.info(`Stopping translation for ${language} to avoid exceeding budget.`);
|
|
885
|
+
|
|
886
|
+
this._logRemainingBatchesSkipped(batches, currentIndex, language);
|
|
887
|
+
|
|
888
|
+
return true;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* Estimates the cost of processing a single batch.
|
|
896
|
+
*
|
|
897
|
+
* @private
|
|
898
|
+
*
|
|
899
|
+
* @since 1.0.0
|
|
900
|
+
*
|
|
901
|
+
* @param {Array} batch - Translation batch.
|
|
902
|
+
* @param {string} language - Target language code.
|
|
903
|
+
*
|
|
904
|
+
* @return {number} Estimated cost for the batch.
|
|
905
|
+
*/
|
|
906
|
+
_estimateBatchCost(batch, language) {
|
|
907
|
+
const systemPrompt = buildSystemPrompt(language, this.config.sourceLanguage, this.config.promptFilePath, this.config.extraPromptPath);
|
|
908
|
+
const costData = this._calculateDryRunCosts(batch, systemPrompt, language);
|
|
909
|
+
|
|
910
|
+
return costData.estimatedCost;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Logs information about remaining batches being skipped.
|
|
915
|
+
*
|
|
916
|
+
* @private
|
|
917
|
+
*
|
|
918
|
+
* @since 1.0.0
|
|
919
|
+
*
|
|
920
|
+
* @param {Array} batches - All translation batches.
|
|
921
|
+
* @param {number} currentIndex - Current batch index.
|
|
922
|
+
* @param {string} language - Target language code.
|
|
923
|
+
*/
|
|
924
|
+
_logRemainingBatchesSkipped(batches, currentIndex, language) {
|
|
925
|
+
const remainingBatches = batches.length - currentIndex;
|
|
926
|
+
const remainingStrings = batches.slice(currentIndex).reduce((sum, batch) => sum + batch.length, 0);
|
|
927
|
+
|
|
928
|
+
this.logger.info(`Skipping ${remainingBatches} remaining batches (${formatNumber(remainingStrings || 0)} strings) due to cost limit.`);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Counts successful and failed translations in a batch and categorizes errors.
|
|
933
|
+
* Provides detailed statistics for batch processing results.
|
|
934
|
+
*
|
|
935
|
+
* @private
|
|
936
|
+
*
|
|
937
|
+
* @since 1.0.0
|
|
938
|
+
*
|
|
939
|
+
* @param {Array} translatedBatchItems - Array of translated items from batch processing.
|
|
940
|
+
*
|
|
941
|
+
* @return {Object} Object containing batchSuccessCount, batchFailedCount, and errorSummary.
|
|
942
|
+
*/
|
|
943
|
+
_countBatchResults(translatedBatchItems) {
|
|
944
|
+
const errorTypes = new Map();
|
|
945
|
+
let batchSuccessCount = 0;
|
|
946
|
+
let batchFailedCount = 0;
|
|
947
|
+
|
|
948
|
+
for (const item of translatedBatchItems) {
|
|
949
|
+
// Check if translation was successful (has valid msgstr content.).
|
|
950
|
+
const msgstr = item.msgstr?.[0];
|
|
951
|
+
const msgstrText = typeof msgstr === 'string' ? msgstr : '';
|
|
952
|
+
|
|
953
|
+
// Handle dry run as successful.
|
|
954
|
+
if (item.dryRun || (msgstr && msgstrText !== '' && msgstrText.startsWith('[DRY RUN]'))) {
|
|
955
|
+
batchSuccessCount++;
|
|
956
|
+
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// Handle regular successful translations.
|
|
961
|
+
if (msgstr && msgstrText !== '' && !msgstrText.startsWith('[DRY RUN')) {
|
|
962
|
+
batchSuccessCount++;
|
|
963
|
+
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// Handle failures.
|
|
968
|
+
batchFailedCount++;
|
|
969
|
+
|
|
970
|
+
// Collect error types for summary.
|
|
971
|
+
let errorType = 'Translation failed';
|
|
972
|
+
|
|
973
|
+
if (item.error) {
|
|
974
|
+
errorType = item.error;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
errorTypes.set(errorType, (errorTypes.get(errorType) || 0) + 1);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// Create error summary.
|
|
981
|
+
let errorSummary = null;
|
|
982
|
+
|
|
983
|
+
if (errorTypes.size > 0) {
|
|
984
|
+
const errorEntries = Array.from(errorTypes.entries());
|
|
985
|
+
|
|
986
|
+
errorSummary = errorEntries.map(([error, count]) => `${error} (${count}x)`).join(', ');
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
return { batchSuccessCount, batchFailedCount, errorSummary };
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* Updates PO data with translated batch items, only applying valid translations.
|
|
994
|
+
* Ensures failed translations don't overwrite existing data.
|
|
995
|
+
*
|
|
996
|
+
* @private
|
|
997
|
+
*
|
|
998
|
+
* @since 1.0.0
|
|
999
|
+
*
|
|
1000
|
+
* @param {Object} outputPoData - PO data structure to update.
|
|
1001
|
+
* @param {Array} translatedBatchItems - Array of translated items from batch processing.
|
|
1002
|
+
*/
|
|
1003
|
+
_updatePoDataWithBatch(outputPoData, translatedBatchItems) {
|
|
1004
|
+
// Update the outputPoData with only successfully translated batch items.
|
|
1005
|
+
for (const item of translatedBatchItems) {
|
|
1006
|
+
// Skip if the item doesn't have a valid translation.
|
|
1007
|
+
if (!item.msgstr || !item.msgstr[0] || item.msgstr[0] === '') {
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// Debug logging to see what we're processing
|
|
1012
|
+
this.logger.debug(`Updating item: "${item.msgid}"`);
|
|
1013
|
+
this.logger.debug(` msgstr type: ${Array.isArray(item.msgstr) ? 'Array' : typeof item.msgstr}`);
|
|
1014
|
+
this.logger.debug(` msgstr length: ${Array.isArray(item.msgstr) ? item.msgstr.length : 'N/A'}`);
|
|
1015
|
+
this.logger.debug(` msgstr content: ${JSON.stringify(item.msgstr)}`);
|
|
1016
|
+
|
|
1017
|
+
// Find the corresponding entry in outputPoData and update it.
|
|
1018
|
+
for (const contextKey in outputPoData.translations) {
|
|
1019
|
+
const context = outputPoData.translations[contextKey];
|
|
1020
|
+
|
|
1021
|
+
if (context[item.msgid]) {
|
|
1022
|
+
// If item has context info, only update if contexts match.
|
|
1023
|
+
if (item.msgctxt !== undefined && contextKey !== (item.msgctxt || '')) {
|
|
1024
|
+
continue;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
this.logger.debug(` Found entry in context "${contextKey}"`);
|
|
1028
|
+
this.logger.debug(` Before update: ${JSON.stringify(context[item.msgid].msgstr)}`);
|
|
1029
|
+
|
|
1030
|
+
context[item.msgid].msgstr = item.msgstr;
|
|
1031
|
+
|
|
1032
|
+
this.logger.debug(` After update: ${JSON.stringify(context[item.msgid].msgstr)}`);
|
|
1033
|
+
break;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Saves PO data to a .po file using the configured template and formatting.
|
|
1041
|
+
* Validates successful save operation and throws on failure.
|
|
1042
|
+
*
|
|
1043
|
+
* @private
|
|
1044
|
+
*
|
|
1045
|
+
* @since 1.0.0
|
|
1046
|
+
*
|
|
1047
|
+
* @param {Object} outputPoData - PO data structure to save.
|
|
1048
|
+
* @param {string} language - Target language code.
|
|
1049
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1050
|
+
*
|
|
1051
|
+
* @return {Promise<void>} Resolves when file is saved successfully.
|
|
1052
|
+
*
|
|
1053
|
+
* @throws {Error} If file save operation fails.
|
|
1054
|
+
*/
|
|
1055
|
+
async _savePoFile(outputPoData, language, outputFile) {
|
|
1056
|
+
const success = await compilePoFile(outputPoData, language, outputFile, this.logger, this.config.poHeaderTemplatePath);
|
|
1057
|
+
|
|
1058
|
+
if (!success) {
|
|
1059
|
+
throw new Error(`Failed to save .po file: ${outputFile}`);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Processes an actual translation batch (non-dry-run).
|
|
1065
|
+
*
|
|
1066
|
+
* @private
|
|
1067
|
+
*
|
|
1068
|
+
* @since 1.0.0
|
|
1069
|
+
*
|
|
1070
|
+
* @param {Array} batch - Translation batch to process.
|
|
1071
|
+
* @param {string} language - Target language code.
|
|
1072
|
+
* @param {number} batchNumber - Current batch number.
|
|
1073
|
+
* @param {number} totalBatches - Total number of batches.
|
|
1074
|
+
* @param {Function|null} progressCallback - Optional callback for progress updates.
|
|
1075
|
+
* @param {number} processedStringsCount - Current count of processed strings.
|
|
1076
|
+
* @param {number} totalStringsToTranslate - Total number of strings to translate.
|
|
1077
|
+
* @param {number} processStartTime - Start time of the entire process in milliseconds.
|
|
1078
|
+
*
|
|
1079
|
+
* @return {Promise<Object>} Object containing batch result and translated items.
|
|
1080
|
+
*/
|
|
1081
|
+
async _processActualBatch(batch, language, batchNumber, totalBatches, progressCallback, processedStringsCount, totalStringsToTranslate, processStartTime) {
|
|
1082
|
+
const systemPrompt = buildSystemPrompt(language, this.config.sourceLanguage, this.config.promptFilePath, this.config.extraPromptPath);
|
|
1083
|
+
|
|
1084
|
+
// Calculate plural count for target language.
|
|
1085
|
+
const pluralFormsString = getPluralForms(language, this.logger);
|
|
1086
|
+
const pluralCount = extractPluralCount(pluralFormsString);
|
|
1087
|
+
|
|
1088
|
+
// Create a function to update progress with current state.
|
|
1089
|
+
const updateProgress = (retryInfo = null) => {
|
|
1090
|
+
// Add retry status to the existing progress callback.
|
|
1091
|
+
const retryStatus = retryInfo && retryInfo.isRetrying ? ` (retry ${retryInfo.attempt}/${retryInfo.maxRetries})` : '';
|
|
1092
|
+
|
|
1093
|
+
// Call the main progress callback with retry info.
|
|
1094
|
+
this._updateProgressCallback(progressCallback, processedStringsCount, totalStringsToTranslate, language, batchNumber, totalBatches, null, processStartTime, retryStatus);
|
|
1095
|
+
};
|
|
1096
|
+
|
|
1097
|
+
// Set up real-time progress updates every 2 seconds.
|
|
1098
|
+
let progressTimer = null;
|
|
1099
|
+
if (progressCallback) {
|
|
1100
|
+
// Initial progress update.
|
|
1101
|
+
updateProgress();
|
|
1102
|
+
|
|
1103
|
+
// Start timer for periodic updates.
|
|
1104
|
+
progressTimer = setInterval(() => {
|
|
1105
|
+
updateProgress();
|
|
1106
|
+
}, 500); // Update every 500ms for real-time feel.
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
const retryProgressCallback = (retryInfo) => {
|
|
1110
|
+
// Update progress with retry information.
|
|
1111
|
+
updateProgress(retryInfo);
|
|
1112
|
+
};
|
|
1113
|
+
|
|
1114
|
+
// Prepare debug configuration if debug mode is enabled.
|
|
1115
|
+
const debugConfig = this.config.saveDebugInfo
|
|
1116
|
+
? {
|
|
1117
|
+
saveDebugInfo: true,
|
|
1118
|
+
outputDir: this.config.outputDir || '.',
|
|
1119
|
+
targetLang: language,
|
|
1120
|
+
batchNum: batchNumber,
|
|
1121
|
+
totalBatches,
|
|
1122
|
+
}
|
|
1123
|
+
: null;
|
|
1124
|
+
|
|
1125
|
+
let batchResult;
|
|
1126
|
+
|
|
1127
|
+
try {
|
|
1128
|
+
batchResult = await this.provider.translateBatch(batch, language, this.config.model, systemPrompt, this.config.maxRetries, this.config.retryDelayMs, this.config.timeout, this.config.dryRun, retryProgressCallback, debugConfig, pluralCount);
|
|
1129
|
+
} finally {
|
|
1130
|
+
// Clear the progress timer.
|
|
1131
|
+
if (progressTimer) {
|
|
1132
|
+
clearInterval(progressTimer);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
let translatedBatchItems;
|
|
1137
|
+
|
|
1138
|
+
if (batchResult.success) {
|
|
1139
|
+
translatedBatchItems = batchResult.translations.map((t, index) => {
|
|
1140
|
+
const originalItem = batch[index];
|
|
1141
|
+
|
|
1142
|
+
// Handle plural forms (msgstr is already an array).
|
|
1143
|
+
if (Array.isArray(t.msgstr)) {
|
|
1144
|
+
return {
|
|
1145
|
+
msgid: t.msgid,
|
|
1146
|
+
msgstr: t.msgstr,
|
|
1147
|
+
msgctxt: originalItem.msgctxt,
|
|
1148
|
+
dryRun: batchResult.isDryRun,
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// Handle regular strings (wrap in array).
|
|
1153
|
+
return {
|
|
1154
|
+
msgid: t.msgid,
|
|
1155
|
+
msgstr: [t.msgstr || ''],
|
|
1156
|
+
msgctxt: originalItem.msgctxt,
|
|
1157
|
+
dryRun: batchResult.isDryRun,
|
|
1158
|
+
};
|
|
1159
|
+
});
|
|
1160
|
+
} else {
|
|
1161
|
+
this.logger.error(`Batch ${batchNumber} failed: ${batchResult.error || 'Unknown error'}`);
|
|
1162
|
+
|
|
1163
|
+
translatedBatchItems = batch.map((item) => ({
|
|
1164
|
+
msgid: item.msgid,
|
|
1165
|
+
msgstr: [''],
|
|
1166
|
+
msgctxt: item.msgctxt,
|
|
1167
|
+
error: batchResult.error || 'Translation failed',
|
|
1168
|
+
}));
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
return {
|
|
1172
|
+
...batchResult,
|
|
1173
|
+
translatedBatchItems,
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Handles batch failure scenarios based on configuration settings.
|
|
1179
|
+
*
|
|
1180
|
+
* @private
|
|
1181
|
+
*
|
|
1182
|
+
* @since 1.0.0
|
|
1183
|
+
*
|
|
1184
|
+
* @param {Object} batchResult - Result from failed batch processing.
|
|
1185
|
+
* @param {Array} batch - Translation batch that failed.
|
|
1186
|
+
* @param {number} batchNumber - Current batch number.
|
|
1187
|
+
* @param {Array} batches - All translation batches.
|
|
1188
|
+
* @param {number} currentIndex - Current batch index.
|
|
1189
|
+
* @param {Object} outputPoData - PO data structure to update.
|
|
1190
|
+
* @param {string} language - Target language code.
|
|
1191
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1192
|
+
* @param {number} successfullyTranslatedCount - Current success count.
|
|
1193
|
+
* @param {number} actuallyFailedCount - Current failure count.
|
|
1194
|
+
* @param {number} processedStringsCount - Current processed count.
|
|
1195
|
+
*
|
|
1196
|
+
* @return {Promise<Object>} Object containing updated counts and control flags.
|
|
1197
|
+
*/
|
|
1198
|
+
async _handleBatchFailure(batchResult, batch, batchNumber, batches, currentIndex, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount) {
|
|
1199
|
+
const translatedBatchItems = batchResult.translatedBatchItems;
|
|
1200
|
+
|
|
1201
|
+
if (this.config.stopOnMaxRetriesFailure) {
|
|
1202
|
+
return await this._handleStopOnFailure(translatedBatchItems, batch, batchNumber, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount);
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
if (this.config.skipJobOnMaxRetriesFailure) {
|
|
1206
|
+
return await this._handleSkipJobOnFailure(translatedBatchItems, batch, batchNumber, batches, currentIndex, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount);
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
this.logger.warn(`Batch ${batchNumber} failed, but continuing with remaining batches for ${language}.`);
|
|
1210
|
+
|
|
1211
|
+
return {
|
|
1212
|
+
shouldStop: false,
|
|
1213
|
+
shouldThrow: false,
|
|
1214
|
+
successfullyTranslatedCount,
|
|
1215
|
+
actuallyFailedCount,
|
|
1216
|
+
processedStringsCount,
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/**
|
|
1221
|
+
* Handles stop-on-failure scenario.
|
|
1222
|
+
*
|
|
1223
|
+
* @private
|
|
1224
|
+
*
|
|
1225
|
+
* @since 1.0.0
|
|
1226
|
+
*
|
|
1227
|
+
* @param {Array} translatedBatchItems - Translated items from failed batch.
|
|
1228
|
+
* @param {Array} batch - Translation batch that failed.
|
|
1229
|
+
* @param {number} batchNumber - Current batch number.
|
|
1230
|
+
* @param {Object} outputPoData - PO data structure to update.
|
|
1231
|
+
* @param {string} language - Target language code.
|
|
1232
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1233
|
+
* @param {number} successfullyTranslatedCount - Current success count.
|
|
1234
|
+
* @param {number} actuallyFailedCount - Current failure count.
|
|
1235
|
+
* @param {number} processedStringsCount - Current processed count.
|
|
1236
|
+
*
|
|
1237
|
+
* @return {Promise<Object>} Object containing updated counts and control flags.
|
|
1238
|
+
*/
|
|
1239
|
+
async _handleStopOnFailure(translatedBatchItems, batch, batchNumber, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount) {
|
|
1240
|
+
this.logger.error(`Batch ${batchNumber} failed after max retries. Stopping entire translation process due to --stop-on-max-retries-failure setting.`);
|
|
1241
|
+
this._updatePoDataWithBatch(outputPoData, translatedBatchItems);
|
|
1242
|
+
|
|
1243
|
+
const { batchSuccessCount, batchFailedCount, errorSummary } = this._countBatchResults(translatedBatchItems);
|
|
1244
|
+
|
|
1245
|
+
const updatedSuccessCount = successfullyTranslatedCount + batchSuccessCount;
|
|
1246
|
+
const updatedFailedCount = actuallyFailedCount + batchFailedCount;
|
|
1247
|
+
const updatedProcessedCount = processedStringsCount + batch.length;
|
|
1248
|
+
|
|
1249
|
+
this.logger.error(`Batch ${batchNumber} processed with failures. Success: ${batchSuccessCount}, Failed: ${batchFailedCount}.`);
|
|
1250
|
+
|
|
1251
|
+
if (batchFailedCount > 0 && errorSummary) {
|
|
1252
|
+
this.logger.warn(`Batch ${batchNumber} errors: ${errorSummary}`);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
await this._savePoFile(outputPoData, language, outputFile);
|
|
1256
|
+
|
|
1257
|
+
return {
|
|
1258
|
+
shouldStop: true,
|
|
1259
|
+
shouldThrow: true,
|
|
1260
|
+
errorMessage: `Translation stopped: Batch ${batchNumber} for ${language} failed after ${this.config.maxRetries} retries`,
|
|
1261
|
+
successfullyTranslatedCount: updatedSuccessCount,
|
|
1262
|
+
actuallyFailedCount: updatedFailedCount,
|
|
1263
|
+
processedStringsCount: updatedProcessedCount,
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* Handles skip-job-on-failure scenario.
|
|
1269
|
+
*
|
|
1270
|
+
* @private
|
|
1271
|
+
*
|
|
1272
|
+
* @since 1.0.0
|
|
1273
|
+
*
|
|
1274
|
+
* @param {Array} translatedBatchItems - Translated items from failed batch.
|
|
1275
|
+
* @param {Array} batch - Translation batch that failed.
|
|
1276
|
+
* @param {number} batchNumber - Current batch number.
|
|
1277
|
+
* @param {Array} batches - All translation batches.
|
|
1278
|
+
* @param {number} currentIndex - Current batch index.
|
|
1279
|
+
* @param {Object} outputPoData - PO data structure to update.
|
|
1280
|
+
* @param {string} language - Target language code.
|
|
1281
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1282
|
+
* @param {number} successfullyTranslatedCount - Current success count.
|
|
1283
|
+
* @param {number} actuallyFailedCount - Current failure count.
|
|
1284
|
+
* @param {number} processedStringsCount - Current processed count.
|
|
1285
|
+
*
|
|
1286
|
+
* @return {Promise<Object>} Object containing updated counts and control flags.
|
|
1287
|
+
*/
|
|
1288
|
+
async _handleSkipJobOnFailure(translatedBatchItems, batch, batchNumber, batches, currentIndex, outputPoData, language, outputFile, successfullyTranslatedCount, actuallyFailedCount, processedStringsCount) {
|
|
1289
|
+
this.logger.warn(`Batch ${batchNumber} failed after max retries. Skipping remaining batches for ${language} due to --skip-job-on-max-retries-failure setting.`);
|
|
1290
|
+
|
|
1291
|
+
const remainingBatches = batches.length - currentIndex;
|
|
1292
|
+
let updatedFailedCount = actuallyFailedCount;
|
|
1293
|
+
let updatedProcessedCount = processedStringsCount;
|
|
1294
|
+
|
|
1295
|
+
if (remainingBatches > 1) {
|
|
1296
|
+
const remainingStrings = batches.slice(currentIndex + 1).reduce((sum, batch) => sum + batch.length, 0);
|
|
1297
|
+
|
|
1298
|
+
this.logger.info(`Skipping ${remainingBatches - 1} remaining batches (${formatNumber(remainingStrings || 0)} strings) for ${language}.`);
|
|
1299
|
+
updatedFailedCount += remainingStrings;
|
|
1300
|
+
updatedProcessedCount += remainingStrings;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
this._updatePoDataWithBatch(outputPoData, translatedBatchItems);
|
|
1304
|
+
|
|
1305
|
+
const { batchSuccessCount, batchFailedCount, errorSummary } = this._countBatchResults(translatedBatchItems);
|
|
1306
|
+
|
|
1307
|
+
const updatedSuccessCount = successfullyTranslatedCount + batchSuccessCount;
|
|
1308
|
+
|
|
1309
|
+
updatedFailedCount += batchFailedCount;
|
|
1310
|
+
updatedProcessedCount += batch.length;
|
|
1311
|
+
|
|
1312
|
+
this.logger.warn(`Batch ${batchNumber} processed with failures. Success: ${batchSuccessCount}, Failed: ${batchFailedCount}.`);
|
|
1313
|
+
|
|
1314
|
+
if (batchFailedCount > 0 && errorSummary) {
|
|
1315
|
+
this.logger.warn(`Batch ${batchNumber} errors: ${errorSummary}`);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
await this._savePoFile(outputPoData, language, outputFile);
|
|
1319
|
+
|
|
1320
|
+
this.logger.info(`${language} processing stopped due to batch failure. Partial data saved to ${outputFile}.`);
|
|
1321
|
+
|
|
1322
|
+
return {
|
|
1323
|
+
shouldStop: true,
|
|
1324
|
+
shouldThrow: false,
|
|
1325
|
+
successfullyTranslatedCount: updatedSuccessCount,
|
|
1326
|
+
actuallyFailedCount: updatedFailedCount,
|
|
1327
|
+
processedStringsCount: updatedProcessedCount,
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/**
|
|
1332
|
+
* Checks if processing should stop after a batch due to cost limits.
|
|
1333
|
+
*
|
|
1334
|
+
* @private
|
|
1335
|
+
*
|
|
1336
|
+
* @since 1.0.0
|
|
1337
|
+
*
|
|
1338
|
+
* @param {Array} batches - All translation batches.
|
|
1339
|
+
* @param {number} currentIndex - Current batch index.
|
|
1340
|
+
* @param {number} skippedDueToBudgetCount - Current count of skipped strings.
|
|
1341
|
+
* @param {number} processedStringsCount - Current count of processed strings.
|
|
1342
|
+
* @param {string} language - Target language code.
|
|
1343
|
+
*
|
|
1344
|
+
* @return {boolean} True if processing should stop.
|
|
1345
|
+
*/
|
|
1346
|
+
_shouldStopAfterBatch(batches, currentIndex, skippedDueToBudgetCount, processedStringsCount, language) {
|
|
1347
|
+
if (this.config.maxCostRemaining === undefined || this.config.maxCostRemaining === null || this.costAccumulator.getTotals().totalCost < this.config.maxCostRemaining) {
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
this.logger.info(`Cost limit approaching. Current cost: ${formatCost(this.costAccumulator.getTotals().totalCost)}, Limit: ${formatCost(this.config.maxCostRemaining)}`);
|
|
1352
|
+
this.logger.info(`Stopping translation for ${language} to avoid exceeding budget.`);
|
|
1353
|
+
|
|
1354
|
+
const remainingBatches = batches.length - (currentIndex + 1);
|
|
1355
|
+
|
|
1356
|
+
if (remainingBatches > 0) {
|
|
1357
|
+
const remainingStrings = batches.slice(currentIndex + 1).reduce((sum, batch) => sum + batch.length, 0);
|
|
1358
|
+
|
|
1359
|
+
this.logger.info(`Skipping ${remainingBatches} remaining batches (${formatNumber(remainingStrings || 0)} strings) due to cost limit.`);
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
return true;
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/**
|
|
1366
|
+
* Logs final summary information after batch processing.
|
|
1367
|
+
*
|
|
1368
|
+
* @private
|
|
1369
|
+
*
|
|
1370
|
+
* @since 1.0.0
|
|
1371
|
+
*
|
|
1372
|
+
* @param {string} language - Target language code.
|
|
1373
|
+
* @param {number} successfullyTranslatedCount - Total successful translations.
|
|
1374
|
+
* @param {Array} batches - All translation batches.
|
|
1375
|
+
* @param {number} skippedDueToBudgetCount - Count of strings skipped due to budget.
|
|
1376
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1377
|
+
*/
|
|
1378
|
+
_logFinalSummary(language, successfullyTranslatedCount, batches, skippedDueToBudgetCount, outputFile) {
|
|
1379
|
+
if (this.config.dryRun) {
|
|
1380
|
+
this._logDryRunSummary(language, successfullyTranslatedCount, batches, outputFile);
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
this._logBudgetSummary(language, successfullyTranslatedCount, skippedDueToBudgetCount);
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
/**
|
|
1387
|
+
* Logs dry run summary information.
|
|
1388
|
+
*
|
|
1389
|
+
* @private
|
|
1390
|
+
*
|
|
1391
|
+
* @since 1.0.0
|
|
1392
|
+
*
|
|
1393
|
+
* @param {string} language - Target language code.
|
|
1394
|
+
* @param {number} successfullyTranslatedCount - Total successful translations.
|
|
1395
|
+
* @param {Array} batches - All translation batches.
|
|
1396
|
+
* @param {string} outputFile - Path to output .po file.
|
|
1397
|
+
*/
|
|
1398
|
+
_logDryRunSummary(language, successfullyTranslatedCount, batches, outputFile) {
|
|
1399
|
+
const totalCostData = this.costAccumulator.getTotals();
|
|
1400
|
+
|
|
1401
|
+
this.logger.info(`=== DRY RUN SUMMARY FOR ${language.toUpperCase()} ===`);
|
|
1402
|
+
this.logger.info(`Total strings that would be translated: ${formatNumber(successfullyTranslatedCount || 0)}`);
|
|
1403
|
+
this.logger.info(`Total batches that would be processed: ${batches.length}`);
|
|
1404
|
+
this.logger.info(`Estimated total tokens: ${formatNumber(totalCostData.totalTokens)} (includes estimated output tokens)`);
|
|
1405
|
+
this.logger.info(`Estimated total cost: $${formatCost(totalCostData.totalCost)} (input + estimated output cost)`);
|
|
1406
|
+
this.logger.info(`Estimated time (rough): ${Math.ceil((batches.length * 10) / 60)} minutes`);
|
|
1407
|
+
this.logger.info(`Output file would be saved to: ${outputFile}`);
|
|
1408
|
+
this.logger.info(`📊 Note: Token counts and costs are estimates based on input analysis + 1.4x output multiplier`);
|
|
1409
|
+
this.logger.info(`=== END DRY RUN SUMMARY ===`);
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* Logs budget-related summary information.
|
|
1414
|
+
*
|
|
1415
|
+
* @private
|
|
1416
|
+
*
|
|
1417
|
+
* @since 1.0.0
|
|
1418
|
+
*
|
|
1419
|
+
* @param {string} language - Target language code.
|
|
1420
|
+
* @param {number} successfullyTranslatedCount - Total successful translations.
|
|
1421
|
+
* @param {number} skippedDueToBudgetCount - Count of strings skipped due to budget.
|
|
1422
|
+
*/
|
|
1423
|
+
_logBudgetSummary(language, successfullyTranslatedCount, skippedDueToBudgetCount) {
|
|
1424
|
+
if (successfullyTranslatedCount === 0 && this.config.maxCostRemaining && !this.config.dryRun) {
|
|
1425
|
+
const totalCostData = this.costAccumulator.getTotals();
|
|
1426
|
+
|
|
1427
|
+
if (totalCostData.totalCost === 0) {
|
|
1428
|
+
this.logger.info(`💰 No translations processed for ${language} - skipped due to budget limit (${formatCost(this.config.maxCostRemaining)})`);
|
|
1429
|
+
this.logger.info(`💡 Consider increasing --max-cost or reducing --batch-size for smaller batches`);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
if (this.config.maxCostRemaining && !this.config.dryRun && skippedDueToBudgetCount > 0) {
|
|
1434
|
+
const totalCostData = this.costAccumulator.getTotals();
|
|
1435
|
+
|
|
1436
|
+
if (totalCostData.totalCost > 0 && totalCostData.totalCost >= this.config.maxCostRemaining * BUDGET_WARNING_THRESHOLD) {
|
|
1437
|
+
this.logger.info(`💰 ${language}: ${formatNumber(skippedDueToBudgetCount || 0)} strings skipped due to budget limit (${formatCost(totalCostData.totalCost)}/${formatCost(this.config.maxCostRemaining)})`);
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* Counts all entries in the POT file across all contexts.
|
|
1444
|
+
*
|
|
1445
|
+
* @private
|
|
1446
|
+
*
|
|
1447
|
+
* @since 1.0.0
|
|
1448
|
+
*
|
|
1449
|
+
* @param {Object} potData - Parsed POT data structure.
|
|
1450
|
+
*
|
|
1451
|
+
* @return {number} Total count of entries in the POT file.
|
|
1452
|
+
*/
|
|
1453
|
+
_countAllPotEntries(potData) {
|
|
1454
|
+
let totalEntries = 0;
|
|
1455
|
+
|
|
1456
|
+
for (const context in potData.translations) {
|
|
1457
|
+
const contextEntries = Object.keys(potData.translations[context]).filter((key) => key !== ''); // exclude header
|
|
1458
|
+
|
|
1459
|
+
totalEntries += contextEntries.length;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
return totalEntries;
|
|
1463
|
+
}
|
|
1464
|
+
}
|