forked from willwade/AACProcessors-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobfProcessor.ts
More file actions
887 lines (793 loc) · 29.1 KB
/
obfProcessor.ts
File metadata and controls
887 lines (793 loc) · 29.1 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
import {
BaseProcessor,
ProcessorOptions,
ExtractStringsResult,
TranslatedString,
SourceString,
} from '../core/baseProcessor';
import {
AACTree,
AACPage,
AACButton,
AACSemanticAction,
AACSemanticCategory,
AACSemanticIntent,
AACTreeMetadata,
} from '../core/treeStructure';
import { generateCloneId } from '../utilities/analytics/utils/idGenerator';
import { ValidationResult } from '../validation/validationTypes';
import {
extractAllButtonsForTranslation,
validateTranslationResults,
type ButtonForTranslation,
type LLMLTranslationResult,
} from '../utilities/translation/translationProcessor';
import { ProcessorInput, encodeBase64, decodeText } from '../utils/io';
import { getZipAdapter, ZipAdapter } from '../utils/zip';
const OBF_FORMAT_VERSION = 'open-board-0.1';
interface ObfButton {
id: string;
label?: string;
vocalization?: string;
load_board?: {
path: string;
};
box_id?: number;
background_color?: string;
border_color?: string;
semantic_id?: string; // Optional semantic identifier for motor planning
hidden?: boolean; // OBF uses boolean hidden field
image_id?: string; // Reference to image in the images array
}
interface ObfManifest {
format?: string;
root?: string;
paths?: {
boards?: { [key: string]: string };
images?: { [key: string]: string };
sounds?: { [key: string]: string };
};
}
/**
* Map OBF hidden value to AAC standard visibility
* OBF: true = hidden, false/undefined = visible
* Maps to: 'Hidden' | 'Visible' | undefined
*/
function mapObfVisibility(hidden: boolean | undefined): 'Hidden' | 'Visible' | undefined {
if (hidden === undefined) {
return undefined; // Default to visible
}
return hidden ? 'Hidden' : 'Visible';
}
interface ObfGrid {
rows: number;
columns: number;
order?: Array<Array<string | number | null>>;
}
interface ObfBoard {
format?: string;
id: string;
locale?: string;
url?: string;
name: string;
description_html?: string;
buttons: ObfButton[];
grid?: ObfGrid;
images?: any[];
sounds?: any[];
}
class ObfProcessor extends BaseProcessor {
private zipFile?: ZipAdapter;
private imageCache: Map<string, string> = new Map(); // Cache for data URLs
constructor(options?: ProcessorOptions) {
super(options);
}
/**
* Extract an image from the ZIP file as a Buffer
*/
private async extractImageAsBuffer(imageId: string, images: any[]): Promise<Buffer | null> {
if (!this.zipFile || !images) {
return null;
}
// Find the image metadata
const imageData = images.find((img: any) => img.id === imageId);
if (!imageData) {
return null;
}
// Try to get the image file from the ZIP
const possiblePaths = [
imageData.path,
`images/${imageData.filename || imageId}`,
imageData.id,
].filter(Boolean);
for (const imagePath of possiblePaths) {
try {
const buffer = await this.zipFile.readFile(imagePath as string);
if (buffer) {
if (typeof Buffer !== 'undefined') {
return Buffer.from(buffer);
}
return null;
}
} catch (err) {
continue;
}
}
return null;
}
/**
* Extract an image from the ZIP file and convert to data URL
*/
private async extractImageAsDataUrl(imageId: string, images: any[]): Promise<string | null> {
// Check cache first
if (this.imageCache.has(imageId)) {
return this.imageCache.get(imageId) ?? null;
}
if (!images) return null;
// Find the image metadata
const imageData = images.find((img: any) => img.id === imageId);
if (!imageData) {
return null;
}
// If image has data property, use that
if ((imageData as { data?: string }).data) {
const dataUrl = (imageData as { data: string }).data;
this.imageCache.set(imageId, dataUrl);
return dataUrl;
}
if (this.zipFile) {
// Try to get the image file from the ZIP
// Images are typically stored in an 'images' folder or root
const possiblePaths = [
imageData.path, // Explicit path if provided
`images/${imageData.filename || imageId}`, // Standard images folder
imageData.id, // Just the ID
].filter(Boolean);
for (const imagePath of possiblePaths) {
try {
const buffer = await this.zipFile.readFile(imagePath as string);
if (buffer) {
const contentType =
(imageData as { content_type?: string }).content_type ||
this.getMimeTypeFromFilename(imagePath as string);
const dataUrl = `data:${contentType};base64,${encodeBase64(buffer)}`;
this.imageCache.set(imageId, dataUrl);
return dataUrl;
}
} catch (err) {
// Continue to next path
continue;
}
}
}
// If image has a URL, use that as fallback
if ((imageData as { url?: string }).url) {
const url = (imageData as { url: string }).url;
this.imageCache.set(imageId, url);
return url;
}
return null;
}
private getMimeTypeFromFilename(filename: string): string {
const ext = filename.toLowerCase().split('.').pop();
switch (ext) {
case 'png':
return 'image/png';
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'gif':
return 'image/gif';
case 'svg':
return 'image/svg+xml';
case 'webp':
return 'image/webp';
default:
return 'image/png';
}
}
private async processBoard(
boardData: ObfBoard,
_boardPath: string,
isZipEntry: boolean
): Promise<AACPage> {
const sourceButtons = boardData.buttons || [];
// Calculate page ID first (used to make button IDs unique)
const pageId = isZipEntry
? _boardPath // Zip entry - use filename to match navigation paths
: boardData?.id
? String(boardData.id)
: _boardPath?.split(/[/\\]/).pop() || '';
const buttons: AACButton[] = await Promise.all(
sourceButtons.map(async (btn: ObfButton): Promise<AACButton> => {
const semanticAction: AACSemanticAction = btn.load_board
? {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.NAVIGATE_TO,
targetId: btn.load_board.path,
fallback: {
type: 'NAVIGATE',
targetPageId: btn.load_board.path,
},
}
: {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.SPEAK_TEXT,
text: String(btn?.vocalization || btn?.label || ''),
fallback: {
type: 'SPEAK',
message: String(btn?.vocalization || btn?.label || ''),
},
};
// Resolve image if image_id is present
let resolvedImage: string | undefined;
let imageBuffer: Buffer | undefined;
if (btn.image_id && boardData.images) {
resolvedImage =
(await this.extractImageAsDataUrl(btn.image_id, boardData.images)) || undefined;
imageBuffer =
(await this.extractImageAsBuffer(btn.image_id, boardData.images)) || undefined;
}
// Build parameters object for Grid3 export compatibility
const buttonParameters: { imageData?: Buffer; image_id?: string; [key: string]: any } = {};
if (imageBuffer) {
buttonParameters.imageData = imageBuffer;
}
// Store image_id for web viewers to fetch images via API
if (btn.image_id) {
buttonParameters.image_id = btn.image_id;
}
return new AACButton({
id: String(btn.id),
label: String(btn?.label || ''),
message: String(btn?.vocalization || btn?.label || ''),
visibility: mapObfVisibility(btn.hidden),
style: {
backgroundColor: btn.background_color,
borderColor: btn.border_color,
},
image: resolvedImage, // Set the resolved image data URL
resolvedImageEntry: resolvedImage,
parameters: Object.keys(buttonParameters).length > 0 ? buttonParameters : undefined,
semanticAction,
targetPageId: btn.load_board?.path,
semantic_id: btn.semantic_id, // Extract semantic_id if present
});
})
);
const buttonMap = new Map(buttons.map((btn) => [btn.id, btn]));
const page = new AACPage({
id: pageId, // Use the page ID we calculated earlier
name: String(boardData?.name || ''),
grid: [],
buttons,
parentId: null,
locale: boardData.locale,
descriptionHtml: boardData.description_html,
images: boardData.images,
sounds: boardData.sounds,
});
// Process grid layout if available
if (boardData.grid) {
const rows =
typeof boardData.grid.rows === 'number'
? boardData.grid.rows
: boardData.grid.order?.length || 0;
const cols =
typeof boardData.grid.columns === 'number'
? boardData.grid.columns
: boardData.grid.order
? boardData.grid.order.reduce(
(max, row) => Math.max(max, Array.isArray(row) ? row.length : 0),
0
)
: 0;
if (rows > 0 && cols > 0) {
const grid: Array<Array<AACButton | null>> = Array.from({ length: rows }, () =>
Array.from({ length: cols }, () => null)
);
if (Array.isArray(boardData.grid.order) && boardData.grid.order.length) {
boardData.grid.order.forEach((orderRow, rowIndex) => {
if (!Array.isArray(orderRow)) return;
orderRow.forEach((cellId, colIndex) => {
if (cellId === null || cellId === undefined) return;
if (rowIndex >= rows || colIndex >= cols) return;
const aacBtn = buttonMap.get(String(cellId));
if (aacBtn) {
grid[rowIndex][colIndex] = aacBtn;
}
});
});
} else {
for (const btn of sourceButtons) {
if (typeof btn.box_id === 'number') {
const row = Math.floor(btn.box_id / cols);
const col = btn.box_id % cols;
if (row < rows && col < cols) {
const aacBtn = buttonMap.get(String(btn.id));
if (aacBtn) {
grid[row][col] = aacBtn;
}
}
}
}
}
page.grid = grid;
// Generate clone_id for buttons in the grid
const semanticIds: string[] = [];
const cloneIds: string[] = [];
grid.forEach((row, rowIndex) => {
row.forEach((btn, colIndex) => {
if (btn) {
// Generate clone_id based on position and label
btn.clone_id = generateCloneId(rows, cols, rowIndex, colIndex, btn.label);
cloneIds.push(btn.clone_id);
// Track semantic_id if present
if (btn.semantic_id) {
semanticIds.push(btn.semantic_id);
}
}
});
});
// Track IDs on the page
if (semanticIds.length > 0) {
page.semantic_ids = semanticIds;
}
if (cloneIds.length > 0) {
page.clone_ids = cloneIds;
}
}
}
return page;
}
async extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]> {
const tree = await this.loadIntoTree(filePathOrBuffer);
const texts: string[] = [];
for (const pageId in tree.pages) {
const page = tree.pages[pageId];
if (page.name) texts.push(page.name);
page.buttons.forEach((btn) => {
if (typeof btn.label === 'string') texts.push(btn.label);
if (typeof btn.message === 'string' && btn.message !== btn.label) texts.push(btn.message);
});
}
return texts;
}
async loadIntoTree(filePathOrBuffer: ProcessorInput): Promise<AACTree> {
const { readBinaryFromInput, readTextFromInput } = this.options.fileAdapter;
// Detailed logging for debugging input
const bufferLength =
typeof filePathOrBuffer === 'string'
? null
: readBinaryFromInput(filePathOrBuffer).byteLength;
console.log('[OBF] loadIntoTree called with:', {
type: typeof filePathOrBuffer,
isBuffer: typeof Buffer !== 'undefined' && Buffer.isBuffer(filePathOrBuffer),
value:
typeof filePathOrBuffer === 'string'
? filePathOrBuffer
: `[Buffer of length ${bufferLength ?? 0}]`,
});
const tree = new AACTree();
// Helper: try to parse JSON OBF
function tryParseObfJson(data: ProcessorInput): ObfBoard | null {
try {
const str = typeof data === 'string' ? data : readTextFromInput(data);
// Check for empty or whitespace-only content
if (!str.trim()) {
return null;
}
const obj = JSON.parse(str);
if (obj && typeof obj === 'object' && 'id' in obj && 'buttons' in obj) {
// Validate buttons is an array
if (!Array.isArray(obj.buttons)) {
throw new Error('Invalid OBF: buttons must be an array');
}
return obj as ObfBoard;
}
} catch (error: any) {
// Log parsing errors for debugging but don't throw
}
return null;
}
// If input is a string path and ends with .obf, treat as JSON
if (typeof filePathOrBuffer === 'string' && filePathOrBuffer.toLowerCase().endsWith('.obf')) {
try {
const content = readTextFromInput(filePathOrBuffer);
const boardData = tryParseObfJson(content);
if (boardData) {
console.log('[OBF] Detected .obf file, parsed as JSON');
const page = await this.processBoard(boardData, filePathOrBuffer, false);
tree.addPage(page);
// Set metadata from root board
tree.metadata.format = 'obf';
tree.metadata.name = boardData.name;
tree.metadata.description = boardData.description_html;
tree.metadata.locale = boardData.locale;
tree.metadata.id = boardData.id;
if (boardData.url) tree.metadata.url = boardData.url;
if (boardData.locale) tree.metadata.languages = [boardData.locale];
tree.rootId = page.id;
return tree;
} else {
throw new Error('Invalid OBF JSON content');
}
} catch (err) {
console.error('[OBF] Error reading .obf file:', err);
throw err;
}
}
// Detect likely zip signature first
function isLikelyZip(input: ProcessorInput): boolean {
if (typeof input === 'string') {
const lowered = input.toLowerCase();
return lowered.endsWith('.zip') || lowered.endsWith('.obz');
}
const bytes = readBinaryFromInput(input);
return bytes.length >= 2 && bytes[0] === 0x50 && bytes[1] === 0x4b;
}
// Check if input is a buffer or string that parses as OBF JSON; throw if neither JSON nor ZIP
if (!isLikelyZip(filePathOrBuffer)) {
const asJson = tryParseObfJson(filePathOrBuffer);
if (!asJson) throw new Error('Invalid OBF content: not JSON and not ZIP');
console.log('[OBF] Detected buffer/string as OBF JSON');
const page = await this.processBoard(asJson, '[bufferOrString]', false);
tree.addPage(page);
// Set metadata from root board
tree.metadata.format = 'obf';
tree.metadata.name = asJson.name;
tree.metadata.description = asJson.description_html;
tree.metadata.locale = asJson.locale;
tree.metadata.id = asJson.id;
if (asJson.url) tree.metadata.url = asJson.url;
if (asJson.locale) {
tree.metadata.languages = [asJson.locale];
}
tree.rootId = page.id;
return tree;
}
try {
this.zipFile = await this.options.zipAdapter(filePathOrBuffer);
} catch (err) {
console.error('[OBF] Error loading ZIP:', err);
throw err;
}
// Store the ZIP file reference for image extraction
this.imageCache.clear(); // Clear cache for new file
console.log('[OBF] Detected zip archive, extracting .obf files');
// List manifest and OBF files
const filesInZip = this.zipFile.listFiles();
const manifestFile = filesInZip.filter((name) => name.toLowerCase() === 'manifest.json');
let obfEntries = filesInZip.filter((name) => name.toLowerCase().endsWith('.obf'));
// Attempt to read manifest
if (manifestFile && manifestFile.length === 1) {
try {
const content = await this.zipFile.readFile(manifestFile[0]);
const data = decodeText(content);
const str = typeof data === 'string' ? data : readTextFromInput(data);
if (!str.trim()) throw new Error('Manifest object missing');
const manifestObject = JSON.parse(str) as ObfManifest;
if (!manifestObject) throw new Error('Manifest object is empty');
// Replace OBF file list
if (manifestObject.paths && manifestObject.paths.boards) {
obfEntries = Object.values(manifestObject.paths.boards);
}
// Move root board to top of list
if (manifestObject.root) {
obfEntries = obfEntries.filter((item) => item !== manifestObject.root);
obfEntries.unshift(manifestObject.root);
}
} catch (err) {
console.warn('[OBF] Error processing mainfest', err);
}
}
// Process each .obf entry
for (const entryName of obfEntries) {
try {
const content = await this.zipFile.readFile(entryName);
const boardData = tryParseObfJson(decodeText(content));
if (boardData) {
const page = await this.processBoard(boardData, entryName, true);
tree.addPage(page);
// Set metadata if not already set (use first board as reference)
if (!tree.metadata.format) {
tree.metadata.format = 'obf';
tree.metadata.name = boardData.name;
tree.metadata.description = boardData.description_html;
tree.metadata.locale = boardData.locale;
tree.metadata.id = boardData.id;
if (boardData.url) tree.metadata.url = boardData.url;
if (boardData.locale) tree.metadata.languages = [boardData.locale];
tree.rootId = page.id;
}
} else {
console.warn('[OBF] Skipped entry (not valid OBF JSON):', entryName);
}
} catch (err) {
console.warn('[OBF] Error processing entry:', entryName, err);
}
}
return tree;
}
private buildGridMetadata(page: AACPage): {
rows: number;
columns: number;
order: (string | null)[][];
buttonPositions: Map<string, number>;
} {
const buttonPositions = new Map<string, number>();
const totalRows = Array.isArray(page.grid) ? page.grid.length : 0;
const totalColumns =
totalRows > 0
? page.grid.reduce((max, row) => Math.max(max, Array.isArray(row) ? row.length : 0), 0)
: 0;
if (totalRows === 0 || totalColumns === 0) {
if (!page.buttons.length) {
return { rows: 0, columns: 0, order: [], buttonPositions };
}
const fallbackRow: string[] = page.buttons.map((button, index) => {
const id = String(button.id ?? '');
buttonPositions.set(id, index);
return id;
});
return {
rows: 1,
columns: fallbackRow.length,
order: [fallbackRow],
buttonPositions,
};
}
const order: (string | null)[][] = [];
for (let rowIndex = 0; rowIndex < totalRows; rowIndex++) {
const sourceRow = page.grid[rowIndex] || [];
const orderRow: (string | null)[] = [];
for (let colIndex = 0; colIndex < totalColumns; colIndex++) {
const cell = sourceRow[colIndex] || null;
if (cell) {
const id = String(cell.id ?? '');
orderRow.push(id);
buttonPositions.set(id, rowIndex * totalColumns + colIndex);
} else {
orderRow.push(null);
}
}
order.push(orderRow);
}
return { rows: totalRows, columns: totalColumns, order, buttonPositions };
}
private createObfBoardFromPage(
page: AACPage,
fallbackName: string,
metadata?: AACTreeMetadata
): ObfBoard {
const { rows, columns, order, buttonPositions } = this.buildGridMetadata(page);
const boardName =
metadata?.name && page.id === metadata?.defaultHomePageId
? metadata.name
: page.name || fallbackName;
return {
format: OBF_FORMAT_VERSION,
id: page.id,
url: metadata?.url,
locale: metadata?.locale || page.locale || 'en',
name: boardName,
description_html:
metadata?.description && page.id === metadata?.defaultHomePageId
? metadata.description
: page.descriptionHtml || boardName,
grid: {
rows,
columns,
order,
},
buttons: page.buttons.map((button) => {
const extraButtonInfo = button as AACButton & { image_id?: string; imageId?: string };
const imageId =
button.parameters?.image_id ||
button.parameters?.imageId ||
extraButtonInfo.image_id ||
extraButtonInfo.imageId;
return {
id: button.id,
label: button.label,
vocalization: button.message || button.label,
load_board:
button.semanticAction?.intent === AACSemanticIntent.NAVIGATE_TO && button.targetPageId
? {
path: button.targetPageId,
}
: undefined,
background_color: button.style?.backgroundColor,
border_color: button.style?.borderColor,
box_id: buttonPositions.get(String(button.id ?? '')),
image_id: imageId,
};
}),
images: Array.isArray(page.images) ? page.images : [],
sounds: Array.isArray(page.sounds) ? page.sounds : [],
};
}
async processTexts(
filePathOrBuffer: ProcessorInput,
translations: Map<string, string>,
outputPath: string
): Promise<Uint8Array> {
const { readBinaryFromInput } = this.options.fileAdapter;
// Load the tree, apply translations, and save to new file
const tree = await this.loadIntoTree(filePathOrBuffer);
// Apply translations to all text content
Object.values(tree.pages).forEach((page) => {
// Translate page names
if (page.name && translations.has(page.name)) {
const translatedName = translations.get(page.name);
if (translatedName !== undefined) {
page.name = translatedName;
}
}
// Translate button labels and messages
page.buttons.forEach((button) => {
if (button.label && translations.has(button.label)) {
const translatedLabel = translations.get(button.label);
if (translatedLabel !== undefined) {
button.label = translatedLabel;
}
}
if (button.message && translations.has(button.message)) {
const translatedMessage = translations.get(button.message);
if (translatedMessage !== undefined) {
button.message = translatedMessage;
}
}
});
});
// Save the translated tree and return its content
await this.saveFromTree(tree, outputPath);
return readBinaryFromInput(outputPath);
}
async saveFromTree(tree: AACTree, outputPath: string): Promise<void> {
const { writeTextToPath, writeBinaryToPath } = this.options.fileAdapter;
if (outputPath.endsWith('.obf')) {
// Save as single OBF JSON file
const rootPage = tree.rootId ? tree.getPage(tree.rootId) : Object.values(tree.pages)[0];
if (!rootPage) {
throw new Error('No pages to save');
}
const obfBoard = this.createObfBoardFromPage(rootPage, 'Exported Board', tree.metadata);
writeTextToPath(outputPath, JSON.stringify(obfBoard, null, 2));
} else {
const files = Object.values(tree.pages).map((page) => {
const obfBoard = this.createObfBoardFromPage(page, 'Board', tree.metadata);
const obfContent = JSON.stringify(obfBoard, null, 2);
const name = page.id.endsWith('.obf') ? page.id : `${page.id}.obf`;
return {
name,
data: new TextEncoder().encode(obfContent),
};
});
const zip = await getZipAdapter(undefined, this.options.fileAdapter);
const zipData = await zip.writeFiles(files);
writeBinaryToPath(outputPath, zipData);
}
}
/**
* Extract strings with metadata for aac-tools-platform compatibility
* Uses the generic implementation from BaseProcessor
*/
async extractStringsWithMetadata(filePath: string): Promise<ExtractStringsResult> {
return this.extractStringsWithMetadataGeneric(filePath);
}
/**
* Generate translated download for aac-tools-platform compatibility
* Uses the generic implementation from BaseProcessor
*/
async generateTranslatedDownload(
filePath: string,
translatedStrings: TranslatedString[],
sourceStrings: SourceString[]
): Promise<string> {
return this.generateTranslatedDownloadGeneric(filePath, translatedStrings, sourceStrings);
}
/**
* Validate OBF/OBZ file format
* @param filePath - Path to the file to validate
* @returns Promise with validation result
*/
async validate(filePath: string): Promise<ValidationResult> {
const ObfValidator = this.getObfValidator();
return ObfValidator.validateFile(filePath, this.options.fileAdapter);
}
/**
* Extract symbol information from an OBF/OBZ file for LLM-based translation.
* Returns a structured format showing which buttons have symbols and their context.
*
* This method uses shared translation utilities that work across all AAC formats.
*
* @param filePathOrBuffer - Path to OBF/OBZ file or buffer
* @returns Array of symbol information for LLM processing
*/
async extractSymbolsForLLM(filePathOrBuffer: ProcessorInput): Promise<ButtonForTranslation[]> {
const tree = await this.loadIntoTree(filePathOrBuffer);
// Collect all buttons from all pages
const allButtons: any[] = [];
Object.values(tree.pages).forEach((page) => {
page.buttons.forEach((button) => {
// Add page context to each button
(button as any).pageId = page.id;
(button as any).pageName = page.name || page.id;
allButtons.push(button);
});
});
// Use shared utility to extract buttons with translation context
return extractAllButtonsForTranslation(allButtons, (button) => ({
pageId: button.pageId,
pageName: button.pageName,
}));
}
/**
* Apply LLM translations with symbol information.
* The LLM should provide translations with symbol attachments in the correct positions.
*
* This method uses shared translation utilities that work across all AAC formats.
*
* @param filePathOrBuffer - Path to OBF/OBZ file or buffer
* @param llmTranslations - Array of LLM translations with symbol info
* @param outputPath - Where to save the translated OBF/OBZ file
* @param options - Translation options (e.g., allowPartial for testing)
* @returns Buffer of the translated OBF/OBZ file
*/
async processLLMTranslations(
filePathOrBuffer: ProcessorInput,
llmTranslations: LLMLTranslationResult[],
outputPath: string,
options?: { allowPartial?: boolean }
): Promise<Uint8Array> {
const { readBinaryFromInput } = this.options.fileAdapter;
const tree = await this.loadIntoTree(filePathOrBuffer);
// Validate translations using shared utility
const buttonIds = Object.values(tree.pages).flatMap((page) => page.buttons.map((b) => b.id));
validateTranslationResults(llmTranslations, buttonIds, options);
// Create a map for quick lookup
const translationMap = new Map(llmTranslations.map((t) => [t.buttonId, t]));
// Apply translations
Object.values(tree.pages).forEach((page) => {
page.buttons.forEach((button) => {
const translation = translationMap.get(button.id);
if (!translation) return;
// Apply label translation
if (translation.translatedLabel) {
button.label = translation.translatedLabel;
}
// Apply message translation (vocalization in OBF)
if (translation.translatedMessage) {
button.message = translation.translatedMessage;
// Update semantic action if symbols provided
if (translation.symbols && translation.symbols.length > 0) {
if (!button.semanticAction) {
button.semanticAction = {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.SPEAK_TEXT,
text: translation.translatedMessage,
};
}
button.semanticAction.richText = {
text: translation.translatedMessage,
symbols: translation.symbols,
};
}
}
});
});
// Save and return
await this.saveFromTree(tree, outputPath);
return readBinaryFromInput(outputPath);
}
private getObfValidator(): typeof import('../validation/obfValidator').ObfValidator {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-return
return require('../validation/obfValidator').ObfValidator;
} catch (error) {
throw new Error('Validation utilities are not available in this environment.');
}
}
}
export { ObfProcessor };