File size: 3,606 Bytes
6d22265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5de2833
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import os
import google.generativeai as genai
import gradio as gr

from dotenv import load_dotenv
from PIL import Image


# 1. SETUP API KEY
# ----------------
# Load environment variables from the .env file (for local development)
load_dotenv()

# Fetch the key. If running on Hugging Face, it will look in their 'Secrets'.
api_key = os.getenv("GEMINI_API_KEY")

if not api_key:
    raise ValueError("API Key not found. Please set GEMINI_API_KEY in .env or Secrets.")

# Configure the Google AI library
genai.configure(api_key=api_key)

def analyze_symptoms(text_input, image_input , temperature=0.7, top_p=0.6 ):
    """
    This function takes text and an image, sends them to Gemini,
    and returns the medical analysis.
    """
    
    # Validation: Ensure at least one input is provided
    if not text_input and not image_input:
        return "Please provide a description or an image."

    # Initialize the model
    # 'gemini-1.5-flash' is excellent for multimodal tasks (fast & accurate).
    model = genai.GenerativeModel('gemini-2.5-flash')
    generation_config = genai.types.GenerationConfig(
        temperature=temperature,
        top_p=top_p
    )
    
    # Create the System Prompt
    # We must instruct the AI to act like a doctor but be safe.
    prompt_text = (
        "You are an AI medical assistant. "
        "Analyze the following symptoms and the provided image (if any). "
        "Provide potential causes and home remedies. "
        "IMPORTANT: You must start your response with a clear disclaimer "
        "that you are an AI and this is not professional medical advice."
        f"\n\nPatient Description: {text_input}"
    )

    # Prepare the content for Gemini
    # Gemini accepts a list containing text and/or image data.
    content = [prompt_text]
    if image_input: 
        content.append(image_input)

    try:
        # Generate content
        response = model.generate_content(content , generation_config=generation_config)
        return response.text
    except Exception as e:
        return f"Error: {str(e)}"
 
# Blocks allows us to build complex layouts (Rows, Columns, etc.)
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    
    # Header
    gr.Markdown("# 🏥 AI Health Symptom Checker")
    gr.Markdown("Describe your symptoms and upload an image (e.g., a rash, sore throat) for preliminary analysis.")

    # Layout: Use a Row to put inputs side-by-side (on large screens)
    with gr.Row():
        # Left Column: Inputs
        with gr.Column():
            symptoms = gr.Textbox(
                label="Describe your symptoms",
                placeholder="E.g., I've had a headache and sore throat for 2 days...",
                lines=4
            )
            # The type='pil' ensures the image is ready for the Python Pillow library
            img_upload = gr.Image(label="Upload Image (Optional)", type="pil")
            
            # Custom Button
            submit_btn = gr.Button("Analyze Symptoms", variant="primary")

        # Right Column: Output
        with gr.Column():
            output_box = gr.Markdown("AI Analysis")

    # 4. CONNECTING LOGIC (Event Listeners)
    # -------------------------------------
    # When the button is clicked, run 'analyze_symptoms'
    # Inputs: [symptoms, img_upload] -> correspond to function arguments
    # Outputs: [output_box] -> where the result goes
    submit_btn.click(
        fn=analyze_symptoms, 
        inputs=[symptoms, img_upload], 
        outputs=output_box
    )
print("App is  Launching...")
# 5. LAUNCH THE APP
# -----------------
demo.launch(share=True)