gnumanth commited on
Commit
f81ca4e
·
verified ·
1 Parent(s): ffb43be
Files changed (2) hide show
  1. app.py +275 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
4
+ import re
5
+
6
+ class MedGemmaSymptomAnalyzer:
7
+ def __init__(self):
8
+ self.model = None
9
+ self.tokenizer = None
10
+ self.model_loaded = False
11
+ print("Initializing MedGemma Symptom Analyzer...")
12
+
13
+ def load_model(self):
14
+ """Load MedGemma model with optimizations for deployment"""
15
+ if self.model_loaded:
16
+ return True
17
+
18
+ model_name = "google/medgemma-2b"
19
+ print(f"Loading model: {model_name}")
20
+
21
+ try:
22
+ # First try without quantization for CPU compatibility
23
+ print("Loading tokenizer...")
24
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
25
+
26
+ print("Loading model...")
27
+ # Simplified loading for CPU/compatibility
28
+ self.model = AutoModelForCausalLM.from_pretrained(
29
+ model_name,
30
+ torch_dtype=torch.float32, # Use float32 for CPU
31
+ device_map="cpu", # Force CPU for compatibility
32
+ low_cpu_mem_usage=True
33
+ )
34
+
35
+ if self.tokenizer.pad_token is None:
36
+ self.tokenizer.pad_token = self.tokenizer.eos_token
37
+
38
+ self.model_loaded = True
39
+ print("Model loaded successfully!")
40
+ return True
41
+
42
+ except Exception as e:
43
+ print(f"Error loading model: {e}")
44
+ print("Falling back to demo mode...")
45
+ self.model = None
46
+ self.tokenizer = None
47
+ self.model_loaded = False
48
+ return False
49
+
50
+ def analyze_symptoms(self, symptoms_text, max_length=512, temperature=0.7):
51
+ """Analyze symptoms and provide medical insights"""
52
+ # Try to load model if not already loaded
53
+ if not self.model_loaded:
54
+ if not self.load_model():
55
+ # Fallback to demo response if model fails to load
56
+ return self._get_demo_response(symptoms_text)
57
+
58
+ if not self.model or not self.tokenizer:
59
+ return self._get_demo_response(symptoms_text)
60
+
61
+ # Format the prompt for medical analysis
62
+ prompt = f"""Patient presents with the following symptoms: {symptoms_text}
63
+
64
+ Based on these symptoms, provide a medical analysis including:
65
+ 1. Possible differential diagnoses
66
+ 2. Recommended next steps
67
+ 3. When to seek immediate medical attention
68
+
69
+ Medical Analysis:"""
70
+
71
+ try:
72
+ # Tokenize input
73
+ inputs = self.tokenizer(
74
+ prompt,
75
+ return_tensors="pt",
76
+ truncation=True,
77
+ max_length=max_length,
78
+ padding=True
79
+ )
80
+
81
+ # Generate response
82
+ with torch.no_grad():
83
+ outputs = self.model.generate(
84
+ inputs.input_ids,
85
+ attention_mask=inputs.attention_mask,
86
+ max_new_tokens=400,
87
+ temperature=temperature,
88
+ do_sample=True,
89
+ pad_token_id=self.tokenizer.eos_token_id,
90
+ eos_token_id=self.tokenizer.eos_token_id
91
+ )
92
+
93
+ # Decode response
94
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
95
+
96
+ # Extract only the generated part (after the prompt)
97
+ generated_text = response[len(prompt):].strip()
98
+
99
+ return generated_text
100
+
101
+ except Exception as e:
102
+ return f"Error during analysis: {str(e)}"
103
+
104
+ def _get_demo_response(self, symptoms_text):
105
+ """Provide a demo response when model is not available"""
106
+ symptoms_lower = symptoms_text.lower()
107
+
108
+ # Simple keyword-based demo responses
109
+ if any(word in symptoms_lower for word in ['fever', 'headache', 'fatigue', 'body aches']):
110
+ return """**DEMO MODE - Model not loaded**
111
+
112
+ Based on the symptoms described (fever, headache, fatigue), here's a general analysis:
113
+
114
+ **Possible Differential Diagnoses:**
115
+ 1. Viral infection (common cold, flu)
116
+ 2. Bacterial infection
117
+ 3. Stress or exhaustion
118
+ 4. Early signs of other conditions
119
+
120
+ **Recommended Next Steps:**
121
+ 1. Rest and adequate hydration
122
+ 2. Monitor temperature regularly
123
+ 3. Over-the-counter pain relievers if appropriate
124
+ 4. Observe for worsening symptoms
125
+
126
+ **When to Seek Immediate Medical Attention:**
127
+ - High fever (>101.3°F/38.5°C)
128
+ - Severe headache or neck stiffness
129
+ - Difficulty breathing
130
+ - Persistent vomiting
131
+ - Symptoms worsen rapidly
132
+
133
+ *Note: This is a demo response. For actual medical analysis, the MedGemma model needs to be loaded.*"""
134
+
135
+ elif any(word in symptoms_lower for word in ['chest pain', 'breathing', 'shortness']):
136
+ return """**DEMO MODE - Model not loaded**
137
+
138
+ Based on chest-related symptoms, here's a general analysis:
139
+
140
+ **Possible Differential Diagnoses:**
141
+ 1. Respiratory infection
142
+ 2. Muscle strain
143
+ 3. Anxiety-related symptoms
144
+ 4. More serious conditions requiring evaluation
145
+
146
+ **Recommended Next Steps:**
147
+ 1. Seek medical evaluation promptly
148
+ 2. Avoid strenuous activity
149
+ 3. Monitor breathing patterns
150
+ 4. Note any associated symptoms
151
+
152
+ **When to Seek Immediate Medical Attention:**
153
+ - Severe chest pain
154
+ - Difficulty breathing
155
+ - Pain spreading to arm, jaw, or back
156
+ - Dizziness or fainting
157
+ - These symptoms require immediate medical care
158
+
159
+ *Note: This is a demo response. For actual medical analysis, the MedGemma model needs to be loaded.*"""
160
+
161
+ else:
162
+ return f"""**DEMO MODE - Model not loaded**
163
+
164
+ Thank you for describing your symptoms. In demo mode, I can provide general guidance:
165
+
166
+ **General Recommendations:**
167
+ 1. Keep track of when symptoms started
168
+ 2. Note any factors that make symptoms better or worse
169
+ 3. Stay hydrated and get adequate rest
170
+ 4. Consider consulting a healthcare provider
171
+
172
+ **When to Seek Medical Attention:**
173
+ - Symptoms persist or worsen
174
+ - You develop new concerning symptoms
175
+ - You have underlying health conditions
176
+ - You're unsure about the severity
177
+
178
+ For a proper AI-powered analysis of your specific symptoms: "{symptoms_text[:100]}...", the MedGemma model would need to be successfully loaded.
179
+
180
+ *Note: This is a demo response. For actual medical analysis, the MedGemma model needs to be loaded.*"""
181
+
182
+ # Initialize the analyzer
183
+ analyzer = MedGemmaSymptomAnalyzer()
184
+
185
+ def analyze_symptoms_interface(symptoms, temperature):
186
+ """Interface function for Gradio"""
187
+ if not symptoms.strip():
188
+ return "Please enter some symptoms to analyze."
189
+
190
+ # Add medical disclaimer
191
+ disclaimer = """⚠️ **MEDICAL DISCLAIMER**: This analysis is for educational purposes only and should not replace professional medical advice. Always consult with a healthcare provider for proper diagnosis and treatment.
192
+
193
+ """
194
+
195
+ analysis = analyzer.analyze_symptoms(symptoms, temperature=temperature)
196
+ return disclaimer + analysis
197
+
198
+ # Create Gradio interface
199
+ with gr.Blocks(title="MedGemma Symptom Analyzer", theme=gr.themes.Soft()) as demo:
200
+ gr.Markdown("""
201
+ # 🏥 MedGemma Symptom Analyzer
202
+
203
+ This application uses Google's MedGemma model to provide preliminary analysis of medical symptoms.
204
+ Enter your symptoms below to get AI-powered insights.
205
+
206
+ **Important**: This tool is for educational purposes only and should not replace professional medical advice.
207
+ """)
208
+
209
+ with gr.Row():
210
+ with gr.Column(scale=2):
211
+ symptoms_input = gr.Textbox(
212
+ label="Describe your symptoms",
213
+ placeholder="Example: I have been experiencing headaches, fever, and fatigue for the past 3 days...",
214
+ lines=5,
215
+ max_lines=10
216
+ )
217
+
218
+ temperature_slider = gr.Slider(
219
+ minimum=0.1,
220
+ maximum=1.0,
221
+ value=0.7,
222
+ step=0.1,
223
+ label="Response Creativity (Temperature)",
224
+ info="Lower values = more focused, Higher values = more creative"
225
+ )
226
+
227
+ analyze_btn = gr.Button("🔍 Analyze Symptoms", variant="primary")
228
+
229
+ with gr.Column(scale=3):
230
+ output = gr.Textbox(
231
+ label="Medical Analysis",
232
+ lines=15,
233
+ max_lines=20,
234
+ interactive=False
235
+ )
236
+
237
+ # Example symptoms
238
+ gr.Markdown("### 📝 Example Symptoms to Try:")
239
+ with gr.Row():
240
+ example1 = gr.Button("Flu-like symptoms", size="sm")
241
+ example2 = gr.Button("Chest pain", size="sm")
242
+ example3 = gr.Button("Digestive issues", size="sm")
243
+
244
+ # Event handlers
245
+ analyze_btn.click(
246
+ analyze_symptoms_interface,
247
+ inputs=[symptoms_input, temperature_slider],
248
+ outputs=output
249
+ )
250
+
251
+ example1.click(
252
+ lambda: "I have been experiencing fever, body aches, headache, and fatigue for the past 2 days. I also have a slight cough.",
253
+ outputs=symptoms_input
254
+ )
255
+
256
+ example2.click(
257
+ lambda: "I'm experiencing chest pain that worsens when I take deep breaths. It started this morning and is accompanied by shortness of breath.",
258
+ outputs=symptoms_input
259
+ )
260
+
261
+ example3.click(
262
+ lambda: "I have been having stomach pain, nausea, and diarrhea for the past day. I also feel bloated and have lost my appetite.",
263
+ outputs=symptoms_input
264
+ )
265
+
266
+ gr.Markdown("""
267
+ ### ⚠️ Important Notes:
268
+ - This is an AI tool for educational purposes only
269
+ - Always consult healthcare professionals for medical concerns
270
+ - Seek immediate medical attention for severe or emergency symptoms
271
+ - The AI may not always provide accurate medical information
272
+ """)
273
+
274
+ if __name__ == "__main__":
275
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ torch>=2.0.0
3
+ transformers>=4.35.0
4
+ accelerate>=0.25.0
5
+ bitsandbytes>=0.41.0
6
+ sentencepiece>=0.1.99
7
+ protobuf>=3.20.0