/** * 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.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}
` : ''}