/** * AI Prescription Assistant with ChatGPT Integration - Frontend JavaScript * Enhanced functionality with OpenAI API integration */ // Global variables let currentFile = null; let currentProcessingId = null; let analysisResult = null; let apiKeyConfigured = false; // API endpoints const API_BASE = "/api"; const ENDPOINTS = { process: `${API_BASE}/process`, configureApiKey: `${API_BASE}/configure-api-key`, config: `${API_BASE}/config`, stats: `${API_BASE}/stats/performance`, pricing: `${API_BASE}/chatgpt/pricing` }; // Initialize application document.addEventListener('DOMContentLoaded', function() { initializeApp(); setupEventListeners(); loadConfiguration(); }); /** * Initialize the application */ function initializeApp() { console.log('🚀🤖 AI Prescription Assistant with ChatGPT initialized'); // Setup drag and drop setupDragAndDrop(); // Load initial configuration loadConfiguration(); // Check API key status checkApiKeyStatus(); // Load stats loadStats(); // Setup periodic refresh setInterval(loadStats, 30000); } /** * Setup all event listeners */ function setupEventListeners() { // File input change const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', handleFileSelect); // Upload area click const uploadArea = document.getElementById('upload-area'); uploadArea.addEventListener('click', () => fileInput.click()); // API key input enter key const apiKeyInput = document.getElementById('api-key-input'); apiKeyInput.addEventListener('keypress', function(e) { if (e.key === 'Enter') { configureApiKey(); } }); } /** * Setup drag and drop functionality */ function setupDragAndDrop() { const uploadArea = document.getElementById('upload-area'); ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { uploadArea.addEventListener(eventName, preventDefaults, false); document.body.addEventListener(eventName, preventDefaults, false); }); ['dragenter', 'dragover'].forEach(eventName => { uploadArea.addEventListener(eventName, highlight, false); }); ['dragleave', 'drop'].forEach(eventName => { uploadArea.addEventListener(eventName, unhighlight, false); }); uploadArea.addEventListener('drop', handleDrop, false); } /** * Configure OpenAI API key */ async function configureApiKey() { const apiKeyInput = document.getElementById('api-key-input'); const apiKey = apiKeyInput.value.trim(); if (!apiKey) { showError('Please enter your OpenAI API key'); return; } if (!apiKey.startsWith('sk-')) { showError('Invalid API key format. OpenAI API keys start with "sk-"'); return; } try { showLoading('Configuring ChatGPT API...', 'Validating your OpenAI API key'); const response = await fetch(ENDPOINTS.configureApiKey, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: apiKey }) }); const result = await response.json(); if (response.ok && result.success) { apiKeyConfigured = true; updateApiKeyStatus(true, result.message); enableEnhancedFeatures(); apiKeyInput.value = ''; // Clear the input for security showToast('ChatGPT API configured successfully! 🤖', 'success'); } else { throw new Error(result.detail || 'Failed to configure API key'); } } catch (error) { showError(`Failed to configure API key: ${error.message}`); } finally { hideLoading(); } } /** * Update API key configuration status */ function updateApiKeyStatus(configured, message = '') { const panel = document.getElementById('api-key-panel'); const status = document.getElementById('api-status'); const chatgptStatus = document.getElementById('chatgpt-status'); if (configured) { panel.classList.add('configured'); status.innerHTML = ` ${message}`; chatgptStatus.innerHTML = 'ChatGPT Active'; // Hide the API key form document.getElementById('api-key-form').style.display = 'none'; } else { panel.classList.remove('configured'); status.innerHTML = ' Configure your OpenAI API key for ultra-accurate analysis'; chatgptStatus.innerHTML = 'ChatGPT Inactive'; } } /** * Enable enhanced features when ChatGPT is configured */ function enableEnhancedFeatures() { const features = ['feature-categories', 'feature-generic', 'feature-side-effects', 'feature-diagnosis']; features.forEach(featureId => { const featureCard = document.getElementById(featureId); if (featureCard) { featureCard.classList.remove('disabled'); featureCard.classList.add('enabled'); } }); } /** * Handle file selection */ function handleFileSelect(event) { const file = event.target.files[0]; if (!file) return; // Validate file const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf']; if (!allowedTypes.includes(file.type)) { showError('Invalid file type. Please upload JPG, PNG, or PDF files.'); return; } const maxSize = 10 * 1024 * 1024; // 10MB if (file.size > maxSize) { showError('File too large. Maximum size is 10MB.'); return; } currentFile = file; displayImagePreview(file); showAnalyzeButton(); hideWelcomeMessage(); } /** * Display image preview */ function displayImagePreview(file) { const previewSection = document.getElementById('image-preview'); const previewImage = document.getElementById('preview-image'); const imageName = document.getElementById('image-name'); const imageSize = document.getElementById('image-size'); previewSection.style.display = 'block'; imageName.textContent = file.name; imageSize.textContent = formatFileSize(file.size); if (file.type !== 'application/pdf') { const reader = new FileReader(); reader.onload = function(e) { previewImage.src = e.target.result; }; reader.readAsDataURL(file); } else { previewImage.alt = 'PDF Document'; previewImage.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGV4dCB4PSI1MCIgeT0iNTAiIGZvbnQtc2l6ZT0iMTYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiM2Yzc1N2QiPlBERjwvdGV4dD48L3N2Zz4='; } } /** * Show analyze button */ function showAnalyzeButton() { document.getElementById('action-buttons').style.display = 'block'; } /** * Hide welcome message */ function hideWelcomeMessage() { document.getElementById('welcome-message').style.display = 'none'; } /** * Format file size for display */ function formatFileSize(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } /** * Analyze prescription with AI */ async function analyzePrescription() { if (!currentFile) { showError('Please select a file first.'); return; } // Show loading with ChatGPT-specific messaging const loadingTitle = apiKeyConfigured ? 'Analyzing with ChatGPT AI...' : 'Analyzing prescription...'; const loadingSubtitle = apiKeyConfigured ? 'ChatGPT is providing ultra-accurate analysis' : 'Using basic OCR analysis'; showLoading(loadingTitle, loadingSubtitle); updateLoadingStep('step-upload', 'completed'); updateLoadingStep('step-ocr', 'active'); try { // Prepare form data const formData = new FormData(); formData.append('file', currentFile); // Make API request const response = await fetch(ENDPOINTS.process, { method: 'POST', body: formData }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const result = await response.json(); if (result.success) { updateLoadingStep('step-ocr', 'completed'); if (apiKeyConfigured) { updateLoadingStep('step-chatgpt', 'active'); // Simulate ChatGPT processing time await new Promise(resolve => setTimeout(resolve, 1000)); updateLoadingStep('step-chatgpt', 'completed'); } analysisResult = result; currentProcessingId = result.processing_id; // Display results displayEnhancedAnalysis(result); hideLoading(); } else { throw new Error(result.error || 'Analysis failed'); } } catch (error) { hideLoading(); showError(`Analysis failed: ${error.message}`); } } /** * Display enhanced analysis results */ function displayEnhancedAnalysis(result) { const analysisSection = document.getElementById('analysis-section'); const aiEngineBadge = document.getElementById('ai-engine-badge'); // Show section analysisSection.style.display = 'block'; // Update AI engine badge const engineText = result.ai_engine === 'ChatGPT' ? `Powered by: ChatGPT (${result.model_used})` : 'Powered by: Basic Analysis'; aiEngineBadge.innerHTML = `${engineText}`; // Display patient information displayPatientInfo(result.prescription_data); // Display diagnosis if available (ChatGPT enhanced) if (result.prescription_data.diagnosis || result.prescription_data.symptoms || result.prescription_data.allergies) { displayDiagnosisInfo(result.prescription_data); } // Display enhanced medicines displayEnhancedMedicines(result.prescription_data.medicines); // Show export options document.getElementById('export-section').style.display = 'block'; } /** * Display patient information */ function displayPatientInfo(prescriptionData) { document.getElementById('patient-name').textContent = prescriptionData.patient_name || 'Not detected'; document.getElementById('patient-age').textContent = prescriptionData.patient_age || 'Not specified'; document.getElementById('patient-gender').textContent = prescriptionData.patient_gender || 'Not specified'; document.getElementById('doctor-name').textContent = prescriptionData.doctor_name || 'Not detected'; document.getElementById('doctor-specialty').textContent = prescriptionData.doctor_specialty || 'Not specified'; document.getElementById('prescription-date').textContent = prescriptionData.date || 'Not detected'; } /** * Display diagnosis information (ChatGPT enhanced) */ function displayDiagnosisInfo(prescriptionData) { const diagnosisCard = document.getElementById('diagnosis-card'); if (prescriptionData.diagnosis || prescriptionData.symptoms || prescriptionData.allergies) { diagnosisCard.style.display = 'block'; document.getElementById('diagnosis').textContent = prescriptionData.diagnosis || 'Not specified'; document.getElementById('symptoms').textContent = prescriptionData.symptoms || 'Not specified'; document.getElementById('allergies').textContent = prescriptionData.allergies || 'Not specified'; } } /** * Display enhanced medicines with ChatGPT features */ function displayEnhancedMedicines(medicines) { const medicinesList = document.getElementById('medicines-list'); if (!medicines || medicines.length === 0) { medicinesList.innerHTML = `

No medicines were detected in this prescription.

Try using a clearer image or configure ChatGPT for better accuracy.
`; return; } medicinesList.innerHTML = medicines.map((medicine, index) => { const isEnhanced = medicine.generic_name || medicine.category || medicine.side_effects || medicine.warnings; return `
${medicine.name || 'Unknown Medicine'} ${(medicine.confidence_score * 100).toFixed(0)}%
${medicine.strength || 'Not specified'}
${medicine.frequency || 'Not specified'}
${medicine.duration || 'Not specified'}
${medicine.instructions || 'No special instructions'}
${isEnhanced ? `
ChatGPT Enhanced Data
${medicine.generic_name ? `

Generic Name: ${medicine.generic_name}

` : ''} ${medicine.category ? `

Category: ${medicine.category}

` : ''} ${medicine.route ? `

Route: ${medicine.route}

` : ''} ${medicine.side_effects ? `

Common Side Effects: ${medicine.side_effects}

` : ''} ${medicine.warnings ? `

Warnings: ${medicine.warnings}

` : ''}
` : ''}
`; }).join(''); } /** * Load application configuration */ async function loadConfiguration() { try { const response = await fetch(ENDPOINTS.config); if (response.ok) { const config = await response.json(); apiKeyConfigured = config.api_key_configured; updateApiKeyStatus(apiKeyConfigured, 'ChatGPT API is active and ready'); if (apiKeyConfigured) { enableEnhancedFeatures(); } } } catch (error) { console.warn('Failed to load configuration:', error); } } /** * Check API key status */ async function checkApiKeyStatus() { try { const response = await fetch('/health'); if (response.ok) { const health = await response.json(); apiKeyConfigured = health.api_key_configured; if (apiKeyConfigured) { updateApiKeyStatus(true, 'ChatGPT API is configured and active'); enableEnhancedFeatures(); } } } catch (error) { console.warn('Failed to check API status:', error); } } /** * Load and display statistics */ async function loadStats() { try { const response = await fetch(ENDPOINTS.stats); if (response.ok) { const stats = await response.json(); document.getElementById('total-processed').textContent = stats.total_processed || 0; document.getElementById('success-rate').textContent = ((stats.success_rate || 0) * 100).toFixed(0) + '%'; } } catch (error) { console.warn('Failed to load stats:', error); } } /** * Copy enhanced results to clipboard */ async function copyToClipboard() { if (!analysisResult) { showError('No results to copy.'); return; } try { const enhancedData = { ...analysisResult.prescription_data, ai_engine: analysisResult.ai_engine, model_used: analysisResult.model_used, confidence: analysisResult.confidence, enhanced_features: analysisResult.enhanced_features || {} }; const jsonText = JSON.stringify(enhancedData, null, 2); await navigator.clipboard.writeText(jsonText); showToast('Enhanced results copied to clipboard! 🤖', 'success'); } catch (error) { showError('Failed to copy to clipboard: ' + error.message); } } /** * Download PDF report */ function downloadPDF() { if (!currentProcessingId) { showError('No processing ID available for PDF download.'); return; } // For now, show a message that PDF generation will be available showToast('Enhanced PDF generation coming soon! 📄', 'info'); } /** * Start a new scan */ function startNewScan() { // Reset all variables currentFile = null; currentProcessingId = null; analysisResult = null; // Clear file input document.getElementById('file-input').value = ''; // Hide sections document.getElementById('image-preview').style.display = 'none'; document.getElementById('action-buttons').style.display = 'none'; document.getElementById('analysis-section').style.display = 'none'; document.getElementById('diagnosis-card').style.display = 'none'; document.getElementById('export-section').style.display = 'none'; // Show welcome message document.getElementById('welcome-message').style.display = 'block'; showToast('Ready for new prescription analysis! 🧠', 'info'); } /** * Clear current upload */ function clearUpload() { startNewScan(); } // Helper functions (same as before) function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } function highlight(e) { document.getElementById('upload-area').classList.add('dragover'); } function unhighlight(e) { document.getElementById('upload-area').classList.remove('dragover'); } function handleDrop(e) { const dt = e.dataTransfer; const files = dt.files; handleFileSelect({ target: { files: files } }); } function showLoading(title, subtitle) { const overlay = document.getElementById('loading-overlay'); const titleElement = document.getElementById('loading-text'); const subtitleElement = document.getElementById('loading-subtitle'); titleElement.textContent = title; subtitleElement.textContent = subtitle; resetLoadingSteps(); overlay.style.display = 'flex'; } function hideLoading() { document.getElementById('loading-overlay').style.display = 'none'; } function updateLoadingStep(stepId, status) { const step = document.getElementById(stepId); if (!step) return; step.classList.remove('active', 'completed'); if (status !== 'pending') { step.classList.add(status); } const icon = step.querySelector('i'); if (status === 'completed') { icon.className = 'fas fa-check-circle'; } else if (status === 'active') { icon.className = 'fas fa-spinner fa-spin'; } else { icon.className = 'fas fa-circle'; } } function resetLoadingSteps() { ['step-upload', 'step-ocr', 'step-chatgpt'].forEach(stepId => { updateLoadingStep(stepId, 'pending'); }); if (currentFile) { updateLoadingStep('step-upload', 'completed'); } } function showError(message) { showToast(message, 'error'); } function showToast(message, type = 'info') { let toast = document.getElementById('toast'); if (!toast) { toast = document.createElement('div'); toast.id = 'toast'; toast.style.cssText = ` position: fixed; top: 20px; right: 20px; padding: 1rem 1.5rem; border-radius: 8px; color: white; font-weight: 500; z-index: 3000; transition: all 0.3s ease; transform: translateX(100%); opacity: 0; max-width: 400px; `; document.body.appendChild(toast); } const colors = { success: '#28a745', error: '#dc3545', warning: '#ffc107', info: '#17a2b8' }; toast.style.backgroundColor = colors[type] || colors.info; toast.textContent = message; toast.style.transform = 'translateX(0)'; toast.style.opacity = '1'; setTimeout(() => { toast.style.transform = 'translateX(100%)'; toast.style.opacity = '0'; }, 4000); } // Export functions for global access window.configureApiKey = configureApiKey; window.analyzePrescription = analyzePrescription; window.copyToClipboard = copyToClipboard; window.downloadPDF = downloadPDF; window.startNewScan = startNewScan; window.clearUpload = clearUpload;