File size: 4,463 Bytes
87ffd91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import os
import google.generativeai as genai
import gradio as gr

from dotenv import load_dotenv
from PIL import Image
##############commands######################
#python3 -m venv venv
#source venv/bin/activate
#pip install google-generativeai gradio python-dotenv pillow
###########################################
# 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, top_p ):
    """

    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")
           
            # Configure the Google AI library
            temperature_slider = gr.Slider(
                minimum=0.0,
                maximum=1.0,
                value=0.7,
                step=0.05,
                label="🔥 Temperature (Creativity Level)"
            )

            top_p_slider = gr.Slider(
                 minimum=0.0,
                 maximum=1.0,
                 value=0.9,
                 step=0.05,
                 label="🎯 Top-p (Response Diversity)"
            )

        # Right Column: Output
        with gr.Column():
            output_box = gr.Markdown(label="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, temperature_slider, top_p_slider], 
        outputs=output_box
    )
print("App is  Launching...")
# 5. LAUNCH THE APP
# -----------------
demo.launch()