-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmain.js
More file actions
2498 lines (2050 loc) · 98.3 KB
/
Copy pathmain.js
File metadata and controls
2498 lines (2050 loc) · 98.3 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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable import/no-cycle */
/// <reference path="./scribe.js/js/global.d.ts" />
/** @typedef {import('./scribe.js/js/objects/ocrObjects.js').OcrPage} OcrPage */
/** @typedef {import('./scribe.js/js/objects/ocrObjects.js').OcrWord} OcrWord */
/** @typedef {import('./scribe.js/js/objects/layoutObjects.js').LayoutPage} LayoutPage */
import { Collapse, Tooltip } from './app/lib/bootstrap.esm.bundle.min.js';
import scribe from './scribe.js/scribe.js';
import { insertAlertMessage } from './app/utils/warningMessages.js';
import { ScribeViewer } from './scribe.js/scribe-ui/viewer.js';
import { elem } from './app/elems.js';
import { RecognitionModelTextractBrowser } from './scribe.js/cloud-adapters/aws-textract/RecognitionModelAwsTextractBrowser.js';
import { ProgressBars } from './app/utils/progressBars.js';
const viewer = ScribeViewer.getDefault();
const doc = viewer.doc;
viewer.enableCanvasSelection = true;
ScribeViewer.KonvaIText.enableEditing = true;
viewer.opt.keyboardScope = 'global';
viewer.init(elem.canvas.canvasContainer, document.documentElement.clientWidth, document.documentElement.clientHeight);
let resizeTimer = null;
window.addEventListener('resize', () => {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
resizeTimer = null;
viewer.resize(document.documentElement.clientWidth, document.documentElement.clientHeight);
}, 150);
});
let batchProcessingActive = false;
/**
*
* @param {ProgressMessage} message
*/
const progressHandler = (message) => {
// During batch processing, skip all viewer rendering and progress bar updates.
if (batchProcessingActive) return;
if (message.type === 'convert') {
ProgressBars.active.increment();
const n = message.n;
const engineName = message.info.engineName;
// Display the page if either (1) this is the currently active OCR or (2) this is Tesseract Legacy and Tesseract LSTM is active, but does not exist yet.
// The latter condition occurs briefly whenever recognition is run in "Quality" mode.
const oemActive = Object.keys(doc.ocr).find((key) => doc.ocr[key] === doc.ocr.active && key !== 'active');
const displayOCR = engineName === oemActive || ['Tesseract Legacy', 'Tesseract LSTM'].includes(engineName) && oemActive === 'Tesseract Latest';
if (displayOCR && viewer.state.cp.n === n) viewer.displayPage(n);
} else if (message.type === 'export') {
ProgressBars.active.increment();
} else if (message.type === 'importImage') {
ProgressBars.active.increment();
if (viewer.state.cp.n === message.n) {
viewer.displayPage(message.n);
} else if (Math.abs(viewer.state.cp.n - message.n) < 2) {
viewer.renderWords(message.n);
}
} else if (message.type === 'importPDF') {
ProgressBars.active.increment();
if (viewer.state.cp.n === message.n) viewer.displayPage(message.n);
} else if (message.type === 'recognize') {
ProgressBars.active.increment();
} else if (message.type === 'render') {
if (ProgressBars.active === ProgressBars.download) ProgressBars.active.increment();
}
};
// Exposing important modules for debugging and testing purposes.
// These should not be relied upon in code--import/export should be used instead.
globalThis.df = {
scribe,
ScribeCanvas: ScribeViewer,
doc,
};
scribe.opt.progressHandler = progressHandler;
scribe.ScribeDoc.defaults.saveDebugImages = true;
scribe.ScribeDoc.defaults.printRecognitionTime = 25;
scribe.init({ font: true });
// Disable mouse wheel + control to zoom by the browser.
// The application supports zooming in on the canvas,
// however when the browser zooms it results in a blurry canvas,
// as the canvas is not drawn at the appropriate resolution.
window.addEventListener('wheel', (event) => {
if (event.ctrlKey) {
event.preventDefault();
}
}, { passive: false });
elem.info.debugPrintWordsOCR.addEventListener('click', () => printSelectedWords(true));
elem.info.debugPrintWordsCanvas.addEventListener('click', () => printSelectedWords(false));
elem.info.debugDownloadCanvas.addEventListener('click', downloadCanvas);
elem.info.debugDownloadImage.addEventListener('click', downloadCurrentImage);
elem.info.debugEvalLine.addEventListener('click', evalSelectedLine);
elem.info.usePDFTextMainCheckbox.addEventListener('click', () => {
scribe.ScribeDoc.defaults.usePDFText.native.main = elem.info.usePDFTextMainCheckbox.checked;
scribe.ScribeDoc.defaults.usePDFText.ocr.main = elem.info.usePDFTextMainCheckbox.checked;
});
scribe.ScribeDoc.defaults.usePDFText.native.main = elem.info.usePDFTextMainCheckbox.checked;
scribe.ScribeDoc.defaults.usePDFText.ocr.main = elem.info.usePDFTextMainCheckbox.checked;
elem.info.usePDFTextSuppCheckbox.addEventListener('click', () => {
scribe.ScribeDoc.defaults.usePDFText.native.supp = elem.info.usePDFTextSuppCheckbox.checked;
scribe.ScribeDoc.defaults.usePDFText.ocr.supp = elem.info.usePDFTextSuppCheckbox.checked;
});
scribe.ScribeDoc.defaults.usePDFText.native.supp = elem.info.usePDFTextSuppCheckbox.checked;
scribe.ScribeDoc.defaults.usePDFText.ocr.supp = elem.info.usePDFTextSuppCheckbox.checked;
elem.download.addOverlayCheckbox.addEventListener('click', () => {
scribe.ScribeDoc.defaults.addOverlay = elem.download.addOverlayCheckbox.checked;
});
elem.download.standardizePageSize.addEventListener('click', () => {
scribe.ScribeDoc.defaults.standardizePageSize = elem.download.standardizePageSize.checked;
});
elem.info.humanReadablePDF.addEventListener('click', () => {
scribe.ScribeDoc.defaults.humanReadablePDF = elem.info.humanReadablePDF.checked;
});
const setDisplayMode = (/** @type {'invis' | 'ebook' | 'eval' | 'proof' | 'annot'} */ mode) => {
viewer.state.displayMode = mode;
scribe.ScribeDoc.defaults.displayMode = mode;
if (mode === 'invis') {
viewer.enableHTMLOverlay = true;
ScribeViewer.KonvaIText.enableEditing = false;
viewer.enableCanvasSelection = false;
} else {
viewer.enableHTMLOverlay = false;
viewer.deleteHTMLOverlay();
ScribeViewer.KonvaIText.enableEditing = true;
viewer.enableCanvasSelection = true;
}
};
elem.view.displayMode.addEventListener('change', () => {
// If currently editing a word, finish the edit before switching modes.
if (ScribeViewer.KonvaIText.inputRemove) {
ScribeViewer.KonvaIText.inputRemove();
}
setDisplayMode(/** @type {'invis' | 'ebook' | 'eval' | 'proof' | 'annot'} */(elem.view.displayMode.value));
viewer.displayPage(viewer.state.cp.n);
enableDisableDownloadPDFAlert();
});
setDisplayMode('proof');
scribe.opt.warningHandler = (x) => insertAlertMessage(x, false);
scribe.opt.errorHandler = insertAlertMessage;
// Opt-in to bootstrap tooltip feature
// https://getbootstrap.com/docs/5.0/components/tooltips/
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.forEach((tooltipTriggerEl) => new Tooltip(tooltipTriggerEl));
elem.batch.batchModeToggle.addEventListener('change', () => {
elem.batch.batchConfigPanel.style.display = elem.batch.batchModeToggle.checked ? '' : 'none';
});
elem.batch.batchReturnButton.addEventListener('click', () => {
elem.batch.batchProgressPanel.style.display = 'none';
elem.batch.uploadOuterContainer.style.display = '';
elem.batch.uploadContentDiv.style.display = '';
elem.upload.uploadDropZone.disabled = false;
elem.upload.openFileInput.value = '';
elem.canvas.canvasContainer.style.display = '';
});
/**
* Process multiple files in batch mode.
* Each file is treated as a separate document: clear → import → recognize → export.
* Results are collected into a zip file and downloaded.
* @param {Array<File>|FileList} files
*/
async function batchProcessFiles(files) {
const fileArr = Array.from(files);
const totalFiles = fileArr.length;
if (totalFiles === 0) return;
const outputFormat = /** @type {string} */ (elem.batch.batchOutputFormat.value);
const runRecognition = elem.batch.batchRunRecognition.checked;
const useZip = elem.batch.batchDownloadZip.checked;
// Activate batch mode: hide the entire upload area and canvas, show the batch panel
batchProcessingActive = true;
elem.batch.uploadOuterContainer.style.display = 'none';
elem.canvas.canvasContainer.style.display = 'none';
elem.upload.uploadDropZone.disabled = true;
elem.batch.batchProgressPanel.style.display = '';
elem.batch.batchCompleteMessage.style.display = 'none';
elem.batch.batchErrorSummary.style.display = 'none';
elem.batch.batchFileList.innerHTML = '';
elem.batch.batchOverallProgressBar.style.width = '0%';
elem.batch.batchOverallPercent.textContent = '0%';
elem.batch.batchOverallLabel.textContent = `File 0 of ${totalFiles}`;
fileArr.forEach((file, i) => {
const row = document.createElement('tr');
row.innerHTML = `<td style="width:80px"><span class="badge bg-secondary" id="batchStatus_${i}">Pending</span></td>`
+ `<td class="text-start text-truncate" style="max-width:350px">${file.name}</td>`;
elem.batch.batchFileList.appendChild(row);
});
const zipModule = useZip ? await import('./scribe.js/lib/zip.js/index.js') : null;
const zipBlobWriter = zipModule ? new zipModule.BlobWriter('application/zip') : null;
const zipWriter = zipModule && zipBlobWriter ? new zipModule.ZipWriter(zipBlobWriter) : null;
let ext = outputFormat;
if (outputFormat === 'alto') {
ext = 'xml';
} else if (outputFormat === 'scribe' && !scribe.ScribeDoc.defaults.compressScribe) {
ext = 'scribe.json';
}
let successCount = 0;
let errorCount = 0;
if (runRecognition) {
const ocrParams = { anyOk: true, vanillaMode: viewer.opt.vanillaMode, langs: viewer.opt.langs };
scribe.init({ ocr: true, ocrParams });
}
for (let i = 0; i < totalFiles; i++) {
const file = fileArr[i];
const statusElem = /** @type {HTMLSpanElement} */ (document.getElementById(`batchStatus_${i}`));
elem.batch.batchOverallLabel.textContent = `File ${i + 1} of ${totalFiles}`;
const pct = Math.round((i / totalFiles) * 100);
elem.batch.batchOverallPercent.textContent = `${pct}%`;
elem.batch.batchOverallProgressBar.style.width = `${pct}%`;
statusElem.textContent = 'Processing';
statusElem.className = 'badge bg-info';
try {
doc.clear();
await doc.importFiles([file]);
if (runRecognition) {
const skipRecOCR = doc.inputData.xmlMode[0] && !doc.inputData.imageMode && !doc.inputData.pdfMode;
const skipRecPDF = doc.inputData.pdfMode && doc.inputData.pdfType === 'text';
if (!skipRecOCR && !skipRecPDF) {
await doc.recognize({ langs: viewer.opt.langs });
}
}
const content = await doc.exportData(/** @type {"pdf"|"hocr"|"alto"|"docx"|"html"|"xlsx"|"txt"|"md"|"scribe"} */ (outputFormat));
const baseName = file.name.replace(/\.\w{1,6}$/, '');
const outputFileName = `${baseName}.${ext}`;
if (useZip && zipWriter && zipModule) {
const contentArray = content instanceof ArrayBuffer
? new Uint8Array(content)
: new TextEncoder().encode(/** @type {string} */ (content));
await zipWriter.add(outputFileName, new zipModule.Uint8ArrayReader(contentArray));
} else {
// Download individually with a delay between files to avoid browser blocking
await scribe.utils.saveAs(content, outputFileName);
if (i < totalFiles - 1) {
await new Promise((resolve) => { setTimeout(resolve, 1000); });
}
}
successCount++;
statusElem.textContent = 'Done';
statusElem.className = 'badge bg-success';
} catch (e) {
console.error(`Batch processing failed for ${file.name}:`, e);
errorCount++;
statusElem.textContent = 'Error';
statusElem.className = 'badge bg-danger';
}
}
if (useZip && zipWriter && zipBlobWriter) {
await zipWriter.close();
if (successCount > 0) {
const zipBlob = await zipBlobWriter.getData();
const a = document.createElement('a');
a.download = 'scribe_batch_output.zip';
a.href = URL.createObjectURL(zipBlob);
a.dispatchEvent(new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
}));
}
}
elem.batch.batchOverallLabel.textContent = `${successCount} of ${totalFiles} files processed`;
elem.batch.batchOverallPercent.textContent = '100%';
elem.batch.batchOverallProgressBar.style.width = '100%';
elem.batch.batchCompleteMessage.style.display = '';
if (errorCount > 0) {
elem.batch.batchErrorSummary.style.display = '';
elem.batch.batchErrorCount.textContent = String(errorCount);
}
doc.clear();
batchProcessingActive = false;
}
elem.upload.openFileInput.addEventListener('change', () => {
if (batchProcessingActive) return;
if (!elem.upload.openFileInput.files || elem.upload.openFileInput.files.length === 0) return;
if (elem.batch.batchModeToggle.checked) {
batchProcessFiles(elem.upload.openFileInput.files);
return;
}
importFilesGUI(elem.upload.openFileInput.files);
// This should run after importFiles so if that function fails the dropzone is not removed
/** @type {HTMLElement} */ (elem.upload.uploadDropZone.parentElement).style.display = 'none';
});
elem.edit.fontImport.addEventListener('change', () => {
if (!elem.edit.fontImport.files || elem.edit.fontImport.files.length === 0) return;
importFontsGUI(elem.edit.fontImport.files);
});
let highlightActiveCt = 0;
elem.upload.uploadDropZone.addEventListener('dragover', (event) => {
event.preventDefault();
elem.upload.uploadDropZone.classList.add('highlight');
highlightActiveCt++;
});
elem.upload.uploadDropZone.addEventListener('dragleave', (event) => {
event.preventDefault();
// Only remove the highlight after 0.1 seconds, and only if it has not since been re-activated.
// This avoids flickering.
const highlightActiveCtNow = highlightActiveCt;
setTimeout(() => {
if (highlightActiveCtNow === highlightActiveCt) {
elem.upload.uploadDropZone.classList.remove('highlight');
}
}, 100);
});
// This is where the drop is handled.
elem.upload.uploadDropZone.addEventListener('drop', async (event) => {
// Prevent navigation.
event.preventDefault();
if (batchProcessingActive) return;
if (!event.dataTransfer) return;
const items = await ScribeViewer.getAllFileEntries(event.dataTransfer.items);
const filesPromises = await Promise.allSettled(items.map((x) => new Promise((resolve, reject) => {
if (x instanceof File) {
resolve(x);
} else {
x.file(resolve, reject);
}
})));
const files = filesPromises.map((x) => x.value);
if (files.length === 0) return;
elem.upload.uploadDropZone.classList.remove('highlight');
if (elem.batch.batchModeToggle.checked) {
batchProcessFiles(files);
return;
}
importFilesGUI(files);
// This should run after importFiles so if that function fails the dropzone is not removed
/** @type {HTMLElement} */ (elem.upload.uploadDropZone.parentElement).style.display = 'none';
});
/**
* Handle paste event to retrieve image from clipboard.
* @param {ClipboardEvent} event - The paste event containing clipboard data.
*/
const handlePaste = async (event) => {
// The event listner is on the `window` so is not deleted when the dropzone is hidden.
if (batchProcessingActive) return;
if (doc.pageMetrics.length > 0) return;
const clipboardData = event.clipboardData;
if (!clipboardData) return;
const items = clipboardData.items;
const imageArr = [];
for (const item of items) {
if (item.type.indexOf('image') === 0) {
const blob = item.getAsFile();
imageArr.push(blob);
}
}
if (imageArr.length > 0) {
if (elem.batch.batchModeToggle.checked) {
batchProcessFiles(imageArr);
return;
}
await importFilesGUI(imageArr);
elem.upload.uploadDropZone.setAttribute('style', 'display:none');
}
};
// The paste listner needs to be on the window, not the dropzone.
// Paste events are only triggered for individual elements if they are either input elements or have contenteditable set to true, neither of which are the case here.
window.addEventListener('paste', handlePaste);
/**
* Fetches an array of URLs and runs `importFiles` on the results.
* Intended only to be used by automated testing and not by users.
*
* @param {Array<string>} urls
*/
globalThis.fetchAndImportFiles = async (urls) => {
// Call the existing importFiles function with the file array
importFilesGUI(urls);
elem.upload.uploadDropZone.setAttribute('style', 'display:none');
};
viewer.interactionCallback = (event) => {
// When a shortcut that interacts with canvas elements is triggered,
// any focused UI element from the nav bar are unfocused.
// If this does not occur, then the UI will remain focused,
// and users attempting to interact with the canvas may instead interact with the UI.
// For example, pressing "enter" while the recognize tab is focused may trigger the "Recognize All" button.
const activeElem = document.activeElement instanceof HTMLElement ? document.activeElement : null;
if (activeElem && elem.nav.navBar.contains(activeElem)) activeElem.blur();
};
viewer.destroyControlsCallback = (deselect) => {
if (deselect) {
const open = elem.edit.collapseRangeBaselineBS._element.classList.contains('show');
if (open) {
elem.edit.collapseRangeBaselineBS.toggle();
return;
}
}
};
/**
* Maps from generic `KeyboardEvent` when user presses a key to the appropriate action.
* This function is responsible for all keyboard shortcuts.
* @param {KeyboardEvent} event - The key down event.
*/
function handleKeyboardEventGUI(event) {
// When a shortcut that interacts with canvas elements is triggered,
// any focused UI element from the nav bar are unfocused.
// If this does not occur, then the UI will remain focused,
// and users attempting to interact with the canvas may instead interact with the UI.
// For example, pressing "enter" while the recognize tab is focused may trigger the "Recognize All" button.
const activeElem = document.activeElement instanceof HTMLElement ? document.activeElement : null;
if (event.key === 'Escape') {
// eslint-disable-next-line no-new
if (elem.nav.editFindCollapse.classList.contains('show')) new Collapse(elem.nav.editFindCollapse, { toggle: true });
}
if (event.ctrlKey && ['f'].includes(event.key)) {
// eslint-disable-next-line no-new
if (!elem.nav.editFindCollapse.classList.contains('show')) new Collapse(elem.nav.editFindCollapse, { toggle: true });
elem.nav.editFind.focus();
event.preventDefault(); // Prevent the default action to avoid browser zoom
event.stopPropagation();
if (activeElem && elem.nav.navBar.contains(activeElem)) activeElem.blur();
return;
}
}
// Add various keyboard shortcuts.
document.addEventListener('keydown', handleKeyboardEventGUI);
// Add various event listners to HTML elements
elem.nav.next.addEventListener('click', () => viewer.displayPage(viewer.state.cp.n + 1, true, false));
elem.nav.prev.addEventListener('click', () => viewer.displayPage(viewer.state.cp.n - 1, true, false));
elem.nav.zoomIn.addEventListener('click', () => {
viewer.zoom(1.1, viewer.getStageCenter());
});
elem.nav.zoomOut.addEventListener('click', () => {
viewer.zoom(0.9, viewer.getStageCenter());
});
// `colorMode` lives on both the viewer (page rendering) and `ScribeDoc.defaults` (exports).
const setColorMode = (/** @type {"color" | "gray" | "binary"} */ mode) => {
viewer.state.colorMode = mode;
scribe.ScribeDoc.defaults.colorMode = mode;
};
elem.view.colorMode.addEventListener('change', () => {
setColorMode(/** @type {"color" | "gray" | "binary"} */ (elem.view.colorMode.value));
viewer.displayPage(viewer.state.cp.n);
});
setColorMode(/** @type {"color" | "gray" | "binary"} */ (elem.view.colorMode.value));
elem.view.overlayOpacity.addEventListener('input', () => {
scribe.ScribeDoc.defaults.overlayOpacity = parseInt(elem.view.overlayOpacity.value);
viewer.setWordColorOpacity();
viewer.layerText.batchDraw();
});
elem.recognize.enableUpscale.addEventListener('click', () => {
scribe.ScribeDoc.defaults.enableUpscale = elem.recognize.enableUpscale.checked;
});
elem.info.showDebugVis.addEventListener('change', () => {
scribe.ScribeDoc.defaults.debugVis = elem.info.showDebugVis.checked;
if (doc.pageMetrics.length === 0) return;
if (scribe.ScribeDoc.defaults.debugVis) {
viewer.displayPage(viewer.state.cp.n);
} else {
viewer.destroyOverlay(false);
viewer.layerOverlay.batchDraw();
}
});
elem.info.showDebugLegend.addEventListener('input', () => {
if (!elem.info.showDebugLegend.checked) {
elem.canvas.legendCanvasParentDiv.style.display = 'none';
} else {
elem.canvas.legendCanvasParentDiv.style.display = '';
}
});
elem.info.debugHidePage.addEventListener('input', () => {
const hidePage = scribe.ScribeDoc.defaults.debugVis && elem.info.selectDebugVis.value !== 'None' && elem.info.debugHidePage.checked;
if (hidePage) {
viewer.layerBackground.hide();
viewer.layerText.hide();
viewer.layerBackground.batchDraw();
viewer.layerText.batchDraw();
} else {
viewer.layerBackground.show();
viewer.layerText.show();
viewer.layerBackground.batchDraw();
viewer.layerText.batchDraw();
}
});
elem.info.selectDebugVis.addEventListener('change', () => { viewer.displayPage(viewer.state.cp.n); });
elem.evaluate.createGroundTruth.addEventListener('click', createGroundTruthClick);
elem.info.enableEval.addEventListener('click', () => {
elem.nav.navEvalTab.style.display = elem.info.enableEval.checked ? '' : 'none';
});
elem.info.enableAdvancedRecognition.addEventListener('click', () => {
const adv = elem.info.enableAdvancedRecognition.checked;
const isTextract = elem.recognize.oemLabelText.innerHTML === 'Textract';
elem.recognize.advancedRecognitionOptions1.style.display = adv ? '' : 'none';
elem.recognize.buildOptions.style.display = (adv && isTextract) ? 'none' : '';
elem.recognize.advancedRecognitionOptions2.style.display = (adv && !isTextract) ? '' : 'none';
elem.recognize.advancedRecognitionOptions3.style.display = (adv && !isTextract) ? '' : 'none';
elem.recognize.basicRecognitionOptions.style.display = !adv ? '' : 'none';
elem.recognize.textractOptions.style.display = (adv && isTextract) ? '' : 'none';
elem.recognize.textractFeatureOptions.style.display = (adv && isTextract) ? '' : 'none';
elem.recognize.textractAcceptChargesDiv.style.display = (adv && isTextract) ? '' : 'none';
elem.recognize.langOptions.style.display = (adv && isTextract) ? 'none' : '';
if (adv && isTextract) {
updateTextractRecognizeButton();
}
});
function updateTextractRecognizeButton() {
const isTextract = elem.info.enableAdvancedRecognition.checked
&& elem.recognize.oemLabelText.innerHTML === 'Textract';
if (!isTextract) return;
const hasCredentials = elem.recognize.textractAccessKeyId.value.trim() !== ''
&& elem.recognize.textractSecretAccessKey.value.trim() !== '';
elem.recognize.recognizeAll.disabled = !elem.recognize.textractAcceptCharges.checked || !hasCredentials;
}
elem.recognize.textractAcceptCharges.addEventListener('change', updateTextractRecognizeButton);
elem.recognize.textractAccessKeyId.addEventListener('input', updateTextractRecognizeButton);
elem.recognize.textractSecretAccessKey.addEventListener('input', updateTextractRecognizeButton);
export const enableRecognitionClick = () => {
elem.nav.navRecognizeTab.style.display = elem.info.enableRecognition.checked ? '' : 'none';
};
elem.info.enableRecognition.addEventListener('click', enableRecognitionClick);
elem.info.enableLayout.addEventListener('click', () => {
scribe.ScribeDoc.defaults.enableLayout = elem.info.enableLayout.checked;
elem.nav.navLayoutTab.style.display = elem.info.enableLayout.checked ? '' : 'none';
});
elem.info.enableAnnotate.addEventListener('click', () => {
const enabled = elem.info.enableAnnotate.checked;
elem.nav.navAnnotateTab.style.display = enabled ? '' : 'none';
elem.view.displayModeAnnot.style.display = enabled ? '' : 'none';
if (!enabled && elem.view.displayMode.value === 'annot') {
elem.view.displayMode.value = 'proof';
elem.view.displayMode.dispatchEvent(new Event('change'));
}
});
export const enableXlsxExportClick = () => {
// Adding layouts is required for xlsx exports
if (!elem.info.enableLayout.checked) elem.info.enableLayout.click();
elem.download.formatLabelOptionXlsx.style.display = elem.info.enableXlsxExport.checked ? '' : 'none';
};
elem.info.enableXlsxExport.addEventListener('click', enableXlsxExportClick);
elem.evaluate.uploadOCRButton.addEventListener('click', importFilesSuppGUI);
elem.evaluate.uploadOCRData.addEventListener('show.bs.collapse', () => {
if (!elem.upload.uploadOCRName.value) {
elem.upload.uploadOCRName.value = `OCR Data ${elem.evaluate.displayLabelOptions.childElementCount}`;
}
});
elem.edit.styleItalic.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
italic: elem.edit.styleItalic.checked,
});
});
elem.edit.styleBold.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
bold: elem.edit.styleBold.checked,
});
});
elem.edit.styleSmallCaps.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
smallCaps: elem.edit.styleSmallCaps.checked,
});
});
elem.edit.styleSuper.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
sup: elem.edit.styleSuper.checked,
});
});
elem.edit.styleUnderline.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
underline: elem.edit.styleUnderline.checked,
});
});
/** Sets the active swatch to the one matching the given color, or the custom swatch if none match. */
function setActiveSwatch(color) {
const swatches = /** @type {NodeListOf<HTMLElement>} */(elem.edit.highlightColorPresets.querySelectorAll('.highlightSwatch'));
let matched = false;
swatches.forEach((sw) => {
if (sw.dataset.color === color) {
sw.classList.add('active');
matched = true;
} else {
sw.classList.remove('active');
}
});
const customSwatch = /** @type {HTMLElement|null} */(elem.edit.highlightColorPresets.querySelector('.highlightSwatchCustom'));
if (!matched && customSwatch) {
customSwatch.classList.add('active');
customSwatch.style.background = color;
}
}
elem.edit.highlightColorPresets.addEventListener('click', (e) => {
const swatch = /** @type {HTMLElement} */(/** @type {HTMLElement} */(e.target).closest('.highlightSwatch'));
if (!swatch) return;
const color = swatch.dataset.color;
if (!color) return;
setActiveSwatch(color);
const selectedWords = viewer.CanvasSelection.getKonvaWords();
if (!selectedWords || selectedWords.length === 0) return;
const n = selectedWords[0].word.line.page.n;
if (color === 'none') {
viewer.removeHighlight(selectedWords, n);
} else {
elem.edit.highlightColor.value = color;
const opacity = parseInt(elem.edit.highlightOpacity.value) / 100;
viewer.applyHighlight(selectedWords, n, color, opacity);
}
});
elem.edit.highlightColor.addEventListener('input', () => {
const color = elem.edit.highlightColor.value;
setActiveSwatch(color);
const selectedWords = viewer.CanvasSelection.getKonvaWords();
if (!selectedWords || selectedWords.length === 0) return;
const n = selectedWords[0].word.line.page.n;
const opacity = parseInt(elem.edit.highlightOpacity.value) / 100;
viewer.applyHighlight(selectedWords, n, color, opacity);
});
elem.edit.highlightOpacity.addEventListener('input', () => {
const selectedWords = viewer.CanvasSelection.getKonvaWords();
if (!selectedWords || selectedWords.length === 0) return;
const n = selectedWords[0].word.line.page.n;
const color = elem.edit.highlightColor.value;
const opacity = parseInt(elem.edit.highlightOpacity.value) / 100;
viewer.applyHighlight(selectedWords, n, color, opacity);
});
elem.edit.highlightComment.addEventListener('input', () => {
const selectedWords = viewer.CanvasSelection.getKonvaWords();
if (!selectedWords || selectedWords.length === 0) return;
const n = selectedWords[0].word.line.page.n;
const comment = elem.edit.highlightComment.value;
viewer.modifyHighlightComment(selectedWords, n, comment);
});
/**
* Collects all unique annotation groups across all pages, sorted by page then vertical position.
* Each entry has { page, groupId, top }.
*/
function getAnnotationGroups() {
const groups = [];
const seen = new Set();
const pages = doc.annotations.pages;
for (let i = 0; i < pages.length; i++) {
if (!pages[i]) continue;
for (const annot of pages[i]) {
if (!annot.groupId || seen.has(annot.groupId)) continue;
seen.add(annot.groupId);
groups.push({ page: i, groupId: annot.groupId, top: annot.bbox.top });
}
}
groups.sort((a, b) => a.page - b.page || a.top - b.top);
return groups;
}
function updateAnnotationCounter() {
const groups = getAnnotationGroups();
elem.edit.annotationCount.textContent = String(groups.length);
const selectedWords = viewer.CanvasSelection.getKonvaWords();
if (selectedWords && selectedWords.length > 0 && selectedWords[0].highlightGroupId) {
const idx = groups.findIndex((g) => g.groupId === selectedWords[0].highlightGroupId);
elem.edit.annotationCurrent.textContent = idx >= 0 ? String(idx + 1) : '0';
} else {
// Show the index of the first annotation on the current page, or 0
const n = viewer.state.cp.n;
const idx = groups.findIndex((g) => g.page === n);
elem.edit.annotationCurrent.textContent = idx >= 0 ? String(idx + 1) : '0';
}
}
/**
* Navigates to the annotation group at the given index, selects its words, and updates UI.
* @param {{ page: number, groupId: string }[]} groups
* @param {number} targetIdx
*/
async function navigateToAnnotation(groups, targetIdx) {
const target = groups[targetIdx];
viewer.CanvasSelection.deselectAll();
await viewer.displayPage(target.page, true);
const pageWords = viewer.getKonvaWords();
const firstGroupWord = pageWords.find((kw) => kw.highlightGroupId === target.groupId);
if (firstGroupWord) {
viewer.CanvasSelection.addWords([firstGroupWord]);
firstGroupWord.select();
ScribeViewer.KonvaOcrWord.updateUI();
viewer.updateHighlightGroupOutline();
viewer.layerText.batchDraw();
}
}
elem.edit.prevAnnotation.addEventListener('click', () => {
const groups = getAnnotationGroups();
if (groups.length === 0) return;
const n = viewer.state.cp.n;
const selectedWords = viewer.CanvasSelection.getKonvaWords();
const currentGroupId = selectedWords?.[0]?.highlightGroupId;
let currentIdx = currentGroupId ? groups.findIndex((g) => g.groupId === currentGroupId) : -1;
if (currentIdx === -1) {
currentIdx = groups.findLastIndex((g) => g.page <= n);
if (currentIdx === -1) currentIdx = 0;
}
const targetIdx = currentIdx > 0 ? currentIdx - 1 : groups.length - 1;
navigateToAnnotation(groups, targetIdx);
});
elem.edit.nextAnnotation.addEventListener('click', () => {
const groups = getAnnotationGroups();
if (groups.length === 0) return;
const n = viewer.state.cp.n;
const selectedWords = viewer.CanvasSelection.getKonvaWords();
const currentGroupId = selectedWords?.[0]?.highlightGroupId;
let currentIdx = currentGroupId ? groups.findIndex((g) => g.groupId === currentGroupId) : -1;
if (currentIdx === -1) {
currentIdx = groups.findIndex((g) => g.page >= n);
if (currentIdx === -1) currentIdx = groups.length - 1;
}
const targetIdx = currentIdx < groups.length - 1 ? currentIdx + 1 : 0;
navigateToAnnotation(groups, targetIdx);
});
elem.edit.wordFont.addEventListener('change', () => {
viewer.modifySelectedWordStyle({
font: elem.edit.wordFont.value,
});
});
elem.edit.fontSize.addEventListener('change', () => {
viewer.modifySelectedWordStyle({
size: parseFloat(elem.edit.fontSize.value),
});
});
elem.edit.fontMinus.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
size: parseFloat(elem.edit.fontSize.value) - 1,
});
});
elem.edit.fontPlus.addEventListener('click', () => {
viewer.modifySelectedWordStyle({
size: parseFloat(elem.edit.fontSize.value) + 1,
});
});
elem.edit.ligatures.addEventListener('change', () => {
scribe.ScribeDoc.defaults.ligatures = elem.edit.ligatures.checked;
viewer.displayPage(viewer.state.cp.n);
});
elem.edit.kerning.addEventListener('change', () => {
scribe.ScribeDoc.defaults.kerning = elem.edit.kerning.checked;
viewer.displayPage(viewer.state.cp.n);
});
/** @type {Array<InstanceType<typeof ScribeViewer.KonvaOcrWord>>} */
let objectsLine;
const baselineRange = 25;
export function adjustBaseline() {
const open = elem.edit.collapseRangeBaselineBS._element.classList.contains('show');
if (open) {
elem.edit.collapseRangeBaselineBS.toggle();
return;
}
const selectedObjects = viewer.CanvasSelection.getKonvaWords();
if (!selectedObjects || selectedObjects.length === 0) {
return;
}
// Only open if a word is selected.
elem.edit.collapseRangeBaselineBS.toggle();
elem.edit.rangeBaseline.value = String(baselineRange + selectedObjects[0].baselineAdj);
// Unlikely identify lines using the ID of the first word on the line.
const lineI = selectedObjects[0]?.word?.line?.words[0]?.id;
console.assert(lineI !== undefined, 'Failed to identify line for word.');
objectsLine = viewer.getKonvaWords().filter((x) => x.word.line.words[0].id === lineI);
}
/**
* Visually moves the selected line's baseline on the canvas.
* Called when user is actively dragging the adjust baseline slider.
*
* @param {string | number} value - New baseline value.
*/
export function adjustBaselineRange(value) {
const valueNum = typeof value === 'string' ? parseInt(value) : value;
// The `topBaseline` is modified for all words, even though position is only changed for non-superscripted words.
// This allows the properties to be accurate if the user ever switches the word to non-superscripted.
objectsLine.forEach((objectI) => {
objectI.topBaseline = objectI.topBaselineOrig + (valueNum - baselineRange);
if (!objectI.word.style.sup) {
objectI.yActual = objectI.topBaseline;
}
});
viewer.layerText.batchDraw();
}
/**
* Adjusts the selected line's baseline in the canvas object and underlying OCR data.
* Called after user releases adjust baseline slider.
*
* @param {string | number} value - New baseline value.
*/
export function adjustBaselineRangeChange(value) {
const valueNum = typeof value === 'string' ? parseInt(value) : value;
const valueNew = valueNum - baselineRange;
const valueChange = valueNew - objectsLine[0].baselineAdj;
for (let i = 0; i < objectsLine.length; i++) {
const wordI = objectsLine[i];
wordI.baselineAdj = valueNew;
// Adjust baseline offset for line
if (i === 0) {
wordI.word.line.baseline[1] += valueChange;
}
}
}
export function toggleEditButtons(disable = true) {
if (!disable && !doc.ocr.active[0]) return;
elem.edit.wordFont.disabled = disable;
elem.edit.fontMinus.disabled = disable;
elem.edit.fontPlus.disabled = disable;
elem.edit.fontSize.disabled = disable;
elem.edit.styleItalic.disabled = disable;
elem.edit.styleBold.disabled = disable;
elem.edit.styleSmallCaps.disabled = disable;
elem.edit.styleSuper.disabled = disable;
elem.edit.styleUnderline.disabled = disable;
elem.edit.deleteWord.disabled = disable;
elem.edit.recognizeWord.disabled = disable;
elem.edit.recognizeWordDropdown.disabled = disable;
elem.edit.editBaseline.disabled = disable;
}
elem.edit.editBaseline.addEventListener('click', adjustBaseline);
elem.edit.rangeBaseline.addEventListener('input', () => { adjustBaselineRange(elem.edit.rangeBaseline.value); });
elem.edit.rangeBaseline.addEventListener('mouseup', () => { adjustBaselineRangeChange(elem.edit.rangeBaseline.value); });
elem.edit.deleteWord.addEventListener('click', () => viewer.deleteSelectedWord());
elem.edit.addWord.addEventListener('click', () => (viewer.mode = 'addWord'));
elem.view.optimizeFont.addEventListener('click', () => {
// This button does nothing if the debug option optimizeFontDebugElem is enabled.
// This approach is used rather than disabling the button, as `optimizeFontElem.disabled` is checked in other functions
// to determine whether font optimization is enabled.
if (elem.info.optimizeFontDebug.checked) return;
optimizeFontClick(elem.view.optimizeFont.checked);
});
elem.info.optimizeFontDebug.addEventListener('click', () => {
if (elem.info.optimizeFontDebug.checked) {
optimizeFontClick(true, true);
} else {
optimizeFontClick(elem.view.optimizeFont.checked, false);
}
});
elem.info.showIntermediateOCR.addEventListener('click', () => {
viewer.opt.showInternalOCRVersions = elem.info.showIntermediateOCR.checked;
updateOcrVersionGUI();
});
elem.info.keepPDFTextAlways.addEventListener('click', () => {
scribe.ScribeDoc.defaults.keepPDFTextAlways = elem.info.keepPDFTextAlways.checked;
});
elem.info.docxLineSplitSentence.addEventListener('click', () => {
scribe.ScribeDoc.defaults.docxLineSplitMode = elem.info.docxLineSplitSentence.checked ? 'sentence' : 'width';
});
elem.info.confThreshHigh.addEventListener('change', () => {
scribe.ScribeDoc.defaults.confThreshHigh = parseInt(elem.info.confThreshHigh.value);
viewer.displayPage(viewer.state.cp.n);
});
elem.info.confThreshMed.addEventListener('change', () => {
scribe.ScribeDoc.defaults.confThreshMed = parseInt(elem.info.confThreshMed.value);
viewer.displayPage(viewer.state.cp.n);
});
elem.view.autoRotate.addEventListener('click', () => {
if (elem.view.autoRotate.checked) {