/** * 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 += `
No patient spelling typos or phonetic mistakes were detected. All fields were extracted cleanly.
| Field Name | 🔷 ${escapeHtml(comparison.model_a)} | 🔶 ${escapeHtml(comparison.model_b)} | Comparison Status |
|---|---|---|---|
|
${escapeHtml(r.field)}
${escapeHtml(r.section_title)}
|
${displayA} ${repairBadgeA}
|
${displayB} ${repairBadgeB}
|
${badgeText} |