-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3021 lines (2622 loc) · 107 KB
/
app.js
File metadata and controls
3021 lines (2622 loc) · 107 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
const { jsPDF } = window.jspdf || {};
window.addEventListener("error", (event) => {
const statusElement = document.querySelector("#status");
if (statusElement) {
statusElement.textContent = `Error: ${event.message || "An unexpected error occurred."}. Try reloading the page.`;
}
});
window.addEventListener("unhandledrejection", (event) => {
const statusElement = document.querySelector("#status");
if (statusElement) {
statusElement.textContent = `Error: ${event.reason?.message || "An unexpected error occurred."}. Try reloading the page.`;
}
});
const pageFormats = {
a4: { width: 210, height: 297 },
letter: { width: 216, height: 279 },
};
const previewMaxDimension = 1200;
const adjustPreviewMaxDimension = 1400;
const maxCropPercent = 45;
const minRemainingCropPercent = 10;
const autoDetectCropPadding = 0.012;
const presetSettings = {
clean: { brightness: 16, contrast: 114, grain: 1, vignette: 2, threshold: 188, shadowBoost: 0.14, binaryMix: 0.58, lineNoise: 0.014, tonerNoise: 0.006, scannerAge: 8, thermalFade: 0, ocrFirstRecommended: false },
"clean-text": { brightness: 12, contrast: 182, grain: 0, vignette: 0, threshold: 172, shadowBoost: 0.54, binaryMix: 1, lineNoise: 0, tonerNoise: 0, scannerAge: 0, thermalFade: 0, ocrFirstRecommended: true, pureMono: true, processingScale: 1, cleanIsolation: true, preserveLightInk: true },
"clean-handwriting": { brightness: 10, contrast: 158, grain: 0, vignette: 0, threshold: 176, shadowBoost: 0.44, binaryMix: 0.94, lineNoise: 0, tonerNoise: 0, scannerAge: 0, thermalFade: 0, ocrFirstRecommended: true, processingScale: 1, cleanIsolation: true, preserveLightInk: true, softerInk: true },
classic: { brightness: 8, contrast: 132, grain: 6, vignette: 5, threshold: 166, shadowBoost: 0.28, binaryMix: 0.74, lineNoise: 0.028, tonerNoise: 0.012, scannerAge: 34, thermalFade: 0, ocrFirstRecommended: false },
"high-contrast": { brightness: 3, contrast: 152, grain: 3, vignette: 1, threshold: 150, shadowBoost: 0.4, binaryMix: 0.88, lineNoise: 0.018, tonerNoise: 0.009, scannerAge: 18, thermalFade: 0, ocrFirstRecommended: true },
thermal: { brightness: 6, contrast: 162, grain: 4, vignette: 0, threshold: 154, shadowBoost: 0.36, binaryMix: 0.92, lineNoise: 0.02, tonerNoise: 0.014, processingScale: 0.76, pureMono: true, streakStrength: 0.02, dropoutChance: 0.0011, scannerAge: 42, thermalFade: 28, dotMatrixColumns: true, ocrFirstRecommended: false },
fax: { brightness: 0, contrast: 172, grain: 7, vignette: 1, threshold: 142, shadowBoost: 0.46, binaryMix: 1, lineNoise: 0.045, tonerNoise: 0.022, processingScale: 0.42, pureMono: true, streakStrength: 0.055, dropoutChance: 0.0024, scannerAge: 72, thermalFade: 0, ocrFirstRecommended: false },
};
const presetDescriptions = {
clean: "Office scanner keeps pages bright and legible while flattening background paper tone.",
"clean-text": "Clean text mode forces a white background, keeps more faint gray ink, and snaps document content into hard black.",
"clean-handwriting": "Clean handwriting keeps the white paper look but softens thresholding so thin strokes survive more often.",
classic: "Photocopier adds rougher toner texture and stronger black-and-white document separation.",
"high-contrast": "Receipts and forms pushes darker text and harder edges for faded print and low-contrast paper.",
thermal: "Dot matrix / thermal receipt mode keeps small print dark, narrow, and slightly banded like receipt stock.",
fax: "Fax mode leans into hard thresholding, feed-line texture, and coarse monochrome contrast.",
};
const broadlySupportedExtensions = new Set([
"jpg",
"jpeg",
"png",
"gif",
"bmp",
"webp",
"avif",
"svg",
"heic",
"heif",
"tif",
"tiff",
]);
const browserNativeExtensions = new Set(["jpg", "jpeg", "png", "gif", "bmp", "webp", "avif", "svg"]);
const exportPresets = {
"archive-pdf": { exportFormat: "pdf", exportVisibleOnly: false, pdfQuality: "high" },
"visible-review-zip": { exportFormat: "png", exportVisibleOnly: true },
"ocr-review-mode": { exportFormat: "pdf", exportVisibleOnly: true },
};
const settingsStorageKey = "safescan-review-settings";
const state = {
files: [],
pageFilters: new Set(),
draggingId: null,
previewRenderFrame: null,
activeAdjustId: null,
activeCornerIndex: null,
activeCropEdge: null,
activeCropPointer: null,
adjustPreviewMetrics: null,
opencvReadyHandled: false,
};
const elements = {
dropzone: document.querySelector("#dropzone"),
fileInput: document.querySelector("#file-input"),
previewList: document.querySelector("#preview-list"),
previewTemplate: document.querySelector("#preview-template"),
status: document.querySelector("#status"),
downloadBtn: document.querySelector("#download-btn"),
pageActionsSelect: document.querySelector("#page-actions-select"),
ocrActionsSelect: document.querySelector("#ocr-actions-select"),
pageSelectionAction: document.querySelector("#page-selection-action"),
pageFilterSelect: document.querySelector("#page-filter-select"),
exportPresetButtons: Array.from(document.querySelectorAll(".export-preset-button")),
activeFiltersSummary: document.querySelector("#active-filters-summary"),
adjustOverlay: document.querySelector("#adjust-overlay"),
adjustPreviewSurface: document.querySelector("#adjust-preview-surface"),
adjustPreviewCanvas: document.querySelector("#adjust-preview-canvas"),
adjustResultCanvas: document.querySelector("#adjust-result-canvas"),
cropOverlay: document.querySelector("#crop-overlay"),
cropBox: document.querySelector("#crop-box"),
cropHandles: Array.from(document.querySelectorAll(".crop-handle")),
cornerOverlay: document.querySelector("#corner-overlay"),
cornerHandles: Array.from(document.querySelectorAll(".corner-handle")),
adjustClose: document.querySelector("#adjust-close"),
adjustDone: document.querySelector("#adjust-done"),
adjustReset: document.querySelector("#adjust-reset"),
adjustApplySelected: document.querySelector("#adjust-apply-selected"),
adjustAutoDetect: document.querySelector("#adjust-auto-detect"),
adjustPerspective: document.querySelector("#adjust-perspective"),
adjustRotate: document.querySelector("#adjust-rotate"),
adjustCropTop: document.querySelector("#adjust-crop-top"),
adjustCropRight: document.querySelector("#adjust-crop-right"),
adjustCropBottom: document.querySelector("#adjust-crop-bottom"),
adjustCropLeft: document.querySelector("#adjust-crop-left"),
adjustCropSummary: document.querySelector("#adjust-crop-summary"),
pageSize: document.querySelector("#page-size"),
pageMargin: document.querySelector("#page-margin"),
imageFit: document.querySelector("#image-fit"),
pdfQuality: document.querySelector("#pdf-quality"),
exportFormat: document.querySelector("#export-format"),
ocrLanguage: document.querySelector("#ocr-language"),
ocrLanguageCustom: document.querySelector("#ocr-language-custom"),
autoCleanup: document.querySelector("#auto-cleanup"),
selectDetectedBlanks: document.querySelector("#select-detected-blanks"),
exportVisibleOnly: document.querySelector("#export-visible-only"),
prefAlwaysVisibleExport: document.querySelector("#pref-always-visible-export"),
prefRememberOcrLanguage: document.querySelector("#pref-remember-ocr-language"),
prefRememberReviewPreset: document.querySelector("#pref-remember-review-preset"),
prefAutoSelectReviewPreset: document.querySelector("#pref-auto-select-review-preset"),
scanLookToggle: document.querySelector("#scan-look-toggle"),
preset: document.querySelector("#scan-preset"),
presetDescription: document.querySelector("#preset-description"),
presetRecommendation: document.querySelector("#preset-recommendation"),
presetComparisonNote: document.querySelector("#preset-comparison-note"),
presetComparisonGrid: document.querySelector("#preset-comparison-grid"),
brightness: document.querySelector("#brightness"),
contrast: document.querySelector("#contrast"),
grain: document.querySelector("#grain"),
vignette: document.querySelector("#vignette"),
scannerAge: document.querySelector("#scanner-age"),
thermalFade: document.querySelector("#thermal-fade"),
ocrFirstMode: document.querySelector("#ocr-first-mode"),
controlsGrid: document.querySelector(".controls-grid"),
};
function generateId() {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function setStatus(message) {
elements.status.textContent = message;
}
function getFileExtension(fileName) {
return fileName.includes(".") ? fileName.split(".").pop().toLowerCase() : "";
}
function replaceFileExtension(fileName, nextExtension) {
const lastDotIndex = fileName.lastIndexOf(".");
const basename = lastDotIndex === -1 ? fileName : fileName.slice(0, lastDotIndex);
return `${basename}.${nextExtension}`;
}
function isLikelyImageFile(file) {
return file.type.startsWith("image/") || broadlySupportedExtensions.has(getFileExtension(file.name));
}
function getControls() {
return {
useScanLook: elements.scanLookToggle.checked,
preset: elements.preset.value,
brightness: Number(elements.brightness.value),
contrast: Number(elements.contrast.value),
grain: Number(elements.grain.value),
vignette: Number(elements.vignette.value),
scannerAge: Number(elements.scannerAge.value),
thermalFade: Number(elements.thermalFade.value),
ocrFirstMode: elements.ocrFirstMode.checked,
pageMargin: Number(elements.pageMargin.value),
imageFit: elements.imageFit.value,
pdfQuality: elements.pdfQuality.value,
exportFormat: elements.exportFormat.value,
ocrLanguage: elements.ocrLanguage.value,
autoCleanup: elements.autoCleanup.checked,
exportVisibleOnly: elements.exportVisibleOnly.checked,
};
}
function getAutomationPreferences() {
return {
alwaysVisibleExport: elements.prefAlwaysVisibleExport.checked,
rememberOcrLanguage: elements.prefRememberOcrLanguage.checked,
rememberReviewPreset: elements.prefRememberReviewPreset.checked,
autoSelectReviewPreset: elements.prefAutoSelectReviewPreset.checked,
};
}
function getScanControls(controls = getControls()) {
return {
useScanLook: controls.useScanLook,
preset: controls.preset,
brightness: controls.brightness,
contrast: controls.contrast,
grain: controls.grain,
vignette: controls.vignette,
scannerAge: controls.scannerAge,
thermalFade: controls.thermalFade,
ocrFirstMode: controls.ocrFirstMode,
autoCleanup: controls.autoCleanup,
};
}
function getPresetLabel(presetKey) {
const option = elements.preset.querySelector(`[value="${presetKey}"]`);
return option ? option.textContent : presetKey;
}
function getPresetRecommendationText(presetKey) {
const preset = presetSettings[presetKey];
if (!preset) {
return "";
}
const parts = [
`Brightness ${preset.brightness >= 0 ? "+" : ""}${preset.brightness}`,
`Contrast ${preset.contrast}`,
`Grain ${preset.grain}`,
`Vignette ${preset.vignette}`,
`Scanner age ${preset.scannerAge ?? 0}`,
];
if ((preset.thermalFade ?? 0) > 0) {
parts.push(`Thermal fade ${preset.thermalFade}`);
}
parts.push(`OCR-first ${preset.ocrFirstRecommended ? "on" : "off"}`);
return `Recommended defaults: ${parts.join(", ")}.`;
}
function updatePresetSpecificControlState() {
const thermalEnabled = elements.scanLookToggle.checked && elements.preset.value === "thermal";
elements.thermalFade.disabled = !thermalEnabled;
}
function getEffectiveControls(entry, controls = getControls()) {
if (!entry?.scanSettings) {
return controls;
}
return {
...controls,
...entry.scanSettings,
};
}
function getOcrLanguageCode() {
const customLanguage = elements.ocrLanguageCustom.value.trim();
return customLanguage || elements.ocrLanguage.value;
}
function cloneAdjustments(adjustments) {
return {
...adjustments,
corners: (adjustments.corners || createDefaultCorners()).map((point) => ({ ...point })),
};
}
function getSelectedEntries() {
return state.files.filter((entry) => entry.selected);
}
function entryMatchesFilter(entry, filter) {
if (filter === "selected") {
return Boolean(entry.selected);
}
if (filter === "blank") {
return Boolean(entry.blankCandidate);
}
if (filter === "scan-override") {
return Boolean(entry.scanSettings);
}
if (filter === "perspective") {
return Boolean(getEntryAdjustments(entry).perspectiveEnabled);
}
return false;
}
function matchesPageFilter(entry) {
if (!state.pageFilters.size) {
return true;
}
return [...state.pageFilters].every((filter) => entryMatchesFilter(entry, filter));
}
function getVisibleEntries() {
return state.files.filter(matchesPageFilter);
}
function clearHiddenPageFilterIfNeeded() {
if (!state.files.length || !state.pageFilters.size) {
return false;
}
if (getVisibleEntries().length > 0) {
return false;
}
state.pageFilters.clear();
saveReviewSettings();
return true;
}
function getActiveExportPresetKey() {
const controls = getControls();
const activeEntry = Object.entries(exportPresets).find(([, preset]) => {
const qualityMatches = !preset.pdfQuality || preset.pdfQuality === controls.pdfQuality;
return preset.exportFormat === controls.exportFormat && preset.exportVisibleOnly === controls.exportVisibleOnly && qualityMatches;
});
return activeEntry?.[0] || null;
}
function getFilterCounts() {
return {
all: state.files.length,
selected: state.files.filter((entry) => entryMatchesFilter(entry, "selected")).length,
blank: state.files.filter((entry) => entryMatchesFilter(entry, "blank")).length,
"scan-override": state.files.filter((entry) => entryMatchesFilter(entry, "scan-override")).length,
perspective: state.files.filter((entry) => entryMatchesFilter(entry, "perspective")).length,
};
}
function updateFilterChipState() {
const counts = getFilterCounts();
const activeFilter = state.pageFilters.size === 0 ? "all" : [...state.pageFilters][0];
elements.pageFilterSelect.value = activeFilter;
// Update option labels with counts
Array.from(elements.pageFilterSelect.options).forEach((option) => {
const filter = option.value;
const count = counts[filter] ?? 0;
const baseLabels = { all: "Show all pages", selected: "Selected only", blank: "Blank candidates", "scan-override": "Scan overrides", perspective: "Perspective corrected" };
option.textContent = `${baseLabels[filter] || filter} (${count})`;
});
const activeExportPresetKey = getActiveExportPresetKey();
elements.exportPresetButtons.forEach((button) => {
const isActive = button.dataset.exportPreset === activeExportPresetKey;
button.classList.toggle("is-active", isActive);
button.setAttribute("aria-pressed", String(isActive));
});
}
function getActiveFilterSummary() {
const visibleOnlySuffix = elements.exportVisibleOnly.checked ? " Visible-only export is on." : "";
if (!state.pageFilters.size) {
return `Showing all pages.${visibleOnlySuffix}`;
}
const filterLabels = { selected: "Selected", blank: "Blank candidates", "scan-override": "Scan overrides", perspective: "Perspective corrected" };
const labels = [...state.pageFilters].map((f) => filterLabels[f] || f);
return `Showing: ${labels.join(" + ")}.${visibleOnlySuffix}`;
}
function sanitizeBaseName(fileName) {
const baseName = fileName.replace(/\.[^.]+$/, "");
return baseName.replace(/[^a-z0-9-_]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "page";
}
function downloadBlob(fileName, blob) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = fileName;
anchor.click();
URL.revokeObjectURL(url);
}
function updateDownloadButtonLabel() {
const format = elements.exportFormat.value;
const targetLabel = elements.exportVisibleOnly.checked
? (format === "pdf" ? "Download Visible PDF" : `Download Visible ${format.toUpperCase()} ZIP`)
: (format === "pdf" ? "Download PDF" : `Download ${format.toUpperCase()} ZIP`);
elements.downloadBtn.textContent = targetLabel;
}
function updateVisibleActionLabels() {
// OCR option text updated inside the dropdown options
const allLabel = elements.exportVisibleOnly.checked ? "Extract all text" : "Extract all text";
const opt = elements.ocrActionsSelect.querySelector('[value="ocr-all"]');
if (opt) opt.textContent = allLabel;
}
function updateAutomationPreferenceState() {
if (elements.prefAlwaysVisibleExport.checked) {
elements.exportVisibleOnly.checked = true;
}
elements.exportVisibleOnly.disabled = elements.prefAlwaysVisibleExport.checked;
}
function updateBlankActionLabel() {
const opt = elements.pageActionsSelect.querySelector('[value="remove-blank"]');
if (opt) opt.textContent = elements.selectDetectedBlanks.checked ? "Select blank pages" : "Remove blank pages";
}
function saveReviewSettings() {
const preferences = getAutomationPreferences();
try {
window.localStorage.setItem(settingsStorageKey, JSON.stringify({
preferences,
pageFilters: preferences.rememberReviewPreset ? [...state.pageFilters] : [],
exportVisibleOnly: preferences.alwaysVisibleExport ? true : elements.exportVisibleOnly.checked,
ocrLanguage: preferences.rememberOcrLanguage ? elements.ocrLanguage.value : "eng",
ocrLanguageCustom: preferences.rememberOcrLanguage ? elements.ocrLanguageCustom.value : "",
}));
} catch {
// Ignore storage failures in private browsing or restricted environments.
}
}
function loadReviewSettings() {
try {
const rawSettings = window.localStorage.getItem(settingsStorageKey);
if (!rawSettings) {
return;
}
const parsed = JSON.parse(rawSettings);
if (parsed.preferences) {
elements.prefAlwaysVisibleExport.checked = Boolean(parsed.preferences.alwaysVisibleExport);
elements.prefRememberOcrLanguage.checked = Boolean(parsed.preferences.rememberOcrLanguage);
elements.prefRememberReviewPreset.checked = Boolean(parsed.preferences.rememberReviewPreset);
elements.prefAutoSelectReviewPreset.checked = Boolean(parsed.preferences.autoSelectReviewPreset);
}
if (Array.isArray(parsed.pageFilters)) {
state.pageFilters = new Set(parsed.pageFilters.filter((filter) => filter in getFilterCounts()));
}
if (typeof parsed.exportVisibleOnly === "boolean") {
elements.exportVisibleOnly.checked = parsed.exportVisibleOnly;
}
if (typeof parsed.ocrLanguage === "string") {
elements.ocrLanguage.value = parsed.ocrLanguage;
}
if (typeof parsed.ocrLanguageCustom === "string") {
elements.ocrLanguageCustom.value = parsed.ocrLanguageCustom;
}
} catch {
// Ignore malformed persisted state and fall back to defaults.
}
updateAutomationPreferenceState();
}
function estimateBlankness(canvas) {
const context = canvas.getContext("2d", { willReadFrequently: true });
const { width, height } = canvas;
const { data } = context.getImageData(0, 0, width, height);
const sampleStep = Math.max(1, Math.round(Math.sqrt((width * height) / 180000)));
let samples = 0;
let brightSum = 0;
let varianceSum = 0;
let darkPixels = 0;
let inkPixels = 0;
for (let y = 0; y < height; y += sampleStep) {
for (let x = 0; x < width; x += sampleStep) {
const index = ((y * width) + x) * 4;
const gray = (data[index] * 0.299) + (data[index + 1] * 0.587) + (data[index + 2] * 0.114);
brightSum += gray;
varianceSum += gray * gray;
if (gray < 245) {
darkPixels += 1;
}
if (gray < 220) {
inkPixels += 1;
}
samples += 1;
}
}
const average = brightSum / Math.max(1, samples);
const variance = (varianceSum / Math.max(1, samples)) - (average * average);
const darkRatio = darkPixels / Math.max(1, samples);
const inkRatio = inkPixels / Math.max(1, samples);
return {
average,
variance,
darkRatio,
inkRatio,
isBlank: average > 247 && variance < 260 && darkRatio < 0.012 && inkRatio < 0.003,
};
}
function toggleSelection(id, selected) {
const entry = state.files.find((file) => file.id === id);
if (!entry) {
return;
}
entry.selected = selected;
entry.blankCandidate = false;
renderPreviews();
}
function setAllSelections(selected) {
state.files.forEach((entry) => {
entry.selected = selected;
entry.blankCandidate = false;
});
renderPreviews();
}
function getPdfQualitySettings(quality) {
if (quality === "compact") {
return { jpegQuality: 0.76, scaleLimit: 1800 };
}
if (quality === "high") {
return { jpegQuality: 0.97, scaleLimit: 3200 };
}
return { jpegQuality: 0.9, scaleLimit: 2400 };
}
function renderOriginalImage(sourceImage) {
return renderOriginalImageAtSize(sourceImage, sourceImage.width, sourceImage.height);
}
function createDefaultAdjustments() {
return {
rotate: 0,
cropTop: 0,
cropRight: 0,
cropBottom: 0,
cropLeft: 0,
perspectiveEnabled: false,
autoDetected: false,
autoDetectionTried: false,
autoDetectionMaxDimension: 0,
corners: createDefaultCorners(),
};
}
function createDefaultCorners() {
return [
{ x: 0.04, y: 0.04 },
{ x: 0.96, y: 0.04 },
{ x: 0.96, y: 0.96 },
{ x: 0.04, y: 0.96 },
];
}
function getEntryAdjustments(entry) {
entry.adjustments ||= createDefaultAdjustments();
entry.adjustments.corners ||= createDefaultCorners();
entry.adjustments.autoDetected ||= false;
entry.adjustments.autoDetectionTried ||= false;
entry.adjustments.autoDetectionMaxDimension ||= 0;
return entry.adjustments;
}
function cornersMatchDefault(corners) {
const defaults = createDefaultCorners();
return (corners || []).every((point, index) => {
const fallback = defaults[index];
return fallback && Math.abs(point.x - fallback.x) < 0.0001 && Math.abs(point.y - fallback.y) < 0.0001;
});
}
function hasMeaningfulAdjustments(adjustments) {
return Boolean(
adjustments.rotate
|| adjustments.cropTop
|| adjustments.cropRight
|| adjustments.cropBottom
|| adjustments.cropLeft
|| adjustments.perspectiveEnabled
|| !cornersMatchDefault(adjustments.corners || createDefaultCorners())
);
}
function applyDetectedDocumentAdjustments(adjustments, detectedDocument, enablePerspective = false) {
adjustments.corners = detectedDocument.corners;
adjustments.cropTop = Math.max(0, Math.min(maxCropPercent, detectedDocument.bounds.top * 100));
adjustments.cropRight = Math.max(0, Math.min(maxCropPercent, (1 - detectedDocument.bounds.right) * 100));
adjustments.cropBottom = Math.max(0, Math.min(maxCropPercent, (1 - detectedDocument.bounds.bottom) * 100));
adjustments.cropLeft = Math.max(0, Math.min(maxCropPercent, detectedDocument.bounds.left * 100));
adjustments.perspectiveEnabled = enablePerspective;
adjustments.autoDetected = true;
adjustments.autoDetectionTried = true;
adjustments.autoDetectionMaxDimension = Math.max(adjustments.autoDetectionMaxDimension || 0, adjustPreviewMaxDimension);
}
function maybeAutoDetectEntryDocument(entry, maxDimension = adjustPreviewMaxDimension) {
const adjustments = getEntryAdjustments(entry);
if (!opencvReady() || adjustments.autoDetected || hasMeaningfulAdjustments(adjustments)) {
return false;
}
if (adjustments.autoDetectionTried && (adjustments.autoDetectionMaxDimension || 0) >= maxDimension) {
return false;
}
// Mark as tried before running detection so errors don't cause infinite retry loops
adjustments.autoDetectionTried = true;
adjustments.autoDetectionMaxDimension = Math.max(adjustments.autoDetectionMaxDimension || 0, maxDimension);
let detectedDocument;
try {
const baseCanvas = getBaseAdjustedCanvas(entry.sourceImage, adjustments, maxDimension);
detectedDocument = detectDocumentShape(baseCanvas);
} catch {
return false;
}
if (!detectedDocument) {
return false;
}
applyDetectedDocumentAdjustments(adjustments, detectedDocument);
return true;
}
function autoDetectPendingEntries(entries = state.files, maxDimension = adjustPreviewMaxDimension) {
if (!opencvReady()) {
return 0;
}
let detectedCount = 0;
entries.forEach((entry) => {
if (maybeAutoDetectEntryDocument(entry, maxDimension)) {
detectedCount += 1;
}
});
return detectedCount;
}
function countPendingAutoDetectEntries(entries = state.files, maxDimension = adjustPreviewMaxDimension) {
return entries.filter((entry) => {
const adjustments = getEntryAdjustments(entry);
return !adjustments.autoDetected
&& !hasMeaningfulAdjustments(adjustments)
&& ((adjustments.autoDetectionMaxDimension || 0) < maxDimension);
}).length;
}
function handleOpenCvReady() {
if (state.opencvReadyHandled) {
return;
}
state.opencvReadyHandled = true;
scheduleRenderPreviews();
if (state.activeAdjustId) {
renderAdjustPreview();
}
}
function watchOpenCvReadiness() {
if (opencvReady()) {
handleOpenCvReady();
return;
}
const readinessPoll = window.setInterval(() => {
if (!opencvReady()) {
return;
}
window.clearInterval(readinessPoll);
handleOpenCvReady();
}, 250);
}
function getBaseAdjustedCanvas(sourceImage, adjustments, maxDimension) {
return createRotatedCanvas(sourceImage, adjustments, maxDimension);
}
function renderOriginalImageAtSize(sourceImage, width, height) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = "high";
context.drawImage(sourceImage, 0, 0, width, height);
return canvas;
}
function getScaledDimensions(width, height, maxDimension) {
if (!maxDimension) {
return { width, height };
}
const largestSide = Math.max(width, height);
if (largestSide <= maxDimension) {
return { width, height };
}
const scale = maxDimension / largestSide;
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
};
}
function getCropRect(sourceImage, adjustments) {
return getCropRectForDimensions(sourceImage.width, sourceImage.height, adjustments);
}
function getCropRectForDimensions(width, height, adjustments) {
const cropLimit = maxCropPercent / 100;
const minRemaining = minRemainingCropPercent / 100;
const cropTop = Math.min(cropLimit, Math.max(0, adjustments.cropTop / 100));
const cropRight = Math.min(cropLimit, Math.max(0, adjustments.cropRight / 100));
const cropBottom = Math.min(cropLimit, Math.max(0, adjustments.cropBottom / 100));
const cropLeft = Math.min(cropLimit, Math.max(0, adjustments.cropLeft / 100));
const croppedWidth = width * Math.max(minRemaining, 1 - cropLeft - cropRight);
const croppedHeight = height * Math.max(minRemaining, 1 - cropTop - cropBottom);
return {
x: width * cropLeft,
y: height * cropTop,
width: croppedWidth,
height: croppedHeight,
};
}
function getRotatedBounds(width, height, angleInDegrees) {
const radians = Math.abs(angleInDegrees) * (Math.PI / 180);
const sin = Math.sin(radians);
const cos = Math.cos(radians);
return {
width: Math.max(1, Math.round((width * cos) + (height * sin))),
height: Math.max(1, Math.round((width * sin) + (height * cos))),
};
}
function createRotatedCanvas(sourceImage, adjustments, maxDimension) {
const scaledDimensions = getScaledDimensions(sourceImage.width, sourceImage.height, maxDimension);
const sourceCanvas = renderOriginalImageAtSize(sourceImage, scaledDimensions.width, scaledDimensions.height);
if (!adjustments.rotate) {
return sourceCanvas;
}
const rotatedBounds = getRotatedBounds(sourceCanvas.width, sourceCanvas.height, adjustments.rotate);
const rotatedCanvas = document.createElement("canvas");
rotatedCanvas.width = rotatedBounds.width;
rotatedCanvas.height = rotatedBounds.height;
const rotatedContext = rotatedCanvas.getContext("2d");
rotatedContext.fillStyle = "#ffffff";
rotatedContext.fillRect(0, 0, rotatedCanvas.width, rotatedCanvas.height);
rotatedContext.translate(rotatedCanvas.width / 2, rotatedCanvas.height / 2);
rotatedContext.rotate(adjustments.rotate * (Math.PI / 180));
rotatedContext.drawImage(sourceCanvas, -sourceCanvas.width / 2, -sourceCanvas.height / 2);
return rotatedCanvas;
}
function createCroppedCanvas(rotatedCanvas, adjustments) {
const cropRect = getCropRect(rotatedCanvas, adjustments);
const cropCanvas = document.createElement("canvas");
cropCanvas.width = Math.max(1, Math.round(cropRect.width));
cropCanvas.height = Math.max(1, Math.round(cropRect.height));
const cropContext = cropCanvas.getContext("2d");
cropContext.fillStyle = "#ffffff";
cropContext.fillRect(0, 0, cropCanvas.width, cropCanvas.height);
cropContext.imageSmoothingEnabled = true;
cropContext.imageSmoothingQuality = "high";
cropContext.drawImage(
rotatedCanvas,
cropRect.x,
cropRect.y,
cropRect.width,
cropRect.height,
0,
0,
cropCanvas.width,
cropCanvas.height
);
return { cropCanvas, cropRect };
}
function createAdjustedCanvas(sourceImage, adjustments, maxDimension, includePerspective = true) {
const rotatedCanvas = createRotatedCanvas(sourceImage, adjustments, maxDimension);
const { cropCanvas, cropRect } = createCroppedCanvas(rotatedCanvas, adjustments);
return includePerspective ? applyPerspectiveCorrection(cropCanvas, adjustments, cropRect, rotatedCanvas) : cropCanvas;
}
function opencvReady() {
return Boolean(window.cv && typeof window.cv.Mat === "function");
}
function clampNormalizedPoint(point) {
return {
x: Math.max(0, Math.min(1, point.x)),
y: Math.max(0, Math.min(1, point.y)),
};
}
function getPerspectivePoints(canvas, adjustments, cropRect = null, sourceCanvas = canvas) {
return (adjustments.corners || createDefaultCorners()).map((point) => ({
x: (clampNormalizedPoint(point).x * sourceCanvas.width) - (cropRect ? cropRect.x : 0),
y: (clampNormalizedPoint(point).y * sourceCanvas.height) - (cropRect ? cropRect.y : 0),
}));
}
function distanceBetween(pointA, pointB) {
return Math.hypot(pointA.x - pointB.x, pointA.y - pointB.y);
}
function orderCorners(points) {
const sortedBySum = [...points].sort((left, right) => (left.x + left.y) - (right.x + right.y));
const topLeft = sortedBySum[0];
const bottomRight = sortedBySum[3];
// Sort ascending by x-y: smallest x-y = bottom-left, largest x-y = top-right
const remaining = sortedBySum.slice(1, 3).sort((left, right) => (left.x - left.y) - (right.x - right.y));
return [topLeft, remaining[1], bottomRight, remaining[0]];
}
function getPolygonArea(points) {
let area = 0;
for (let index = 0; index < points.length; index += 1) {
const current = points[index];
const next = points[(index + 1) % points.length];
area += (current.x * next.y) - (next.x * current.y);
}
return Math.abs(area / 2);
}
function getNormalizedBounds(points) {
const normalizedPoints = points.map(clampNormalizedPoint);
const xs = normalizedPoints.map((point) => point.x);
const ys = normalizedPoints.map((point) => point.y);
const left = Math.max(0, Math.min(...xs));
const top = Math.max(0, Math.min(...ys));
const right = Math.min(1, Math.max(...xs));
const bottom = Math.min(1, Math.max(...ys));
return {
left,
top,
right,
bottom,
width: Math.max(0, right - left),
height: Math.max(0, bottom - top),
};
}
function expandBounds(bounds, padding = 0) {
return {
left: Math.max(0, bounds.left - padding),
top: Math.max(0, bounds.top - padding),
right: Math.min(1, bounds.right + padding),
bottom: Math.min(1, bounds.bottom + padding),
};
}
function createCornersFromBounds(bounds) {
return [
{ x: bounds.left, y: bounds.top },
{ x: bounds.right, y: bounds.top },
{ x: bounds.right, y: bounds.bottom },
{ x: bounds.left, y: bounds.bottom },
];
}
function getContourPoints(approximation, canvas) {
const points = [];
for (let row = 0; row < approximation.rows; row += 1) {
points.push({
x: approximation.data32S[row * 2] / canvas.width,
y: approximation.data32S[(row * 2) + 1] / canvas.height,
});
}
return points;
}
function scoreDocumentCandidate(points) {
const orderedPoints = orderCorners(points).map(clampNormalizedPoint);
const bounds = getNormalizedBounds(orderedPoints);
const polygonArea = getPolygonArea(orderedPoints);
const boundingArea = Math.max(0.0001, bounds.width * bounds.height);
const fillRatio = polygonArea / boundingArea;
const centerX = (bounds.left + bounds.right) / 2;
const centerY = (bounds.top + bounds.bottom) / 2;
const centerDistance = Math.hypot(centerX - 0.5, centerY - 0.5) / Math.hypot(0.5, 0.5);
const centerScore = 1 - Math.min(1, centerDistance);
const minMargin = Math.min(bounds.left, bounds.top, 1 - bounds.right, 1 - bounds.bottom);
const aspectRatio = bounds.width / Math.max(bounds.height, 0.0001);
if (polygonArea < 0.08 || bounds.width < 0.2 || bounds.height < 0.2) {
return null;
}
if (bounds.width > 0.99 && bounds.height > 0.99) {
return null;
}
let score = polygonArea * 5;
score += fillRatio * 1.8;
score += centerScore * 0.9;
if (minMargin < 0.004) {
score -= 0.45;
} else if (minMargin < 0.015) {
score -= 0.2;
}
if (aspectRatio < 0.35 || aspectRatio > 2.4) {
score -= 0.3;
}
return {
score,
corners: orderedPoints,
bounds,
};
}
function buildDocumentCandidate(points) {
const candidate = scoreDocumentCandidate(points);
if (!candidate) {
return null;
}
return candidate;
}
function getBoundingRectPoints(contour, canvas) {
const rect = window.cv.boundingRect(contour);
return createCornersFromBounds({
left: rect.x / canvas.width,
top: rect.y / canvas.height,
right: (rect.x + rect.width) / canvas.width,
bottom: (rect.y + rect.height) / canvas.height,
});
}
function getMinAreaRectPoints(contour, canvas) {
const rect = window.cv.minAreaRect(contour);
const angle = (rect.angle || 0) * Math.PI / 180;
const cx = rect.center.x;
const cy = rect.center.y;
const hw = rect.size.width / 2;
const hh = rect.size.height / 2;
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return [
{ x: (cx + cos * hw - sin * hh) / canvas.width, y: (cy + sin * hw + cos * hh) / canvas.height },
{ x: (cx - cos * hw - sin * hh) / canvas.width, y: (cy - sin * hw + cos * hh) / canvas.height },
{ x: (cx - cos * hw + sin * hh) / canvas.width, y: (cy - sin * hw - cos * hh) / canvas.height },
{ x: (cx + cos * hw + sin * hh) / canvas.width, y: (cy + sin * hw - cos * hh) / canvas.height },
];
}
function getBestDocumentCandidateFromContours(contours, canvas, preferQuadrilateral = false) {
let bestCandidate = null;
for (let index = 0; index < contours.size(); index += 1) {
const contour = contours.get(index);
const perimeter = window.cv.arcLength(contour, true);
const approx = new window.cv.Mat();
window.cv.approxPolyDP(contour, approx, 0.02 * perimeter, true);
const contourArea = Math.abs(window.cv.contourArea(contour)) / (canvas.width * canvas.height);
let candidate = null;
if (approx.rows === 4) {
candidate = buildDocumentCandidate(getContourPoints(approx, canvas));
if (candidate) {
candidate.score += 0.4;
}
}
// Try a looser approximation — helps with slightly curved or crumpled pages
if (!candidate) {
const looseApprox = new window.cv.Mat();
window.cv.approxPolyDP(contour, looseApprox, 0.05 * perimeter, true);
if (looseApprox.rows === 4) {
candidate = buildDocumentCandidate(getContourPoints(looseApprox, canvas));
if (candidate) {
candidate.score += 0.2;
}
}
looseApprox.delete();