|
|
|
import gradio as gr |
|
import torch |
|
from transformers import AutoProcessor, AutoModelForImageTextToText |
|
from PIL import Image |
|
import os |
|
import logging |
|
from huggingface_hub import login |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
def authenticate_hf(): |
|
"""Authenticate with Hugging Face using token""" |
|
try: |
|
hf_token = os.getenv('HF_TOKEN') |
|
if hf_token: |
|
login(token=hf_token) |
|
logger.info("β
Authenticated with Hugging Face") |
|
return True |
|
else: |
|
logger.warning("β οΈ No HF_TOKEN found in environment") |
|
return False |
|
except Exception as e: |
|
logger.error(f"β Authentication failed: {e}") |
|
return False |
|
|
|
|
|
MODEL_ID = "google/medgemma-4b-it" |
|
|
|
|
|
model = None |
|
processor = None |
|
|
|
def load_model(): |
|
"""Load model and processor with authentication""" |
|
global model, processor |
|
|
|
try: |
|
|
|
auth_success = authenticate_hf() |
|
if not auth_success: |
|
logger.error("β Authentication required for MedGemma") |
|
return False |
|
|
|
logger.info(f"Loading model: {MODEL_ID}") |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
logger.info(f"Using device: {device}") |
|
|
|
|
|
model = AutoModelForImageTextToText.from_pretrained( |
|
MODEL_ID, |
|
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32, |
|
device_map="auto" if device == "cuda" else None, |
|
trust_remote_code=True, |
|
low_cpu_mem_usage=True, |
|
token=True |
|
) |
|
|
|
processor = AutoProcessor.from_pretrained( |
|
MODEL_ID, |
|
trust_remote_code=True, |
|
token=True |
|
) |
|
|
|
logger.info("β
Model loaded successfully!") |
|
return True |
|
|
|
except Exception as e: |
|
logger.error(f"β Error loading model: {str(e)}") |
|
return False |
|
|
|
|
|
model_loaded = load_model() |
|
|
|
def analyze_medical_image(image, clinical_question, patient_history=""): |
|
"""Analyze medical image with clinical context""" |
|
global model, processor |
|
|
|
|
|
if not model_loaded or model is None or processor is None: |
|
return """β **Model Authentication Issue** |
|
|
|
MedGemma requires authentication. Please ensure: |
|
|
|
1. **HF_TOKEN is set**: The Space owner needs to add their Hugging Face token to Space Settings β Repository secrets |
|
2. **Model access approved**: Make sure you have access to MedGemma at https://huggingface.co/google/medgemma-4b-it |
|
3. **Space restart**: After adding the token, restart the Space |
|
|
|
**Current Status**: Authentication failed - model cannot load without proper token.""" |
|
|
|
if image is None: |
|
return "β οΈ Please upload a medical image first." |
|
|
|
if not clinical_question.strip(): |
|
return "β οΈ Please provide a clinical question." |
|
|
|
try: |
|
|
|
messages = [ |
|
{ |
|
"role": "system", |
|
"content": [{"type": "text", "text": "You are MedGemma, an expert medical AI assistant specialized in medical image analysis. Provide detailed, structured analysis while emphasizing that this is for educational purposes only and should not replace professional medical diagnosis. Be thorough but clear in your explanations."}] |
|
} |
|
] |
|
|
|
|
|
user_content = [] |
|
|
|
|
|
if patient_history.strip(): |
|
user_content.append({"type": "text", "text": f"Patient History: {patient_history}\n\n"}) |
|
|
|
|
|
user_content.append({"type": "text", "text": f"Clinical Question: {clinical_question}"}) |
|
|
|
|
|
user_content.append({"type": "image", "image": image}) |
|
|
|
messages.append({ |
|
"role": "user", |
|
"content": user_content |
|
}) |
|
|
|
|
|
inputs = processor.apply_chat_template( |
|
messages, |
|
add_generation_prompt=True, |
|
tokenize=True, |
|
return_dict=True, |
|
return_tensors="pt" |
|
) |
|
|
|
|
|
device = next(model.parameters()).device |
|
inputs = {k: v.to(device) for k, v in inputs.items()} |
|
|
|
input_len = inputs["input_ids"].shape[-1] |
|
|
|
|
|
with torch.inference_mode(): |
|
generation = model.generate( |
|
**inputs, |
|
max_new_tokens=1500, |
|
do_sample=True, |
|
temperature=0.3, |
|
top_p=0.95, |
|
repetition_penalty=1.1, |
|
pad_token_id=processor.tokenizer.eos_token_id |
|
) |
|
generation = generation[0][input_len:] |
|
|
|
|
|
response = processor.decode(generation, skip_special_tokens=True) |
|
|
|
|
|
response = response.strip() |
|
|
|
|
|
disclaimer = """ |
|
|
|
--- |
|
### β οΈ MEDICAL DISCLAIMER |
|
**This analysis is for educational and research purposes only.** |
|
- This AI assistant is not a substitute for professional medical advice |
|
- Always consult qualified healthcare professionals for diagnosis and treatment |
|
- Do not make medical decisions based solely on this analysis |
|
- In case of medical emergency, contact emergency services immediately |
|
--- |
|
""" |
|
|
|
return response + disclaimer |
|
|
|
except Exception as e: |
|
logger.error(f"Error in analyze_medical_image: {str(e)}") |
|
return f"β Error processing request: {str(e)}\n\nPlease try again or contact support if the issue persists." |
|
|
|
|
|
def create_interface(): |
|
with gr.Blocks( |
|
title="MedGemma Medical Image Analysis", |
|
theme=gr.themes.Soft(), |
|
css=""" |
|
.gradio-container { |
|
max-width: 1200px !important; |
|
} |
|
.disclaimer { |
|
background-color: #fef2f2; |
|
border: 1px solid #fecaca; |
|
border-radius: 8px; |
|
padding: 16px; |
|
margin: 16px 0; |
|
} |
|
.auth-warning { |
|
background-color: #fffbeb; |
|
border: 1px solid #fed7aa; |
|
border-radius: 8px; |
|
padding: 16px; |
|
margin: 16px 0; |
|
} |
|
""" |
|
) as demo: |
|
|
|
|
|
gr.Markdown(""" |
|
# π₯ MedGemma Medical Image Analysis |
|
|
|
**Advanced Medical AI Assistant powered by Google's MedGemma-4B** |
|
|
|
This tool can analyze various medical imaging modalities including: |
|
- π« **Chest X-rays** - Pneumonia, COVID-19, lung pathology |
|
- π§ **CT Scans** - Brain, chest, abdomen imaging |
|
- π¬ **Histopathology** - Microscopic tissue analysis |
|
- ποΈ **Ophthalmology** - Retinal imaging, eye conditions |
|
- π©Ί **Dermatology** - Skin lesions and conditions |
|
""") |
|
|
|
|
|
if not model_loaded: |
|
gr.Markdown(""" |
|
<div class="auth-warning"> |
|
π <strong>AUTHENTICATION REQUIRED</strong><br> |
|
MedGemma model requires authentication. Please: |
|
<ol> |
|
<li>Ensure you have access to the model at <a href="https://huggingface.co/google/medgemma-4b-it">MedGemma page</a></li> |
|
<li>Add your HF_TOKEN to Space Settings β Repository secrets</li> |
|
<li>Restart the Space</li> |
|
</ol> |
|
</div> |
|
""") |
|
|
|
|
|
gr.Markdown(""" |
|
<div class="disclaimer"> |
|
β οΈ <strong>IMPORTANT MEDICAL DISCLAIMER</strong><br> |
|
This tool is for <strong>educational and research purposes only</strong>. |
|
Do not upload real patient data or use for actual medical diagnosis. |
|
Always consult qualified healthcare professionals. |
|
</div> |
|
""") |
|
|
|
with gr.Row(): |
|
|
|
with gr.Column(scale=1): |
|
gr.Markdown("## π€ Upload & Configure") |
|
|
|
image_input = gr.Image( |
|
label="Medical Image", |
|
type="pil", |
|
height=350, |
|
sources=["upload", "clipboard"] |
|
) |
|
|
|
clinical_question = gr.Textbox( |
|
label="Clinical Question *", |
|
placeholder="Examples:\nβ’ Describe the findings in this chest X-ray\nβ’ What pathological changes are visible?\nβ’ Provide differential diagnosis based on imaging\nβ’ Identify any abnormalities present", |
|
lines=4, |
|
max_lines=6 |
|
) |
|
|
|
patient_history = gr.Textbox( |
|
label="Patient History (Optional)", |
|
placeholder="Example: 65-year-old male presenting with chronic cough, shortness of breath, and chest pain. History of smoking for 30 years.", |
|
lines=3, |
|
max_lines=5 |
|
) |
|
|
|
with gr.Row(): |
|
clear_btn = gr.Button("ποΈ Clear All", variant="secondary") |
|
analyze_btn = gr.Button("π Analyze Image", variant="primary", size="lg") |
|
|
|
|
|
auth_status = "β
Authenticated" if model_loaded else "π Authentication Required" |
|
model_status = "β
Loaded" if model_loaded else "β Not Loaded" |
|
|
|
gr.Markdown(f""" |
|
**Authentication:** {auth_status} |
|
**Model Status:** {model_status} |
|
**Model:** {MODEL_ID} |
|
**Device:** {'CUDA' if torch.cuda.is_available() else 'CPU'} |
|
""") |
|
|
|
|
|
with gr.Column(scale=1): |
|
gr.Markdown("## π Medical Analysis Results") |
|
|
|
output = gr.Textbox( |
|
label="AI Medical Analysis", |
|
lines=25, |
|
max_lines=35, |
|
show_copy_button=True, |
|
placeholder="Upload an image and ask a clinical question to get started..." |
|
) |
|
|
|
|
|
gr.Markdown("## π‘ Example Use Cases") |
|
|
|
with gr.Accordion("Click to see example cases", open=False): |
|
examples = gr.Examples( |
|
examples=[ |
|
[ |
|
"https://upload.wikimedia.org/wikipedia/commons/c/c8/Chest_Xray_PA_3-8-2010.png", |
|
"Analyze this chest X-ray and describe any abnormal findings. Comment on the heart size, lung fields, and overall chest anatomy.", |
|
"Adult patient presenting with respiratory symptoms including cough and shortness of breath." |
|
], |
|
[ |
|
None, |
|
"What pathological changes are visible in this medical image? Provide a structured analysis including anatomical observations and potential diagnoses.", |
|
"Patient with acute onset symptoms" |
|
], |
|
[ |
|
None, |
|
"Perform a systematic review of this imaging study. Include: 1) Technical quality assessment, 2) Normal anatomical structures, 3) Abnormal findings, 4) Clinical significance.", |
|
"" |
|
], |
|
[ |
|
None, |
|
"Compare the findings in this image to normal anatomy. What are the key differences and what might they suggest clinically?", |
|
"Follow-up imaging for known condition" |
|
] |
|
], |
|
inputs=[image_input, clinical_question, patient_history], |
|
label="Click any example to load it" |
|
) |
|
|
|
|
|
analyze_btn.click( |
|
fn=analyze_medical_image, |
|
inputs=[image_input, clinical_question, patient_history], |
|
outputs=output, |
|
show_progress=True |
|
) |
|
|
|
def clear_all(): |
|
return None, "", "", "" |
|
|
|
clear_btn.click( |
|
fn=clear_all, |
|
outputs=[image_input, clinical_question, patient_history, output] |
|
) |
|
|
|
|
|
gr.Markdown(""" |
|
--- |
|
### π¬ About MedGemma |
|
|
|
MedGemma is Google's specialized medical AI model trained on medical imaging and clinical text. |
|
**Note**: This model requires authentication and access approval. |
|
|
|
### π Privacy & Data Policy |
|
- **No data storage**: Images and text are processed in real-time and not saved |
|
- **No patient data**: Use only synthetic, anonymized, or educational images |
|
- **Educational use**: This tool is designed for learning and research purposes |
|
|
|
### π Support |
|
For technical issues or questions, please create an issue in the [Hugging Face Space repository](https://huggingface.co/spaces). |
|
|
|
**Model**: Google MedGemma-4B | **Framework**: Transformers + Gradio | **License**: Apache 2.0 |
|
""") |
|
|
|
return demo |
|
|
|
|
|
if __name__ == "__main__": |
|
demo = create_interface() |
|
demo.launch( |
|
server_name="0.0.0.0", |
|
server_port=7860, |
|
show_error=True |
|
) |