Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
from PIL import Image | |
import torch | |
import os | |
import spaces | |
# --- Initialize the Model Pipeline (No changes) --- | |
print("Loading MedGemma model...") | |
try: | |
pipe = pipeline( | |
"image-to-text", | |
model="google/medgemma-4b-it", | |
torch_dtype=torch.bfloat16, | |
device_map="auto", | |
token=os.environ.get("HF_TOKEN") | |
) | |
model_loaded = True | |
print("Model loaded successfully!") | |
except Exception as e: | |
model_loaded = False | |
print(f"Error loading model: {e}") | |
# --- Core Analysis Function (Final Corrected Version) --- | |
def analyze_symptoms(symptom_image: Image.Image, symptoms_text: str): | |
""" | |
Analyzes user's symptoms using the recommended chat format and correct | |
parameter passing for the MedGemma multimodal model. | |
""" | |
if not model_loaded: | |
return "Error: The AI model could not be loaded. Please check the Space logs." | |
symptoms_text = symptoms_text.strip() if symptoms_text else "" | |
if symptom_image is None and not symptoms_text: | |
return "Please describe your symptoms or upload an image for analysis." | |
try: | |
# --- CHAT-BASED PROMPT LOGIC (Unchanged) --- | |
system_instruction = ( | |
"You are an expert, empathetic AI medical assistant. " | |
"Analyze the potential medical condition based on the user's input. " | |
"Provide a list of possible conditions, your reasoning, and a clear, " | |
"actionable next-steps plan. Begin your analysis by describing the information " | |
"the user provided." | |
) | |
user_content = [] | |
text_to_send = symptoms_text if symptoms_text else "Please analyze this medical image." | |
user_content.append({"type": "text", "text": text_to_send}) | |
if symptom_image: | |
user_content.append({"type": "image", "image": symptom_image}) | |
messages = [ | |
{"role": "system", "content": system_instruction}, | |
{"role": "user", "content": user_content}, | |
] | |
print("Generating pipeline output with chat format...") | |
# --- DEFINITIVE PIPELINE CALL --- | |
# All text-generation parameters must be nested within a 'generate_kwargs' dictionary. | |
generate_kwargs = { | |
"max_new_tokens": 512, | |
"do_sample": True, | |
"temperature": 0.7, | |
} | |
# The `messages` list is the primary argument. | |
# `generate_kwargs` is a dedicated keyword argument for generation options. | |
output = pipe(messages, generate_kwargs=generate_kwargs) | |
print("Pipeline Output:", output) | |
# --- OUTPUT PROCESSING (Unchanged) --- | |
if output and isinstance(output, list) and output[0].get('generated_text'): | |
full_conversation = output[0]['generated_text'] | |
assistant_message = full_conversation[-1] | |
if assistant_message['role'] == 'assistant': | |
result = assistant_message['content'] | |
else: | |
result = str(assistant_message) | |
else: | |
result = "The model did not return a valid response. Please try again." | |
disclaimer = "\n\n***Disclaimer: I am an AI assistant and not a medical professional. This is not a diagnosis. Please consult a doctor for any health concerns.***" | |
return result + disclaimer | |
except Exception as e: | |
print(f"An exception occurred during analysis: {type(e).__name__}: {e}") | |
return f"An error occurred during analysis. Please check the logs for details: {str(e)}" | |
# --- Gradio Interface (No changes needed) --- | |
with gr.Blocks(theme=gr.themes.Soft(), title="AI Symptom Analyzer") as demo: | |
gr.HTML(""" | |
<div style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem; border-radius: 10px; margin-bottom: 2rem;"> | |
<h1>๐ฉบ AI Symptom Analyzer</h1> | |
<p>Advanced symptom analysis powered by Google's MedGemma AI</p> | |
</div> | |
""") | |
gr.HTML(""" | |
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 1rem; margin: 1rem 0; color: #856404;"> | |
<strong>โ ๏ธ Medical Disclaimer:</strong> This AI tool is for informational purposes only and is not a substitute for professional medical diagnosis or treatment. | |
</div> | |
""") | |
with gr.Row(equal_height=True): | |
with gr.Column(scale=1): | |
gr.Markdown("### 1. Describe Your Symptoms") | |
symptoms_input = gr.Textbox( | |
label="Symptoms", | |
placeholder="e.g., 'I have a rash on my arm that is red and itchy...'", lines=5) | |
gr.Markdown("### 2. Upload an Image (Optional)") | |
image_input = gr.Image(label="Symptom Image", type="pil", height=300) | |
with gr.Row(): | |
clear_btn = gr.Button("๐๏ธ Clear All", variant="secondary") | |
analyze_btn = gr.Button("๐ Analyze Symptoms", variant="primary", size="lg") | |
with gr.Column(scale=1): | |
gr.Markdown("### ๐ Analysis Report") | |
output_text = gr.Textbox( | |
label="AI Analysis", lines=25, show_copy_button=True, placeholder="Analysis results will appear here...") | |
def clear_all(): | |
return None, "", "" | |
analyze_btn.click(fn=analyze_symptoms, inputs=[image_input, symptoms_input], outputs=output_text) | |
clear_btn.click(fn=clear_all, outputs=[image_input, symptoms_input, output_text]) | |
if __name__ == "__main__": | |
print("Starting Gradio interface...") | |
demo.launch(debug=True) | |