""" ChatGPT-Powered Prescription Analyzer Ultra-accurate prescription analysis using OpenAI's GPT models """ import openai import json import os from typing import Dict, Any, Optional import logging from dataclasses import dataclass, asdict from datetime import datetime @dataclass class ChatGPTMedicine: """Medicine information extracted by ChatGPT""" name: str = "" generic_name: str = "" strength: str = "" frequency: str = "" duration: str = "" instructions: str = "" route: str = "" # oral, topical, injection category: str = "" # antibiotic, painkiller, vitamin, etc. side_effects: str = "" warnings: str = "" confidence_score: float = 0.0 @dataclass class ChatGPTPrescription: """Complete prescription analysis by ChatGPT""" patient_name: str = "" patient_age: str = "" patient_gender: str = "" doctor_name: str = "" doctor_specialty: str = "" clinic_name: str = "" prescription_date: str = "" medicines: list = None diagnosis: str = "" symptoms: str = "" allergies: str = "" special_instructions: str = "" follow_up: str = "" analysis_confidence: float = 0.0 extracted_by: str = "ChatGPT" analysis_timestamp: str = "" def __post_init__(self): if self.medicines is None: self.medicines = [] if not self.analysis_timestamp: self.analysis_timestamp = datetime.now().isoformat() class ChatGPTPrescriptionAnalyzer: """ Advanced prescription analyzer using OpenAI's ChatGPT """ def __init__(self, api_key: str, model: str = "gpt-4"): """ Initialize ChatGPT analyzer Args: api_key: OpenAI API key model: GPT model to use (gpt-4, gpt-3.5-turbo, gpt-4-turbo) """ self.api_key = api_key self.model = model self.client = openai.OpenAI(api_key=api_key) # Setup logging self.logger = logging.getLogger(__name__) # Validate API key on initialization self._validate_api_key() def _validate_api_key(self): """Validate OpenAI API key""" try: # Test API key with a simple request response = self.client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Test"}], max_tokens=1 ) self.logger.info("✅ OpenAI API key validated successfully") except Exception as e: self.logger.error(f"❌ Invalid OpenAI API key: {e}") raise ValueError(f"Invalid OpenAI API key: {e}") def analyze_prescription(self, raw_text: str) -> ChatGPTPrescription: """ Analyze prescription text using ChatGPT Args: raw_text: Raw text extracted from prescription image Returns: ChatGPTPrescription with detailed analysis """ try: # Create the analysis prompt prompt = self._create_analysis_prompt(raw_text) # Get ChatGPT analysis response = self.client.chat.completions.create( model=self.model, messages=[ { "role": "system", "content": self._get_system_prompt() }, { "role": "user", "content": prompt } ], temperature=0.1, # Low temperature for consistent medical analysis max_tokens=2000, response_format={"type": "json_object"} ) # Parse the response analysis_text = response.choices[0].message.content analysis_data = json.loads(analysis_text) # Convert to our data structure prescription = self._parse_chatgpt_response(analysis_data) # Calculate confidence based on completeness prescription.analysis_confidence = self._calculate_confidence(prescription) return prescription except json.JSONDecodeError as e: self.logger.error(f"Failed to parse ChatGPT response: {e}") return self._create_fallback_response(raw_text, f"JSON parsing error: {e}") except Exception as e: self.logger.error(f"ChatGPT analysis failed: {e}") return self._create_fallback_response(raw_text, str(e)) def _get_system_prompt(self) -> str: """Get the system prompt for ChatGPT""" return """You are an expert medical prescription analyzer. Your task is to extract and analyze prescription information with high accuracy. IMPORTANT INSTRUCTIONS: 1. Extract ALL medical information from the prescription text 2. Identify medicine names, strengths, frequencies, durations, and instructions 3. Recognize medical abbreviations (BID, TID, QD, PRN, etc.) 4. Identify patient and doctor information 5. Categorize medicines (antibiotic, painkiller, vitamin, etc.) 6. Provide generic names when possible 7. Extract any warnings, side effects, or special instructions 8. Be conservative with confidence scores - only high confidence for clear text RESPONSE FORMAT: Always respond with valid JSON in this exact structure: { "patient_name": "string", "patient_age": "string", "patient_gender": "string", "doctor_name": "string", "doctor_specialty": "string", "clinic_name": "string", "prescription_date": "string", "diagnosis": "string", "symptoms": "string", "allergies": "string", "medicines": [ { "name": "string", "generic_name": "string", "strength": "string", "frequency": "string", "duration": "string", "instructions": "string", "route": "string", "category": "string", "side_effects": "string", "warnings": "string", "confidence_score": 0.95 } ], "special_instructions": "string", "follow_up": "string" } MEDICAL ABBREVIATIONS TO RECOGNIZE: - OD/QD = Once daily - BID = Twice daily - TID = Three times daily - QID = Four times daily - PRN = As needed - AC = Before meals - PC = After meals - HS = At bedtime - mg = milligrams - ml = milliliters - mcg = micrograms MEDICINE CATEGORIES: - Antibiotic, Painkiller, Anti-inflammatory, Vitamin, Antacid, Antihistamine, - Antihypertensive, Antidiabetic, Bronchodilator, Steroid, etc. Be thorough and accurate. If information is unclear, mark it as "Not clearly specified" rather than guessing.""" def _create_analysis_prompt(self, raw_text: str) -> str: """Create the analysis prompt for ChatGPT""" return f"""Analyze this prescription text and extract all medical information: PRESCRIPTION TEXT: {raw_text} Please provide a comprehensive analysis including: 1. Patient information (name, age, gender if mentioned) 2. Doctor information (name, specialty, clinic) 3. All medicines with complete details: - Brand/generic names - Strength (mg, ml, etc.) - Frequency (how often to take) - Duration (how many days/weeks) - Instructions (before/after food, timing, etc.) - Route of administration - Medicine category/type - Any warnings or side effects mentioned 4. Diagnosis or condition if mentioned 5. Any special instructions or follow-up requirements Assign confidence scores (0.0-1.0) based on text clarity: - 0.9-1.0: Very clear, unambiguous text - 0.7-0.9: Clear but some minor uncertainty - 0.5-0.7: Somewhat unclear but interpretable - 0.3-0.5: Unclear text, low confidence interpretation - 0.0-0.3: Very unclear or illegible text Return the analysis as valid JSON following the specified format.""" def _parse_chatgpt_response(self, analysis_data: Dict) -> ChatGPTPrescription: """Parse ChatGPT response into our data structure""" # Parse medicines medicines = [] for med_data in analysis_data.get("medicines", []): medicine = ChatGPTMedicine( name=med_data.get("name", ""), generic_name=med_data.get("generic_name", ""), strength=med_data.get("strength", ""), frequency=med_data.get("frequency", ""), duration=med_data.get("duration", ""), instructions=med_data.get("instructions", ""), route=med_data.get("route", ""), category=med_data.get("category", ""), side_effects=med_data.get("side_effects", ""), warnings=med_data.get("warnings", ""), confidence_score=med_data.get("confidence_score", 0.5) ) medicines.append(medicine) # Create prescription object prescription = ChatGPTPrescription( patient_name=analysis_data.get("patient_name", ""), patient_age=analysis_data.get("patient_age", ""), patient_gender=analysis_data.get("patient_gender", ""), doctor_name=analysis_data.get("doctor_name", ""), doctor_specialty=analysis_data.get("doctor_specialty", ""), clinic_name=analysis_data.get("clinic_name", ""), prescription_date=analysis_data.get("prescription_date", ""), diagnosis=analysis_data.get("diagnosis", ""), symptoms=analysis_data.get("symptoms", ""), allergies=analysis_data.get("allergies", ""), special_instructions=analysis_data.get("special_instructions", ""), follow_up=analysis_data.get("follow_up", ""), medicines=medicines ) return prescription def _calculate_confidence(self, prescription: ChatGPTPrescription) -> float: """Calculate overall analysis confidence""" scores = [] # Patient info confidence if prescription.patient_name: scores.append(0.8) if prescription.doctor_name: scores.append(0.8) if prescription.prescription_date: scores.append(0.6) # Medicine confidence if prescription.medicines: medicine_scores = [med.confidence_score for med in prescription.medicines] scores.extend(medicine_scores) # Calculate average if scores: return sum(scores) / len(scores) else: return 0.0 def _create_fallback_response(self, raw_text: str, error: str) -> ChatGPTPrescription: """Create fallback response when ChatGPT analysis fails""" return ChatGPTPrescription( patient_name="Analysis failed", doctor_name="Analysis failed", medicines=[], analysis_confidence=0.0, special_instructions=f"ChatGPT analysis failed: {error}. Raw text: {raw_text[:200]}..." ) def get_usage_stats(self) -> Dict[str, Any]: """Get API usage statistics""" # This would require storing usage data # For now, return basic info return { "model_used": self.model, "api_status": "active", "estimated_cost_per_prescription": self._estimate_cost() } def _estimate_cost(self) -> str: """Estimate cost per prescription analysis""" cost_estimates = { "gpt-4": "$0.015", "gpt-4-turbo": "$0.012", "gpt-3.5-turbo": "$0.003" } return cost_estimates.get(self.model, "$0.010") def to_json(self, prescription: ChatGPTPrescription) -> str: """Convert prescription to JSON string""" # Convert medicines to dict format prescription_dict = asdict(prescription) prescription_dict["medicines"] = [asdict(med) for med in prescription.medicines] return json.dumps(prescription_dict, indent=2, ensure_ascii=False) def get_medical_summary(self, prescription: ChatGPTPrescription) -> str: """Generate human-readable medical summary""" summary = [] summary.append("🏥 CHATGPT-POWERED PRESCRIPTION ANALYSIS") summary.append("=" * 50) # Patient Information if prescription.patient_name: summary.append(f"👤 Patient: {prescription.patient_name}") if prescription.patient_age: summary.append(f"📅 Age: {prescription.patient_age}") if prescription.patient_gender: summary.append(f"⚧ Gender: {prescription.patient_gender}") # Doctor Information if prescription.doctor_name: summary.append(f"👨‍⚕️ Doctor: {prescription.doctor_name}") if prescription.doctor_specialty: summary.append(f"🎓 Specialty: {prescription.doctor_specialty}") if prescription.clinic_name: summary.append(f"🏥 Clinic: {prescription.clinic_name}") if prescription.prescription_date: summary.append(f"📅 Date: {prescription.prescription_date}") summary.append("") # Diagnosis & Symptoms if prescription.diagnosis: summary.append(f"🔍 Diagnosis: {prescription.diagnosis}") if prescription.symptoms: summary.append(f"🤒 Symptoms: {prescription.symptoms}") if prescription.allergies: summary.append(f"⚠️ Allergies: {prescription.allergies}") # Medicines if prescription.medicines: summary.append("💊 PRESCRIBED MEDICINES:") summary.append("─" * 30) for i, med in enumerate(prescription.medicines, 1): summary.append(f"{i}. {med.name}") if med.generic_name: summary.append(f" 📋 Generic: {med.generic_name}") if med.strength: summary.append(f" 💪 Strength: {med.strength}") if med.frequency: summary.append(f" 🕐 Frequency: {med.frequency}") if med.duration: summary.append(f" ⏰ Duration: {med.duration}") if med.instructions: summary.append(f" 📝 Instructions: {med.instructions}") if med.category: summary.append(f" 🏷️ Category: {med.category}") if med.route: summary.append(f" 💉 Route: {med.route}") if med.warnings: summary.append(f" ⚠️ Warnings: {med.warnings}") confidence_color = "🟢" if med.confidence_score > 0.8 else "🟡" if med.confidence_score > 0.6 else "🔴" summary.append(f" {confidence_color} Confidence: {med.confidence_score:.1%}") summary.append("") # Special Instructions if prescription.special_instructions: summary.append(f"📋 Special Instructions: {prescription.special_instructions}") if prescription.follow_up: summary.append(f"🔄 Follow-up: {prescription.follow_up}") summary.append("") summary.append(f"🤖 Analysis Confidence: {prescription.analysis_confidence:.1%}") summary.append(f"⚡ Powered by: ChatGPT ({self.model})") summary.append(f"🕐 Analyzed at: {prescription.analysis_timestamp}") summary.append("") summary.append("⚠️ MEDICAL DISCLAIMER:") summary.append("This AI analysis is for informational purposes only.") summary.append("Always consult healthcare professionals for medical advice.") return "\n".join(summary)