Spaces:
Sleeping
Sleeping
Download backend/chatgpt_analyzer.py from Presight-AI/app: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/chatgpt_analyzer.py
- Command line
-
hf download hf://spaces/Presight-AI/app/backend/chatgpt_analyzer.py
-
curl -L -o chatgpt_analyzer.py https://huggingface.co/spaces/Presight-AI/app/resolve/main/backend/chatgpt_analyzer.py
15.9 kB
| """ | |
| 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 | |
| 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 | |
| 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) |