File size: 7,918 Bytes
ea8a8db
3096cd6
c9d91fc
3096cd6
ea8a8db
c9d91fc
3096cd6
 
c9d91fc
497aad4
c9d91fc
 
3096cd6
 
c9d91fc
 
5cbfd6d
3096cd6
 
8753221
 
 
3096cd6
8753221
 
30fac12
8753221
30fac12
 
 
 
 
 
 
 
8753221
 
 
 
30fac12
 
a1a6bd3
8753221
30fac12
8753221
 
 
 
 
 
30fac12
8753221
 
30fac12
8753221
 
 
 
 
 
30fac12
8753221
 
 
 
 
 
 
 
 
 
30fac12
8753221
 
 
30fac12
8753221
30fac12
8753221
 
 
30fac12
0f1b622
30fac12
 
 
 
 
 
 
 
 
3f59421
30fac12
 
 
8753221
30fac12
 
 
 
3096cd6
 
8753221
3096cd6
8753221
 
3096cd6
 
 
8753221
3096cd6
 
 
 
 
 
 
 
8753221
 
 
3096cd6
 
8753221
ea8a8db
3096cd6
8753221
 
 
 
ea8a8db
8753221
 
3096cd6
 
8753221
 
 
 
52bfc48
8753221
 
 
3096cd6
 
 
 
 
 
 
 
 
 
 
 
8753221
a1a6bd3
3096cd6
 
 
 
 
8753221
ea8a8db
8753221
ea8a8db
8753221
3096cd6
 
8753221
 
 
 
3096cd6
 
ea8a8db
 
3096cd6
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import gradio as gr
import google.generativeai as genai
import os
from dotenv import load_dotenv

# βœ… Load environment variables (for local .env use)
load_dotenv()

# βœ… Fetch Gemini API Key (works for both local + Hugging Face + Render)
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

if not GEMINI_API_KEY:
    raise ValueError("❌ GEMINI_API_KEY not found. Please set it in your .env or Hugging Face secrets.")

# πŸ”Ή Configure Gemini client
genai.configure(api_key=GEMINI_API_KEY)
MODEL_ID = "gemini-2.0-flash"  # or gemini-1.5-flash for faster inference

# ---------------- AI Response Function ----------------
def respond(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc, lymphocytes,
            hemoglobin, pv, age, gender, height, weight):

    system_message = (
        "You are an AI Health Assistant that analyzes laboratory biomarkers "
        "and generates beautifully formatted, easy-to-read health summaries.\n\n"
    
        "FORMATTING RULES - EXTREMELY IMPORTANT:\n"
        "β€’ Use clear section headers with emojis\n"
        "β€’ Add blank lines between sections for better readability\n"
        "β€’ Use bullet points (β€’) instead of dashes\n"
        "β€’ Use bold (**text**) for emphasis on important values\n"
        "β€’ Use status emojis: 🟒 Normal | 🟑 Monitor | πŸ”΄ Needs Attention\n"
        "β€’ Keep paragraphs short (2-3 sentences max)\n"
        "β€’ Add visual separators (---) between major sections\n\n"
            
        "REQUIRED STRUCTURE:\n\n"
        "# πŸ“Š Your Health Report\n\n"
        "---\n\n"
        "## πŸ”¬ Biomarker Analysis Table\n\n"
        "| Biomarker          | Your Value | Status | What This Means              | Normal Range                                 |\n"
        "|--------------------|------------|--------|-----------------------------|----------------------------------------------|\n"
        "Include ALL biomarkers: Albumin, Creatinine, Glucose, CRP, MCV, RDW, ALP, WBC, Lymphocytes, Hemoglobin, Plasma Volume\n"
        "Use emojis in Status column: 🟒 Normal, 🟑 Borderline, πŸ”΄ High/Low\n\n"
        
        "---\n\n"
        "## πŸ“‹ Quick Summary\n\n"
        "### 🎯 Top 3 Health Priorities\n"
        "1. **[Priority 1]** - Brief explanation\n"
        "2. **[Priority 2]** - Brief explanation\n"
        "3. **[Priority 3]** - Brief explanation\n\n"
        
        "### βœ… What's Working Well\n"
        "β€’ List normal biomarkers and what they indicate\n\n"
        
        "---\n\n"
        "## πŸ₯ Detailed System Analysis\n\n"
        "For each system, use this format:\n"
        "### [Emoji] [System Name] - Status: [🟒/🟑/πŸ”΄]\n"
        "Brief explanation in simple language.\n\n"
        "Cover: Metabolic, Kidney, Blood Health, Immune System, Circulation\n\n"
        
        "---\n\n"
        "## πŸ’‘ Your Action Plan\n\n"
        "### πŸ₯— Nutrition Recommendations\n"
        "β€’ Specific dietary advice\n\n"
        "### πŸƒ Lifestyle Changes\n"
        "β€’ Exercise and daily habits\n\n"
        "### πŸ” Recommended Tests\n"
        "β€’ Follow-up tests to discuss with your doctor\n\n"
        "### πŸ‘¨β€βš•οΈ Medical Consultation\n"
        "β€’ When and why to see your healthcare provider\n\n"
        
        "---\n\n"
        "## ⚠️ Important Connections\n\n"
        "Highlight how different biomarkers relate to each other.\n\n"
        
        "---\n\n"
        "## πŸ“Œ Important Reminders\n\n"
        "β€’ This is an AI analysis, not a medical diagnosis\n"
        "β€’ Always consult your healthcare provider\n"
        "β€’ Bring this report to your next appointment\n\n"
        
        "NORMAL RANGE DEFINITIONS:\n"
        "β€’ **Glucose (fasting)**: 70–99 mg/dL β†’ <70: Low, 70–99: Normal, >99: High\n"
        "β€’ **Albumin**: 3.4–5.4 g/dL β†’ <3.4: Low, 3.4–5.4: Normal, >5.4: High\n"
        "β€’ **Creatinine**: 0.6–1.3 mg/dL β†’ <0.6: Low, 0.6–1.3: Normal, >1.3: High\n"
        "β€’ **RDW**: 11.5–14.5% β†’ <11.5: Low, 11.5–14.5: Normal, >14.5: High\n"
        "β€’ **Alkaline Phosphatase (ALP)**: 44–147 IU/L β†’ <44: Low, 44–147: Normal, >147: High\n"
        "β€’ **WBC Count**: 4.0–11.0 Γ—10⁹/L β†’ <4.0: Low, 4.0–11.0: Normal, >11.0: High\n"
        "β€’ **CRP**: <5 mg/L β†’ <1: Low, 1–5: Normal, >5: High\n"
        "β€’ **MCV**: 80–100 fL β†’ <80: Low, 80–100: Normal, >100: High\n"
        "β€’ **Hemoglobin**: 13.8–17.2 g/dL (men), 12.1–15.1 g/dL (women) β†’ Below or above these ranges: Low or High\n"
        "β€’ **Plasma Volume**: Approximately 50–55 mL/kg body weight β†’ Values outside this range may indicate fluid imbalances\n"
        "β€’ **Lymphocytes**: 1.0–3.0 Γ—10⁹/L β†’ <1.0: Low, 1.0–3.0: Normal, >3.0: High\n"
        "β€’ Units must be shown clearly in reports\n\n"
        
        "CONSTRAINTS:\n"
        "β€’ Never diagnose or prescribe medication\n"
        "β€’ Use simple, encouraging language\n"
        "β€’ Include reference ranges for all biomarkers\n"
        "β€’ Make the report visually scannable with emojis and formatting"
    )

    # ----- User Message -----
    user_message = (
        f"Patient Information:\n"
        f"- Age: {age} years\n"
        f"- Gender: {gender}\n"
        f"- Height: {height} cm\n"
        f"- Weight: {weight} kg\n\n"
        f"Biomarker Values:\n"
        f"- Albumin: {albumin} g/dL\n"
        f"- Creatinine: {creatinine} mg/dL\n"
        f"- Glucose: {glucose} mg/dL\n"
        f"- CRP: {crp} mg/L\n"
        f"- MCV: {mcv} fL\n"
        f"- RDW: {rdw} %\n"
        f"- ALP: {alp} U/L\n"
        f"- WBC: {wbc} x10^3/ΞΌL\n"
        f"- Lymphocytes: {lymphocytes} %\n"
        f"- Hemoglobin: {hemoglobin} g/dL\n"
        f"- Plasma(PV) (ML): {pv} ML"
    )

    # ----- Generate AI Response -----
    try:
        model = genai.GenerativeModel(MODEL_ID)
        prompt = f"{system_message}\n\n{user_message}"
        
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        return f"Error: {str(e)}\n\nPlease check the model name. Try running the list_models.py script first."


# ---------------- Gradio UI ----------------
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # πŸ₯ AI Health Assistant
        ### Powered by Gemini 2.0
        Get instant insights from your biomarker results with AI-powered analysis.
        """
    )

    with gr.Row():
        with gr.Column():
            albumin = gr.Textbox(label="Albumin (g/dL)", value="4.5")
            creatinine = gr.Textbox(label="Creatinine (mg/dL)", value="1.5")
            glucose = gr.Textbox(label="Glucose (mg/dL, fasting)", value="160")
            crp = gr.Textbox(label="CRP (mg/L)", value="2.5")
            mcv = gr.Textbox(label="MCV (fL)", value="150")
            rdw = gr.Textbox(label="RDW (%)", value="15")
            alp = gr.Textbox(label="ALP (U/L)", value="146")
            wbc = gr.Textbox(label="WBC (10^3/ΞΌL)", value="10.5")
            lymphocytes = gr.Textbox(label="Lymphocytes (%)", value="38")
            hemoglobin = gr.Textbox(label="Hemoglobin (g/dL)", value="13.5")
            pv = gr.Textbox(label="Plasma(PV) (ML)", value="3000")

        with gr.Column():
            age = gr.Textbox(label="Age (years)", value="30")
            gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
            height = gr.Textbox(label="Height (cm)", value="170")
            weight = gr.Textbox(label="Weight (kg)", value="65")

    output = gr.Markdown(label="AI Health Report")

    btn = gr.Button("Generate Report")
    btn.click(
        respond,
        inputs=[
            albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
            lymphocytes, hemoglobin, pv, age, gender, height, weight
        ],
        outputs=output
    )

if __name__ == "__main__":
    demo.launch()