-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbaseProcessor.ts
More file actions
411 lines (356 loc) · 13.4 KB
/
Copy pathbaseProcessor.ts
File metadata and controls
411 lines (356 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/**
* Base Processor for AAC File Formats
*
* This module provides base functionality for processing AAC (Augmentative and Alternative
* Communication) files across various formats (gridset, OBF, Snap, TouchChat, etc.).
*
* ## LLM-Based Translation with Symbol Preservation
*
* All processor formats support LLM-based translation that preserves symbol-to-word
* associations across languages. This is critical for AAC systems where visual symbols
* are attached to specific words.
*
* ### Usage Example:
*
* ```typescript
* import { extractAllButtonsForTranslation, createTranslationPrompt } from '../optional/translation/translationProcessor';
*
* // 1. Extract buttons from your format
* const buttons = extractAllButtonsForTranslation(myFormatButtons, (button) => ({
* pageId: button.pageId,
* pageName: button.pageName
* }));
*
* // 2. Create prompt for LLM
* const prompt = createTranslationPrompt(buttons, 'Spanish');
*
* // 3. Send to LLM (Gemini, GPT, etc.) and get response
* const llmResponse = await callLLMAPI(prompt);
*
* // 4. Apply translations to your format
* processor.processLLMTranslations(filePath, llmResponse, outputPath);
* ```
*
* ### Format-Specific Implementation:
*
* Each processor should implement:
* - `extractSymbolsForLLM()` - Uses extractAllButtonsForTranslation() utility
* - `processLLMTranslations()` - Applies translations using format-specific logic
*
* See `src/utilities/translation/translationProcessor.ts` for shared utilities.
*/
import { AACTree, AACButton, AACSemanticCategory } from './treeStructure';
import { StringCasing, detectCasing, isNumericOrEmpty } from './stringCasing';
import { ValidationResult } from '../validation/validationTypes';
import { BinaryOutput, ProcessorInput } from '../utils/io';
// Configuration options for processors
export interface ProcessorOptions {
// Filter out navigation/system buttons (enabled by default)
excludeNavigationButtons?: boolean;
excludeSystemButtons?: boolean;
// Optional password for protected gridset archives (.gridsetx)
gridsetPassword?: string;
// Custom filtering function for advanced use cases
customButtonFilter?: (button: AACButton) => boolean;
// Preserve original behavior for backwards compatibility
preserveAllButtons?: boolean;
// Grid 3 symbol library directory (for resolving [widgit]/ style references)
// If not specified, will attempt to auto-detect from Grid 3 installation
grid3SymbolDir?: string;
// Grid 3 installation path (for auto-detecting symbol directory)
// If not specified, will use default platform-specific path
grid3Path?: string;
// Locale for symbol libraries (e.g., 'en-GB', 'en-US')
// Defaults to 'en-GB' if not specified
grid3Locale?: string;
}
// Types for aac-tools-platform compatibility
export interface ExtractedString {
string: string;
vocabPlacementMeta: VocabPlacementMetadata;
}
export interface VocabPlacementMetadata {
vocabLocations: VocabLocation[];
}
export interface VocabLocation {
table: string;
id: string | number;
column: string;
casing: StringCasing;
}
export interface ProcessingError {
message: string;
step: 'EXTRACT' | 'PROCESS' | 'SAVE';
}
export interface ExtractStringsResult {
errors: ProcessingError[];
extractedStrings: ExtractedString[];
}
export interface TranslatedString {
sourcestringid: number;
overridestring: string;
translatedstring: string;
}
export interface SourceString {
id: number;
sourcestring: string;
vocabplacementmetadata: VocabPlacementMetadata;
}
abstract class BaseProcessor {
protected options: ProcessorOptions;
constructor(options: ProcessorOptions = {}) {
// Default configuration: exclude navigation/system buttons
this.options = {
excludeNavigationButtons: true,
excludeSystemButtons: true,
preserveAllButtons: false,
...options,
};
}
// Extract all text content (for translation, analysis, etc.)
abstract extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]>;
// Load file into common tree structure
abstract loadIntoTree(filePathOrBuffer: ProcessorInput): Promise<AACTree>;
// Process texts (e.g., apply translations) and return new file/buffer
// If targetLocale is provided, it attempts to add the language to the file (multilingual support)
// Otherwise, it replaces the existing text (translation/localization)
abstract processTexts(
filePathOrBuffer: ProcessorInput,
translations: Map<string, string>,
outputPath: string,
targetLocale?: string
): Promise<BinaryOutput>;
// Save tree structure back to file/buffer
abstract saveFromTree(tree: AACTree, outputPath: string): Promise<void>;
// Validate file format
validate?(filePath: string): Promise<ValidationResult>;
// Optional alias methods for aac-tools-platform compatibility
// These provide a unified interface across all AAC formats
/**
* Extract strings with metadata for external platform integration
* @param filePath - Path to the AAC file
* @returns Promise with extracted strings and any errors
*/
extractStringsWithMetadata?(filePath: string): Promise<ExtractStringsResult>;
/**
* Generate translated download with external translation data
* @param filePath - Path to the original AAC file
* @param translatedStrings - Array of translated string data
* @param sourceStrings - Array of source string data with metadata
* @returns Promise with path to the generated translated file
*/
generateTranslatedDownload?(
filePath: string,
translatedStrings: TranslatedString[],
sourceStrings: SourceString[]
): Promise<string>;
// Helper method to determine if a button should be filtered out
protected shouldFilterButton(button: AACButton): boolean {
// If preserveAllButtons is true, never filter
if (this.options.preserveAllButtons) {
return false;
}
// Apply custom filter if provided
if (this.options.customButtonFilter) {
return !this.options.customButtonFilter(button);
}
// Check semantic action-based filtering
if (button.semanticAction) {
const { category, intent } = button.semanticAction;
// Filter specific navigation intents (toolbar navigation only)
if (this.options.excludeNavigationButtons) {
const i = String(intent);
if (i === 'GO_BACK' || i === 'GO_HOME') {
return true;
}
}
// Filter system/text editing buttons by category
if (this.options.excludeSystemButtons && category === AACSemanticCategory.TEXT_EDITING) {
return true;
}
// Filter specific system intents
if (this.options.excludeSystemButtons) {
const i = String(intent);
if (
i === 'DELETE_WORD' ||
i === 'DELETE_CHARACTER' ||
i === 'CLEAR_TEXT' ||
i === 'COPY_TEXT'
) {
return true;
}
}
}
// Fallback: check button labels for common navigation/system terms
// Only apply label-based filtering if button doesn't have semantic actions
if (
!button.semanticAction &&
(this.options.excludeNavigationButtons || this.options.excludeSystemButtons)
) {
const label = button.label?.toLowerCase() || '';
const message = button.message?.toLowerCase() || '';
// More conservative navigation terms (exclude "more" since it's often used for legitimate page navigation)
const navigationTerms = ['back', 'home', 'menu', 'settings'];
const systemTerms = ['delete', 'clear', 'copy', 'paste', 'undo', 'redo'];
if (
this.options.excludeNavigationButtons &&
navigationTerms.some((term) => label.includes(term) || message.includes(term))
) {
return true;
}
if (
this.options.excludeSystemButtons &&
systemTerms.some((term) => label.includes(term) || message.includes(term))
) {
return true;
}
}
return false;
}
// Helper method to filter buttons from a page
protected filterPageButtons(buttons: AACButton[]): AACButton[] {
return buttons.filter((button) => !this.shouldFilterButton(button));
}
/**
* Generic implementation for extracting strings with metadata
* Can be used by any processor that doesn't need format-specific logic
* @param filePath - Path to the AAC file
* @returns Promise with extracted strings and metadata
*/
protected async extractStringsWithMetadataGeneric(
filePath: string
): Promise<ExtractStringsResult> {
try {
const tree = await this.loadIntoTree(filePath);
const extractedMap = new Map<string, ExtractedString>();
// Process all pages and buttons
Object.values(tree.pages).forEach((page) => {
// Process page names
if (page.name && page.name.trim().length > 1 && !isNumericOrEmpty(page.name)) {
const key = page.name.trim().toLowerCase();
const vocabLocation: VocabLocation = {
table: 'pages',
id: page.id,
column: 'NAME',
casing: detectCasing(page.name),
};
this.addToExtractedMap(extractedMap, key, page.name.trim(), vocabLocation);
}
page.buttons.forEach((button) => {
// Process button labels
if (button.label && button.label.trim().length > 1 && !isNumericOrEmpty(button.label)) {
const key = button.label.trim().toLowerCase();
const vocabLocation: VocabLocation = {
table: 'buttons',
id: button.id,
column: 'LABEL',
casing: detectCasing(button.label),
};
this.addToExtractedMap(extractedMap, key, button.label.trim(), vocabLocation);
}
// Process button messages (if different from label)
if (
button.message &&
button.message !== button.label &&
button.message.trim().length > 1 &&
!isNumericOrEmpty(button.message)
) {
const key = button.message.trim().toLowerCase();
const vocabLocation: VocabLocation = {
table: 'buttons',
id: button.id,
column: 'MESSAGE',
casing: detectCasing(button.message),
};
this.addToExtractedMap(extractedMap, key, button.message.trim(), vocabLocation);
}
});
});
const extractedStrings = Array.from(extractedMap.values());
return { errors: [], extractedStrings };
} catch (error) {
return {
errors: [
{
message: error instanceof Error ? error.message : 'Unknown extraction error',
step: 'EXTRACT' as const,
},
],
extractedStrings: [],
};
}
}
/**
* Generic implementation for generating translated downloads
* Can be used by any processor that doesn't need format-specific logic
* @param filePath - Path to the original AAC file
* @param translatedStrings - Array of translated string data
* @param sourceStrings - Array of source string data
* @returns Promise with path to the generated translated file
*/
protected async generateTranslatedDownloadGeneric(
filePath: string,
translatedStrings: TranslatedString[],
sourceStrings: SourceString[]
): Promise<string> {
// Build translation map from the provided data
const translations = new Map<string, string>();
sourceStrings.forEach((sourceString) => {
const translated = translatedStrings.find(
(ts) => ts.sourcestringid.toString() === sourceString.id.toString()
);
if (translated) {
const translatedText =
translated.overridestring.length > 0
? translated.overridestring
: translated.translatedstring;
translations.set(sourceString.sourcestring, translatedText);
}
});
// Generate output path based on file extension
const outputPath = this.generateTranslatedOutputPath(filePath);
// Use existing processTexts method (now async)
await this.processTexts(filePath, translations, outputPath);
return outputPath;
}
/**
* Helper method to add extracted strings to the map, handling duplicates
* @param extractedMap - Map to store extracted strings
* @param key - Lowercase key for deduplication
* @param originalString - Original string with proper casing
* @param vocabLocation - Metadata about where the string was found
*/
protected addToExtractedMap(
extractedMap: Map<string, ExtractedString>,
key: string,
originalString: string,
vocabLocation: VocabLocation
): void {
const existing = extractedMap.get(key);
if (existing) {
existing.vocabPlacementMeta.vocabLocations.push(vocabLocation);
} else {
extractedMap.set(key, {
string: originalString, // Use original casing for the string value
vocabPlacementMeta: {
vocabLocations: [vocabLocation],
},
});
}
}
/**
* Generate output path for translated file based on input file extension
* @param filePath - Original file path
* @returns Path for the translated output file
*/
protected generateTranslatedOutputPath(filePath: string): string {
const lastDotIndex = filePath.lastIndexOf('.');
if (lastDotIndex === -1) {
return filePath + '_translated';
}
const basePath = filePath.substring(0, lastDotIndex);
const extension = filePath.substring(lastDotIndex);
return `${basePath}_translated${extension}`;
}
}
export { BaseProcessor };