Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,32 @@
|
|
1 |
-
# app.py -
|
2 |
import gradio as gr
|
3 |
import torch
|
4 |
from transformers import AutoProcessor, AutoModelForImageTextToText
|
5 |
from PIL import Image
|
6 |
import os
|
7 |
import logging
|
|
|
8 |
|
9 |
# Configure logging
|
10 |
logging.basicConfig(level=logging.INFO)
|
11 |
logger = logging.getLogger(__name__)
|
12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
# Model configuration
|
14 |
MODEL_ID = "google/medgemma-4b-it"
|
15 |
|
@@ -18,46 +35,63 @@ model = None
|
|
18 |
processor = None
|
19 |
|
20 |
def load_model():
|
21 |
-
"""Load model and processor with
|
22 |
global model, processor
|
23 |
|
24 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
logger.info(f"Loading model: {MODEL_ID}")
|
26 |
|
27 |
# Check if CUDA is available
|
28 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
29 |
logger.info(f"Using device: {device}")
|
30 |
|
31 |
-
# Load model with
|
32 |
model = AutoModelForImageTextToText.from_pretrained(
|
33 |
MODEL_ID,
|
34 |
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
|
35 |
device_map="auto" if device == "cuda" else None,
|
36 |
trust_remote_code=True,
|
37 |
-
low_cpu_mem_usage=True
|
|
|
38 |
)
|
39 |
|
40 |
-
processor = AutoProcessor.from_pretrained(
|
|
|
|
|
|
|
|
|
41 |
|
42 |
-
logger.info("Model loaded successfully!")
|
43 |
return True
|
44 |
|
45 |
except Exception as e:
|
46 |
-
logger.error(f"Error loading model: {str(e)}")
|
47 |
return False
|
48 |
|
49 |
# Initialize model at startup
|
50 |
model_loaded = load_model()
|
51 |
|
52 |
def analyze_medical_image(image, clinical_question, patient_history=""):
|
53 |
-
"""
|
54 |
-
Analyze medical image with clinical context
|
55 |
-
"""
|
56 |
global model, processor
|
57 |
|
58 |
# Check if model is loaded
|
59 |
if not model_loaded or model is None or processor is None:
|
60 |
-
return "β Model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
if image is None:
|
63 |
return "β οΈ Please upload a medical image first."
|
@@ -103,7 +137,6 @@ def analyze_medical_image(image, clinical_question, patient_history=""):
|
|
103 |
|
104 |
# Move to appropriate device
|
105 |
device = next(model.parameters()).device
|
106 |
-
dtype = next(model.parameters()).dtype
|
107 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
108 |
|
109 |
input_len = inputs["input_ids"].shape[-1]
|
@@ -129,7 +162,7 @@ def analyze_medical_image(image, clinical_question, patient_history=""):
|
|
129 |
|
130 |
# Add structured disclaimer
|
131 |
disclaimer = """
|
132 |
-
|
133 |
---
|
134 |
### β οΈ MEDICAL DISCLAIMER
|
135 |
**This analysis is for educational and research purposes only.**
|
@@ -162,6 +195,13 @@ def create_interface():
|
|
162 |
padding: 16px;
|
163 |
margin: 16px 0;
|
164 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
"""
|
166 |
) as demo:
|
167 |
|
@@ -179,17 +219,30 @@ def create_interface():
|
|
179 |
- π©Ί **Dermatology** - Skin lesions and conditions
|
180 |
""")
|
181 |
|
182 |
-
#
|
183 |
-
|
184 |
gr.Markdown("""
|
185 |
-
<div class="
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
|
|
|
|
|
|
190 |
</div>
|
191 |
""")
|
192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
with gr.Row():
|
194 |
# Left column - Inputs
|
195 |
with gr.Column(scale=1):
|
@@ -221,8 +274,12 @@ def create_interface():
|
|
221 |
analyze_btn = gr.Button("π Analyze Image", variant="primary", size="lg")
|
222 |
|
223 |
# Model status
|
|
|
|
|
|
|
224 |
gr.Markdown(f"""
|
225 |
-
**
|
|
|
226 |
**Model:** {MODEL_ID}
|
227 |
**Device:** {'CUDA' if torch.cuda.is_available() else 'CPU'}
|
228 |
""")
|
@@ -289,18 +346,10 @@ def create_interface():
|
|
289 |
# Footer information
|
290 |
gr.Markdown("""
|
291 |
---
|
292 |
-
###
|
293 |
|
294 |
MedGemma is Google's specialized medical AI model trained on medical imaging and clinical text.
|
295 |
-
|
296 |
-
- Multi-modal medical image analysis
|
297 |
-
- Clinical reasoning and differential diagnosis
|
298 |
-
- Structured medical reporting
|
299 |
-
- Educational medical content generation
|
300 |
-
|
301 |
-
**Supported Image Types:** JPEG, PNG, TIFF, DICOM (converted)
|
302 |
-
**Max Image Size:** 10MB
|
303 |
-
**Optimal Resolution:** 896x896 pixels (auto-resized)
|
304 |
|
305 |
### π Privacy & Data Policy
|
306 |
- **No data storage**: Images and text are processed in real-time and not saved
|
@@ -321,5 +370,5 @@ if __name__ == "__main__":
|
|
321 |
demo.launch(
|
322 |
server_name="0.0.0.0",
|
323 |
server_port=7860,
|
324 |
-
|
325 |
)
|
|
|
1 |
+
# app.py - MedGemma with Authentication
|
2 |
import gradio as gr
|
3 |
import torch
|
4 |
from transformers import AutoProcessor, AutoModelForImageTextToText
|
5 |
from PIL import Image
|
6 |
import os
|
7 |
import logging
|
8 |
+
from huggingface_hub import login
|
9 |
|
10 |
# Configure logging
|
11 |
logging.basicConfig(level=logging.INFO)
|
12 |
logger = logging.getLogger(__name__)
|
13 |
|
14 |
+
# Authenticate with Hugging Face
|
15 |
+
def authenticate_hf():
|
16 |
+
"""Authenticate with Hugging Face using token"""
|
17 |
+
try:
|
18 |
+
hf_token = os.getenv('HF_TOKEN')
|
19 |
+
if hf_token:
|
20 |
+
login(token=hf_token)
|
21 |
+
logger.info("β
Authenticated with Hugging Face")
|
22 |
+
return True
|
23 |
+
else:
|
24 |
+
logger.warning("β οΈ No HF_TOKEN found in environment")
|
25 |
+
return False
|
26 |
+
except Exception as e:
|
27 |
+
logger.error(f"β Authentication failed: {e}")
|
28 |
+
return False
|
29 |
+
|
30 |
# Model configuration
|
31 |
MODEL_ID = "google/medgemma-4b-it"
|
32 |
|
|
|
35 |
processor = None
|
36 |
|
37 |
def load_model():
|
38 |
+
"""Load model and processor with authentication"""
|
39 |
global model, processor
|
40 |
|
41 |
try:
|
42 |
+
# First authenticate
|
43 |
+
auth_success = authenticate_hf()
|
44 |
+
if not auth_success:
|
45 |
+
logger.error("β Authentication required for MedGemma")
|
46 |
+
return False
|
47 |
+
|
48 |
logger.info(f"Loading model: {MODEL_ID}")
|
49 |
|
50 |
# Check if CUDA is available
|
51 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
52 |
logger.info(f"Using device: {device}")
|
53 |
|
54 |
+
# Load model with authentication
|
55 |
model = AutoModelForImageTextToText.from_pretrained(
|
56 |
MODEL_ID,
|
57 |
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32,
|
58 |
device_map="auto" if device == "cuda" else None,
|
59 |
trust_remote_code=True,
|
60 |
+
low_cpu_mem_usage=True,
|
61 |
+
token=True # Use authenticated token
|
62 |
)
|
63 |
|
64 |
+
processor = AutoProcessor.from_pretrained(
|
65 |
+
MODEL_ID,
|
66 |
+
trust_remote_code=True,
|
67 |
+
token=True # Use authenticated token
|
68 |
+
)
|
69 |
|
70 |
+
logger.info("β
Model loaded successfully!")
|
71 |
return True
|
72 |
|
73 |
except Exception as e:
|
74 |
+
logger.error(f"β Error loading model: {str(e)}")
|
75 |
return False
|
76 |
|
77 |
# Initialize model at startup
|
78 |
model_loaded = load_model()
|
79 |
|
80 |
def analyze_medical_image(image, clinical_question, patient_history=""):
|
81 |
+
"""Analyze medical image with clinical context"""
|
|
|
|
|
82 |
global model, processor
|
83 |
|
84 |
# Check if model is loaded
|
85 |
if not model_loaded or model is None or processor is None:
|
86 |
+
return """β **Model Authentication Issue**
|
87 |
+
|
88 |
+
MedGemma requires authentication. Please ensure:
|
89 |
+
|
90 |
+
1. **HF_TOKEN is set**: The Space owner needs to add their Hugging Face token to Space Settings β Repository secrets
|
91 |
+
2. **Model access approved**: Make sure you have access to MedGemma at https://huggingface.co/google/medgemma-4b-it
|
92 |
+
3. **Space restart**: After adding the token, restart the Space
|
93 |
+
|
94 |
+
**Current Status**: Authentication failed - model cannot load without proper token."""
|
95 |
|
96 |
if image is None:
|
97 |
return "β οΈ Please upload a medical image first."
|
|
|
137 |
|
138 |
# Move to appropriate device
|
139 |
device = next(model.parameters()).device
|
|
|
140 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
141 |
|
142 |
input_len = inputs["input_ids"].shape[-1]
|
|
|
162 |
|
163 |
# Add structured disclaimer
|
164 |
disclaimer = """
|
165 |
+
|
166 |
---
|
167 |
### β οΈ MEDICAL DISCLAIMER
|
168 |
**This analysis is for educational and research purposes only.**
|
|
|
195 |
padding: 16px;
|
196 |
margin: 16px 0;
|
197 |
}
|
198 |
+
.auth-warning {
|
199 |
+
background-color: #fffbeb;
|
200 |
+
border: 1px solid #fed7aa;
|
201 |
+
border-radius: 8px;
|
202 |
+
padding: 16px;
|
203 |
+
margin: 16px 0;
|
204 |
+
}
|
205 |
"""
|
206 |
) as demo:
|
207 |
|
|
|
219 |
- π©Ί **Dermatology** - Skin lesions and conditions
|
220 |
""")
|
221 |
|
222 |
+
# Authentication status
|
223 |
+
if not model_loaded:
|
224 |
gr.Markdown("""
|
225 |
+
<div class="auth-warning">
|
226 |
+
π <strong>AUTHENTICATION REQUIRED</strong><br>
|
227 |
+
MedGemma model requires authentication. Please:
|
228 |
+
<ol>
|
229 |
+
<li>Ensure you have access to the model at <a href="https://huggingface.co/google/medgemma-4b-it">MedGemma page</a></li>
|
230 |
+
<li>Add your HF_TOKEN to Space Settings β Repository secrets</li>
|
231 |
+
<li>Restart the Space</li>
|
232 |
+
</ol>
|
233 |
</div>
|
234 |
""")
|
235 |
|
236 |
+
# Warning banner
|
237 |
+
gr.Markdown("""
|
238 |
+
<div class="disclaimer">
|
239 |
+
β οΈ <strong>IMPORTANT MEDICAL DISCLAIMER</strong><br>
|
240 |
+
This tool is for <strong>educational and research purposes only</strong>.
|
241 |
+
Do not upload real patient data or use for actual medical diagnosis.
|
242 |
+
Always consult qualified healthcare professionals.
|
243 |
+
</div>
|
244 |
+
""")
|
245 |
+
|
246 |
with gr.Row():
|
247 |
# Left column - Inputs
|
248 |
with gr.Column(scale=1):
|
|
|
274 |
analyze_btn = gr.Button("π Analyze Image", variant="primary", size="lg")
|
275 |
|
276 |
# Model status
|
277 |
+
auth_status = "β
Authenticated" if model_loaded else "π Authentication Required"
|
278 |
+
model_status = "β
Loaded" if model_loaded else "β Not Loaded"
|
279 |
+
|
280 |
gr.Markdown(f"""
|
281 |
+
**Authentication:** {auth_status}
|
282 |
+
**Model Status:** {model_status}
|
283 |
**Model:** {MODEL_ID}
|
284 |
**Device:** {'CUDA' if torch.cuda.is_available() else 'CPU'}
|
285 |
""")
|
|
|
346 |
# Footer information
|
347 |
gr.Markdown("""
|
348 |
---
|
349 |
+
### π¬ About MedGemma
|
350 |
|
351 |
MedGemma is Google's specialized medical AI model trained on medical imaging and clinical text.
|
352 |
+
**Note**: This model requires authentication and access approval.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
353 |
|
354 |
### π Privacy & Data Policy
|
355 |
- **No data storage**: Images and text are processed in real-time and not saved
|
|
|
370 |
demo.launch(
|
371 |
server_name="0.0.0.0",
|
372 |
server_port=7860,
|
373 |
+
show_error=True
|
374 |
)
|