import gradio as gr from transformers import pipeline from PIL import Image import torch import os import spaces # --- Initialize the Model Pipeline (As per your working example) --- print("Loading MedGemma model...") try: pipe = pipeline( "image-text-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 (Using the logic from your working example) --- @spaces.GPU() def analyze_symptoms(symptom_image: Image.Image, symptoms_text: str): """ Analyzes user's symptoms using the definitive calling convention demonstrated in the working X-ray analyzer example. """ 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: # --- DEFINITIVE MESSAGE CONSTRUCTION (from your example) --- system_prompt = ( "You are an expert, empathetic AI medical assistant. Analyze the potential " "medical condition based on the following information. Provide a list of " "possible conditions, your reasoning, and a clear, actionable next-steps plan. " "Start your analysis by describing the user-provided information." ) user_content = [] # The user's prompt text is always present. user_content.append({"type": "text", "text": symptoms_text}) # The actual PIL image object is added to the content list if it exists. if symptom_image: user_content.append({"type": "image", "image": symptom_image}) messages = [ {"role": "system", "content": [{"type": "text", "text": system_prompt}]}, {"role": "user", "content": user_content} ] generation_args = { "max_new_tokens": 512, "do_sample": True, "temperature": 0.7, } # --- DEFINITIVE PIPELINE CALL (from your example) --- # The entire messages structure is passed to the `text` argument. output = pipe(text=messages, **generation_args) # The result is the 'content' of the last generated message. result = output[0]["generated_text"][-1]["content"] 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.strip() + 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 (Your original, no changes needed) --- with gr.Blocks(theme=gr.themes.Soft(), title="AI Symptom Analyzer") as demo: gr.HTML("""
Advanced symptom analysis powered by Google's MedGemma AI