File size: 11,716 Bytes
123160d
deed5ef
123160d
0bee0bb
 
 
123160d
1196b1e
0bee0bb
 
 
 
 
 
 
1196b1e
0bee0bb
 
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
07559cf
0bee0bb
 
 
 
 
 
 
 
1196b1e
 
0bee0bb
 
 
1196b1e
 
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
1196b1e
0bee0bb
 
 
 
1196b1e
0bee0bb
 
 
 
1196b1e
0bee0bb
 
 
 
 
1196b1e
0bee0bb
 
 
 
1196b1e
0bee0bb
 
 
 
 
1196b1e
0bee0bb
 
 
 
1196b1e
0bee0bb
 
 
 
1196b1e
e707a78
1196b1e
0bee0bb
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
1196b1e
0bee0bb
 
 
deed5ef
0bee0bb
 
 
 
1196b1e
0bee0bb
 
 
 
1196b1e
0bee0bb
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43430f1
0bee0bb
 
 
 
43430f1
 
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1196b1e
0bee0bb
 
 
 
 
 
 
 
 
 
 
 
123160d
0bee0bb
123160d
0bee0bb
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
    )