/** * Handwritten Marathi Hospital Form Extraction * Frontend Application Logic */ // ════════════════════════════════════════════════════════════ // State // ════════════════════════════════════════════════════════════ const AppState = { selectedFile: null, lastResult: null, isProcessing: false, testResults: [] }; // ════════════════════════════════════════════════════════════ // DOM References // ════════════════════════════════════════════════════════════ const DOM = {}; function cacheDom() { DOM.uploadZone = document.getElementById('upload-zone'); DOM.fileInput = document.getElementById('file-input'); DOM.filePreview = document.getElementById('file-preview'); DOM.fileName = document.getElementById('file-name'); DOM.fileSize = document.getElementById('file-size'); DOM.removeFileBtn = document.getElementById('remove-file'); DOM.languageSelect = document.getElementById('language-select'); DOM.preprocessToggle = document.getElementById('preprocess-toggle'); DOM.methodSelect = document.getElementById('method-select'); DOM.extractBtn = document.getElementById('extract-btn'); DOM.resetBtn = document.getElementById('reset-btn'); DOM.imagePreviewContainer = document.getElementById('image-preview-container'); DOM.originalImage = document.getElementById('original-image'); DOM.processedImage = document.getElementById('processed-image'); DOM.processedPanel = document.getElementById('processed-panel'); DOM.resultsContainer = document.getElementById('results-container'); DOM.errorDisplay = document.getElementById('error-display'); DOM.errorMessage = document.getElementById('error-message'); DOM.errorDetails = document.getElementById('error-details'); DOM.loadingOverlay = document.getElementById('loading-overlay'); DOM.loadingStep = document.getElementById('loading-step'); DOM.statTime = document.getElementById('stat-time'); DOM.statLang = document.getElementById('stat-lang'); DOM.statFields = document.getElementById('stat-fields'); DOM.statRepairs = document.getElementById('stat-repairs'); DOM.statMissing = document.getElementById('stat-missing'); DOM.statMethod = document.getElementById('stat-method'); DOM.tabRepairsCount = document.getElementById('tab-repairs-count'); DOM.repairsContainer = document.getElementById('repairs-container'); DOM.jsonViewer = document.getElementById('json-viewer'); DOM.transcriptionBox = document.getElementById('transcription-box'); DOM.fieldsGrid = document.getElementById('fields-grid'); DOM.downloadJsonBtn = document.getElementById('download-json'); DOM.downloadTextBtn = document.getElementById('download-text'); DOM.compareTextarea = document.getElementById('compare-textarea'); DOM.compareBtn = document.getElementById('compare-btn'); DOM.compareResults = document.getElementById('compare-results'); DOM.historyBody = document.getElementById('history-body'); DOM.preprocessInfo = document.getElementById('preprocess-info'); DOM.modelSelect = document.getElementById('model-select'); DOM.geminiModelGroup = document.getElementById('gemini-model-group'); DOM.geminiModelSelect = document.getElementById('gemini-model-select'); DOM.geminiCustomInput = document.getElementById('gemini-custom-input'); DOM.statModel = document.getElementById('stat-model'); DOM.tabBtnModelCompare = document.getElementById('tab-btn-model-compare'); DOM.modelMatchPct = document.getElementById('model-match-pct'); DOM.modelCompareContainer = document.getElementById('model-compare-container'); } // ════════════════════════════════════════════════════════════ // Init // ════════════════════════════════════════════════════════════ document.addEventListener('DOMContentLoaded', () => { cacheDom(); bindEvents(); loadTestHistory(); checkModelAvailability(); }); function bindEvents() { // Upload DOM.fileInput.addEventListener('change', handleFileSelect); DOM.removeFileBtn.addEventListener('click', clearFile); // Model controls if (DOM.modelSelect) { DOM.modelSelect.addEventListener('change', updateModelControls); updateModelControls(); } if (DOM.geminiModelSelect) { DOM.geminiModelSelect.addEventListener('change', () => { if (DOM.geminiCustomInput) { DOM.geminiCustomInput.style.display = DOM.geminiModelSelect.value === 'custom' ? 'block' : 'none'; } }); } // Drag & drop DOM.uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); DOM.uploadZone.classList.add('drag-over'); }); DOM.uploadZone.addEventListener('dragleave', () => { DOM.uploadZone.classList.remove('drag-over'); }); DOM.uploadZone.addEventListener('drop', (e) => { e.preventDefault(); DOM.uploadZone.classList.remove('drag-over'); if (e.dataTransfer.files.length > 0) { DOM.fileInput.files = e.dataTransfer.files; handleFileSelect({ target: DOM.fileInput }); } }); // Actions DOM.extractBtn.addEventListener('click', handleExtract); DOM.resetBtn.addEventListener('click', handleReset); DOM.downloadJsonBtn.addEventListener('click', downloadJson); DOM.downloadTextBtn.addEventListener('click', downloadText); DOM.compareBtn.addEventListener('click', handleCompare); // Tabs document.querySelectorAll('.tab').forEach(tab => { tab.addEventListener('click', () => switchTab(tab.dataset.tab)); }); } async function checkModelAvailability() { try { const resp = await fetch('/api/models'); if (!resp.ok) return; const data = await resp.json(); const configured = data.configured || {}; const geminiOpt = DOM.modelSelect?.querySelector('option[value="gemini"]'); const sarvamOpt = DOM.modelSelect?.querySelector('option[value="sarvam"]'); const compareOpt = DOM.modelSelect?.querySelector('option[value="compare"]'); if (geminiOpt) { if (!configured.gemini) { geminiOpt.textContent = '🔷 Google Gemini (Requires GEMINI_API_KEY in .env)'; } else { geminiOpt.textContent = '🔷 Google Gemini Flash (Vision) • Ready'; } } if (sarvamOpt) { if (!configured.sarvam) { sarvamOpt.textContent = '🔶 DocVision AI (Requires SARVAM_API_KEY in .env)'; } else { sarvamOpt.textContent = '🔶 DocVision AI (Sarvam Vision) • Ready'; } } if (compareOpt) { if (configured.gemini && configured.sarvam) { compareOpt.textContent = '⚖️ Run Both Models & Compare (Benchmark Ready)'; } else { compareOpt.textContent = '⚖️ Run Both Models & Compare (Benchmark)'; } } } catch (e) { console.warn('Could not check model status:', e); } } function updateModelControls() { if (!DOM.modelSelect || !DOM.geminiModelGroup) return; const val = DOM.modelSelect.value; DOM.geminiModelGroup.style.display = (val === 'gemini' || val === 'compare') ? 'flex' : 'none'; } // ════════════════════════════════════════════════════════════ // File Handling // ════════════════════════════════════════════════════════════ function handleFileSelect(e) { const file = e.target.files[0]; if (!file) return; const allowed = ['jpg', 'jpeg', 'png', 'pdf', 'bmp', 'tiff', 'tif']; const ext = file.name.split('.').pop().toLowerCase(); if (!allowed.includes(ext)) { showError('Unsupported file type', `Allowed formats: ${allowed.join(', ').toUpperCase()}`); return; } AppState.selectedFile = file; DOM.fileName.textContent = file.name; DOM.fileSize.textContent = formatFileSize(file.size); DOM.filePreview.classList.add('visible'); DOM.extractBtn.disabled = false; // Show image preview for image files if (file.type.startsWith('image/')) { const reader = new FileReader(); reader.onload = (ev) => { DOM.originalImage.src = ev.target.result; DOM.imagePreviewContainer.classList.add('visible', 'single'); DOM.processedPanel.style.display = 'none'; }; reader.readAsDataURL(file); } else { DOM.imagePreviewContainer.classList.remove('visible'); } hideError(); } function clearFile() { AppState.selectedFile = null; DOM.fileInput.value = ''; DOM.filePreview.classList.remove('visible'); DOM.extractBtn.disabled = true; DOM.imagePreviewContainer.classList.remove('visible'); } // ════════════════════════════════════════════════════════════ // Extraction // ════════════════════════════════════════════════════════════ async function handleExtract() { if (!AppState.selectedFile || AppState.isProcessing) return; AppState.isProcessing = true; DOM.extractBtn.classList.add('loading'); DOM.extractBtn.disabled = true; showLoading(); hideError(); DOM.resultsContainer.classList.remove('visible'); const formData = new FormData(); formData.append('file', AppState.selectedFile); formData.append('preprocess', DOM.preprocessToggle.checked ? 'true' : 'false'); formData.append('method', DOM.methodSelect.value); formData.append('language', DOM.languageSelect ? DOM.languageSelect.value : 'auto'); // Multi-model selection const selectedModel = DOM.modelSelect ? DOM.modelSelect.value : 'auto'; formData.append('model', selectedModel); let geminiModelName = 'gemini-2.0-flash'; if (DOM.geminiModelSelect) { geminiModelName = DOM.geminiModelSelect.value === 'custom' && DOM.geminiCustomInput ? DOM.geminiCustomInput.value.trim() : DOM.geminiModelSelect.value; } if (geminiModelName) { formData.append('gemini_model', geminiModelName); } updateLoadingStep('Uploading document...'); try { const startTime = Date.now(); if (selectedModel === 'compare') { updateLoadingStep('Benchmarking: Running both Gemini Flash & Sarvam Vision concurrently...'); } else if (selectedModel === 'gemini') { updateLoadingStep(`Analyzing with Google Gemini Flash (${geminiModelName})...`); } else { updateLoadingStep('Analyzing with DocVision AI...'); } const response = await fetch('/api/extract', { method: 'POST', body: formData }); updateLoadingStep('Processing response & applying auto-repairs...'); const data = await response.json(); if (!response.ok || data.error) { throw { message: data.error || `Server returned ${response.status}`, details: data.api_response || data.status_code || '' }; } AppState.lastResult = data; renderResults(data); } catch (err) { showError( err.message || 'Extraction failed', err.details || 'Please check your API key configuration in .env and try again.' ); } finally { AppState.isProcessing = false; DOM.extractBtn.classList.remove('loading'); DOM.extractBtn.disabled = false; hideLoading(); } } // ════════════════════════════════════════════════════════════ // Render Results // ════════════════════════════════════════════════════════════ function renderResults(data) { AppState.lastResult = data; const extraction = data.extraction || {}; const meta = extraction._meta || {}; // Stats DOM.statTime.textContent = `${data.total_time_seconds || meta.api_response_time_seconds || '—'}s`; if (DOM.statLang) { const lang = (extraction.form_language || extraction.language || '').toLowerCase(); if (lang === 'en' || lang === 'en-in') { DOM.statLang.innerHTML = '🇬🇧 English Form'; } else if (lang === 'mr' || lang === 'mr-in') { DOM.statLang.innerHTML = '🇮🇳 Marathi Form'; } else { DOM.statLang.textContent = lang || '—'; } } DOM.statFields.textContent = countFields(extraction); const repairs = extraction.repaired_fields || []; if (DOM.statRepairs) DOM.statRepairs.textContent = repairs.length; if (DOM.tabRepairsCount) DOM.tabRepairsCount.textContent = repairs.length; DOM.statMissing.textContent = (extraction.unreadable_fields || []).length; DOM.statMethod.textContent = meta.method || 'auto'; if (DOM.statModel) { if (data.is_comparison) { DOM.statModel.innerHTML = 'Gemini vs Sarvam'; } else { const rawModel = meta.model || 'DocVision AI'; const cleanModel = rawModel.replace('Gemini (', '').replace(')', ''); DOM.statModel.textContent = cleanModel; } } // JSON Viewer const displayJson = { ...extraction }; delete displayJson._meta; DOM.jsonViewer.innerHTML = syntaxHighlightJson(JSON.stringify(displayJson, null, 2)); // Raw Transcription DOM.transcriptionBox.textContent = extraction.raw_transcription || ''; // Fields Grid & Repairs renderFieldsGrid(extraction); renderRepairsTab(repairs); // Model Comparison tab if (data.is_comparison && data.comparison) { if (DOM.tabBtnModelCompare) { DOM.tabBtnModelCompare.style.display = 'inline-flex'; } if (DOM.modelMatchPct) { DOM.modelMatchPct.textContent = `${data.comparison.overall_match_percent}%`; } renderModelComparisonTab(data.comparison, data.gemini_result, data.sarvam_result); switchTab('model-compare'); } else { if (DOM.tabBtnModelCompare) { DOM.tabBtnModelCompare.style.display = 'none'; } switchTab('fields'); } // Image previews if (data.original_image_b64) { DOM.originalImage.src = `data:image/jpeg;base64,${data.original_image_b64}`; DOM.imagePreviewContainer.classList.add('visible'); } else if (data.original_image_url) { DOM.originalImage.src = data.original_image_url; DOM.imagePreviewContainer.classList.add('visible'); } else { DOM.imagePreviewContainer.classList.remove('visible'); } if (data.processed_image_b64) { DOM.processedImage.src = `data:image/jpeg;base64,${data.processed_image_b64}`; DOM.processedPanel.style.display = 'block'; DOM.imagePreviewContainer.classList.remove('single'); } else if (data.processed_image_url) { DOM.processedImage.src = data.processed_image_url; DOM.processedPanel.style.display = 'block'; DOM.imagePreviewContainer.classList.remove('single'); } else { DOM.processedPanel.style.display = 'none'; DOM.imagePreviewContainer.classList.add('single'); } // Preprocessing info if (data.preprocessing && data.preprocessing.steps_applied) { const steps = data.preprocessing.steps_applied; DOM.preprocessInfo.innerHTML = steps.map(s => `✓ ${formatStepName(s)}` ).join(''); DOM.preprocessInfo.style.display = steps.length > 0 ? 'flex' : 'none'; } else { DOM.preprocessInfo.style.display = 'none'; } // Show results DOM.resultsContainer.classList.add('visible'); // Update history loadTestHistory(); // Scroll to results DOM.resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); } function renderFieldsGrid(extraction) { const sections = [ { title: '🏥 Hospital & Registration — रुग्णालय व नोंदणी माहिती', icon: '🏥', data: extraction.hospital_details || {} }, { title: '👤 Patient Identification — रुग्ण ओळख व नाव', icon: '👤', data: extraction.patient_details || {} }, { title: '📍 Local Address (Pune) — स्थानिक पत्ता (पुण्यातील)', icon: '📍', data: { local_address: (extraction.address_details || {}).local_address, local_flat_room: (extraction.address_details || {}).local_flat_room, local_premises: (extraction.address_details || {}).local_premises, local_landmark: (extraction.address_details || {}).local_landmark, local_road: (extraction.address_details || {}).local_road, local_taluka: (extraction.address_details || {}).local_taluka, local_pincode: (extraction.address_details || {}).local_pincode } }, { title: '🏡 Permanent Address — कायमचा पत्ता', icon: '🏡', data: { permanent_address: (extraction.address_details || {}).permanent_address, perm_flat_room: (extraction.address_details || {}).perm_flat_room, perm_premises: (extraction.address_details || {}).perm_premises, perm_landmark: (extraction.address_details || {}).perm_landmark, perm_road: (extraction.address_details || {}).perm_road, perm_taluka: (extraction.address_details || {}).perm_taluka, city_district: (extraction.address_details || {}).city_district, perm_state: (extraction.address_details || {}).perm_state, pincode: (extraction.address_details || {}).pincode, perm_country: (extraction.address_details || {}).perm_country, nationality: (extraction.address_details || {}).nationality } }, { title: '💳 Socio-Economic & Billing — उत्पन्न व शुल्क', icon: '💳', data: extraction.billing_details || {} }, { title: '✍️ Representative / Signatory — प्रतिनिधी माहिती', icon: '✍️', data: extraction.representative_details || {} }, { title: '🩺 Medical Notes — वैद्यकीय नोंदी', icon: '🩺', data: extraction.medical_details || {} } ].filter(s => s.data && Object.keys(s.data).length > 0); const fieldLabels = { // Hospital & Registration hospital_name: 'Hospital Name / रुग्णालयाचे नाव', mrd_number: 'MRD No. / एमआरडी क्र.', barcode_number: 'Registration Barcode / बारकोड नोंदणी क्र.', visit_date: 'Date / दिनांक', examiner_name: 'Audited by / तपासणीसाचे नाव', registrar_name: 'Entered by / नोंद घेणाऱ्याचे नाव', department: 'Department / विभाग', doctor_name: 'Consultant / डॉक्टरांचे नाव', remarks: 'Remark / शेरा', // Patient Details patient_name: 'Full Name / पूर्ण नाव', first_name: 'First Name / पहिले नाव', middle_name: 'Middle Name / मधले किंवा वडिलांचे नाव', surname: 'Last Name / Surname / आडनाव', father_or_husband_name: 'Father/Husband / वडील किंवा पतीचे नाव', salutation: 'Title / Salutation / संबोधन', gender: 'Gender / लिंग', dob: 'Date of Birth / जन्मतारीख', age: 'Approximate Age / वय', id_proof_type: 'ID Proof / ओळखपत्र प्रकार', mobile_number: 'Mobile / मोबाईल क्रमांक', alternate_mobile: 'Alt Mobile / पर्यायी मोबाईल', telephone: 'Telephone / दूरध्वनी क्रमांक', email: 'Email / ईमेल', aadhaar_number: 'AADHAAR / आधार क्रमांक', pan_number: 'PAN / पॅन क्रमांक', address: 'Combined Address / पत्ता', // Local Address local_address: 'Full Local Address / स्थानिक पूर्ण पत्ता', local_flat_room: 'Flat / Room No. / फ्लॅट क्र.', local_premises: 'Premises / Building / गाव इमारत', local_landmark: 'Landmark / घराजवळची खूण', local_road: 'Road / Lane / रस्ता आळी', local_taluka: 'Area / Taluka / विभाग तालुका', local_pincode: 'PIN / Zip Code / पिनकोड', // Permanent Address permanent_address: 'Full Permanent Address / कायमचा पूर्ण पत्ता', perm_flat_room: 'Flat / Room No. / फ्लॅट क्र.', perm_premises: 'Premises / Building / गाव इमारत', perm_landmark: 'Landmark / घराजवळची खूण', perm_road: 'Road / Lane / रस्ता आळी', perm_taluka: 'Area / Taluka / विभाग तालुका', city_district: 'City / District / शहर जिल्हा', perm_state: 'State / Union Territory / राज्य', pincode: 'PIN / Zip Code / पिनकोड', perm_country: 'Country / देश', nationality: 'Nationality / राष्ट्रीयत्व', // Billing income_source: 'Source of Income / उत्पन्नाचा स्रोत', monthly_income: 'Monthly Income / मासिक उत्पन्न', bill_payer: 'Bill Payer / शुल्क कोण भरणार?', company_name: 'Company / कंपनीचे नाव', // Representative signatory: 'Signature / स्वाक्षरी', representative_name: 'Representative / प्रतिनिधीचे नाव', relationship: 'Relationship / नाते', // Clinical symptoms: 'Symptoms / लक्षणे', medical_history: 'Medical History / इतिहास', diagnosis: 'Diagnosis / निदान', medicines: 'Medicines / औषधे', additional_notes: 'Additional Notes / नोंदी' }; let html = ''; // Language & Form Header Badge const formLang = (extraction.form_language || extraction.language || '').toLowerCase(); const isEnglish = formLang === 'en' || formLang === 'en-in'; const formTitle = isEnglish ? '🇬🇧 English Form: DEENANATH MANGESHKAR HOSPITAL & RESEARCH CENTRE (PATIENT REGISTRATION FORM)' : '🇮🇳 मराठी अर्ज: दीनानाथ मंगेशकर रुग्णालय आणि संशोधन केंद्र (रुग्ण नावनोंदणी अर्ज)'; html += `
${formTitle}
🛡️ ZERO-HALLUCINATION SHIELD APPLIED
`; // Map of repaired fields const repairMap = {}; (extraction.repaired_fields || []).forEach(r => { repairMap[r.field] = r; }); sections.forEach(section => { html += `
${section.title}
`; html += `
`; Object.entries(section.data).forEach(([key, value]) => { // Skip redundant father_or_husband_name if middle_name is already shown if (key === 'father_or_husband_name' && section.data.middle_name) { return; } if (key === 'mrp_number') { return; } const label = fieldLabels[key] || key; const isMissing = value === null || value === '' || (Array.isArray(value) && value.length === 0); const cssClass = isMissing ? 'missing' : 'filled'; let displayValue; if (Array.isArray(value)) { if (value.length === 0) { displayValue = '— empty —'; } else { displayValue = value.map(item => { if (typeof item === 'object') { return `${item.name || '—'} : ${item.dosage || '—'}`; } return item; }).join('
'); } } else if (value === null || value === undefined) { displayValue = '— null (unwritten) —'; } else { displayValue = escapeHtml(String(value)); } const repairInfo = repairMap[key]; const repairBadge = repairInfo ? `✨ Auto-Repaired` : ''; const repairSubnote = repairInfo ? `
Patient wrote: ${escapeHtml(repairInfo.original)}
` : ''; html += `
${label} ${repairBadge}
${displayValue}
${repairSubnote}
`; }); html += `
`; }); // Warnings const warnings = extraction.validation_warnings || []; if (warnings.length > 0) { html += `
⚠️ Warnings & Auto-Repair Audit
`; warnings.forEach(w => { const isHallucinationGuard = w.includes('Hallucination') || w.includes('विसंगत') || w.includes('Anti-Hallucination') || w.includes('दुरुस्त') || w.includes('Auto-Repaired'); const icon = isHallucinationGuard ? '🛡️' : '⚠️'; const cardStyle = isHallucinationGuard ? 'background: #eff6ff; border: 1px solid #bfdbfe; border-left: 4px solid #1e40af;' : ''; const textStyle = isHallucinationGuard ? 'color: #1e40af; font-weight: 500;' : 'color: var(--warning);'; html += `
${icon} ${escapeHtml(w)}
`; }); } DOM.fieldsGrid.innerHTML = html; } function renderRepairsTab(repairs) { if (!DOM.repairsContainer) return; if (!repairs || repairs.length === 0) { DOM.repairsContainer.innerHTML = `
✨ Clean Handwriting Extraction

No patient spelling typos or phonetic mistakes were detected. All fields were extracted cleanly.

`; return; } let html = `
✨ Auto-Repair Engine Applied: ${repairs.length} patient handwriting mistake(s) / phonetic slips were repaired and converted into standard, properly spelled English.
`; repairs.forEach(r => { html += `
${escapeHtml(r.field)} REPAIRED & CONVERTED
Patient Handwrote: ${escapeHtml(r.original)}
➔
Standard English: ${escapeHtml(r.repaired)}
💡 ${escapeHtml(r.note)}
`; }); html += `
`; DOM.repairsContainer.innerHTML = html; } function renderModelComparisonTab(comparison, geminiRes, sarvamRes) { if (!DOM.modelCompareContainer) return; if (!comparison) { DOM.modelCompareContainer.innerHTML = '
No comparison data available.
'; return; } const timeA = comparison.time_a_seconds !== undefined && comparison.time_a_seconds !== null ? comparison.time_a_seconds : '—'; const timeB = comparison.time_b_seconds !== undefined && comparison.time_b_seconds !== null ? comparison.time_b_seconds : '—'; let speedBadge = ''; if (typeof timeA === 'number' && typeof timeB === 'number' && timeA > 0 && timeB > 0) { const faster = timeA < timeB ? comparison.model_a : comparison.model_b; const ratio = (Math.max(timeA, timeB) / Math.min(timeA, timeB)).toFixed(1); const firstName = faster.includes('Gemini') ? 'Gemini' : 'Sarvam'; speedBadge = `⚡ ${firstName} ${ratio}x Faster`; } let html = `
⚖️ AI Vision Model Benchmark & Accuracy Comparison
🔷 ${escapeHtml(comparison.model_a)} vs 🔶 ${escapeHtml(comparison.model_b)}
⏱️ Response Time
${timeA}s vs ${timeB}s
${speedBadge}
📋 Extracted Fields
${comparison.fields_a_count} vs ${comparison.fields_b_count}
Active evaluated: ${comparison.active_fields}
🤝 Agreement Rate
${comparison.agreement_percent}%
${comparison.matches} matches · ${comparison.mismatches} differences
✨ Auto-Repairs Applied
${comparison.repairs_a_count} vs ${comparison.repairs_b_count}
Handwriting mistakes repaired
Field-by-Field Matrix (${comparison.field_rows.length} fields)
`; comparison.field_rows.forEach(r => { let badgeClass = 'both_empty'; let badgeText = 'BOTH EMPTY'; if (r.status === 'MATCH') { badgeClass = 'match'; badgeText = '✓ MATCH'; } else if (r.status === 'DIFFERENT') { badgeClass = 'different'; badgeText = '≠ DIFFERENCE'; } else if (r.status === 'ONLY_IN_A') { badgeClass = 'only_in_a'; badgeText = 'GEMINI ONLY'; } else if (r.status === 'ONLY_IN_B') { badgeClass = 'only_in_b'; badgeText = 'SARVAM ONLY'; } const displayA = r.value_a ? escapeHtml(String(r.value_a)) : '— null —'; const displayB = r.value_b ? escapeHtml(String(r.value_b)) : '— null —'; const repairBadgeA = r.repaired_a ? `✨ Repaired` : ''; const repairBadgeB = r.repaired_b ? `✨ Repaired` : ''; const filterTag = r.status === 'MATCH' ? 'match' : (r.status === 'DIFFERENT' ? 'diff' : (r.status === 'BOTH_EMPTY' ? 'empty' : 'active')); html += ` `; }); html += `
Field Name 🔷 ${escapeHtml(comparison.model_a)} 🔶 ${escapeHtml(comparison.model_b)} Comparison Status
${escapeHtml(r.field)}
${escapeHtml(r.section_title)}
${displayA} ${repairBadgeA}
${displayB} ${repairBadgeB}
${badgeText}
`; DOM.modelCompareContainer.innerHTML = html; } window.filterComparisonRows = function(type, btn) { if (btn) { document.querySelectorAll('.view-mode-buttons .view-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); } const rows = document.querySelectorAll('#compare-table-body tr'); rows.forEach(r => { const filter = r.getAttribute('data-filter'); if (type === 'all') { r.style.display = ''; } else if (type === 'match') { r.style.display = filter === 'match' ? '' : 'none'; } else if (type === 'diff') { r.style.display = filter === 'diff' ? '' : 'none'; } else if (type === 'active') { r.style.display = filter !== 'empty' ? '' : 'none'; } }); }; // ════════════════════════════════════════════════════════════ // Comparison // ════════════════════════════════════════════════════════════ async function handleCompare() { if (!AppState.lastResult) { showError('No extraction result', 'Run an extraction first before comparing.'); return; } const refText = DOM.compareTextarea.value.trim(); if (!refText) { showError('Empty reference', 'Paste a reference JSON to compare against.'); return; } let reference; try { reference = JSON.parse(refText); } catch (e) { showError('Invalid JSON', `Could not parse reference JSON: ${e.message}`); return; } try { const response = await fetch('/api/compare', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ extracted: AppState.lastResult.extraction, reference: reference }) }); const result = await response.json(); renderCompareResults(result); } catch (err) { showError('Comparison failed', err.message); } } function renderCompareResults(result) { const circumference = 2 * Math.PI * 27; const offset = circumference - (result.accuracy_percent / 100) * circumference; let html = `
${result.accuracy_percent}%
${result.matches}/${result.total_fields} fields match
${result.note}
`; result.field_results.forEach(fr => { const icon = fr.match ? '✅' : '❌'; const iconClass = fr.match ? 'yes' : 'no'; html += `
${icon} ${fr.field} ${escapeHtml(fr.extracted ?? 'null')} → ${escapeHtml(fr.reference ?? 'null')}
`; }); DOM.compareResults.innerHTML = html; } // ════════════════════════════════════════════════════════════ // Test History // ════════════════════════════════════════════════════════════ function formatTimestamp(isoStr) { if (!isoStr) return ''; try { const d = new Date(isoStr); return d.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); } catch { return isoStr; } } async function loadTestHistory() { try { const resp = await fetch('/api/test-results'); const data = await resp.json(); AppState.testResults = data.results || []; renderHistory(); } catch (e) { console.error('Failed to load test history:', e); } } function renderHistory() { if (!DOM.historyBody) return; const countEl = document.getElementById('history-count'); if (countEl) { countEl.textContent = `${AppState.testResults.length} test${AppState.testResults.length === 1 ? '' : 's'}`; } if (AppState.testResults.length === 0) { DOM.historyBody.innerHTML = ` No tests run yet. Upload a document and extract to begin. `; return; } DOM.historyBody.innerHTML = AppState.testResults.map(r => { const isSuccess = r.status === 'success'; const statusBadge = isSuccess ? `● success` : `● failed`; const timeDisplay = formatTimestamp(r.timestamp); const isGemini = r.model && r.model.toLowerCase().includes('gemini'); const modelBadge = isGemini ? `🔷 ${escapeHtml(r.model)}` : `🔶 ${escapeHtml(r.model || 'DocVision AI')}`; return `
${escapeHtml(r.filename)}
${timeDisplay} ${modelBadge} ${escapeHtml(r.method || 'auto')} ${statusBadge} ${r.api_response_time ? r.api_response_time + 's' : '—'} ${r.fields_extracted ?? '—'} ${r.fields_missing ?? '—'}
${isSuccess ? `` : ''}
`; }).join(''); } async function viewHistoryResult(id) { try { const resp = await fetch(`/api/test-results/${id}`); if (!resp.ok) { showError('Record not found', 'Could not load details for this test.'); return; } const record = await resp.json(); if (!record || !record.result) return; const origUrl = record.has_original_image ? `/api/test-results/${id}/image/original` : null; const procUrl = record.has_processed_image ? `/api/test-results/${id}/image/processed` : null; renderResults({ filename: record.filename, extraction: record.result, total_time_seconds: record.total_time, preprocessing: record.preprocessing || null, original_image_url: origUrl, processed_image_url: procUrl }); if (DOM.resultsContainer) { DOM.resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); } } catch (e) { console.error('Failed to view history result:', e); } } async function deleteHistoryResult(id, event) { if (event) event.stopPropagation(); if (!confirm('Delete this test result from history?')) return; try { const resp = await fetch(`/api/test-results/${id}`, { method: 'DELETE' }); if (resp.ok) { await loadTestHistory(); } } catch (e) { console.error('Delete failed:', e); } } async function clearAllHistory() { if (!confirm('Are you sure you want to permanently clear ALL test history and saved images?')) return; try { const resp = await fetch('/api/test-results/clear', { method: 'POST' }); if (resp.ok) { await loadTestHistory(); } } catch (e) { console.error('Clear history failed:', e); } } // Expose globally for inline onclick handlers window.viewHistoryResult = viewHistoryResult; window.deleteHistoryResult = deleteHistoryResult; window.clearAllHistory = clearAllHistory; // ════════════════════════════════════════════════════════════ // Downloads // ════════════════════════════════════════════════════════════ function downloadJson() { if (!AppState.lastResult) return; const extraction = { ...AppState.lastResult.extraction }; delete extraction._meta; const blob = new Blob([JSON.stringify(extraction, null, 2)], { type: 'application/json' }); downloadBlob(blob, `extraction_${Date.now()}.json`); } function downloadText() { if (!AppState.lastResult) return; const text = AppState.lastResult.extraction?.raw_transcription || 'No transcription available.'; const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); downloadBlob(blob, `transcription_${Date.now()}.txt`); } function downloadBlob(blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } // ════════════════════════════════════════════════════════════ // Tabs // ════════════════════════════════════════════════════════════ function switchTab(tabId) { document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); const tab = document.querySelector(`.tab[data-tab="${tabId}"]`); const content = document.getElementById(`tab-${tabId}`); if (tab) tab.classList.add('active'); if (content) content.classList.add('active'); } // ════════════════════════════════════════════════════════════ // Reset // ════════════════════════════════════════════════════════════ function handleReset() { clearFile(); AppState.lastResult = null; DOM.resultsContainer.classList.remove('visible'); DOM.imagePreviewContainer.classList.remove('visible'); hideError(); DOM.preprocessToggle.checked = false; DOM.methodSelect.value = 'auto'; DOM.compareTextarea.value = ''; DOM.compareResults.innerHTML = ''; DOM.preprocessInfo.style.display = 'none'; window.scrollTo({ top: 0, behavior: 'smooth' }); } // ════════════════════════════════════════════════════════════ // UI Helpers // ════════════════════════════════════════════════════════════ function showLoading() { DOM.loadingOverlay.classList.add('visible'); } function hideLoading() { DOM.loadingOverlay.classList.remove('visible'); } function updateLoadingStep(text) { DOM.loadingStep.textContent = text; } function showError(title, details) { DOM.errorMessage.textContent = title; DOM.errorDetails.textContent = details || ''; DOM.errorDetails.style.display = details ? 'block' : 'none'; DOM.errorDisplay.classList.add('visible'); } function hideError() { DOM.errorDisplay.classList.remove('visible'); } function formatFileSize(bytes) { if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; } function formatStepName(step) { const names = { 'resize': 'Resized', 'auto_rotate': 'Deskewed', 'noise_reduction': 'Denoised', 'contrast_enhancement': 'Contrast Enhanced', 'sharpen': 'Sharpened' }; return names[step] || step; } function countFields(extraction) { let count = 0; ['patient_details', 'hospital_details', 'medical_details'].forEach(section => { const data = extraction[section]; if (data && typeof data === 'object') { Object.values(data).forEach(v => { if (v !== null && v !== '' && !(Array.isArray(v) && v.length === 0)) count++; }); } }); return count; } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // JSON syntax highlighting function syntaxHighlightJson(json) { return json.replace( /("(\\u[\da-fA-F]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(\.\d+)?([eE][+-]?\d+)?)/g, (match) => { let cls = 'json-number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'json-key'; } else { cls = 'json-string'; } } else if (/true|false/.test(match)) { cls = 'json-bool'; } else if (/null/.test(match)) { cls = 'json-null'; } return `${match}`; } ); }