-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1727 lines (1395 loc) · 67.3 KB
/
app.js
File metadata and controls
1727 lines (1395 loc) · 67.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
/**
* Advanced OCR Application
*
* This JavaScript file handles all frontend functionality including:
* - Image loading and display
* - Annotation creation and management
* - API communication with the backend
* - Results display
*/
// Main application class
class OCRApp {
constructor() {
this.image = null;
this.annotations = [];
this.results = null;
this.drawingAnnotation = false;
this.currentAnnotation = null;
this.startX = 0;
this.startY = 0;
this.colorMap = {
'text': '#198754',
'checkbox': '#0d6efd',
'minimal_character': '#6f42c1',
'qr': '#fd7e14'
};
// For batch processing
this.batchFiles = [];
this.batchResults = null;
this.batchId = null;
this.currentBatchIndex = 0;
this.isBatchMode = false;
// Initialize the application
this.init();
}
init() {
// Bind event listeners
this.bindEventListeners();
// Initialize Bootstrap modal
this.annotationModal = new bootstrap.Modal(document.getElementById('annotationModal'));
// Initialize batch processing data
this.batchFiles = [];
this.batchResults = null;
this.batchId = null;
}
bindEventListeners() {
// Mode selection
document.getElementById('singleMode').addEventListener('change', this.toggleProcessingMode.bind(this));
document.getElementById('batchMode').addEventListener('change', this.toggleProcessingMode.bind(this));
// File uploads
document.getElementById('imageInput').addEventListener('change', this.handleImageUpload.bind(this));
document.getElementById('jsonInput').addEventListener('change', this.handleJsonUpload.bind(this));
document.getElementById('folderInput').addEventListener('change', this.handleFolderSelection.bind(this));
document.getElementById('batchJsonInput').addEventListener('change', this.handleJsonUpload.bind(this));
document.getElementById('refreshFolderBtn').addEventListener('click', () => {
document.getElementById('folderInput').click();
});
// Buttons
document.getElementById('processButton').addEventListener('click', this.processDocument.bind(this));
document.getElementById('processFolderBtn').addEventListener('click', this.processBatch.bind(this));
document.getElementById('downloadButton').addEventListener('click', this.downloadResults.bind(this));
document.getElementById('downloadLearningButton').addEventListener('click',
this.isBatchMode ? this.downloadBatchLearningData.bind(this) : this.downloadLearningData.bind(this));
document.getElementById('createAnnotationsBtn').addEventListener('click', this.openAnnotationModal.bind(this));
document.getElementById('addRegionBtn').addEventListener('click', this.addAnnotation.bind(this));
document.getElementById('saveAnnotationsBtn').addEventListener('click', this.saveAnnotations.bind(this));
// Batch annotation buttons
document.getElementById('batchCreateAnnotationsBtn').addEventListener('click', this.openAnnotationModal.bind(this));
document.getElementById('batchAddRegionBtn').addEventListener('click', this.addAnnotation.bind(this));
document.getElementById('batchSaveAnnotationsBtn').addEventListener('click', this.saveAnnotations.bind(this));
// Batch navigation buttons
document.getElementById('prevImageBtn').addEventListener('click', () => this.navigateBatchImage('prev'));
document.getElementById('nextImageBtn').addEventListener('click', () => this.navigateBatchImage('next'));
// Modal buttons
document.getElementById('modalAddRegionBtn').addEventListener('click', this.addModalAnnotation.bind(this));
document.getElementById('saveModalAnnotationsBtn').addEventListener('click', this.saveModalAnnotations.bind(this));
// Canvas drawing events for annotation modal
const annotationCanvas = document.getElementById('annotationCanvas');
annotationCanvas.addEventListener('mousedown', this.startDrawing.bind(this));
annotationCanvas.addEventListener('mousemove', this.drawAnnotation.bind(this));
annotationCanvas.addEventListener('mouseup', this.finishDrawing.bind(this));
annotationCanvas.addEventListener('mouseleave', this.cancelDrawing.bind(this));
// Toggle switches
document.getElementById('showDebugImages').addEventListener('change', this.toggleDebugImages.bind(this));
document.getElementById('showBoundingBoxes').addEventListener('change', this.toggleBoundingBoxes.bind(this));
}
// File handling
handleImageUpload(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
// Create an image and strip EXIF data by drawing to a canvas
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
// Draw image on canvas, which strips EXIF metadata
ctx.drawImage(img, 0, 0);
// Convert canvas to data URL (removes EXIF)
this.image = new Image();
this.image.onload = () => {
this.displayImagePreview();
this.showStatus('Image loaded successfully');
};
this.image.src = canvas.toDataURL('image/png');
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
handleJsonUpload(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
try {
this.annotations = JSON.parse(e.target.result);
this.showStatus(`Loaded ${this.annotations.length} annotations`);
this.updateAnnotationsList();
// If in batch mode, enable the process button if we have files
if (this.isBatchMode && this.batchFiles && this.batchFiles.length > 0) {
document.getElementById('processFolderBtn').disabled = false;
}
// If image is already loaded in single mode, display with annotations
if (!this.isBatchMode && this.image) {
this.displayImagePreview();
}
} catch (error) {
this.showError('Invalid JSON file: ' + error.message);
}
};
reader.readAsText(file);
}
// UI display functions
displayImagePreview() {
const previewImg = document.getElementById('imagePreview');
previewImg.src = this.image.src;
document.getElementById('imagePreviewContainer').style.display = 'block';
// Also draw on main canvas if available
this.drawImageWithAnnotations();
}
drawImageWithAnnotations() {
const canvas = document.getElementById('outputCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to match image
canvas.width = this.image.width;
canvas.height = this.image.height;
// Draw image
ctx.drawImage(this.image, 0, 0);
// Draw annotations if they exist and checkbox is checked
if (this.annotations.length > 0 && document.getElementById('showBoundingBoxes').checked) {
this.drawAnnotationOverlay();
}
}
drawAnnotationOverlay() {
const overlay = document.getElementById('annotationOverlay');
overlay.innerHTML = '';
overlay.style.width = this.image.width + 'px';
overlay.style.height = this.image.height + 'px';
this.annotations.forEach((annotation, index) => {
const { name, coordinates, type = 'text' } = annotation;
const { x1, y1, x2, y2 } = coordinates;
// Create annotation box
const box = document.createElement('div');
box.className = 'annotation-box';
box.style.left = x1 + 'px';
box.style.top = y1 + 'px';
box.style.width = (x2 - x1) + 'px';
box.style.height = (y2 - y1) + 'px';
box.style.borderColor = this.colorMap[type] || '#198754';
// Create annotation label
const label = document.createElement('div');
label.className = 'annotation-label';
label.style.left = x1 + 'px';
label.style.top = (y1 - 20) + 'px';
label.style.backgroundColor = this.colorMap[type] || '#198754';
// Set label text based on results if available
if (this.results && this.results[name]) {
const resultText = this.results[name].text;
label.textContent = `${name}: ${resultText || '[empty]'}`;
} else {
label.textContent = `${name} (${type})`;
}
overlay.appendChild(box);
overlay.appendChild(label);
});
}
updateAnnotationsList() {
const listContainer = document.getElementById('annotationsList');
listContainer.innerHTML = '';
this.annotations.forEach((annotation, index) => {
const item = document.createElement('div');
item.className = 'annotation-list-item';
item.innerHTML = `
<span>${annotation.name} (${annotation.type || 'text'})</span>
<div class="controls">
<button class="btn btn-sm btn-outline-danger" data-index="${index}">Remove</button>
</div>
`;
// Add event listener for remove button
item.querySelector('button').addEventListener('click', (e) => {
const index = parseInt(e.target.dataset.index);
this.annotations.splice(index, 1);
this.updateAnnotationsList();
});
listContainer.appendChild(item);
});
}
updateModalAnnotationsList() {
const listContainer = document.getElementById('modalAnnotationsList');
listContainer.innerHTML = '';
this.annotations.forEach((annotation, index) => {
const item = document.createElement('div');
item.className = 'annotation-list-item';
item.innerHTML = `
<span>${annotation.name} (${annotation.type || 'text'}) - [${annotation.coordinates.x1},${annotation.coordinates.y1},${annotation.coordinates.x2},${annotation.coordinates.y2}]</span>
<div class="controls">
<button class="btn btn-sm btn-outline-danger" data-index="${index}">Remove</button>
</div>
`;
// Add event listener for remove button
item.querySelector('button').addEventListener('click', (e) => {
const index = parseInt(e.target.dataset.index);
this.annotations.splice(index, 1);
this.updateModalAnnotationsList();
this.drawAnnotationsOnModalCanvas();
});
listContainer.appendChild(item);
});
}
// Annotation creation
openAnnotationModal() {
if (!this.image) {
this.showError('Please upload an image first');
return;
}
const canvas = document.getElementById('annotationCanvas');
const ctx = canvas.getContext('2d');
// Set canvas size to match image (or container if image is larger)
const container = document.querySelector('.annotation-canvas-container');
const containerWidth = container.clientWidth;
// Calculate scale to fit image in container
const scale = containerWidth / this.image.width;
canvas.width = containerWidth;
canvas.height = this.image.height * scale;
// Store scale for coordinate translation
this.annotationScale = scale;
// Draw image
ctx.drawImage(this.image, 0, 0, canvas.width, canvas.height);
// Draw existing annotations
this.drawAnnotationsOnModalCanvas();
// Show modal
this.annotationModal.show();
}
drawAnnotationsOnModalCanvas() {
const canvas = document.getElementById('annotationCanvas');
const ctx = canvas.getContext('2d');
// Clear and redraw image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this.image, 0, 0, canvas.width, canvas.height);
// Draw existing annotations
this.annotations.forEach(annotation => {
const { coordinates, type = 'text' } = annotation;
const { x1, y1, x2, y2 } = coordinates;
// Scale coordinates
const scaledX1 = x1 * this.annotationScale;
const scaledY1 = y1 * this.annotationScale;
const scaledX2 = x2 * this.annotationScale;
const scaledY2 = y2 * this.annotationScale;
// Draw rectangle
ctx.strokeStyle = this.colorMap[type] || '#198754';
ctx.lineWidth = 2;
ctx.strokeRect(scaledX1, scaledY1, scaledX2 - scaledX1, scaledY2 - scaledY1);
// Draw label
ctx.fillStyle = this.colorMap[type] || '#198754';
ctx.fillRect(scaledX1, scaledY1 - 20, 80, 20);
ctx.fillStyle = 'white';
ctx.font = '12px Arial';
ctx.fillText(annotation.name, scaledX1 + 5, scaledY1 - 5);
});
}
startDrawing(event) {
if (!this.image) return;
this.drawingAnnotation = true;
// Get canvas coordinates
const canvas = document.getElementById('annotationCanvas');
const rect = canvas.getBoundingClientRect();
this.startX = event.clientX - rect.left;
this.startY = event.clientY - rect.top;
// Create new annotation
this.currentAnnotation = {
x1: this.startX,
y1: this.startY,
x2: this.startX,
y2: this.startY
};
}
drawAnnotation(event) {
if (!this.drawingAnnotation || !this.currentAnnotation) return;
const canvas = document.getElementById('annotationCanvas');
const ctx = canvas.getContext('2d');
const rect = canvas.getBoundingClientRect();
// Update end coordinates
this.currentAnnotation.x2 = event.clientX - rect.left;
this.currentAnnotation.y2 = event.clientY - rect.top;
// Redraw canvas
this.drawAnnotationsOnModalCanvas();
// Draw current annotation
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(
this.currentAnnotation.x1,
this.currentAnnotation.y1,
this.currentAnnotation.x2 - this.currentAnnotation.x1,
this.currentAnnotation.y2 - this.currentAnnotation.y1
);
}
finishDrawing() {
if (!this.drawingAnnotation || !this.currentAnnotation) return;
this.drawingAnnotation = false;
// Ensure coordinates are ordered (x1 < x2, y1 < y2)
const { x1, y1, x2, y2 } = this.currentAnnotation;
this.currentAnnotation = {
x1: Math.min(x1, x2),
y1: Math.min(y1, y2),
x2: Math.max(x1, x2),
y2: Math.max(y1, y2)
};
// Convert coordinates back to original image scale
document.getElementById('modalRegionName').focus();
}
cancelDrawing() {
this.drawingAnnotation = false;
this.currentAnnotation = null;
}
addModalAnnotation() {
if (!this.currentAnnotation) {
this.showError('Please draw a region first');
return;
}
const name = document.getElementById('modalRegionName').value.trim();
const type = document.getElementById('modalRegionType').value;
if (!name) {
this.showError('Please enter a region name');
return;
}
// Convert coordinates back to original image scale
const { x1, y1, x2, y2 } = this.currentAnnotation;
const annotation = {
name: name,
type: type,
coordinates: {
x1: Math.round(x1 / this.annotationScale),
y1: Math.round(y1 / this.annotationScale),
x2: Math.round(x2 / this.annotationScale),
y2: Math.round(y2 / this.annotationScale)
}
};
// Add to annotations array
this.annotations.push(annotation);
// Update UI
this.updateModalAnnotationsList();
this.drawAnnotationsOnModalCanvas();
// Reset
this.currentAnnotation = null;
document.getElementById('modalRegionName').value = '';
}
saveModalAnnotations() {
this.annotationModal.hide();
this.updateAnnotationsList();
// Show annotation editor
document.getElementById('annotationEditor').style.display = 'block';
// Draw on main canvas
if (this.image) {
this.drawImageWithAnnotations();
}
this.showStatus(`Saved ${this.annotations.length} annotations`);
}
addAnnotation() {
const name = document.getElementById('regionName').value.trim();
const type = document.getElementById('regionType').value;
if (!name) {
this.showError('Please enter a region name');
return;
}
const annotation = {
name: name,
type: type,
coordinates: {
x1: 0,
y1: 0,
x2: 100,
y2: 100
}
};
// Add to annotations array
this.annotations.push(annotation);
// Update UI
this.updateAnnotationsList();
document.getElementById('regionName').value = '';
}
saveAnnotations() {
// Create JSON file and trigger download
const json = JSON.stringify(this.annotations, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'annotations.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// API communication
// Add these methods to the OCRApp class
// Modify the processDocument method to include OCR engine selection
async processDocument() {
if (!this.image || this.annotations.length === 0) {
this.showError('Please upload both an image and annotations');
return;
}
// Show loading indicator
this.showLoading('Processing document...');
try {
// Get selected OCR engine
const engineElement = document.querySelector('input[name="ocrEngine"]:checked');
const ocrEngine = engineElement ? engineElement.value : 'claude';
// Get PaddleOCR settings if applicable
let paddleSettings = {};
if (ocrEngine !== 'claude') {
const langElement = document.getElementById('paddleLang');
const useGpuElement = document.getElementById('useGpu');
paddleSettings = {
lang: langElement ? langElement.value : 'en',
useGpu: useGpuElement ? useGpuElement.checked : false
};
}
// Prepare data for API
const data = {
image: this.image.src,
annotations: this.annotations,
ocrEngine: ocrEngine,
paddleSettings: paddleSettings
};
// Send to API
const response = await fetch('/api/process_full_document', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const result = await response.json();
if (result.error) {
throw new Error(result.error);
}
// Store results
this.results = result.results;
// Update UI
this.hideLoading();
this.drawImageWithAnnotations();
this.displayResults();
// Enable download button
document.getElementById('downloadButton').disabled = false;
this.showStatus('Processing complete! Review the results below.');
} catch (error) {
this.hideLoading();
this.showError('Processing failed: ' + error.message);
}
}
// Modify the displayResultsTable method to show engine-specific results
displayResultsTable() {
const tableBody = document.getElementById('resultsTableBody');
tableBody.innerHTML = '';
// Create a row for each result
for (const [name, result] of Object.entries(this.results)) {
const row = document.createElement('tr');
// Region name
const nameCell = document.createElement('td');
nameCell.textContent = name;
// Type
const typeCell = document.createElement('td');
typeCell.textContent = result.type;
// Recognized text
const textCell = document.createElement('td');
textCell.className = 'text-result';
textCell.textContent = result.text || '(empty)';
// Confidence
const confidenceCell = document.createElement('td');
confidenceCell.textContent = `${Math.round(result.confidence)}%`;
// Engine details
const engineCell = document.createElement('td');
if (result.engine_results) {
let engineHtml = '<small class="text-muted">';
if (result.engine_results.claude) {
engineHtml += `Claude: "${result.engine_results.claude.text}" (${Math.round(result.engine_results.claude.confidence)}%)<br>`;
}
if (result.engine_results.paddle) {
engineHtml += `PaddleOCR: "${result.engine_results.paddle.text}" (${Math.round(result.engine_results.paddle.confidence)}%)`;
}
engineHtml += '</small>';
engineCell.innerHTML = engineHtml;
} else {
engineCell.textContent = 'N/A';
}
row.appendChild(nameCell);
row.appendChild(typeCell);
row.appendChild(textCell);
row.appendChild(confidenceCell);
row.appendChild(engineCell);
tableBody.appendChild(row);
}
// Show results table section
document.getElementById('resultsTableSection').style.display = 'block';
}
// Results display
displayResults() {
// Display debug images if enabled
if (document.getElementById('showDebugImages').checked) {
this.displayDebugImages();
}
// Display results table
this.displayResultsTable();
}
updateResultsTableRow(regionName) {
const tableBody = document.getElementById('resultsTableBody');
if (!tableBody) return;
// Find the row for this region
const rows = tableBody.querySelectorAll('tr');
for (const row of rows) {
const nameCell = row.cells[0];
if (nameCell && nameCell.textContent === regionName) {
// Update text cell
const textCell = row.cells[2];
if (textCell) {
textCell.textContent = this.results[regionName].text || '(empty)';
// Add "edited" indicator if manually edited
if (this.results[regionName].manuallyEdited) {
if (!textCell.querySelector('.edited-indicator')) {
const indicator = document.createElement('span');
indicator.className = 'badge bg-warning ms-2 edited-indicator';
indicator.textContent = 'Edited';
textCell.appendChild(indicator);
}
}
}
break;
}
}
}
saveTextEdit(event) {
const input = event.target;
const regionName = input.dataset.regionName;
const newText = input.value;
// Update results in memory
if (this.results && this.results[regionName]) {
// Store the original text for learning data if it's the first edit
if (!this.results[regionName].originalText) {
this.results[regionName].originalText = this.results[regionName].text;
}
// Update the text
this.results[regionName].text = newText;
// Mark as manually edited
this.results[regionName].manuallyEdited = true;
// Update the results table
this.updateResultsTableRow(regionName);
// Update the annotation overlay to show the new text
this.drawImageWithAnnotations();
// Show status message
this.showStatus(`Updated text for region "${regionName}"`);
}
}
displayDebugImages() {
const container = document.getElementById('debugImagesContainer');
container.innerHTML = '';
// Create a row for each region
for (const [name, result] of Object.entries(this.results)) {
if (!result.debug_paths) continue;
// Create a card for each debug image version
const row = document.createElement('div');
row.className = 'col-md-4 mb-3';
const card = document.createElement('div');
card.className = 'card debug-image-card';
// Card header with region name
const header = document.createElement('div');
header.className = 'card-header';
header.textContent = `Region: ${name} (${result.type})`;
// Card body with images
const body = document.createElement('div');
body.className = 'card-body';
// Add each version as a tab
const versions = Object.entries(result.debug_paths).slice(0, 3); // Limit to 3 versions
versions.forEach(([version, url]) => {
const imgWrapper = document.createElement('div');
imgWrapper.className = 'debug-image-wrapper mb-2';
const img = document.createElement('img');
img.src = url;
img.className = 'debug-image';
img.alt = `${name} (${version})`;
const caption = document.createElement('div');
caption.className = 'text-center small mt-1';
caption.textContent = version;
imgWrapper.appendChild(img);
imgWrapper.appendChild(caption);
body.appendChild(imgWrapper);
});
// Add editable recognized text
const textDiv = document.createElement('div');
textDiv.className = 'mt-2 border-top pt-2';
const textLabel = document.createElement('strong');
textLabel.textContent = 'Recognized: ';
textDiv.appendChild(textLabel);
// Create editable input for the recognized text
const textInput = document.createElement('input');
textInput.type = 'text';
textInput.className = 'form-control form-control-sm recognized-text-input';
textInput.value = result.text || '';
textInput.dataset.regionName = name;
// Add event listeners for saving changes
textInput.addEventListener('blur', (e) => this.saveTextEdit(e));
textInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.target.blur();
}
});
textDiv.appendChild(textInput);
// Add confidence display
const confidenceDiv = document.createElement('div');
confidenceDiv.className = 'small text-muted mt-1';
confidenceDiv.textContent = `Confidence: ${Math.round(result.confidence)}%`;
textDiv.appendChild(confidenceDiv);
body.appendChild(textDiv);
card.appendChild(header);
card.appendChild(body);
row.appendChild(card);
container.appendChild(row);
}
// Show debug images section
document.getElementById('debugImagesSection').style.display = 'block';
}
// Toggle functions
toggleDebugImages(event) {
const show = event.target.checked;
document.getElementById('debugImagesSection').style.display = show ? 'block' : 'none';
}
toggleBoundingBoxes(event) {
const show = event.target.checked;
if (this.image) {
this.drawImageWithAnnotations();
}
}
// Utility functions
showError(message) {
const errorContainer = document.getElementById('errorContainer');
errorContainer.textContent = message;
errorContainer.style.display = 'block';
// Hide status
document.getElementById('statusContainer').style.display = 'none';
// Automatically hide after 5 seconds
setTimeout(() => {
errorContainer.style.display = 'none';
}, 5000);
}
showStatus(message) {
const statusContainer = document.getElementById('statusContainer');
statusContainer.textContent = message;
statusContainer.style.display = 'block';
// Hide error
document.getElementById('errorContainer').style.display = 'none';
}
showLoading(message) {
const loadingIndicator = document.getElementById('loadingIndicator');
document.getElementById('loadingMessage').textContent = message;
loadingIndicator.style.display = 'flex';
// Reset progress
document.getElementById('progressBar').style.width = '0%';
document.getElementById('progressText').textContent = '0%';
}
hideLoading() {
document.getElementById('loadingIndicator').style.display = 'none';
}
updateProgress(message, progress) {
document.getElementById('loadingMessage').textContent = message;
document.getElementById('progressBar').style.width = `${progress}%`;
document.getElementById('progressText').textContent = `${Math.round(progress)}%`;
}
downloadResults() {
if (!this.results) return;
// Combine annotations with results
const downloadData = this.annotations.map(annotation => {
const result = this.results[annotation.name] || {
text: '',
type: annotation.type,
confidence: 0
};
return {
...annotation,
recognized: {
text: result.text,
confidence: result.confidence
}
};
});
// Create JSON file and trigger download
const json = JSON.stringify(downloadData, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'ocr_results.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
downloadLearningData() {
if (!this.results) return;
// Create learning dataset from edited results
const learningData = [];
for (const [name, result] of Object.entries(this.results)) {
if (result.manuallyEdited && result.originalText !== undefined) {
learningData.push({
region_name: name,
data_type: result.type,
original_text: result.originalText,
corrected_text: result.text,
confidence: result.confidence,
engine_results: result.engine_results
});
}
}
if (learningData.length === 0) {
this.showError('No edited data found. Edit some recognized text first.');
return;
}
// Create JSON file and trigger download
const json = JSON.stringify(learningData, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'paddle_learning_data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.showStatus(`Downloaded learning dataset with ${learningData.length} entries`);
}
handleFolderSelection(event) {
const files = event.target.files;
if (!files || files.length === 0) return;
// Filter for image files
this.batchFiles = Array.from(files).filter(file => {
const ext = file.name.toLowerCase().split('.').pop();
return ['jpg', 'jpeg', 'png'].includes(ext);
});
if (this.batchFiles.length === 0) {
this.showError('No image files found in the selected folder');
document.getElementById('processFolderBtn').disabled = true;
document.getElementById('folderStats').style.display = 'none';
return;
}
// Enable the process button if we have both files and annotations
const processFolderBtn = document.getElementById('processFolderBtn');
processFolderBtn.disabled = this.annotations.length === 0;
// Update folder stats
const imageCountBadge = document.getElementById('imageCountBadge');
imageCountBadge.textContent = `${this.batchFiles.length} images`;
document.getElementById('folderStats').style.display = 'block';
this.showStatus(`Found ${this.batchFiles.length} image files ready for batch processing. ${
this.annotations.length ? 'Ready to process.' : 'Please upload or create annotations.'
}`);
// Show a preview of the first image
if (this.batchFiles.length > 0) {
const reader = new FileReader();
reader.onload = (e) => {
// Create an image preview (optional)
const img = new Image();
img.onload = () => {
const canvas = document.getElementById('outputCanvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions to match image
canvas.width = img.width;
canvas.height = img.height;
// Draw image
ctx.drawImage(img, 0, 0);
};
img.src = e.target.result;
};
reader.readAsDataURL(this.batchFiles[0]);
}
}
async processBatch() {
if (!this.batchFiles || this.batchFiles.length === 0) {
this.showError('Please select a folder with images');
return;
}
if (this.annotations.length === 0) {
this.showError('Please upload or create annotations first');
return;
}
// Show loading indicator
this.showLoading(`Processing batch of ${this.batchFiles.length} images...`);
try {
// Read all image files and convert to base64
const imagesData = [];
for (let i = 0; i < this.batchFiles.length; i++) {
const file = this.batchFiles[i];
// Update progress