Gemini / app.py
Muhammadidrees's picture
Update app.py
3f59421 verified
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()