@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.
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Centralized cost calculation utilities for translation runs.
3
+ * Provides functions for cost aggregation, formatting, and summary generation.
4
+ *
5
+ * @since 1.0.0
6
+ */
7
+
8
+ import { createEmptyValidationStats, accumulateValidationStats, VALIDATION_TYPES, getTotalValidationIssues } from './validationStats.js';
9
+
10
+ /**
11
+ * Calculates aggregate totals from an array of language statistics.
12
+ * This is the single source of truth for cost and token aggregation.
13
+ *
14
+ * @since 1.0.0
15
+ *
16
+ * @param {Array} allLanguageStats - Array of language processing statistics.
17
+ *
18
+ * @return {Object} Aggregated totals with consistent structure.
19
+ */
20
+ export function calculateAggregateTotals(allLanguageStats) {
21
+ if (!Array.isArray(allLanguageStats) || allLanguageStats.length === 0) {
22
+ return {
23
+ languagesProcessed: 0,
24
+ languagesWithErrors: 0,
25
+ totalTranslated: 0,
26
+ totalFailed: 0,
27
+ totalCost: 0,
28
+ totalTokens: 0,
29
+ totalPromptTokens: 0,
30
+ totalCompletionTokens: 0,
31
+ isDryRun: false,
32
+ models: [],
33
+ methods: {},
34
+ };
35
+ }
36
+
37
+ return allLanguageStats.reduce(
38
+ (acc, stat) => {
39
+ const translatedInRun = stat.translatedInRun || 0;
40
+ const failedInRun = stat.failedInRun || 0;
41
+ const totalCost = stat.costData?.totalCost || 0;
42
+ const totalTokens = stat.costData?.totalTokens || 0;
43
+ const promptTokens = stat.costData?.totalPromptTokens || stat.costData?.inputTokens || 0;
44
+ const completionTokens = stat.costData?.totalCompletionTokens || stat.costData?.outputTokens || 0;
45
+
46
+ acc.totalTranslated += translatedInRun;
47
+ acc.totalFailed += failedInRun;
48
+ acc.totalCost += totalCost;
49
+ acc.totalTokens += totalTokens;
50
+ acc.totalPromptTokens += promptTokens;
51
+ acc.totalCompletionTokens += completionTokens;
52
+
53
+ if (stat.error) {
54
+ acc.languagesWithErrors++;
55
+ } else {
56
+ acc.languagesProcessed++;
57
+ }
58
+
59
+ if (stat.costData?.isDryRun) {
60
+ acc.isDryRun = true;
61
+ }
62
+
63
+ if (stat.costData?.models && Array.isArray(stat.costData.models)) {
64
+ stat.costData.models.forEach((model) => {
65
+ if (model && !acc.models.includes(model)) {
66
+ acc.models.push(model);
67
+ }
68
+ });
69
+ }
70
+
71
+ if (stat.method) {
72
+ acc.methods[stat.method] = (acc.methods[stat.method] || 0) + 1;
73
+ }
74
+
75
+ return acc;
76
+ },
77
+ {
78
+ languagesProcessed: 0,
79
+ languagesWithErrors: 0,
80
+ totalTranslated: 0,
81
+ totalFailed: 0,
82
+ totalCost: 0,
83
+ totalTokens: 0,
84
+ totalPromptTokens: 0,
85
+ totalCompletionTokens: 0,
86
+ isDryRun: false,
87
+ models: [],
88
+ methods: {},
89
+ }
90
+ );
91
+ }
92
+
93
+ /**
94
+ * Formats a cost value as a USD currency string with consistent precision.
95
+ *
96
+ * @since 1.0.0
97
+ *
98
+ * @param {number} cost - Cost value in USD.
99
+ * @param {number} decimals - Number of decimal places to show (default: 4).
100
+ *
101
+ * @return {string} Formatted cost string (e.g., "$0.0123").
102
+ */
103
+ export function formatCost(cost, decimals = 4) {
104
+ if (typeof cost !== 'number' || isNaN(cost)) {
105
+ return '$0.0000';
106
+ }
107
+
108
+ return `$${cost.toFixed(decimals)}`;
109
+ }
110
+
111
+ /**
112
+ * Formats a number with locale-appropriate thousands separators.
113
+ * Used for consistent number formatting throughout the application.
114
+ *
115
+ * @since 1.0.0
116
+ *
117
+ * @param {number} number - Number to format.
118
+ *
119
+ * @return {string} Formatted number string (e.g., "1,234").
120
+ */
121
+ export function formatNumber(number) {
122
+ if (typeof number !== 'number' || isNaN(number)) {
123
+ return '0';
124
+ }
125
+
126
+ return number.toLocaleString();
127
+ }
128
+
129
+ /**
130
+ * Formats time duration in milliseconds to a human-readable format.
131
+ * Uses minutes and seconds format for consistency (e.g., "1m 30s", "45s").
132
+ *
133
+ * @since 1.0.0
134
+ *
135
+ * @param {number} durationMs - Duration in milliseconds.
136
+ *
137
+ * @return {string} Formatted time string (e.g., "1m 30s", "45s").
138
+ */
139
+ export function formatDuration(durationMs) {
140
+ if (typeof durationMs !== 'number' || isNaN(durationMs) || durationMs < 0) {
141
+ return 'N/A';
142
+ }
143
+
144
+ const totalSeconds = Math.round(durationMs / 1000);
145
+ const minutes = Math.floor(totalSeconds / 60);
146
+ const seconds = totalSeconds % 60;
147
+
148
+ if (minutes > 0) {
149
+ return `${minutes}m ${seconds}s`;
150
+ }
151
+
152
+ return `${seconds}s`;
153
+ }
154
+
155
+ /**
156
+ * Creates a standardized summary object for reporting.
157
+ * Used by both console and JSON reporters to ensure consistency.
158
+ *
159
+ * @since 1.0.0
160
+ *
161
+ * @param {Array} allLanguageStats - Array of language processing statistics.
162
+ *
163
+ * @return {Object} Standardized summary object.
164
+ */
165
+ export function createSummary(allLanguageStats) {
166
+ const totals = calculateAggregateTotals(allLanguageStats);
167
+ const totalAlreadyTranslated = allLanguageStats.reduce((sum, stat) => sum + (stat.alreadyTranslated || 0), 0);
168
+ const totalSkippedDueToBudget = allLanguageStats.reduce((sum, stat) => sum + (stat.skippedDueToBudget || 0), 0);
169
+ const totalSkippedDueToLimits = allLanguageStats.reduce((sum, stat) => sum + (stat.skippedDueToLimits || 0), 0);
170
+
171
+ // Aggregate validation stats across all languages.
172
+ const totalValidationStats = createEmptyValidationStats();
173
+
174
+ for (const stat of allLanguageStats) {
175
+ if (stat.validationStats) {
176
+ accumulateValidationStats(totalValidationStats, stat.validationStats);
177
+ }
178
+ }
179
+
180
+ // Convert validation stats to snake_case for JSON consistency.
181
+ const totalValidationFormatted = {};
182
+
183
+ for (const key of Object.keys(VALIDATION_TYPES)) {
184
+ const snakeKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
185
+
186
+ totalValidationFormatted[snakeKey] = totalValidationStats[key];
187
+ }
188
+
189
+ // Calculate total warnings count.
190
+ const totalWarnings = getTotalValidationIssues(totalValidationStats);
191
+
192
+ // Count languages with warnings.
193
+ const languagesWithWarnings = allLanguageStats.filter((stat) => {
194
+ return stat.validationStats && getTotalValidationIssues(stat.validationStats) > 0;
195
+ }).length;
196
+
197
+ // Collect all errors from individual jobs.
198
+ const errors = allLanguageStats
199
+ .filter((stat) => stat.error)
200
+ .map((stat) => ({
201
+ language: stat.language,
202
+ error: stat.error,
203
+ }));
204
+
205
+ return {
206
+ status: totals.languagesWithErrors > 0 ? 'error' : 'success',
207
+ languages_processed: totals.languagesProcessed + totals.languagesWithErrors,
208
+ languages_successful: totals.languagesProcessed,
209
+ languages_failed: totals.languagesWithErrors,
210
+ languages_with_warnings: languagesWithWarnings,
211
+ total_cost: totals.totalCost,
212
+ total_tokens: totals.totalTokens,
213
+ total_prompt_tokens: totals.totalPromptTokens,
214
+ total_completion_tokens: totals.totalCompletionTokens,
215
+ total_strings: {
216
+ processed: totals.totalTranslated + totals.totalFailed,
217
+ successful: totals.totalTranslated,
218
+ already_translated: totalAlreadyTranslated,
219
+ skipped_due_to_budget: totalSkippedDueToBudget,
220
+ skipped_due_to_limits: totalSkippedDueToLimits,
221
+ failed: totals.totalFailed,
222
+ warnings: totalWarnings,
223
+ },
224
+ total_validation: totalValidationFormatted,
225
+ methods_used: totals.methods,
226
+ models_used: totals.models,
227
+ is_dry_run: totals.isDryRun,
228
+ errors: errors.length > 0 ? errors : undefined,
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Gets the appropriate cost label based on whether any stats are from dry runs.
234
+ *
235
+ * @since 1.0.0
236
+ *
237
+ * @param {Array} allLanguageStats - Array of language processing statistics.
238
+ *
239
+ * @return {string} Cost label ('Estimated cost' or 'Total cost').
240
+ */
241
+ export function getCostLabel(allLanguageStats) {
242
+ const isDryRun = allLanguageStats.some((stat) => stat.costData?.isDryRun);
243
+
244
+ return isDryRun ? 'Estimated cost' : 'Total cost';
245
+ }
@@ -0,0 +1,277 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import { FALLBACK_PRICING as OPENAI_FALLBACK_PRICING } from '../providers/openai/modelCapabilities.js';
5
+
6
+ /**
7
+ * Cost Tracking Utility.
8
+ *
9
+ * Provides functionality to track and estimate costs for AI provider API calls.
10
+ * Supports loading pricing data from provider-specific configuration files
11
+ * and calculating costs for various models.
12
+ *
13
+ * @since 1.0.0
14
+ */
15
+
16
+ /**
17
+ * Cached pricing data loaded from provider pricing files.
18
+ *
19
+ * @since 1.0.0
20
+ *
21
+ * @type {Map<string, Object>}
22
+ */
23
+ const cachedPricingData = new Map();
24
+
25
+ /**
26
+ * Emergency fallback pricing data for when config files are missing.
27
+ *
28
+ * @since 1.0.0
29
+ *
30
+ * @type {Object}
31
+ */
32
+ const EMERGENCY_FALLBACK = {
33
+ openai: {
34
+ models: OPENAI_FALLBACK_PRICING.models,
35
+ fallback: OPENAI_FALLBACK_PRICING.fallback,
36
+ },
37
+ };
38
+
39
+ /**
40
+ * Loads pricing data from provider-specific pricing file.
41
+ * Implements caching to avoid repeated file reads.
42
+ *
43
+ * @since 1.0.0
44
+ *
45
+ * @param {string} providerName - Name of the provider (e.g., 'openai', 'anthropic')
46
+ *
47
+ * @return {Object} Pricing data object with models and fallback pricing
48
+ */
49
+ function loadProviderPricingData(providerName) {
50
+ if (cachedPricingData.has(providerName)) {
51
+ return cachedPricingData.get(providerName);
52
+ }
53
+
54
+ try {
55
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
56
+
57
+ // Look for {provider}-pricing.json in the config directory relative to this module.
58
+ const jsonPath = path.resolve(currentDir, '../../config', `${providerName}-pricing.json`);
59
+
60
+ // Fallback to working directory if not found.
61
+ const fallbackPath = path.join(process.cwd(), 'config', `${providerName}-pricing.json`);
62
+
63
+ let pricingContent;
64
+
65
+ try {
66
+ pricingContent = fs.readFileSync(jsonPath, 'utf-8');
67
+ } catch {
68
+ pricingContent = fs.readFileSync(fallbackPath, 'utf-8');
69
+ }
70
+
71
+ const pricingData = JSON.parse(pricingContent);
72
+
73
+ if (!pricingData.models || !pricingData.fallback) {
74
+ throw new Error(`Invalid ${providerName}-pricing.json structure: missing models or fallback`);
75
+ }
76
+
77
+ cachedPricingData.set(providerName, pricingData);
78
+
79
+ return pricingData;
80
+ } catch (error) {
81
+ if (error.code === 'ENOENT') {
82
+ console.warn(`Warning: ${providerName}-pricing.json not found. Using emergency fallback pricing.`);
83
+ } else if (error instanceof SyntaxError) {
84
+ console.warn(`Warning: Invalid JSON in ${providerName}-pricing.json. Using emergency fallback pricing.`);
85
+ } else if (error.message.includes(`Invalid ${providerName}-pricing.json structure`)) {
86
+ throw new Error(`Invalid ${providerName}-pricing.json structure: missing models or fallback`);
87
+ } else {
88
+ console.warn(`Warning: Failed to load ${providerName}-pricing.json: ${error.message}. Using emergency fallback pricing.`);
89
+ }
90
+
91
+ // Use emergency fallback pricing for the provider.
92
+ const fallbackData = EMERGENCY_FALLBACK[providerName] || {
93
+ models: {},
94
+ fallback: { prompt: 0.0005, completion: 0.0015 },
95
+ };
96
+
97
+ cachedPricingData.set(providerName, fallbackData);
98
+
99
+ return fallbackData;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Calculates the cost of API usage based on token counts and model pricing.
105
+ * Uses pricing data from provider-specific pricing file.
106
+ *
107
+ * @since 1.0.0
108
+ *
109
+ * @param {Object} usage - Usage data from API response
110
+ * @param {number} usage.prompt_tokens - Number of prompt tokens used
111
+ * @param {number} usage.completion_tokens - Number of completion tokens used
112
+ * @param {string} providerName - Provider name (e.g., 'openai', 'anthropic')
113
+ * @param {string} model - Model name used for the request
114
+ *
115
+ * @return {Object} Cost breakdown object
116
+ */
117
+ export function calculateCost(usage, providerName, model) {
118
+ if (!usage || typeof usage !== 'object') {
119
+ return {
120
+ model,
121
+ promptTokens: 0,
122
+ completionTokens: 0,
123
+ totalTokens: 0,
124
+ promptCost: 0,
125
+ completionCost: 0,
126
+ totalCost: 0,
127
+ pricingUsed: null,
128
+ error: 'Invalid usage data',
129
+ };
130
+ }
131
+
132
+ const promptTokens = usage.prompt_tokens || usage.inputTokens || 0;
133
+ const completionTokens = usage.completion_tokens || usage.outputTokens || 0;
134
+ const totalTokens = usage.total_tokens || promptTokens + completionTokens;
135
+
136
+ const pricingData = loadProviderPricingData(providerName);
137
+ const modelPricing = pricingData.models[model] || pricingData.fallback;
138
+
139
+ const promptCost = (promptTokens / 1000) * modelPricing.prompt;
140
+ const completionCost = (completionTokens / 1000) * modelPricing.completion;
141
+ const totalCost = promptCost + completionCost;
142
+
143
+ return {
144
+ model,
145
+ promptTokens,
146
+ completionTokens,
147
+ totalTokens,
148
+ promptCost,
149
+ completionCost,
150
+ totalCost,
151
+ pricingUsed: modelPricing,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Creates a new cost accumulator for tracking costs across multiple requests.
157
+ *
158
+ * @since 1.0.0
159
+ *
160
+ * @return {Object} Cost accumulator with methods to add costs and get totals
161
+ */
162
+ export function createCostAccumulator() {
163
+ const costs = [];
164
+
165
+ return {
166
+ /**
167
+ * Adds a cost entry to the accumulator.
168
+ *
169
+ * @param {Object} costData - Cost data from calculateCost()
170
+ *
171
+ * @since 1.0.0
172
+ */
173
+ addCost(costData) {
174
+ if (costData && typeof costData === 'object') {
175
+ costs.push(costData);
176
+ }
177
+ },
178
+
179
+ /**
180
+ * Gets the total accumulated costs.
181
+ *
182
+ * @return {Object} Total cost breakdown
183
+ *
184
+ * @since 1.0.0
185
+ */
186
+ getTotals() {
187
+ if (costs.length === 0) {
188
+ return {
189
+ totalPromptTokens: 0,
190
+ totalCompletionTokens: 0,
191
+ totalTokens: 0,
192
+ totalPromptCost: 0,
193
+ totalCompletionCost: 0,
194
+ totalCost: 0,
195
+ requestCount: 0,
196
+ models: [],
197
+ isDryRun: false,
198
+ };
199
+ }
200
+
201
+ const totals = costs.reduce(
202
+ (acc, cost) => {
203
+ acc.totalPromptTokens += cost.promptTokens || cost.inputTokens || 0;
204
+ acc.totalCompletionTokens += cost.completionTokens || cost.outputTokens || 0;
205
+ acc.totalTokens += cost.totalTokens || 0;
206
+ acc.totalPromptCost += cost.promptCost || 0;
207
+ acc.totalCompletionCost += cost.completionCost || 0;
208
+ acc.totalCost += cost.totalCost || 0;
209
+ acc.requestCount += 1;
210
+
211
+ if (cost.model && !acc.models.includes(cost.model)) {
212
+ acc.models.push(cost.model);
213
+ }
214
+
215
+ // Preserve dry-run flag if any cost entry is from dry-run.
216
+ if (cost.isDryRun) {
217
+ acc.isDryRun = true;
218
+ }
219
+
220
+ return acc;
221
+ },
222
+ {
223
+ totalPromptTokens: 0,
224
+ totalCompletionTokens: 0,
225
+ totalTokens: 0,
226
+ totalPromptCost: 0,
227
+ totalCompletionCost: 0,
228
+ totalCost: 0,
229
+ requestCount: 0,
230
+ models: [],
231
+ isDryRun: false,
232
+ }
233
+ );
234
+
235
+ return totals;
236
+ },
237
+
238
+ /**
239
+ * Gets all individual cost entries.
240
+ *
241
+ * @return {Array} Array of cost data objects
242
+ *
243
+ * @since 1.0.0
244
+ */
245
+ getAllCosts() {
246
+ return [...costs];
247
+ },
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Reloads pricing data from the JSON file for a specific provider.
253
+ * Useful for updating prices without restarting the application.
254
+ *
255
+ * @since 1.0.0
256
+ *
257
+ * @param {string} providerName - Provider name to reload pricing for.
258
+ *
259
+ * @return {Object} Reloaded pricing data
260
+ */
261
+ export function reloadProviderPricingData(providerName) {
262
+ cachedPricingData.delete(providerName);
263
+
264
+ return loadProviderPricingData(providerName);
265
+ }
266
+
267
+ /**
268
+ * Reloads all cached pricing data.
269
+ * Useful for updating all provider prices without restarting the application.
270
+ *
271
+ * @since 1.0.0
272
+ *
273
+ * @return {void}
274
+ */
275
+ export function reloadAllPricingData() {
276
+ cachedPricingData.clear();
277
+ }