medicalmodel / app.py
walaa2022's picture
Update app.py
43430f1 verified
import gradio as gr
import google.generativeai as genai
from PIL import Image
import io
import base64
from typing import Optional, List, Tuple
import json
# Configure Gemini API using HuggingFace secrets
def setup_gemini():
"""Setup Gemini API with HuggingFace secrets"""
try:
# Access API key from HuggingFace secrets
import os
api_key = None
# Try multiple ways to access the secret
if hasattr(gr, 'secrets'):
api_key = gr.secrets.get("GEMINI_API_KEY")
if not api_key:
# Fallback to environment variable for local testing
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in secrets")
genai.configure(api_key=api_key)
return genai.GenerativeModel('gemini-2.0-flash')
except Exception as e:
print(f"Error setting up Gemini: {e}")
return None
def create_medical_prompt(patient_data: dict, complaints: str, has_image: bool = False) -> str:
"""Create an optimized prompt for Gemini's medical analysis"""
base_prompt = """You are an expert medical AI assistant with extensive training in medical imaging, diagnostics, and clinical decision support. Please provide a comprehensive medical analysis based on the provided information.
**IMPORTANT DISCLAIMERS:**
- This is for educational and decision support purposes only
- Always requires human physician review and validation
- Not a substitute for professional medical judgment
- Emergency cases require immediate medical attention
**PATIENT INFORMATION:**"""
# Add patient demographics
if patient_data.get('age'):
base_prompt += f"\n- Age: {patient_data['age']} years"
if patient_data.get('gender'):
base_prompt += f"\n- Gender: {patient_data['gender']}"
if patient_data.get('weight'):
base_prompt += f"\n- Weight: {patient_data['weight']} kg"
if patient_data.get('height'):
base_prompt += f"\n- Height: {patient_data['height']} cm"
# Add medical history
if patient_data.get('medical_history'):
base_prompt += f"\n- Medical History: {patient_data['medical_history']}"
if patient_data.get('medications'):
base_prompt += f"\n- Current Medications: {patient_data['medications']}"
if patient_data.get('allergies'):
base_prompt += f"\n- Allergies: {patient_data['allergies']}"
# Add chief complaints
base_prompt += f"\n\n**CHIEF COMPLAINTS AND SYMPTOMS:**\n{complaints}"
# Add image analysis instruction if image is provided
if has_image:
base_prompt += "\n\n**MEDICAL IMAGE ANALYSIS:**\nPlease analyze the provided medical image(s) in detail, describing all visible findings, abnormalities, and relevant anatomical structures."
# Analysis framework
base_prompt += """
**PLEASE PROVIDE YOUR ANALYSIS IN THE FOLLOWING STRUCTURED FORMAT:**
## 1. CLINICAL ASSESSMENT
- **Primary Findings:** [Key observations from history and/or imaging]
- **Vital Signs Assessment:** [If provided, comment on vital signs]
- **Physical Examination Notes:** [Relevant physical findings mentioned]
## 2. DIFFERENTIAL DIAGNOSIS
- **Most Likely Diagnosis:** [Primary consideration with reasoning]
- **Alternative Diagnoses:** [Other possibilities to consider]
- **Ruling Out:** [Important conditions to exclude]
## 3. IMAGING ANALYSIS (if applicable)
- **Technical Quality:** [Assessment of image quality]
- **Anatomical Structures:** [Normal structures identified]
- **Abnormal Findings:** [Any pathological changes]
- **Measurements:** [Relevant measurements if applicable]
## 4. RECOMMENDED INVESTIGATIONS
- **Laboratory Tests:** [Suggested blood work, cultures, etc.]
- **Imaging Studies:** [Additional imaging if needed]
- **Specialized Tests:** [ECG, spirometry, biopsy, etc.]
## 5. TREATMENT RECOMMENDATIONS
- **Immediate Management:** [Urgent interventions if needed]
- **Medication Suggestions:** [Pharmacological interventions]
- **Non-Pharmacological:** [Lifestyle, physical therapy, etc.]
- **Follow-up:** [Monitoring and reassessment timeline]
## 6. RED FLAGS & URGENCY
- **Emergency Indicators:** [Signs requiring immediate attention]
- **Warning Signs:** [Symptoms to monitor]
- **When to Seek Help:** [Clear escalation criteria]
## 7. PATIENT EDUCATION
- **Condition Explanation:** [Simple explanation of likely diagnosis]
- **Lifestyle Modifications:** [Relevant lifestyle advice]
- **Prognosis:** [Expected outcome with treatment]
**Remember:** Always correlate with clinical judgment and seek appropriate medical consultation."""
return base_prompt
def analyze_medical_case(image_files, age, gender, weight, height, medical_history,
medications, allergies, complaints):
"""Analyze medical case using Gemini AI"""
model = setup_gemini()
if not model:
return "❌ Error: Could not initialize Gemini AI. Please check API key in secrets."
try:
# Prepare patient data
patient_data = {
'age': age,
'gender': gender,
'weight': weight,
'height': height,
'medical_history': medical_history,
'medications': medications,
'allergies': allergies
}
# Validate input
if not complaints.strip():
return "❌ Please provide patient complaints and symptoms."
# Create prompt
has_images = image_files is not None and len(image_files) > 0
prompt = create_medical_prompt(patient_data, complaints, has_images)
# Prepare content for Gemini
content = [prompt]
# Process images if provided
if has_images:
for img_file in image_files:
try:
# Open and process image
image = Image.open(img_file.name)
# Convert to RGB if necessary
if image.mode != 'RGB':
image = image.convert('RGB')
content.append(image)
except Exception as e:
return f"❌ Error processing image: {str(e)}"
# Generate response
response = model.generate_content(content)
if response.text:
return f"""# πŸ₯ Medical AI Analysis Report
{response.text}
---
**⚠️ IMPORTANT MEDICAL DISCLAIMER:**
This AI analysis is for educational and decision support purposes only. It should not replace professional medical judgment, clinical examination, or established medical protocols. Always consult with qualified healthcare professionals for medical decisions. In emergency situations, seek immediate medical attention."""
else:
return "❌ Could not generate analysis. Please try again."
except Exception as e:
return f"❌ Error during analysis: {str(e)}"
def create_interface():
"""Create Gradio interface for the medical assistant"""
with gr.Blocks(title="πŸ₯ Medical AI Assistant", theme=gr.themes.Soft()) as interface:
gr.Markdown("""
# πŸ₯ Medical AI Assistant with Gemini
**Advanced Medical Case Analysis and Decision Support**
Upload medical images, enter patient data, and get comprehensive AI-powered medical insights using Google's Gemini AI, specially trained on medical data and imaging.
⚠️ **For Healthcare Professionals Only** - This tool is designed for medical professionals and should not replace clinical judgment.
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ“ Medical Images")
image_files = gr.File(
label="Upload Medical Images",
file_types=[".jpg", ".jpeg", ".png", ".bmp", ".tiff"],
file_count="multiple",
height=200
)
gr.Markdown("### πŸ‘€ Patient Demographics")
with gr.Row():
age = gr.Number(label="Age (years)", value=None, minimum=0, maximum=120)
gender = gr.Dropdown(
label="Gender",
choices=["Male", "Female"],
value=None
)
with gr.Row():
weight = gr.Number(label="Weight (kg)", value=None, minimum=3)
height = gr.Number(label="Height (cm)", value=None, minimum=50)
gr.Markdown("### πŸ“‹ Medical History")
medical_history = gr.Textbox(
label="Past Medical History",
placeholder="Previous diagnoses, surgeries, chronic conditions...",
lines=3
)
medications = gr.Textbox(
label="Current Medications",
placeholder="List current medications, dosages, frequency...",
lines=2
)
allergies = gr.Textbox(
label="Known Allergies",
placeholder="Drug allergies, food allergies, environmental...",
lines=2
)
with gr.Column(scale=1):
gr.Markdown("### 🩺 Chief Complaints & Symptoms")
complaints = gr.Textbox(
label="Patient Complaints and Symptoms",
placeholder="""Describe the patient's main complaints, symptoms, and clinical presentation:
β€’ Chief complaint and duration
β€’ Associated symptoms
β€’ Severity and progression
β€’ Triggering factors
β€’ Previous treatments tried
β€’ Vital signs (if available)
β€’ Physical examination findings
β€’ Any relevant recent changes""",
lines=12
)
analyze_btn = gr.Button(
"πŸ” Analyze Medical Case",
variant="primary",
size="lg"
)
gr.Markdown("### πŸ“Š AI Medical Analysis")
output = gr.Markdown(label="Analysis Results")
# Examples section
gr.Markdown("""
### πŸ’‘ Example Use Cases
**Radiology:** Upload X-rays, CT scans, MRIs for detailed imaging analysis
**Dermatology:** Skin lesion photos with patient history
**Cardiology:** ECGs, echocardiogram images with cardiac symptoms
**Pathology:** Microscopic images with clinical context
**Emergency Medicine:** Multi-modal case analysis with urgency assessment
""")
# Set up the analysis function
analyze_btn.click(
fn=analyze_medical_case,
inputs=[
image_files, age, gender, weight, height,
medical_history, medications, allergies, complaints
],
outputs=output
)
gr.Markdown("""
### ⚠️ Important Medical Disclaimers
- Always requires validation by qualified healthcare professionals
- Emergency cases require immediate medical attention
- Users assume responsibility for clinical decisions
""")
return interface
# Create and launch the interface
if __name__ == "__main__":
demo = create_interface()
demo.launch(
share=True,
server_name="0.0.0.0",
server_port=7860
)