forked from vorojar/Folio-OCR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1531 lines (1328 loc) · 51.2 KB
/
script.js
File metadata and controls
1531 lines (1328 loc) · 51.2 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
// --- State ---
const state = {
activeDocId: null,
activeDocFilename: null,
pages: [],
activePageNum: null,
modelLoaded: false,
layoutModelLoaded: false,
isLoadingModel: false,
ocrRunning: false,
ocrAbort: false,
viewMode: 'preview',
layoutEnabled: true,
docs: [], // [{doc_id, filename, page_count, ocr_count, created_at}]
};
// --- DOM refs ---
const $ = id => document.getElementById(id);
const topFilename = $('topFilename');
const deleteDocBtn = $('deleteDocBtn');
const statusDot = $('statusDot');
const statusText = $('statusText');
const loadModelBtn = $('loadModelBtn');
const newFileBtn = $('newFileBtn');
const layoutToggleWrap = $('layoutToggleWrap');
const layoutSwitch = $('layoutSwitch');
const ocrAllBtn = $('ocrAllBtn');
const exportWrap = $('exportWrap');
const exportBtn = $('exportBtn');
const exportMenu = $('exportMenu');
const copyAllBtn = $('copyAllBtn');
const ocrProgress = $('ocrProgress');
const ocrProgressBar = $('ocrProgressBar');
const panelLeft = $('panelLeft');
const pageList = $('pageList');
const panelCenter = $('panelCenter');
const uploadZone = $('uploadZone');
const previewContainer = $('previewContainer');
const previewWrap = $('previewWrap');
const previewImage = $('previewImage');
const bboxOverlay = $('bboxOverlay');
const panelRight = $('panelRight');
const resultBody = $('resultBody');
const resultTime = $('resultTime');
const resultToolbar = $('resultToolbar');
const viewToggle = $('viewToggle');
const reflowBtn = $('reflowBtn');
const reflowAllBtn = $('reflowAllBtn');
const copyPageBtn = $('copyPageBtn');
const fileInput = $('fileInput');
const searchWrap = $('searchWrap');
const searchToggle = $('searchToggle');
const searchInput = $('searchInput');
const searchInfo = $('searchInfo');
const searchPrev = $('searchPrev');
const searchNext = $('searchNext');
const docListSection = $('docListSection');
const docListHeader = $('docListHeader');
const docList = $('docList');
const docListCount = $('docListCount');
const docListToggle = $('docListToggle');
const resizeHandle = $('resizeHandle');
const toastContainer = $('toastContainer');
// --- Resize handle (drag to resize right panel) ---
{
let startX, startWidth;
resizeHandle.addEventListener('mousedown', (e) => {
e.preventDefault();
startX = e.clientX;
startWidth = panelRight.offsetWidth;
resizeHandle.classList.add('dragging');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
document.addEventListener('mousemove', onDrag);
document.addEventListener('mouseup', onDragEnd);
});
function onDrag(e) {
const delta = startX - e.clientX;
const newWidth = Math.min(Math.max(startWidth + delta, 280), window.innerWidth * 0.6);
panelRight.style.width = newWidth + 'px';
}
function onDragEnd() {
resizeHandle.classList.remove('dragging');
document.body.style.cursor = '';
document.body.style.userSelect = '';
document.removeEventListener('mousemove', onDrag);
document.removeEventListener('mouseup', onDragEnd);
}
}
// --- Fetch with timeout ---
function fetchT(url, opts = {}, timeoutMs = 15000) {
const controller = new AbortController();
const existing = opts.signal;
if (existing) existing.addEventListener('abort', () => controller.abort());
const timer = setTimeout(() => controller.abort(), timeoutMs);
return fetch(url, { ...opts, signal: controller.signal })
.finally(() => clearTimeout(timer));
}
// --- Toast notifications ---
function showToast(message, type = 'error', duration = 3500) {
const el = document.createElement('div');
el.className = `toast toast-${type}`;
el.textContent = message;
toastContainer.appendChild(el);
requestAnimationFrame(() => el.classList.add('show'));
setTimeout(() => {
el.classList.remove('show');
setTimeout(() => el.remove(), 300);
}, duration);
}
// --- Status polling ---
async function checkStatus() {
try {
const res = await fetchT('/api/status', {}, 5000);
const data = await res.json();
state.modelLoaded = data.model_loaded;
state.layoutModelLoaded = data.layout_loaded;
if (state.isLoadingModel) {
// Don't override loading UI
return;
}
if (!data.model_loaded) {
statusDot.className = 'status-dot error';
statusText.textContent = 'OCR model not found';
loadModelBtn.style.display = 'none';
} else if (!data.layout_loaded) {
statusDot.className = 'status-dot loading';
statusText.textContent = 'Layout not loaded';
loadModelBtn.style.display = '';
} else {
statusDot.className = 'status-dot online';
statusText.textContent = 'Ready';
loadModelBtn.style.display = 'none';
}
} catch (e) {
statusDot.className = 'status-dot error';
statusText.textContent = 'Offline';
}
}
checkStatus();
setInterval(checkStatus, 3000);
// --- Load model (shared logic) ---
let _modelLoadPromise = null;
async function ensureModelsLoaded() {
if (state.layoutModelLoaded) return true;
// If already loading, piggyback on existing request
if (_modelLoadPromise) return _modelLoadPromise;
_modelLoadPromise = (async () => {
state.isLoadingModel = true;
loadModelBtn.disabled = true;
loadModelBtn.textContent = 'Loading...';
statusDot.className = 'status-dot loading';
statusText.textContent = 'Loading model...';
const t0 = Date.now();
const timer = setInterval(() => {
const s = Math.round((Date.now() - t0) / 1000);
statusText.textContent = `Loading model... ${s}s`;
loadModelBtn.textContent = `Loading... ${s}s`;
}, 1000);
try {
const res = await fetchT('/api/load-model', { method: 'POST' }, 180000);
if (!res.ok) throw new Error('Load failed');
const elapsed = ((Date.now() - t0) / 1000).toFixed(1);
state.layoutModelLoaded = true;
statusDot.className = 'status-dot online';
statusText.textContent = `Ready (loaded ${elapsed}s)`;
loadModelBtn.style.display = 'none';
return true;
} catch (e) {
console.error('Load model failed:', e);
statusDot.className = 'status-dot error';
statusText.textContent = 'Load failed';
return false;
} finally {
clearInterval(timer);
state.isLoadingModel = false;
loadModelBtn.disabled = false;
loadModelBtn.textContent = 'Load Model';
_modelLoadPromise = null;
}
})();
return _modelLoadPromise;
}
loadModelBtn.addEventListener('click', () => ensureModelsLoaded());
// --- Layout toggle ---
layoutSwitch.addEventListener('click', () => {
state.layoutEnabled = !state.layoutEnabled;
layoutSwitch.classList.toggle('on', state.layoutEnabled);
// Update bbox overlay visibility
bboxOverlay.style.display = state.layoutEnabled ? '' : 'none';
});
// --- Stop batch OCR helper ---
function stopBatchOcr() {
state.ocrAbort = true;
if (_batchAbortController) _batchAbortController.abort();
state.ocrRunning = false;
ocrAllBtn.textContent = 'OCR All Pages';
ocrAllBtn.classList.remove('danger');
ocrProgress.style.display = 'none';
}
// --- Reset view state ---
function resetViewState() {
state.activeDocId = null;
state.activeDocFilename = null;
state.pages = [];
state.activePageNum = null;
pageList.innerHTML = '';
previewContainer.classList.remove('show');
previewImage.src = '';
bboxOverlay.innerHTML = '';
resultBody.innerHTML = '<div class="result-placeholder">Select a page to view OCR result</div>';
resultTime.style.display = 'none';
resultToolbar.style.display = 'none';
}
// --- File upload ---
uploadZone.addEventListener('click', () => fileInput.click());
newFileBtn.addEventListener('click', () => fileInput.click());
uploadZone.addEventListener('dragover', e => {
e.preventDefault();
uploadZone.classList.add('dragover');
});
uploadZone.addEventListener('dragleave', () => {
uploadZone.classList.remove('dragover');
});
uploadZone.addEventListener('drop', e => {
e.preventDefault();
uploadZone.classList.remove('dragover');
if (e.dataTransfer.files.length > 0) uploadFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', () => {
if (fileInput.files.length > 0) uploadFiles(fileInput.files);
fileInput.value = '';
});
panelCenter.addEventListener('dragover', e => {
e.preventDefault();
if (!uploadZone.classList.contains('hidden')) {
uploadZone.classList.add('dragover');
}
});
panelCenter.addEventListener('drop', e => {
e.preventDefault();
uploadZone.classList.remove('dragover');
if (e.dataTransfer.files.length > 0) uploadFiles(e.dataTransfer.files);
});
async function uploadFiles(fileList) {
// Build FormData FIRST (before any await) — fileList may be a live
// FileList reference that gets cleared when fileInput.value is reset
const formData = new FormData();
const label = fileList.length === 1 ? fileList[0].name : `${fileList.length} files`;
for (const f of fileList) formData.append('files', f);
if (state.ocrRunning) stopBatchOcr();
resetViewState();
topFilename.textContent = `Uploading ${label}...`;
try {
const res = await fetchT('/api/upload', { method: 'POST', body: formData }, 120000);
if (!res.ok) {
let msg = 'Upload failed';
try {
const err = await res.json();
msg = typeof err.detail === 'string' ? err.detail : JSON.stringify(err.detail);
} catch (_) { msg = `HTTP ${res.status}`; }
throw new Error(msg);
}
await handleUploadStream(res);
} catch (e) {
topFilename.textContent = 'Upload failed: ' + e.message;
console.error(e);
}
}
function initDoc(docId, filename) {
state.activeDocId = docId;
state.activeDocFilename = filename;
state.pages = [];
state.activePageNum = null;
topFilename.textContent = filename;
deleteDocBtn.style.display = '';
pageList.innerHTML = '';
panelLeft.classList.remove('hidden');
panelRight.classList.remove('hidden');
resizeHandle.classList.remove('hidden');
uploadZone.classList.add('hidden');
layoutToggleWrap.style.display = '';
ocrAllBtn.style.display = '';
exportWrap.style.display = '';
copyAllBtn.style.display = '';
searchWrap.style.display = '';
clearSearch();
updateDocItemActiveState();
}
function addPage(page) {
state.pages.push(page);
appendPageThumb(page);
}
async function handleUploadStream(res) {
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split('\n\n');
buffer = parts.pop();
for (const part of parts) {
const line = part.split('\n').find(l => l.startsWith('data: '));
if (!line) continue;
const evt = JSON.parse(line.slice(6));
if (evt.type === 'init') {
initDoc(evt.doc_id, evt.filename);
// Add new doc to list at top
state.docs.unshift({
doc_id: evt.doc_id,
filename: evt.filename,
page_count: 0,
ocr_count: 0,
created_at: new Date().toISOString(),
});
renderDocList();
} else if (evt.type === 'page') {
addPage(evt.page);
// Update page count in doc list
const docEntry = state.docs.find(d => d.doc_id === state.activeDocId);
if (docEntry) {
docEntry.page_count = state.pages.length;
if (evt.page.ocr_text != null) docEntry.ocr_count++;
updateDocItemCounts(state.activeDocId, docEntry.page_count, docEntry.ocr_count);
}
if (state.pages.length === 1) selectPage(1);
}
}
}
}
// --- Append a single thumbnail ---
function appendPageThumb(page) {
const div = document.createElement('div');
div.className = 'page-thumb' + (page.num === state.activePageNum ? ' active' : '');
div.dataset.num = page.num;
let sc = '', sl = 'Pending';
if (page.ocr_text != null) { sc = 'done'; sl = `Done (${page.ocr_time}s)`; }
div.innerHTML = `
<img src="${page.image_url}" alt="Page ${page.num}" loading="lazy">
<div class="page-thumb-info">
<div class="page-thumb-label">Page ${page.num}</div>
<div class="page-thumb-status ${sc}">${sl}</div>
</div>
`;
div.addEventListener('click', () => selectPage(page.num));
pageList.appendChild(div);
}
function renderPageList() {
pageList.innerHTML = '';
state.pages.forEach(page => appendPageThumb(page));
}
// --- Keyboard navigation (↑/↓ to switch pages) ---
document.addEventListener('keydown', (e) => {
// Don't intercept when typing in textarea
if (e.target.tagName === 'TEXTAREA' || e.target.tagName === 'INPUT') return;
if (!state.activeDocId || state.pages.length === 0) return;
if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
e.preventDefault();
const idx = state.pages.findIndex(p => p.num === state.activePageNum);
if (idx > 0) selectPage(state.pages[idx - 1].num);
} else if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
e.preventDefault();
const idx = state.pages.findIndex(p => p.num === state.activePageNum);
if (idx < state.pages.length - 1) selectPage(state.pages[idx + 1].num);
}
});
// --- Select page ---
async function selectPage(num) {
// Save current editor content before switching
saveCurrentEditor();
state.activePageNum = num;
pageList.querySelectorAll('.page-thumb').forEach(el => {
el.classList.toggle('active', parseInt(el.dataset.num) === num);
});
const page = state.pages.find(p => p.num === num);
if (!page) return;
previewContainer.classList.add('show');
previewImage.src = page.image_url;
// Render bbox overlay once image loads (needs natural dimensions)
previewImage.onload = () => renderBboxOverlay(page.ocr_regions);
if (page.ocr_text != null) {
showEditor(page.ocr_text, page.ocr_time, page.ocr_regions);
preOcrNext(num);
} else {
await runOcrForPage(page);
}
}
// --- Save textarea edits back to state + server ---
function saveCurrentEditor() {
// Always cancel pending debounce first — prevents stale timer from
// saving old text to a different document after a fast switch.
clearTimeout(_saveTimer);
const ta = resultBody.querySelector('.result-editor');
if (ta && state.activePageNum != null) {
const page = state.pages.find(p => p.num === state.activePageNum);
if (page) {
page.ocr_text = ta.value;
if (state.activeDocId) {
saveTextToServer(state.activeDocId, state.activePageNum, ta.value);
}
}
}
}
// --- Run OCR for a single page ---
async function runOcrForPage(page) {
// Ensure models are loaded before OCR
if (!state.layoutModelLoaded) {
resultBody.innerHTML = '<div class="result-loading"><div class="spinner"></div>Loading model...</div>';
resultTime.style.display = 'none';
const ok = await ensureModelsLoaded();
if (!ok) {
resultBody.innerHTML = '<div class="result-error">Model loading failed</div>';
return;
}
}
resultBody.innerHTML = '<div class="result-loading"><div class="spinner"></div>Recognizing page ' + page.num + '...</div>';
resultTime.style.display = 'none';
const thumbStatus = pageList.querySelector(`.page-thumb[data-num="${page.num}"] .page-thumb-status`);
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status running';
thumbStatus.textContent = 'Running...';
}
try {
const res = await fetchT(`/api/ocr/${state.activeDocId}/${page.num}?layout=${state.layoutEnabled}`, { method: 'POST' }, 120000);
if (!res.ok) {
const err = await res.json();
throw new Error(err.detail || 'OCR failed');
}
const data = await res.json();
page.ocr_text = data.text;
page.ocr_regions = data.regions || [];
page.ocr_time = data.time;
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status done';
thumbStatus.textContent = `Done (${data.time}s)`;
}
if (state.activePageNum === page.num) {
renderBboxOverlay(page.ocr_regions);
showEditor(data.text, data.time, page.ocr_regions);
}
// Update doc list badge
updateDocOcrCount();
// Pre-OCR next page in background
preOcrNext(page.num);
} catch (e) {
const isTimeout = e.name === 'AbortError';
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status error';
thumbStatus.textContent = isTimeout ? 'Timeout' : 'Error';
}
if (state.activePageNum === page.num) {
const msg = isTimeout ? 'OCR timed out — retry?' : `OCR failed: ${e.message}`;
resultBody.innerHTML = `<div class="result-error">${msg}</div>`;
}
if (isTimeout) showToast('OCR timed out — retry?', 'error');
}
}
// --- Background pre-OCR for next page ---
let _preOcrRunning = false;
async function preOcrNext(currentNum) {
if (_preOcrRunning || state.ocrRunning || !state.layoutModelLoaded) return;
const idx = state.pages.findIndex(p => p.num === currentNum);
if (idx < 0 || idx >= state.pages.length - 1) return;
const next = state.pages[idx + 1];
if (next.ocr_text != null) return;
_preOcrRunning = true;
const thumbStatus = pageList.querySelector(`.page-thumb[data-num="${next.num}"] .page-thumb-status`);
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status running';
thumbStatus.textContent = 'Pre-OCR...';
}
try {
const res = await fetchT(`/api/ocr/${state.activeDocId}/${next.num}?layout=${state.layoutEnabled}`, { method: 'POST' }, 120000);
if (!res.ok) throw new Error('Pre-OCR failed');
const data = await res.json();
next.ocr_text = data.text;
next.ocr_regions = data.regions || [];
next.ocr_time = data.time;
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status done';
thumbStatus.textContent = `Done (${data.time}s)`;
}
// Update doc list badge
updateDocOcrCount();
// If user already navigated to this page while we were pre-OCR'ing, show the result
if (state.activePageNum === next.num) {
renderBboxOverlay(next.ocr_regions);
showEditor(data.text, data.time, next.ocr_regions);
}
} catch (e) {
// Reset thumbnail status so user sees "Pending" instead of stuck "Pre-OCR..."
if (thumbStatus) {
thumbStatus.className = 'page-thumb-status';
thumbStatus.textContent = 'Pending';
}
} finally {
_preOcrRunning = false;
}
}
// --- Auto-save debounce ---
let _saveTimer = null;
function saveTextToServer(docId, pageNum, text) {
fetchT(`/api/pages/${docId}/${pageNum}/text`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
}, 10000).catch(e => {
console.warn('Auto-save failed:', e);
showToast('Auto-save failed', 'warn');
});
}
// --- Show editable textarea + preview ---
function showEditor(text, time, regions) {
resultBody.innerHTML = '';
const ta = document.createElement('textarea');
ta.className = 'result-editor' + (state.viewMode !== 'edit' ? ' hidden' : '');
ta.value = text || '';
ta.placeholder = 'No text recognized';
ta.addEventListener('input', () => {
const page = state.pages.find(p => p.num === state.activePageNum);
if (page) page.ocr_text = ta.value;
// Capture current context at input time, not when timer fires
const docId = state.activeDocId;
const pageNum = state.activePageNum;
clearTimeout(_saveTimer);
_saveTimer = setTimeout(() => {
if (docId && pageNum != null) {
saveTextToServer(docId, pageNum, ta.value);
}
}, 800);
});
resultBody.appendChild(ta);
const preview = document.createElement('div');
preview.className = 'result-preview' + (state.viewMode !== 'preview' ? ' hidden' : '');
// If we have regions, render as clickable blocks; otherwise fallback
if (regions && regions.length > 0) {
preview.innerHTML = renderRegionBlocks(regions, _searchQuery);
} else {
preview.innerHTML = renderPreview(text || '', _searchQuery);
}
resultBody.appendChild(preview);
resultToolbar.style.display = '';
updateViewToggleButtons();
if (time != null) {
resultTime.textContent = time + 's';
resultTime.style.display = '';
} else {
resultTime.style.display = 'none';
}
}
// --- Render region blocks for preview with bidirectional highlighting ---
function renderRegionBlocks(regions, searchQuery) {
return regions.map(r => {
const rendered = renderPreview(r.text || '', searchQuery);
return `<div class="region-block" data-idx="${r.idx}" onclick="highlightRegion(${r.idx})">${rendered}</div>`;
}).join('');
}
// --- Render bbox overlay on image ---
function renderBboxOverlay(regions) {
bboxOverlay.innerHTML = '';
if (!regions || regions.length === 0) return;
const img = previewImage;
if (!img.naturalWidth) return;
const scaleX = img.clientWidth / img.naturalWidth;
const scaleY = img.clientHeight / img.naturalHeight;
for (const r of regions) {
const [x1, y1, x2, y2] = r.bbox;
const div = document.createElement('div');
div.className = 'bbox-rect';
div.dataset.idx = r.idx;
div.style.left = (x1 * scaleX) + 'px';
div.style.top = (y1 * scaleY) + 'px';
div.style.width = ((x2 - x1) * scaleX) + 'px';
div.style.height = ((y2 - y1) * scaleY) + 'px';
div.addEventListener('click', () => highlightRegion(r.idx));
bboxOverlay.appendChild(div);
}
}
// --- Bidirectional highlighting ---
function highlightRegion(idx) {
// Clear previous highlights
document.querySelectorAll('.bbox-rect.active').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.region-block.active').forEach(el => el.classList.remove('active'));
// Highlight bbox on image
const bbox = bboxOverlay.querySelector(`.bbox-rect[data-idx="${idx}"]`);
if (bbox) bbox.classList.add('active');
// Highlight text block and scroll into view
const block = resultBody.querySelector(`.region-block[data-idx="${idx}"]`);
if (block) {
block.classList.add('active');
block.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// If in edit mode, switch to preview to show highlighting
if (state.viewMode === 'edit') {
state.viewMode = 'preview';
updateViewToggleButtons();
const ta = resultBody.querySelector('.result-editor');
const preview = resultBody.querySelector('.result-preview');
if (ta) ta.classList.add('hidden');
if (preview) {
preview.classList.remove('hidden');
// Re-highlight after mode switch
const b2 = preview.querySelector(`.region-block[data-idx="${idx}"]`);
if (b2) {
b2.classList.add('active');
b2.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
}
}
}
// Make highlightRegion available for inline onclick
window.highlightRegion = highlightRegion;
// --- Render markdown/HTML to preview HTML ---
function renderPreview(text, searchQuery) {
if (!text) return '<span style="color:rgba(45,45,45,0.3)">No text recognized</span>';
// Split by HTML block elements (tables) to preserve them
// Process non-HTML parts as simple markdown
const parts = text.split(/(<table[\s\S]*?<\/table>)/gi);
let html = '';
for (const part of parts) {
if (part.match(/^<table[\s\S]*<\/table>$/i)) {
// HTML table — pass through, then highlight text nodes
html += searchQuery ? highlightHtml(part, searchQuery) : part;
} else {
// Process as simple markdown
let rendered = markdownToHtml(part);
if (searchQuery) rendered = highlightHtml(rendered, searchQuery);
html += rendered;
}
}
return html;
}
function markdownToHtml(text) {
let html = '';
const lines = text.split('\n');
let inTable = false;
let tableRows = [];
function flushTable() {
if (tableRows.length === 0) return;
html += '<table>';
for (let i = 0; i < tableRows.length; i++) {
const cleanCells = tableRows[i].replace(/^\||\|$/g, '').split('|').map(c => c.trim());
// Skip separator row (---, :--:, etc.)
if (cleanCells.every(c => /^[-:]+$/.test(c))) continue;
const tag = i === 0 ? 'th' : 'td';
html += '<tr>' + cleanCells.map(c => `<${tag}>${escHtml(c)}</${tag}>`).join('') + '</tr>';
}
html += '</table>';
tableRows = [];
inTable = false;
}
for (const line of lines) {
const trimmed = line.trim();
// Detect markdown table rows (contain |)
if (trimmed.includes('|') && (trimmed.startsWith('|') || trimmed.match(/\w\s*\|/))) {
inTable = true;
tableRows.push(trimmed);
continue;
}
if (inTable) flushTable();
// Headers
if (trimmed.startsWith('### ')) {
html += `<h3>${escHtml(trimmed.slice(4))}</h3>`;
} else if (trimmed.startsWith('## ')) {
html += `<h2>${escHtml(trimmed.slice(3))}</h2>`;
} else if (trimmed.startsWith('# ')) {
html += `<h1>${escHtml(trimmed.slice(2))}</h1>`;
} else if (trimmed === '') {
html += '<br>';
} else {
// Inline: bold, italic
let s = escHtml(trimmed);
s = s.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
s = s.replace(/\*(.+?)\*/g, '<em>$1</em>');
html += `<p>${s}</p>`;
}
}
if (inTable) flushTable();
return html;
}
function escHtml(s) {
return (s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
// --- View toggle ---
viewToggle.addEventListener('click', (e) => {
const btn = e.target.closest('.view-btn');
if (!btn) return;
const mode = btn.dataset.mode;
if (mode === state.viewMode) return;
if (state.viewMode === 'edit') saveCurrentEditor();
state.viewMode = mode;
updateViewToggleButtons();
const ta = resultBody.querySelector('.result-editor');
const preview = resultBody.querySelector('.result-preview');
if (!ta || !preview) return;
if (mode === 'edit') {
ta.classList.remove('hidden');
preview.classList.add('hidden');
} else {
// Refresh preview from current state
const page = state.pages.find(p => p.num === state.activePageNum);
if (page && page.ocr_regions && page.ocr_regions.length > 0) {
preview.innerHTML = renderRegionBlocks(page.ocr_regions, _searchQuery);
} else {
preview.innerHTML = renderPreview(page ? page.ocr_text || '' : '', _searchQuery);
}
ta.classList.add('hidden');
preview.classList.remove('hidden');
}
});
function updateViewToggleButtons() {
viewToggle.querySelectorAll('.view-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.mode === state.viewMode);
});
}
// --- Paragraph reflow ---
// Terminal punctuation: line ends here intentionally
const TERMINAL_RE = /[。!?;…」』)】》!?\]);::]$/;
// Lines that should never be merged with the previous line
const BLOCK_START_RE = /^(#{1,3}\s|[-*+]\s|\d+[.、]\s*|[||<]|\s*$)/;
// Lines that should never be merged with the next line
const BLOCK_END_RE = /^(#{1,3}\s|[-*+]\s|\d+[.、]\s*|[||])/;
function reflowText(text) {
if (!text) return text;
const lines = text.split('\n');
const result = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
const trimmed = line.trim();
// Blank line → preserve as paragraph separator
if (trimmed === '') {
result.push('');
i++;
continue;
}
// Block-level element (heading, list, table, HTML) → keep as-is
if (BLOCK_START_RE.test(trimmed)) {
result.push(line);
i++;
continue;
}
// Start accumulating a paragraph
let para = trimmed;
i++;
while (i < lines.length) {
const next = lines[i].trim();
// Stop merging if: blank line, block element, or previous line had terminal punctuation
if (next === '' || BLOCK_START_RE.test(next) || TERMINAL_RE.test(para)) {
break;
}
// Decide joiner: space for Latin chars at boundary, nothing for CJK
const lastChar = para.slice(-1);
const firstChar = next.charAt(0);
const cjk = /[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]/;
const joiner = (cjk.test(lastChar) || cjk.test(firstChar)) ? '' : ' ';
para += joiner + next;
i++;
}
result.push(para);
}
return result.join('\n');
}
reflowBtn.addEventListener('click', () => {
saveCurrentEditor();
const page = state.pages.find(p => p.num === state.activePageNum);
if (!page || !page.ocr_text) return;
page.ocr_text = reflowText(page.ocr_text);
// Update editor/preview
const ta = resultBody.querySelector('.result-editor');
if (ta) ta.value = page.ocr_text;
const preview = resultBody.querySelector('.result-preview');
if (preview) preview.innerHTML = renderPreview(page.ocr_text);
// Save reflowed text to server
if (state.activeDocId) {
saveTextToServer(state.activeDocId, page.num, page.ocr_text);
}
reflowBtn.textContent = 'Done!';
setTimeout(() => reflowBtn.textContent = 'Reflow', 1200);
});
reflowAllBtn.addEventListener('click', () => {
saveCurrentEditor();
let count = 0;
for (const page of state.pages) {
if (page.ocr_text) {
page.ocr_text = reflowText(page.ocr_text);
count++;
// Save each reflowed page to server
if (state.activeDocId) {
saveTextToServer(state.activeDocId, page.num, page.ocr_text);
}
}
}
// Refresh current view
const page = state.pages.find(p => p.num === state.activePageNum);
if (page && page.ocr_text) {
const ta = resultBody.querySelector('.result-editor');
if (ta) ta.value = page.ocr_text;
const preview = resultBody.querySelector('.result-preview');
if (preview) preview.innerHTML = renderPreview(page.ocr_text);
}
reflowAllBtn.textContent = `${count} pages`;
setTimeout(() => reflowAllBtn.textContent = 'Reflow All', 1500);
});
// --- Copy current page ---
copyPageBtn.addEventListener('click', () => {
saveCurrentEditor();
const page = state.pages.find(p => p.num === state.activePageNum);
if (page && page.ocr_text) {
navigator.clipboard.writeText(page.ocr_text);
copyPageBtn.textContent = 'Copied!';
setTimeout(() => copyPageBtn.textContent = 'Copy', 1500);
}
});
// --- Copy all pages ---
copyAllBtn.addEventListener('click', () => {
saveCurrentEditor();
const md = buildMarkdown();
if (md) {
navigator.clipboard.writeText(md);
copyAllBtn.textContent = 'Copied!';
setTimeout(() => copyAllBtn.textContent = 'Copy All', 1500);
}
});
// --- Build Markdown content ---
function buildMarkdown() {
const pagesWithText = state.pages.filter(p => p.ocr_text);
if (pagesWithText.length === 0) return '';
const title = state.activeDocFilename || 'Document';
if (pagesWithText.length === 1 && state.pages.length === 1) {
return pagesWithText[0].ocr_text;
}
let md = `# ${title}\n\n`;
for (const p of state.pages) {
md += `## Page ${p.num}\n\n`;
md += (p.ocr_text || '*(not recognized)*') + '\n\n';
}
return md.trim();
}
// --- Download blob helper ---
function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// --- Export dropdown ---
exportBtn.addEventListener('click', (e) => {
e.stopPropagation();
exportMenu.classList.toggle('show');
});
document.addEventListener('click', () => exportMenu.classList.remove('show'));
exportMenu.addEventListener('click', async (e) => {
const item = e.target.closest('.export-item');
if (!item) return;
e.stopPropagation();
exportMenu.classList.remove('show');
saveCurrentEditor();
const fmt = item.dataset.fmt;
const baseName = (state.activeDocFilename || 'document').replace(/\.[^.]+$/, '');
if (fmt === 'docx') {
// Server-side DOCX generation
const pages = state.pages.map(p => ({ num: p.num, text: p.ocr_text || '' }));
if (pages.every(p => !p.text)) return;
// Extract title from first page's layout regions (label === "title")
const firstPage = state.pages[0];
const titleRegion = (firstPage && firstPage.ocr_regions || [])
.find(r => r.label === 'title');