1230 lines
54 KiB
JavaScript
1230 lines
54 KiB
JavaScript
/**
|
|
* 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 = '<span style="color:#1d4ed8;font-weight:600;">🇬🇧 English Form</span>';
|
|
} else if (lang === 'mr' || lang === 'mr-in') {
|
|
DOM.statLang.innerHTML = '<span style="color:#059669;font-weight:600;">🇮🇳 Marathi Form</span>';
|
|
} 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 = '<span style="color:#0284c7;font-weight:700;">Gemini</span> vs <span style="color:#ea580c;font-weight:700;">Sarvam</span>';
|
|
} 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 =>
|
|
`<span class="preprocess-step">✓ ${formatStepName(s)}</span>`
|
|
).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 += `
|
|
<div style="margin-bottom: 18px; padding: 10px 14px; background: #f8fafc; border: 1px solid var(--border-color); border-radius: var(--radius-md); display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
|
|
<div style="font-size: 13px; font-weight: 600; color: var(--text-primary);">${formTitle}</div>
|
|
<div style="font-size: 11px; background: #ecfdf5; color: #059669; border: 1px solid #a7f3d0; padding: 2px 8px; border-radius: 12px; font-weight: 600;">
|
|
🛡️ ZERO-HALLUCINATION SHIELD APPLIED
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
// Map of repaired fields
|
|
const repairMap = {};
|
|
(extraction.repaired_fields || []).forEach(r => {
|
|
repairMap[r.field] = r;
|
|
});
|
|
|
|
sections.forEach(section => {
|
|
html += `<div class="field-section-title">${section.title}</div>`;
|
|
html += `<div class="field-grid-inner">`;
|
|
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 = '<span class="null-value">— empty —</span>';
|
|
} else {
|
|
displayValue = value.map(item => {
|
|
if (typeof item === 'object') {
|
|
return `${item.name || '—'} : ${item.dosage || '—'}`;
|
|
}
|
|
return item;
|
|
}).join('<br>');
|
|
}
|
|
} else if (value === null || value === undefined) {
|
|
displayValue = '<span class="null-value">— null (unwritten) —</span>';
|
|
} else {
|
|
displayValue = escapeHtml(String(value));
|
|
}
|
|
|
|
const repairInfo = repairMap[key];
|
|
const repairBadge = repairInfo
|
|
? `<span class="repair-pill-inline" title="${escapeHtml(repairInfo.note)}">✨ Auto-Repaired</span>`
|
|
: '';
|
|
const repairSubnote = repairInfo
|
|
? `<div class="repair-subnote">Patient wrote: <s>${escapeHtml(repairInfo.original)}</s></div>`
|
|
: '';
|
|
|
|
html += `
|
|
<div class="field-card ${cssClass}">
|
|
<div class="field-label">${label} ${repairBadge}</div>
|
|
<div class="field-value">${displayValue}</div>
|
|
${repairSubnote}
|
|
</div>
|
|
`;
|
|
});
|
|
html += `</div>`;
|
|
});
|
|
|
|
// Warnings
|
|
const warnings = extraction.validation_warnings || [];
|
|
if (warnings.length > 0) {
|
|
html += `<div class="field-section-title">⚠️ Warnings & Auto-Repair Audit</div>`;
|
|
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 += `
|
|
<div class="field-card" style="grid-column: 1 / -1; padding: 10px 14px; ${cardStyle}">
|
|
<div class="field-value" style="${textStyle} font-family: var(--font-sans); font-size: 13px;">${icon} ${escapeHtml(w)}</div>
|
|
</div>
|
|
`;
|
|
});
|
|
}
|
|
|
|
DOM.fieldsGrid.innerHTML = html;
|
|
}
|
|
|
|
function renderRepairsTab(repairs) {
|
|
if (!DOM.repairsContainer) return;
|
|
if (!repairs || repairs.length === 0) {
|
|
DOM.repairsContainer.innerHTML = `
|
|
<div style="padding: 40px; text-align: center; color: var(--text-muted);">
|
|
<span style="font-size: 36px; display: block; margin-bottom: 8px;">✨</span>
|
|
<strong>Clean Handwriting Extraction</strong>
|
|
<p style="font-size: 13px; margin-top: 4px;">No patient spelling typos or phonetic mistakes were detected. All fields were extracted cleanly.</p>
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
let html = `
|
|
<div style="margin-bottom: 16px; padding: 12px 16px; background: #eff6ff; border: 1px solid #bfdbfe; border-radius: var(--radius-md); font-size: 13px; color: #1e40af;">
|
|
<strong>✨ Auto-Repair Engine Applied:</strong> ${repairs.length} patient handwriting mistake(s) / phonetic slips were repaired and converted into standard, properly spelled English.
|
|
</div>
|
|
<div class="repairs-grid">
|
|
`;
|
|
|
|
repairs.forEach(r => {
|
|
html += `
|
|
<div class="repair-card">
|
|
<div class="repair-card-header">
|
|
<span class="repair-card-field">${escapeHtml(r.field)}</span>
|
|
<span class="repair-card-badge">REPAIRED & CONVERTED</span>
|
|
</div>
|
|
<div class="repair-card-diff">
|
|
<div class="repair-diff-item original">
|
|
<span class="diff-label">Patient Handwrote:</span>
|
|
<span class="diff-value">${escapeHtml(r.original)}</span>
|
|
</div>
|
|
<div class="repair-diff-arrow">➔</div>
|
|
<div class="repair-diff-item corrected">
|
|
<span class="diff-label">Standard English:</span>
|
|
<span class="diff-value">${escapeHtml(r.repaired)}</span>
|
|
</div>
|
|
</div>
|
|
<div class="repair-card-note">💡 ${escapeHtml(r.note)}</div>
|
|
</div>
|
|
`;
|
|
});
|
|
|
|
html += `</div>`;
|
|
DOM.repairsContainer.innerHTML = html;
|
|
}
|
|
|
|
function renderModelComparisonTab(comparison, geminiRes, sarvamRes) {
|
|
if (!DOM.modelCompareContainer) return;
|
|
if (!comparison) {
|
|
DOM.modelCompareContainer.innerHTML = '<div style="padding:40px;text-align:center;color:var(--text-muted);">No comparison data available.</div>';
|
|
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 = `<span class="metric-badge-speed">⚡ ${firstName} ${ratio}x Faster</span>`;
|
|
}
|
|
|
|
let html = `
|
|
<div class="model-benchmark-hero">
|
|
<div class="benchmark-hero-top">
|
|
<div class="benchmark-title">
|
|
<span>⚖️</span>
|
|
<span>AI Vision Model Benchmark & Accuracy Comparison</span>
|
|
</div>
|
|
<div class="model-tags-group">
|
|
<span class="model-tag gemini">🔷 ${escapeHtml(comparison.model_a)}</span>
|
|
<span style="font-size:12px;color:var(--text-muted);font-weight:700;">vs</span>
|
|
<span class="model-tag sarvam">🔶 ${escapeHtml(comparison.model_b)}</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="model-metrics-grid">
|
|
<div class="model-metric-card">
|
|
<div class="metric-label">⏱️ Response Time</div>
|
|
<div class="metric-values">
|
|
<span class="metric-subval gemini">${timeA}s</span>
|
|
<span style="color:var(--text-muted);font-size:11px;">vs</span>
|
|
<span class="metric-subval sarvam">${timeB}s</span>
|
|
</div>
|
|
<div style="margin-top:6px;">${speedBadge}</div>
|
|
</div>
|
|
|
|
<div class="model-metric-card">
|
|
<div class="metric-label">📋 Extracted Fields</div>
|
|
<div class="metric-values">
|
|
<span class="metric-subval gemini">${comparison.fields_a_count}</span>
|
|
<span style="color:var(--text-muted);font-size:11px;">vs</span>
|
|
<span class="metric-subval sarvam">${comparison.fields_b_count}</span>
|
|
</div>
|
|
<div style="margin-top:6px;font-size:11px;color:var(--text-muted);">
|
|
Active evaluated: ${comparison.active_fields}
|
|
</div>
|
|
</div>
|
|
|
|
<div class="model-metric-card">
|
|
<div class="metric-label">🤝 Agreement Rate</div>
|
|
<div class="metric-values">
|
|
<span style="font-size:18px;font-weight:800;color:#059669;">${comparison.agreement_percent}%</span>
|
|
</div>
|
|
<div style="margin-top:4px;font-size:11px;color:var(--text-muted);">
|
|
${comparison.matches} matches · ${comparison.mismatches} differences
|
|
</div>
|
|
</div>
|
|
|
|
<div class="model-metric-card">
|
|
<div class="metric-label">✨ Auto-Repairs Applied</div>
|
|
<div class="metric-values">
|
|
<span class="metric-subval gemini">${comparison.repairs_a_count}</span>
|
|
<span style="color:var(--text-muted);font-size:11px;">vs</span>
|
|
<span class="metric-subval sarvam">${comparison.repairs_b_count}</span>
|
|
</div>
|
|
<div style="margin-top:6px;font-size:11px;color:var(--text-muted);">
|
|
Handwriting mistakes repaired
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="model-switcher-bar">
|
|
<div style="font-size:13px;font-weight:600;color:var(--text-primary);">
|
|
Field-by-Field Matrix (${comparison.field_rows.length} fields)
|
|
</div>
|
|
<div class="view-mode-buttons">
|
|
<button class="view-btn active" onclick="filterComparisonRows('all', this)">All (${comparison.field_rows.length})</button>
|
|
<button class="view-btn" onclick="filterComparisonRows('match', this)">Matches (${comparison.matches})</button>
|
|
<button class="view-btn" onclick="filterComparisonRows('diff', this)">Differences (${comparison.mismatches})</button>
|
|
<button class="view-btn" onclick="filterComparisonRows('active', this)">Active Only (${comparison.active_fields})</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="model-compare-table-wrapper">
|
|
<table class="model-compare-table">
|
|
<thead>
|
|
<tr>
|
|
<th style="width:24%;">Field Name</th>
|
|
<th style="width:28%;">🔷 ${escapeHtml(comparison.model_a)}</th>
|
|
<th style="width:28%;">🔶 ${escapeHtml(comparison.model_b)}</th>
|
|
<th style="width:20%;">Comparison Status</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="compare-table-body">
|
|
`;
|
|
|
|
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)) : '<span class="null-value">— null —</span>';
|
|
const displayB = r.value_b ? escapeHtml(String(r.value_b)) : '<span class="null-value">— null —</span>';
|
|
|
|
const repairBadgeA = r.repaired_a ? `<span class="repair-pill-inline" title="${escapeHtml(r.note_a || '')}">✨ Repaired</span>` : '';
|
|
const repairBadgeB = r.repaired_b ? `<span class="repair-pill-inline" title="${escapeHtml(r.note_b || '')}">✨ Repaired</span>` : '';
|
|
|
|
const filterTag = r.status === 'MATCH' ? 'match' : (r.status === 'DIFFERENT' ? 'diff' : (r.status === 'BOTH_EMPTY' ? 'empty' : 'active'));
|
|
|
|
html += `
|
|
<tr data-filter="${filterTag}" class="compare-row-${filterTag}">
|
|
<td>
|
|
<strong>${escapeHtml(r.field)}</strong>
|
|
<div style="font-size:11px;color:var(--text-muted);">${escapeHtml(r.section_title)}</div>
|
|
</td>
|
|
<td style="background:${r.status === 'MATCH' ? '#f0fdf4' : (r.status === 'DIFFERENT' ? '#fffbeb' : '#ffffff')};">
|
|
<div>${displayA} ${repairBadgeA}</div>
|
|
</td>
|
|
<td style="background:${r.status === 'MATCH' ? '#f0fdf4' : (r.status === 'DIFFERENT' ? '#fffbeb' : '#ffffff')};">
|
|
<div>${displayB} ${repairBadgeB}</div>
|
|
</td>
|
|
<td>
|
|
<span class="status-badge ${badgeClass}">${badgeText}</span>
|
|
</td>
|
|
</tr>
|
|
`;
|
|
});
|
|
|
|
html += `
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
`;
|
|
|
|
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 = `
|
|
<div class="compare-bar">
|
|
<div class="accuracy-ring">
|
|
<svg viewBox="0 0 64 64">
|
|
<circle class="ring-bg" cx="32" cy="32" r="27"/>
|
|
<circle class="ring-fill" cx="32" cy="32" r="27"
|
|
stroke-dasharray="${circumference}"
|
|
stroke-dashoffset="${offset}"/>
|
|
</svg>
|
|
<div class="ring-text">${result.accuracy_percent}%</div>
|
|
</div>
|
|
<div>
|
|
<div style="font-weight:700;font-size:16px;color:var(--text-primary)">
|
|
${result.matches}/${result.total_fields} fields match
|
|
</div>
|
|
<div style="font-size:12px;color:var(--text-muted);margin-top:4px">
|
|
${result.note}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
result.field_results.forEach(fr => {
|
|
const icon = fr.match ? '✅' : '❌';
|
|
const iconClass = fr.match ? 'yes' : 'no';
|
|
html += `
|
|
<div class="compare-field-row">
|
|
<span class="match-icon ${iconClass}">${icon}</span>
|
|
<span class="field-name">${fr.field}</span>
|
|
<span class="field-val">${escapeHtml(fr.extracted ?? 'null')}</span>
|
|
<span style="color:var(--text-muted);margin:0 8px">→</span>
|
|
<span class="field-val">${escapeHtml(fr.reference ?? 'null')}</span>
|
|
</div>
|
|
`;
|
|
});
|
|
|
|
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 = `
|
|
<tr>
|
|
<td colspan="8" class="text-center text-muted" style="padding:40px">
|
|
No tests run yet. Upload a document and extract to begin.
|
|
</td>
|
|
</tr>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
DOM.historyBody.innerHTML = AppState.testResults.map(r => {
|
|
const isSuccess = r.status === 'success';
|
|
const statusBadge = isSuccess
|
|
? `<span class="status-badge success">● success</span>`
|
|
: `<span class="status-badge error" title="${escapeHtml(r.error || 'Failed')}">● failed</span>`;
|
|
const timeDisplay = formatTimestamp(r.timestamp);
|
|
|
|
const isGemini = r.model && r.model.toLowerCase().includes('gemini');
|
|
const modelBadge = isGemini
|
|
? `<span class="badge" style="background:rgba(59,130,246,0.12);color:#2563eb;border:1px solid rgba(59,130,246,0.25);font-size:11px;font-weight:600;padding:2px 8px;border-radius:12px;white-space:nowrap;display:inline-block">🔷 ${escapeHtml(r.model)}</span>`
|
|
: `<span class="badge" style="background:rgba(245,158,11,0.12);color:#d97706;border:1px solid rgba(245,158,11,0.25);font-size:11px;font-weight:600;padding:2px 8px;border-radius:12px;white-space:nowrap;display:inline-block">🔶 ${escapeHtml(r.model || 'DocVision AI')}</span>`;
|
|
|
|
return `
|
|
<tr>
|
|
<td>
|
|
<div style="font-weight:600;color:var(--text-primary);max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${escapeHtml(r.filename)}">
|
|
${escapeHtml(r.filename)}
|
|
</div>
|
|
<span class="history-time">${timeDisplay}</span>
|
|
</td>
|
|
<td>${modelBadge}</td>
|
|
<td><span style="font-family:var(--font-mono);font-size:11px">${escapeHtml(r.method || 'auto')}</span></td>
|
|
<td>${statusBadge}</td>
|
|
<td>${r.api_response_time ? r.api_response_time + 's' : '—'}</td>
|
|
<td class="text-success">${r.fields_extracted ?? '—'}</td>
|
|
<td class="text-warning">${r.fields_missing ?? '—'}</td>
|
|
<td>
|
|
<div class="btn-action-group">
|
|
${isSuccess ? `<button class="btn btn-sm btn-secondary" onclick="viewHistoryResult('${r.id}')" title="View extraction results">👁️ View</button>` : ''}
|
|
<button class="btn btn-sm btn-danger" onclick="deleteHistoryResult('${r.id}', event)" title="Delete record">🗑️</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
`;
|
|
}).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 `<span class="${cls}">${match}</span>`;
|
|
}
|
|
);
|
|
}
|