app / backend /gemini_analyzer.py
sabareesh4317
Initial deploy (Clean)
e2a1a46
Raw History Blame Contribute Delete
26.9 kB
"""
Google Gemini-Powered Prescription Analyzer
FREE ultra-accurate prescription analysis using Google's Gemini API
"""
import google.generativeai as genai
import json
import os
from typing import Dict, Any, Optional
import logging
from dataclasses import dataclass, asdict
from datetime import datetime
from datetime import datetime
from .usage_tracker import UsageTracker
@dataclass
class GeminiMedicine:
"""Medicine information extracted by Gemini"""
name: str = ""
generic_name: str = ""
strength: str = ""
frequency: str = ""
duration: str = ""
instructions: str = ""
route: str = "" # oral, topical, injection
uses: str = "" # What is this for?
side_effects: str = "" # Common side effects
category: str = "" # antibiotic, painkiller, vitamin, etc.
side_effects: str = ""
warnings: str = ""
confidence_score: float = 0.0
@dataclass
class GeminiPrescription:
"""Complete prescription analysis by Gemini"""
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 = "Google Gemini (FREE)"
analysis_timestamp: str = ""
analysis_timestamp: str = ""
is_prescription: bool = True # Flag to indicate if the image is a valid prescription
health_tip: str = "" # Pharmacist's health tip for the patient
def __post_init__(self):
if self.medicines is None:
self.medicines = []
if not self.analysis_timestamp:
self.analysis_timestamp = datetime.now().isoformat()
class GeminiPrescriptionAnalyzer:
"""
Advanced prescription analyzer using Google's FREE Gemini API
"""
def __init__(self, api_key: str, model: str = "gemini-1.5-flash"):
"""
Initialize Gemini analyzer
Args:
api_key: Google API key (FREE from Google AI Studio)
model: Gemini model to use (gemini-1.5-pro is the smartest free model available)
"""
self.api_key = api_key
self.model = model
# Configure Gemini
genai.configure(api_key=api_key)
# System instruction - Make AI think like an expert pharmacist
system_instruction = """
You are an expert Pharmacist with 20+ years of experience interpreting handwritten prescriptions.
CRITICAL RULES:
1. **Extract ALL Medicines:** Even if medicine names are unclear, demo text, or abbreviated - ALWAYS extract the dosage structure.
2. **Demo Prescriptions:** If you see "DEMO MEDICINE" or placeholder text, still extract the dosage, frequency, and duration information.
3. **Pattern Recognition:** Look for medicine patterns like:
- "TAB" = Tablet
- "CAP" = Capsule
- "SYR" = Syrup
- Numbers like "1 Morning, 1 Night" = dosage frequency
- "10 Days" = duration
- "Before Food" / "After Food" = instructions
4. **Smart Extraction:** Even from garbled text, extract:
- Medicine type (Tab/Cap/Syrup)
- Dosage frequency (Morning/Night/Evening)
- Duration (Days/Weeks)
- Instructions (Before/After food)
5. **MANDATORY MEDICINE EXTRACTION:** If you see patterns like "1) TAB", "2) CAP", "3) TAB" followed by ANY text, extract them as medicines.
6. **Never Return Empty:** ALWAYS find at least one medicine if you see numbered medicine entries. Use placeholders if needed.
7. **CONFIDENCE SCORING (THINK LIKE A PHARMACIST):**
- **HIGH (0.9-1.0):** Text is clear AND dosage makes medical sense for the inferred condition.
- **MEDIUM (0.7-0.8):** Text is slightly ambiguous BUT dosage pattern is standard.
- **LOW (<0.6):** Text is illegible OR dosage is unusual/unsafe.
- **SAFETY CHECK:** Always check for potential drug interactions or contraindications based on the patient's age/condition.
8. **Context Clues:** Use patient age, symptoms, or diagnosis to suggest likely medicine categories.
"""
self.client = genai.GenerativeModel(
model_name=model,
system_instruction=system_instruction
)
# Setup logging
self.logger = logging.getLogger(__name__)
# Validate API key (temporarily disabled for testing)
# self._validate_api_key()
# Load medicine database for correction
# self.medicine_db = load_medicine_database()
# Initialize usage tracker
self.usage_tracker = UsageTracker()
def _validate_api_key(self):
"""Validate Google API key"""
try:
# Test API key with a simple request
response = self.client.generate_content("Test")
self.logger.info("✅ Google Gemini API key validated successfully")
except Exception as e:
self.logger.error(f"❌ Invalid Google API key: {e}")
raise ValueError(f"Invalid Google API key: {e}")
def analyze_prescription(self, raw_text: str, image_path: Optional[str] = None) -> GeminiPrescription:
"""
Analyze prescription text/image using FREE Gemini
Args:
raw_text: Raw text extracted from prescription image (fallback/context)
image_path: Path to the prescription image (for Vision analysis)
Returns:
GeminiPrescription with detailed analysis
"""
try:
# Prepare content for Gemini
content = []
# Add image if available (Vision mode)
if image_path and os.path.exists(image_path):
try:
from PIL import Image
image = Image.open(image_path)
content.append(image)
self.logger.info(f"📸 Added image to Gemini request: {image_path}")
except Exception as e:
self.logger.warning(f"Failed to load image for Gemini: {e}")
# Add text prompt
prompt = self._create_analysis_prompt(raw_text, has_image=bool(content))
content.append(prompt)
# Get Gemini analysis
try:
# Increment usage counter
self.usage_tracker.increment()
response = self.client.generate_content(content)
except Exception as e:
# Fallback for 404 Model Not Found
if "404" in str(e) and "not found" in str(e):
self.logger.warning(f"⚠️ Model {self.model} not found. Trying fallback to 'gemini-flash-latest'...")
print(f"⚠️ Model {self.model} not found. Switching to fallback...")
# Create fallback client
fallback_model = "gemini-flash-latest"
self.client = genai.GenerativeModel(
model_name=fallback_model,
system_instruction=self.client._system_instruction
)
self.model = fallback_model
response = self.client.generate_content(content)
else:
raise e
# Parse the response
analysis_text = response.text
# Debug logging
self.logger.info(f"🔍 Gemini raw response: {analysis_text[:500]}...")
print(f"🔍 DEBUG - Gemini response: {analysis_text}") # Console output
# Write raw response to file for debugging
with open("gemini_debug.log", "w", encoding="utf-8") as f:
f.write(analysis_text)
# Extract JSON from response
json_start = analysis_text.find('{')
json_end = analysis_text.rfind('}') + 1
if json_start >= 0 and json_end > json_start:
json_text = analysis_text[json_start:json_end]
analysis_data = json.loads(json_text)
else:
# Fallback parsing
analysis_data = self._parse_text_response(analysis_text)
# Convert to our data structure
prescription = self._parse_gemini_response(analysis_data)
# Verify and correct medicine names with a dedicated pass
if prescription.medicines:
self.logger.info("🕵️ Running dedicated spell-check verification on medicines...")
prescription.medicines = self.verify_medicines(prescription.medicines)
# Calculate confidence
prescription.analysis_confidence = self._calculate_confidence(prescription)
return prescription
except json.JSONDecodeError as e:
self.logger.error(f"Failed to parse Gemini response: {e}")
return self._create_fallback_response(raw_text, f"JSON parsing error: {e}")
except Exception as e:
self.logger.error(f"Gemini analysis failed: {e}")
return self._create_fallback_response(raw_text, str(e))
def _create_analysis_prompt(self, raw_text: str, has_image: bool = False) -> str:
"""Create focused prompt for pharmacist system instruction"""
context_intro = ""
if has_image:
context_intro = "Analyze the provided PRESCRIPTION IMAGE directly. Use the OCR text below only as a hint/backup if handwriting is unclear."
else:
context_intro = "EXTRACT ALL MEDICINES from this prescription text."
return f"""{context_intro} Even if names are unclear or say "DEMO MEDICINE", extract the dosage patterns.
OCR TEXT HINT:
{raw_text}
MANDATORY EXTRACTION RULES:
1. Find ALL medicine entries (TAB, CAP, SYR patterns)
2. Extract dosage frequency (Morning, Night, Evening numbers)
3. Extract duration (Days, Weeks)
4. Extract instructions (Before Food, After Food)
5. If medicine name is "DEMO MEDICINE X", use it as placeholder but extract all other details
6. NEVER return empty medicines array if you can see medicine patterns in the text
7. CRITICAL: CHECK IF THIS IS A PRESCRIPTION.
- If the image is a landscape, selfie, car, animal, or random object -> Set "is_prescription": false.
- If it contains NO medical text -> Set "is_prescription": false.
- If it is just a receipt or invoice -> Set "is_prescription": false.
- ONLY set "is_prescription": true if it looks like a medical document.
Return analysis in this JSON format:
{{
"medical_context": {{
"is_prescription": true,
"diagnosis": "condition being treated",
"symptoms": "symptoms mentioned",
"allergies": "known allergies"
}},
"patient_info": {{
"name": "patient name or empty",
"age": "age or empty",
"gender": "gender or empty"
}},
"healthcare_provider": {{
"doctor_name": "doctor name or empty",
"specialty": "specialty or empty",
"clinic_name": "clinic name or empty"
}},
"prescription_details": {{
"date": "prescription date or empty",
"prescription_number": "rx number or empty"
}},
"medicines": [
{{
"name": "corrected medicine name",
"generic_name": "generic equivalent",
"strength": "precise dosage",
"frequency": "how often (BID/TID/etc)",
"duration": "treatment duration",
"route": "oral/topical/injection",
"uses": "simple explanation of what it treats",
"side_effects": "common side effects",
"instructions": "special instructions",
"category": "therapeutic category",
"confidence_score": 0.95,
"confidence_reason": "Text is clear and dosage matches standard protocol for bronchitis",
"ocr_correction_applied": "yes/no"
}}
],
"special_instructions": "additional notes",
"follow_up": "follow-up requirements"
"special_instructions": "additional notes",
"follow_up": "follow-up requirements",
"health_tip": "A short, friendly, and practical health tip for the patient (e.g., 'Drink plenty of water', 'Avoid driving if drowsy')"
}}"""
def _parse_text_response(self, text: str) -> Dict:
"""Parse non-JSON response from Gemini"""
# Basic fallback parsing for when JSON isn't returned
lines = text.split('\n')
result = {
"patient_name": "",
"doctor_name": "",
"medicines": [],
"diagnosis": "",
"special_instructions": text[:200] + "..." if len(text) > 200 else text
}
# Try to extract basic info
for line in lines:
line = line.lower()
if 'patient' in line and ':' in line:
result["patient_name"] = line.split(':')[1].strip()
elif 'doctor' in line or 'dr.' in line:
result["doctor_name"] = line.split(':')[1].strip() if ':' in line else line
return result
def _parse_gemini_response(self, analysis_data: Dict) -> GeminiPrescription:
"""Parse Gemini response into our data structure"""
# Parse medicines
medicines = []
for med_data in analysis_data.get("medicines", []):
# Apply fuzzy matching correction
original_name = med_data.get("name", "")
# corrected_name = get_best_match(original_name, self.medicine_db) or original_name
corrected_name = original_name
# if corrected_name != original_name:
# self.logger.info(f"✨ Auto-corrected medicine: {original_name} -> {corrected_name}")
medicine = GeminiMedicine(
name=corrected_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", ""),
uses=med_data.get("uses", ""),
side_effects=med_data.get("side_effects", ""),
category=med_data.get("category", ""),
warnings=med_data.get("warnings", ""),
confidence_score=med_data.get("confidence_score", 0.8)
)
medicines.append(medicine)
# Extract nested data from new Golden Prompt structure
patient_info = analysis_data.get("patient_info", {})
healthcare_provider = analysis_data.get("healthcare_provider", {})
prescription_details = analysis_data.get("prescription_details", {})
medical_context = analysis_data.get("medical_context", {})
# Create prescription object with new structure support
prescription = GeminiPrescription(
patient_name=patient_info.get("name", "") or analysis_data.get("patient_name", ""),
patient_age=patient_info.get("age", "") or analysis_data.get("patient_age", ""),
patient_gender=patient_info.get("gender", "") or analysis_data.get("patient_gender", ""),
doctor_name=healthcare_provider.get("doctor_name", "") or analysis_data.get("doctor_name", ""),
doctor_specialty=healthcare_provider.get("specialty", "") or analysis_data.get("doctor_specialty", ""),
clinic_name=healthcare_provider.get("clinic_name", "") or analysis_data.get("clinic_name", ""),
prescription_date=prescription_details.get("date", "") or analysis_data.get("prescription_date", ""),
diagnosis=medical_context.get("diagnosis", "") or analysis_data.get("diagnosis", ""),
symptoms=medical_context.get("symptoms", "") or analysis_data.get("symptoms", ""),
allergies=medical_context.get("allergies", "") or analysis_data.get("allergies", ""),
special_instructions=analysis_data.get("special_instructions", ""),
follow_up=analysis_data.get("follow_up", ""),
medicines=medicines,
is_prescription=medical_context.get("is_prescription", False),
health_tip=analysis_data.get("health_tip", "")
)
return prescription
def _calculate_confidence(self, prescription: GeminiPrescription) -> 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) -> GeminiPrescription:
"""Create fallback response when Gemini analysis fails"""
return GeminiPrescription(
patient_name="Analysis failed",
doctor_name="Analysis failed",
medicines=[],
analysis_confidence=0.0,
special_instructions=f"Gemini analysis failed: {error}. Raw text: {raw_text[:200]}..."
)
def get_usage_stats(self) -> Dict[str, Any]:
"""Get API usage statistics"""
return {
"model_used": self.model,
"api_status": "active",
"cost": "FREE (15 requests/minute, 1500/day)",
"provider": "Google Gemini"
}
def to_json(self, prescription: GeminiPrescription) -> str:
"""Convert prescription to JSON string"""
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 verify_medicines(self, medicines: list) -> list:
"""
Verify and correct medicine names using a dedicated Gemini pass
"""
if not medicines:
return []
try:
# Extract names for verification
med_names = [med.name for med in medicines]
prompt = f"""
You are an expert Medical Editor. Verify these medicine names for spelling errors.
Input Names: {json.dumps(med_names)}
Task:
1. Check each name against a medical database.
2. Correct any spelling mistakes (e.g., "Paracctamol" -> "Paracetamol").
3. If the name is already correct, keep it as is.
4. Return ONLY a JSON object mapping original names to corrected names.
Format:
{{
"original_name_1": "corrected_name_1",
"original_name_2": "corrected_name_2"
}}
"""
response = self.client.generate_content(prompt)
# Parse response
text = response.text
json_start = text.find('{')
json_end = text.rfind('}') + 1
if json_start >= 0:
corrections = json.loads(text[json_start:json_end])
# Apply corrections
for med in medicines:
if med.name in corrections:
corrected = corrections[med.name]
if corrected != med.name:
self.logger.info(f"✨ Spell-check corrected: {med.name} -> {corrected}")
med.name = corrected
# Boost confidence for corrected items
med.confidence_score = max(med.confidence_score, 0.95)
return medicines
except Exception as e:
self.logger.warning(f"Spell-check verification failed: {e}")
return medicines
def check_interactions(self, medicines: list) -> list:
"""
Check for drug interactions between prescribed medicines using Gemini
"""
if not medicines or len(medicines) < 2:
return []
try:
med_names = [med.name for med in medicines]
prompt = f"""
You are an expert Clinical Pharmacist. Check for drug interactions between these medicines:
Medicines: {json.dumps(med_names)}
Task:
1. Identify any significant drug-drug interactions.
2. For each interaction, provide:
- Severity (High/Moderate/Low)
- Description: CONCISE, bulleted points (max 30 words). NO long paragraphs.
- Recommendation: Short, actionable advice.
3. Return a JSON array of interactions. If none, return empty array [].
Format:
[
{{
"medicines": ["Med1", "Med2"],
"severity": "High",
"description": "• Interaction point 1\n• Interaction point 2",
"recommendation": "Monitor for..."
}}
]
"""
response = self.client.generate_content(prompt)
# Parse response
text = response.text
json_start = text.find('[')
json_end = text.rfind(']') + 1
if json_start >= 0:
interactions = json.loads(text[json_start:json_end])
self.logger.info(f"⚠️ Found {len(interactions)} potential interactions")
return interactions
return []
except Exception as e:
self.logger.warning(f"Interaction check failed: {e}")
return []
def get_medical_summary(self, prescription: GeminiPrescription) -> str:
"""Generate human-readable medical summary"""
summary = []
summary.append("EXPERT PHARMACIST PRESCRIPTION ANALYSIS")
summary.append("AI Pharmacist + Intelligent OCR Correction")
summary.append("=" * 60)
# 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("-" * 40)
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_label = "[HIGH CONFIDENCE]" if med.confidence_score > 0.8 else "[MEDIUM CONFIDENCE]" if med.confidence_score > 0.6 else "[LOW CONFIDENCE]"
summary.append(f" Confidence: {med.confidence_score:.1%} {confidence_label}")
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}")
if prescription.health_tip:
summary.append("")
summary.append(f"💡 PHARMACIST TIP: {prescription.health_tip}")
summary.append("")
summary.append(f"Analysis Confidence: {prescription.analysis_confidence:.1%}")
summary.append(f"Powered by: {self.model} + Expert Pharmacist System")
summary.append(f"AI Pharmacist: Advanced medical intelligence with 20+ years expertise")
summary.append(f"Cost: $0.00 (Free Tier)")
summary.append(f"Analyzed at: {prescription.analysis_timestamp}")
summary.append("")
summary.append("PHARMACIST-LEVEL ACCURACY:")
summary.append("- Context-first diagnosis-based drug prediction")
summary.append("- Intelligent OCR auto-correction (Slbtmlo -> Salbutamol)")
summary.append("- Medical logic-driven spelling fixes")
summary.append("- Pharmacological knowledge database")
summary.append("- High confidence scoring for corrections")
summary.append("")
summary.append("MEDICAL DISCLAIMER:")
summary.append("This AI pharmacist analysis is for informational purposes only.")
summary.append("Always consult healthcare professionals for medical advice.")
return "\n".join(summary)