-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2168 lines (1892 loc) · 76.4 KB
/
Copy pathscript.js
File metadata and controls
2168 lines (1892 loc) · 76.4 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
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
let pdfFiles = [];
let cleanResults = [];
let latestResult = null;
let currentPageResults = [];
let sensitivity = 2;
let totalCreditsUsed = 0;
let stopRequested = false;
let processing = false;
let metadataSources = [];
let metadataRows = [];
let googleAccessToken = '';
let googleTokenClient = null;
let activeGoogleClientId = '';
let driveFolderId = '';
const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
let automateCancelRequested = false;
let automateRunning = false;
let automateResults = [];
let automateCsvText = '';
let excelData = [];
let excelColumns = [];
let excelMappings = { title: '', code: '', year: '', dept: '' };
const MODELS = {
anthropic: [
{ id: 'claude-opus-4-5', label: 'Claude Opus 4.5' },
{ id: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' },
{ id: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5' },
],
openai: [
{ id: 'gpt-4o-mini', label: 'ChatGPT 4o mini' },
{ id: 'gpt-5-nano', label: 'ChatGPT 5 nano' },
{ id: 'gpt-5-mini', label: 'ChatGPT 5 mini' },
{ id: 'gpt-5.4-nano', label: 'ChatGPT 5.4 nano' },
{ id: 'gpt-5.4-mini', label: 'ChatGPT 5.4 mini' },
],
openrouter: [
{ id: 'openai/gpt-4o-mini', label: 'OpenRouter · GPT-4o mini' },
{ id: 'openai/gpt-5-mini', label: 'OpenRouter · GPT-5 mini' },
{ id: 'anthropic/claude-3.5-sonnet', label: 'OpenRouter · Claude 3.5 Sonnet' },
{ id: 'google/gemini-2.5-flash', label: 'OpenRouter · Gemini 2.5 Flash' },
],
groq: [
{ id: 'llama-3.3-70b-versatile', label: 'Groq · Llama 3.3 70B Versatile' },
{ id: 'llama-3.1-8b-instant', label: 'Groq · Llama 3.1 8B Instant' },
{ id: 'qwen/qwen3-32b', label: 'Groq · Qwen3 32B' },
],
gemini: [
{ id: 'gemini-3-flash', label: 'Gemini 3 Flash' },
{ id: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
{ id: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
],
local: [
{ id: 'local-vision-v2', label: 'Local Vision v2 (non-AI)' }
]
};
const PLACEHOLDERS = {
anthropic: 'sk-ant-...',
openai: 'sk-...',
openrouter: 'sk-or-...',
groq: 'gsk_...',
gemini: 'AIza...',
local: 'No key needed for local mode'
};
function switchView(view) {
const manual = document.getElementById('manual-view');
const automate = document.getElementById('automate-view');
const mBtn = document.getElementById('view-manual-btn');
const aBtn = document.getElementById('view-automate-btn');
const isAuto = view === 'automate';
manual.classList.toggle('active', !isAuto);
automate.classList.toggle('active', isAuto);
mBtn.classList.toggle('active', !isAuto);
aBtn.classList.toggle('active', isAuto);
if (isAuto) window.scrollTo({ top: 0, behavior: 'smooth' });
}
function onProviderChange() {
const p = document.getElementById('provider-select').value;
const ms = document.getElementById('model-select');
ms.innerHTML = '';
MODELS[p].forEach(m => {
const o = document.createElement('option');
o.value = m.id; o.textContent = m.label;
ms.appendChild(o);
});
document.getElementById('api-key').placeholder = PLACEHOLDERS[p];
document.getElementById('api-key').disabled = p === 'local';
}
function onAutoProviderChange(phase) {
const pSel = document.getElementById(`auto-${phase}-provider`);
const mSel = document.getElementById(`auto-${phase}-model`);
if (!pSel || !mSel) return;
const provider = pSel.value;
mSel.innerHTML = '';
if (provider === 'local') {
const opt = document.createElement('option');
opt.value = 'local-v1';
opt.textContent = (phase === 'clean') ? 'Local Detector' : 'Local NLP + OCR';
mSel.appendChild(opt);
return;
}
const models = MODELS[provider] || [];
models.forEach(m => {
const opt = document.createElement('option');
opt.value = m.id;
opt.textContent = m.label;
mSel.appendChild(opt);
});
}
function initAutomateProviderSelects() {
['clean', 'meta'].forEach(phase => {
const pSel = document.getElementById(`auto-${phase}-provider`);
if (!pSel) return;
pSel.innerHTML = '';
Object.keys(MODELS).forEach(key => {
const op = document.createElement('option');
op.value = key;
op.textContent = key.charAt(0).toUpperCase() + key.slice(1);
pSel.appendChild(op);
});
pSel.value = 'openai';
onAutoProviderChange(phase);
});
}
function setAutoStatus(text, state) {
const el = document.getElementById('auto-drive-status');
if (!el) return;
el.textContent = text || '';
el.className = 'drive-status' + (state ? ` ${state}` : '');
}
function autoLog(message, state) {
const box = document.getElementById('auto-log');
if (!box) return;
const line = document.createElement('div');
const stamp = new Date().toLocaleTimeString();
line.className = 'auto-log-line' + (state ? ` ${state}` : '');
line.textContent = `[${stamp}] ${message}`;
box.appendChild(line);
box.scrollTop = box.scrollHeight;
}
function resetAutoSteps() {
for (let i = 1; i <= 5; i++) {
const el = document.getElementById(`auto-step-${i}`);
if (el) el.classList.remove('active', 'done', 'fail');
}
}
function setAutoStepState(step, state) {
const el = document.getElementById(`auto-step-${step}`);
if (!el) return;
el.classList.remove('active', 'done', 'fail');
if (state) el.classList.add(state);
}
function getActiveGoogleClientId() {
const autoClient = document.getElementById('auto-google-client-id')?.value.trim();
if (autoClient) return autoClient;
const mainClient = document.getElementById('google-client-id')?.value.trim();
return mainClient;
}
function getActiveDriveFolderId() {
const autoDest = document.getElementById('auto-destination-folder-id')?.value.trim();
if (autoDest) return autoDest;
return document.getElementById('drive-folder-id')?.value.trim();
}
function toggleKeyVis() {
const inp = document.getElementById('api-key');
const btn = document.querySelector('.toggle-vis');
if (inp.type === 'password') { inp.type = 'text'; btn.textContent = 'Hide'; }
else { inp.type = 'password'; btn.textContent = 'Show'; }
}
function setSens(v) {
sensitivity = v;
document.querySelectorAll('.sens-btn').forEach(b => b.classList.toggle('active', +b.dataset.v === v));
}
function handleDrop(e) {
e.preventDefault();
document.getElementById('drop-zone').classList.remove('drag-over');
handleFile(e.dataTransfer.files);
}
function toPdfArray(input) {
if (!input) return [];
if (input instanceof FileList) return Array.from(input).filter(f => f.type === 'application/pdf' || /\.pdf$/i.test(f.name));
if (Array.isArray(input)) return input.filter(f => f && (f.type === 'application/pdf' || /\.pdf$/i.test(f.name)));
if (input instanceof File) return (input.type === 'application/pdf' || /\.pdf$/i.test(input.name)) ? [input] : [];
return [];
}
function handleFile(input) {
const picked = toPdfArray(input);
if (!picked.length) return showError('Please upload one or more PDF files.');
const keyed = new Map(pdfFiles.map(f => [f.name + '|' + f.size + '|' + f.lastModified, f]));
picked.forEach(f => keyed.set(f.name + '|' + f.size + '|' + f.lastModified, f));
pdfFiles = Array.from(keyed.values());
const totalBytes = pdfFiles.reduce((acc, f) => acc + f.size, 0);
document.getElementById('file-name-display').textContent = `${pdfFiles.length} PDF${pdfFiles.length > 1 ? 's' : ''} selected`;
document.getElementById('file-size-display').textContent = `${(totalBytes / 1024).toFixed(0)} KB total`;
const list = document.getElementById('file-list');
list.innerHTML = '';
pdfFiles.forEach(f => {
const li = document.createElement('li');
li.textContent = `• ${f.name}`;
list.appendChild(li);
});
document.getElementById('file-info').style.display = 'flex';
const first = pdfFiles[0];
document.getElementById('output-name').value = pdfFiles.length === 1
? first.name.replace(/\.pdf$/i, '') + '_cleaned'
: 'folio_batch_cleaned';
document.getElementById('run-btn').disabled = false;
hideError();
}
function resetAll() {
pdfFiles = [];
cleanResults = [];
latestResult = null;
currentPageResults = [];
totalCreditsUsed = 0;
['file-info','progress-section','result-section'].forEach(id => {
const el = document.getElementById(id);
if (el) el.style.display = 'none';
});
document.getElementById('page-chips').innerHTML = '';
document.getElementById('result-list').innerHTML = '';
document.getElementById('file-list').innerHTML = '';
document.getElementById('run-btn').disabled = true;
document.getElementById('file-input').value = '';
metadataSources = [];
metadataRows = [];
document.getElementById('metadata-file-input').value = '';
document.getElementById('metadata-stage').style.display = 'none';
document.getElementById('meta-papers').innerHTML = '';
document.getElementById('meta-table-body').innerHTML = '<tr><td colspan="7" class="meta-empty">Run extraction to populate this table.</td></tr>';
setMetaStatus('No papers selected yet.');
const ds = document.getElementById('drive-status');
if (ds) { ds.textContent = ''; ds.className = 'drive-status'; }
hideError();
}
function showError(m) { const e = document.getElementById('error-box'); e.textContent = m; e.style.display = 'block'; }
function hideError() { document.getElementById('error-box').style.display = 'none'; }
function setProgress(pct, label, count) {
document.getElementById('progress-fill').style.width = pct + '%';
if (label) document.getElementById('progress-label').textContent = label;
if (count !== undefined) document.getElementById('progress-count').textContent = count;
}
function addChip(i) {
const el = document.createElement('span');
el.className = 'chip pending';
el.textContent = i + 1;
el.id = 'chip-' + i;
document.getElementById('page-chips').appendChild(el);
}
function updateChip(i, status) {
const el = document.getElementById('chip-' + i);
if (!el) return;
el.className = 'chip ' + status;
if (status === 'empty') el.textContent = '✕ ' + (i + 1);
else if (status === 'content') el.textContent = '✓ ' + (i + 1);
else el.textContent = i + 1;
}
function sanitizeBaseName(name) {
return name.replace(/\.pdf$/i, '').replace(/[^a-zA-Z0-9-_]+/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
}
function getOutputName(file, fileIndex) {
const base = document.getElementById('output-name').value.trim() || 'cleaned-document';
if (pdfFiles.length === 1) return `${base}.pdf`;
const src = sanitizeBaseName(file.name) || `file_${fileIndex + 1}`;
return `${base}_${String(fileIndex + 1).padStart(2, '0')}_${src}.pdf`;
}
function buildResultCard(result, idx) {
const wrap = document.createElement('div');
wrap.className = 'result-item';
const head = document.createElement('div');
head.className = 'result-item-head';
const nm = document.createElement('div');
nm.className = 'result-item-name';
nm.textContent = result.outputName;
const meta = document.createElement('div');
meta.className = 'result-item-meta';
meta.textContent = `${result.kept}/${result.totalPages} kept · ${result.removed} removed · ${result.creditsUsed} credits`;
head.appendChild(nm);
head.appendChild(meta);
wrap.appendChild(head);
const actions = document.createElement('div');
actions.className = 'result-actions';
const dBtn = document.createElement('button');
dBtn.className = 'btn-mini';
dBtn.type = 'button';
dBtn.textContent = 'Download';
dBtn.addEventListener('click', () => downloadResultByIndex(idx));
const uBtn = document.createElement('button');
uBtn.className = 'btn-mini';
uBtn.type = 'button';
uBtn.textContent = 'Upload to Drive';
uBtn.addEventListener('click', () => uploadResultByIndex(idx));
actions.appendChild(dBtn);
actions.appendChild(uBtn);
wrap.appendChild(actions);
return wrap;
}
function refreshResultCards() {
const list = document.getElementById('result-list');
list.innerHTML = '';
cleanResults.forEach((r, idx) => {
const card = buildResultCard(r, idx);
card.style.animationDelay = `${Math.min(idx * 55, 380)}ms`;
list.appendChild(card);
});
}
function updateSummaryStats() {
const total = cleanResults.reduce((a, r) => a + r.totalPages, 0);
const removed = cleanResults.reduce((a, r) => a + r.removed, 0);
const kept = cleanResults.reduce((a, r) => a + r.kept, 0);
document.getElementById('stat-total').textContent = total;
document.getElementById('stat-removed').textContent = removed;
document.getElementById('stat-kept').textContent = kept;
document.getElementById('stat-credits').textContent = totalCreditsUsed;
}
function setMetaStatus(text, state) {
const el = document.getElementById('meta-status');
if (!el) return;
el.textContent = text;
el.className = 'meta-status' + (state ? ` ${state}` : '');
}
function renderMetadataSourceList() {
const holder = document.getElementById('meta-papers');
if (!holder) return;
holder.innerHTML = '';
if (!metadataSources.length) {
holder.innerHTML = '<div class="meta-paper-item">No files selected.</div>';
return;
}
metadataSources.forEach((s, idx) => {
const item = document.createElement('div');
item.className = 'meta-paper-item';
item.textContent = `${idx + 1}. ${s.name}`;
holder.appendChild(item);
});
}
function openMetadataStage(useCleaned) {
const stage = document.getElementById('metadata-stage');
if (!stage) return;
stage.style.display = 'block';
stage.classList.remove('reveal');
void stage.offsetWidth;
stage.classList.add('reveal');
if (useCleaned) {
if (!cleanResults.length) {
setMetaStatus('No cleaned PDFs available yet. Run step 03 first.', 'err');
stage.scrollIntoView({ behavior: 'smooth', block: 'start' });
return;
}
metadataSources = cleanResults.map(r => ({ name: r.outputName, bytes: r.cleanPdfBytes }));
renderMetadataSourceList();
setMetaStatus(`${metadataSources.length} cleaned PDF(s) ready for extraction.`, 'ok');
}
stage.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function handleMetadataUpload(files) {
const picked = toPdfArray(files);
if (!picked.length) {
setMetaStatus('Upload one or more PDF files.', 'err');
return;
}
metadataSources = picked.map(f => ({ name: f.name, file: f }));
const stage = document.getElementById('metadata-stage');
if (!stage) return;
stage.style.display = 'block';
stage.classList.remove('reveal');
void stage.offsetWidth;
stage.classList.add('reveal');
renderMetadataSourceList();
setMetaStatus(`${metadataSources.length} uploaded PDF(s) ready for extraction.`, 'ok');
}
async function getSourceBytes(source) {
if (source.bytes) {
if (source.bytes instanceof Uint8Array) return source.bytes;
if (source.bytes instanceof ArrayBuffer) return new Uint8Array(source.bytes);
}
if (source.file) {
const ab = await source.file.arrayBuffer();
return new Uint8Array(ab);
}
throw new Error('Invalid metadata source bytes.');
}
async function renderPdfPageToBase64(doc, pageNumber, scale = 1.6, quality = 0.8, enhance = false) {
const page = await doc.getPage(pageNumber);
const viewport = page.getViewport({ scale });
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
canvas.width = viewport.width;
canvas.height = viewport.height;
await page.render({ canvasContext: ctx, viewport }).promise;
if (enhance) {
// Advanced Image Enhancement for OCR/Vision
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
// 1. Grayscale & Contrast Boost
for (let i = 0; i < data.length; i += 4) {
const avg = (data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114);
// Histogram stretching / Contrast boost
// We map [30, 220] to [0, 255] to remove gray haze and faint noise
let v = (avg - 30) * (255 / 190);
v = Math.max(0, Math.min(255, v));
data[i] = v; // R
data[i + 1] = v; // G
data[i + 2] = v; // B
}
ctx.putImageData(imageData, 0, 0);
// 2. Subtle sharpening using a convolution kernel (Laplacian)
// This helps the OCR engine see edges more clearly
const weight = 0.15;
ctx.globalAlpha = weight;
ctx.drawImage(canvas, -1, 0);
ctx.drawImage(canvas, 1, 0);
ctx.drawImage(canvas, 0, -1);
ctx.drawImage(canvas, 0, 1);
ctx.globalAlpha = 1.0;
}
return canvas.toDataURL('image/jpeg', quality).split(',')[1];
}
function parseFirstJsonObject(text) {
const cleaned = (text || '').trim().replace(/^```json/i, '').replace(/^```/, '').replace(/```$/, '').trim();
const start = cleaned.indexOf('{');
const end = cleaned.lastIndexOf('}');
if (start === -1 || end === -1 || end <= start) throw new Error('No JSON object found in model response.');
return JSON.parse(cleaned.slice(start, end + 1));
}
function normalizeMetadata(obj, sourceFile) {
const rawDepartments = Array.isArray(obj.departments)
? obj.departments
: String(obj.departments || '').split(/[;,|]/g);
const departments = rawDepartments
.map(v => String(v).trim())
.filter(Boolean)
.join(', ');
return {
school: String(obj.school || '').trim(),
departments,
semester: String(obj.semester || '').trim(),
subjectCode: String(obj.subject_code || obj.subjectCode || '').trim(),
subject: String(obj.subject || '').trim(),
month: String(obj.month || '').trim(),
year: String(obj.year || '').trim(),
isFirstPage: Boolean(obj.is_first_page),
confidence: Number(obj.confidence || 0),
sourceFile
};
}
async function extractQuestionPaperFields(b64, provider, model, apiKey) {
const prompt = `Identify if this image is the FIRST PAGE of a question paper/exam paper.
If it is, extract:
1. School/University Name (Full)
2. Departments/Faculty (Array of strings)
3. Semester (e.g., "1", "VI", "Autumn")
4. Subject Code (e.g., "CS101", "ME-202")
5. Subject Title (Full Name)
6. Month of Exam
7. Year of Exam (4 digits)
Return ONLY a JSON object with these keys: is_first_page (boolean), school, departments (array), semester, subject_code, subject, month, year, confidence (0-1).
If it is NOT a first page (e.g., a middle page of an exam), set is_first_page to false and return empty strings for the rest.`;
async function openAiCompatibleMeta(endpoint, authHeader, tokenField, maxTokens) {
const body = {
model,
messages: [{ role: 'user', content: [
{ type: 'image_url', image_url: { url: 'data:image/jpeg;base64,' + b64, detail: 'high' } },
{ type: 'text', text: prompt }
] }]
};
body[tokenField] = maxTokens;
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...authHeader
},
body: JSON.stringify(body)
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e.error?.message || `Metadata API error ${res.status}`);
}
const d = await res.json();
return parseFirstJsonObject(d.choices?.[0]?.message?.content || '');
}
if (provider === 'anthropic') {
const res = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
body: JSON.stringify({
model,
max_tokens: 220,
messages: [{ role: 'user', content: [
{ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: b64 } },
{ type: 'text', text: prompt }
] }]
})
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error?.message || 'Anthropic metadata error ' + res.status); }
const d = await res.json();
return parseFirstJsonObject(d.content?.[0]?.text || '');
}
if (provider === 'openai') {
return openAiCompatibleMeta(
'https://api.openai.com/v1/chat/completions',
{ 'Authorization': 'Bearer ' + apiKey },
'max_completion_tokens',
220
);
}
if (provider === 'openrouter') {
return openAiCompatibleMeta(
'https://openrouter.ai/api/v1/chat/completions',
{
'Authorization': 'Bearer ' + apiKey,
'HTTP-Referer': window.location.origin || 'http://localhost',
'X-Title': 'Folio PDF Cleaner'
},
'max_tokens',
220
);
}
if (provider === 'groq') {
return openAiCompatibleMeta(
'https://api.groq.com/openai/v1/chat/completions',
{ 'Authorization': 'Bearer ' + apiKey },
'max_tokens',
220
);
}
if (provider === 'gemini') {
const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [
{ inline_data: { mime_type: 'image/jpeg', data: b64 } },
{ text: prompt }
] }],
generationConfig: { maxOutputTokens: 220 }
})
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error?.message || 'Gemini metadata error ' + res.status); }
const d = await res.json();
return parseFirstJsonObject(d.candidates?.[0]?.content?.parts?.[0]?.text || '');
}
throw new Error('Unknown provider for metadata extraction.');
}
function renderMetadataRows() {
const body = document.getElementById('meta-table-body');
if (!body) return;
body.innerHTML = '';
if (!metadataRows.length) {
body.innerHTML = '<tr><td colspan="7" class="meta-empty">No rows extracted yet.</td></tr>';
return;
}
metadataRows.forEach((r, idx) => {
const tr = document.createElement('tr');
tr.style.animationDelay = `${Math.min(idx * 45, 320)}ms`;
tr.innerHTML = `
<td>${r.school || '—'}</td>
<td>${r.departments || '—'}</td>
<td>${r.subjectCode || '—'}</td>
<td>${r.subject || '—'}</td>
<td>${r.month || '—'}</td>
<td>${r.year || '—'}</td>
<td>${r.sourceFile || '—'}</td>
`;
body.appendChild(tr);
});
}
async function extractMetadataTable() {
const provider = document.getElementById('provider-select').value;
const model = document.getElementById('model-select').value;
const apiKey = document.getElementById('api-key').value.trim();
if (!metadataSources.length) return setMetaStatus('Select cleaned or uploaded PDFs first.', 'err');
if (provider !== 'local' && !apiKey) return setMetaStatus('Enter API key in step 02 before extraction.', 'err');
metadataRows = [];
setMetaStatus(`Scanning all pages to detect question-paper starts across ${metadataSources.length} file(s)…`);
for (let i = 0; i < metadataSources.length; i++) {
const src = metadataSources[i];
setMetaStatus(`Scanning ${i + 1}/${metadataSources.length}: ${src.name}`);
const bytes = await getSourceBytes(src);
const doc = await pdfjsLib.getDocument({ data: bytes }).promise;
for (let p = 1; p <= doc.numPages; p++) {
setMetaStatus(`Scanning ${src.name} · page ${p}/${doc.numPages}`);
let raw;
if (provider === 'local') {
const page = await doc.getPage(p);
raw = await extractQuestionPaperFieldsLocalFromPage(page, doc);
} else {
const b64 = await renderPdfPageToBase64(doc, p, 1.6, 0.8);
raw = await extractQuestionPaperFields(b64, provider, model, apiKey);
}
const normalized = normalizeMetadata(raw, `${src.name} (p.${p})`);
if (normalized.isFirstPage && normalized.confidence >= 0.5) {
metadataRows.push(normalized);
}
}
}
renderMetadataRows();
setMetaStatus(`Complete. Found ${metadataRows.length} detected first-page record(s).`, 'ok');
}
function downloadMetadataCsv() {
if (!metadataRows.length) return setMetaStatus('No metadata rows to export yet.', 'err');
const header = 'school,department,subject_code,subject,month,year,source_file';
const rows = metadataRows.map(r => [
r.school,
r.departments,
r.subjectCode,
r.subject,
r.month,
r.year,
r.sourceFile
].map(v => `"${String(v || '').replace(/"/g, '""')}"`).join(','));
const csv = [header, ...rows].join('\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'question_paper_metadata.csv';
a.click();
URL.revokeObjectURL(a.href);
}
async function pageToBase64(pdfDoc, i) {
const page = await pdfDoc.getPage(i + 1);
const vp = page.getViewport({ scale: 1.5 });
const canvas = document.createElement('canvas');
canvas.width = vp.width; canvas.height = vp.height;
await page.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise;
return canvas.toDataURL('image/jpeg', 0.75).split(',')[1];
}
async function getPageTextLines(page) {
const textContent = await page.getTextContent();
const grouped = new Map();
textContent.items.forEach(it => {
const t = String(it.str || '').replace(/\s+/g, ' ').trim();
if (!t) return;
const y = Math.round((it.transform?.[5] || 0) / 3);
if (!grouped.has(y)) grouped.set(y, []);
grouped.get(y).push(t);
});
return Array.from(grouped.keys())
.sort((a, b) => b - a)
.map(y => grouped.get(y).join(' ').replace(/\s+/g, ' ').trim())
.filter(Boolean);
}
async function extractQuestionPaperFieldsLocalFromPage(page, pdfDoc) {
let lines = await getPageTextLines(page);
let text = lines.join(' \n ');
// OCR Fallback if text layer is sparse
// We use "Super-Resolution" (3.5x) and Enhancement for detection to find even faint text
if (text.trim().length < 50 && pdfDoc) {
const pageNum = page.pageNumber;
const b64 = await renderPdfPageToBase64(pdfDoc, pageNum, 3.5, 0.95, true);
const ocrResult = await Tesseract.recognize('data:image/jpeg;base64,' + b64, 'eng');
text = ocrResult.data.text;
lines = text.split('\n');
if (metaProvider === 'local') {
autoLog(`Enhanced Super-OCR performed on page ${pageNum} for detection.`, 'ok');
}
}
return extractPaperMetadataLocal(text, lines);
}
function extractPaperMetadataLocal(text, lines) {
if (!text) return { is_first_page: false, confidence: 0 };
const doc = nlp(text);
// Extract Schools/Universities using NLP
let school = doc.organizations().filter(o => /university|college|school|institute|academy|polytechnic/i.test(o.text())).first().text();
if (!school) {
school = lines.find(l => /(university|college|institute|school|polytechnic|academy)/i.test(l)) || (lines[0] || '');
}
const deptLines = lines
.filter(l => /(department|dept\.?|programme|program|faculty|school of)/i.test(l))
.slice(0, 3)
.map(l => l.replace(/^(department|dept\.?|faculty|school of)\s*(of)?\s*/i, '').trim())
.filter(Boolean);
const codeMatch = text.match(/\b[A-Z]{2,}[\s\/-]?[A-Z0-9]{2,}[\s\/-]?\d{1,4}[A-Z0-9]*\b/);
let subjectLine = lines.find(l => /(subject|course|paper)\s*[:\-]/i.test(l)) || '';
if (!subjectLine) {
// Try to find a line that looks like a title (Title Case, no numbers)
const candidates = lines.filter(l => l.length > 10 && l.length < 60 && !/\d/.test(l));
subjectLine = candidates[0] || '';
}
const monthMatch = text.match(/\b(January|February|March|April|May|June|July|August|September|October|November|December)\b/i);
const yearMatch = text.match(/\b(19|20)\d{2}\b/);
let score = 0;
if (school && school.length > 5) score += 1;
if (deptLines.length) score += 1;
if (codeMatch) score += 1;
if (subjectLine) score += 1;
if (monthMatch) score += 1;
if (yearMatch) score += 1;
if (/\b(time|max\s*marks|duration|instructions?)\b/i.test(text)) score += 1;
const semesterMatch = text.match(/Sem(?:ester)?\s*[:\-]?\s*([I|V|X|0-9]+|[A-Za-z]+)/i);
const semester = semesterMatch ? semesterMatch[1] : '';
return {
is_first_page: score >= 3,
school: school,
departments: deptLines,
subject_code: codeMatch ? codeMatch[0] : '',
subject: subjectLine.replace(/^(subject|course|paper)\s*[:\-]?\s*/i, '').trim(),
month: monthMatch ? monthMatch[0] : '',
year: yearMatch ? yearMatch[0] : '',
semester: semester,
confidence: Math.min(1, score / 7)
};
}
async function classifyPageLocal(pdfDoc, pageIndex) {
const page = await pdfDoc.getPage(pageIndex + 1);
const textContent = await page.getTextContent();
const textChars = textContent.items
.map(it => String(it.str || ''))
.join('')
.replace(/\s+/g, '')
.length;
const viewport = page.getViewport({ scale: 1.5 });
const canvas = document.createElement('canvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
await page.render({ canvasContext: ctx, viewport }).promise;
const { data, width, height } = ctx.getImageData(0, 0, canvas.width, canvas.height);
const marginX = Math.floor(width * 0.03);
const marginY = Math.floor(height * 0.03);
const x0 = Math.max(0, marginX);
const y0 = Math.max(0, marginY);
const x1 = Math.max(x0 + 1, width - marginX);
const y1 = Math.max(y0 + 1, height - marginY);
let sum = 0;
let sumSq = 0;
let pix = 0;
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = (y * width + x) * 4;
const g = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
sum += g;
sumSq += g * g;
pix++;
}
}
const mean = sum / Math.max(1, pix);
const variance = Math.max(0, sumSq / Math.max(1, pix) - mean * mean);
const stdDev = Math.sqrt(variance);
const threshold = Math.min(235, Math.max(185, mean - stdDev * 0.65));
let darkCount = 0;
let minX = x1;
let minY = y1;
let maxX = x0;
let maxY = y0;
const dw = Math.max(1, Math.floor((x1 - x0) / 2));
const dh = Math.max(1, Math.floor((y1 - y0) / 2));
const grid = new Uint8Array(dw * dh);
for (let gy = 0; gy < dh; gy++) {
for (let gx = 0; gx < dw; gx++) {
const sx = x0 + gx * 2;
const sy = y0 + gy * 2;
const i = (sy * width + sx) * 4;
const g = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
if (g < threshold - 8) {
grid[gy * dw + gx] = 1;
}
}
}
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const i = (y * width + x) * 4;
const g = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
if (g < threshold) {
darkCount++;
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
}
}
const visited = new Uint8Array(grid.length);
let largestComp = 0;
let significantInk = 0;
const minComp = 26;
const stack = [];
for (let idx = 0; idx < grid.length; idx++) {
if (!grid[idx] || visited[idx]) continue;
visited[idx] = 1;
stack.push(idx);
let comp = 0;
while (stack.length) {
const cur = stack.pop();
comp++;
const x = cur % dw;
const y = Math.floor(cur / dw);
const nbs = [
[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1],
[x - 1, y - 1], [x + 1, y - 1], [x - 1, y + 1], [x + 1, y + 1]
];
for (let n = 0; n < nbs.length; n++) {
const nx = nbs[n][0];
const ny = nbs[n][1];
if (nx < 0 || ny < 0 || nx >= dw || ny >= dh) continue;
const ni = ny * dw + nx;
if (!grid[ni] || visited[ni]) continue;
visited[ni] = 1;
stack.push(ni);
}
}
if (comp > largestComp) largestComp = comp;
if (comp >= minComp) significantInk += comp;
}
const roiArea = Math.max(1, (x1 - x0) * (y1 - y0));
const inkRatio = darkCount / roiArea;
const bboxArea = darkCount ? (maxX - minX + 1) * (maxY - minY + 1) : 0;
const bboxRatio = bboxArea / roiArea;
if (sensitivity === 1) {
if (textChars >= 1) return 'content';
if (significantInk > 210 && inkRatio > 0.0012) return 'content';
if (largestComp > 150 && bboxRatio > 0.009) return 'content';
return 'empty';
}
if (sensitivity === 2) {
if (textChars >= 5) return 'content';
if (significantInk > 320 && inkRatio > 0.0019 && bboxRatio > 0.013) return 'content';
if (largestComp > 280 && stdDev > 8) return 'content';
return 'empty';
}
if (textChars >= 28) return 'content';
if (significantInk > 760 && inkRatio > 0.0045 && bboxRatio > 0.03) return 'content';
if (largestComp > 680 && stdDev > 13) return 'content';
return 'empty';
}
const PROMPTS = {
1: "Analyze this scanned document page. Reply ONLY with the single word 'empty' or 'content'. Reply 'empty' ONLY if the page is completely blank — pure white or near-white with at most faint scanner dust or grain, zero readable text, drawings, or marks. Reply 'content' for everything else.",
2: "Analyze this scanned document page. Reply ONLY with the single word 'empty' or 'content'. Reply 'empty' if the page has no meaningful content — only scanner noise, dust, smudges, shadow at edges, or faint texture with no readable text, diagrams, or actual marks. Reply 'content' if there is any readable text, drawings, tables, stamps, or meaningful marks.",
3: "Analyze this scanned document page. Reply ONLY with the single word 'empty' or 'content'. Reply 'empty' if the page has no significant content — includes pages with only a lone page number, an isolated header or footer line, faint watermarks, scanner noise, or sparse marks conveying no real information. Reply 'content' only if the page contains substantial readable content: paragraphs, data, diagrams, or important annotations."
};
async function classifyPage(b64, provider, model, apiKey) {
const prompt = PROMPTS[sensitivity];
async function openAiCompatibleRequest(endpoint, authHeader, tokenField, maxTokens) {
const body = {
model,
messages: [{ role: 'user', content: [
{ type: 'image_url', image_url: { url: 'data:image/jpeg;base64,' + b64, detail: 'low' } },
{ type: 'text', text: prompt }
] }]
};
body[tokenField] = maxTokens;
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...authHeader
},
body: JSON.stringify(body)
});
if (!res.ok) {
const e = await res.json().catch(() => ({}));
throw new Error(e.error?.message || `API error ${res.status}`);
}
const d = await res.json();
return (d.choices?.[0]?.message?.content || '').toLowerCase().includes('empty') ? 'empty' : 'content';
}
if (provider === 'anthropic') {
const res = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
body: JSON.stringify({ model, max_tokens: 10, messages: [{ role: 'user', content: [
{ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: b64 } },
{ type: 'text', text: prompt }
]}]})
});
if (!res.ok) { const e = await res.json().catch(()=>({})); throw new Error(e.error?.message || 'Anthropic error ' + res.status); }
const d = await res.json();
return (d.content?.[0]?.text || '').toLowerCase().includes('empty') ? 'empty' : 'content';
}
if (provider === 'openai') {
return openAiCompatibleRequest(
'https://api.openai.com/v1/chat/completions',
{ 'Authorization': 'Bearer ' + apiKey },
'max_completion_tokens',
10