Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,59 +1,117 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
# --- Initialize client securely ---
|
| 6 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 7 |
-
|
| 8 |
-
if not HF_TOKEN:
|
| 9 |
-
raise ValueError("❌ HF_TOKEN not found. Please set it in your Hugging Face Space secrets.")
|
| 10 |
-
|
| 11 |
-
client = OpenAI(
|
| 12 |
-
base_url="https://router.huggingface.co/v1",
|
| 13 |
-
api_key=HF_TOKEN,
|
| 14 |
-
)
|
| 15 |
-
|
| 16 |
-
# --- Chat handler ---
|
| 17 |
-
def chat_with_model(message, history):
|
| 18 |
-
# Build messages list safely
|
| 19 |
-
messages = []
|
| 20 |
-
|
| 21 |
-
if history:
|
| 22 |
-
for msg in history:
|
| 23 |
-
# Handle both dict and tuple formats
|
| 24 |
-
if isinstance(msg, dict):
|
| 25 |
-
# Keep only allowed keys
|
| 26 |
-
messages.append({
|
| 27 |
-
"role": msg.get("role", "user"),
|
| 28 |
-
"content": msg.get("content", "")
|
| 29 |
-
})
|
| 30 |
-
elif isinstance(msg, (list, tuple)) and len(msg) == 2:
|
| 31 |
-
messages.append({"role": "user", "content": msg[0]})
|
| 32 |
-
messages.append({"role": "assistant", "content": msg[1]})
|
| 33 |
-
|
| 34 |
-
# Add latest user message
|
| 35 |
-
messages.append({"role": "user", "content": message})
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
)
|
| 43 |
-
|
| 44 |
except Exception as e:
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
examples=["Hello!", "Tell me a joke.", "Explain AI in simple terms."],
|
| 55 |
-
type="messages", # required
|
| 56 |
-
)
|
| 57 |
|
| 58 |
if __name__ == "__main__":
|
| 59 |
-
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
import google.generativeai as genai
|
| 4 |
+
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
# --- Load API Key ---
|
| 7 |
+
load_dotenv()
|
| 8 |
+
api_key = os.getenv("AIzaSyB1l7od1mPJ3CdN1AVF509xtHx1unYqnww")
|
| 9 |
+
|
| 10 |
+
if not api_key:
|
| 11 |
+
raise ValueError("❌ GEMINI_API_KEY not found. Please set it in your .env or Hugging Face secrets.")
|
| 12 |
+
|
| 13 |
+
# --- Configure Gemini ---
|
| 14 |
+
genai.configure(api_key=api_key)
|
| 15 |
+
MODEL_ID = "gemini-1.5-pro" # or gemini-1.5-flash for faster inference
|
| 16 |
+
|
| 17 |
+
# ---------------- AI Response Function ----------------
|
| 18 |
+
def respond(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc, lymphocytes, age, gender, height, weight):
|
| 19 |
+
system_message = (
|
| 20 |
+
"You are an AI health assistant that only analyzes lab reports based on the given Levine Biomarkers "
|
| 21 |
+
"and generates clear, structured, and patient-friendly summaries.\n"
|
| 22 |
+
"Your role is to transform raw lab values into a structured medical report with actionable insights "
|
| 23 |
+
"but never recommend medicine and never calculate anything else.\n"
|
| 24 |
+
"Follow this exact output format:\n\n"
|
| 25 |
+
"Tabular Mapping\n"
|
| 26 |
+
"- This section must always include a Markdown table.\n"
|
| 27 |
+
"- The table must contain exactly four columns:\n"
|
| 28 |
+
"| Biomarker | Value | Status (Low/Normal/High) | AI-Inferred Insight |\n"
|
| 29 |
+
"- Include ALL 9 Levine biomarkers (Albumin, Creatinine, Glucose, CRP, MCV, RDW, ALP, WBC, Lymphocytes).\n"
|
| 30 |
+
"- The first row after the header must begin directly with 'Albumin'.\n"
|
| 31 |
+
"- Do NOT add any index numbers or empty rows.\n"
|
| 32 |
+
"- Each biomarker must appear exactly once as a separate row.\n\n"
|
| 33 |
+
"Executive Summary\n"
|
| 34 |
+
"- List Top 3 Priorities.\n"
|
| 35 |
+
"- Highlight Key Strengths.\n\n"
|
| 36 |
+
"System-Specific Analysis\n"
|
| 37 |
+
"- Status: “Optimal” | “Monitor” | “Needs Attention”.\n"
|
| 38 |
+
"- Write a 2–3 sentence explanation in plain language.\n\n"
|
| 39 |
+
"Personalized Action Plan\n"
|
| 40 |
+
"- Nutrition, Lifestyle, Medical, Testing.\n\n"
|
| 41 |
+
"Interaction Alerts\n"
|
| 42 |
+
"- Note possible interactions between lab markers.\n\n"
|
| 43 |
+
"Constraints:\n"
|
| 44 |
+
"- Never provide direct diagnosis, prescriptions, or medical treatment.\n"
|
| 45 |
+
"- Never give anything that isn't present in the input.\n"
|
| 46 |
+
"- Always recommend consulting a doctor.\n"
|
| 47 |
+
"- Don't show input in output.\n"
|
| 48 |
+
"- Also give normal reference ranges.\n"
|
| 49 |
+
"- Keep the language simple, clear, and supportive."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
user_message = (
|
| 53 |
+
f"Patient Info:\n"
|
| 54 |
+
f"- Age: {age}\n"
|
| 55 |
+
f"- Gender: {gender}\n"
|
| 56 |
+
f"- Height: {height} cm\n"
|
| 57 |
+
f"- Weight: {weight} kg\n\n"
|
| 58 |
+
f"Biomarkers:\n"
|
| 59 |
+
f"- Albumin: {albumin} g/dL\n"
|
| 60 |
+
f"- Creatinine: {creatinine} mg/dL\n"
|
| 61 |
+
f"- Glucose: {glucose} mg/dL\n"
|
| 62 |
+
f"- CRP: {crp} mg/L\n"
|
| 63 |
+
f"- MCV: {mcv} fL\n"
|
| 64 |
+
f"- RDW: {rdw} %\n"
|
| 65 |
+
f"- ALP: {alp} U/L\n"
|
| 66 |
+
f"- WBC: {wbc} x10^3/μL\n"
|
| 67 |
+
f"- Lymphocytes: {lymphocytes} %"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# --- Generate response ---
|
| 71 |
try:
|
| 72 |
+
model = genai.GenerativeModel(MODEL_ID)
|
| 73 |
+
response = model.generate_content(
|
| 74 |
+
[system_message, user_message],
|
| 75 |
+
generation_config=genai.GenerationConfig(
|
| 76 |
+
temperature=0.2,
|
| 77 |
+
top_p=0.9,
|
| 78 |
+
max_output_tokens=2000
|
| 79 |
+
),
|
| 80 |
)
|
| 81 |
+
return response.text.strip()
|
| 82 |
except Exception as e:
|
| 83 |
+
return f"⚠️ Error: {str(e)}"
|
| 84 |
+
|
| 85 |
+
# ---------------- Gradio UI ----------------
|
| 86 |
+
with gr.Blocks() as demo:
|
| 87 |
+
gr.Markdown("## 🧪 AI Health Assistant (Levine Biomarkers via Google Gemini 1.5 Pro)")
|
| 88 |
+
|
| 89 |
+
with gr.Row():
|
| 90 |
+
with gr.Column():
|
| 91 |
+
albumin = gr.Textbox(label="Albumin (g/dL)", value="4.5")
|
| 92 |
+
creatinine = gr.Textbox(label="Creatinine (mg/dL)", value="1.5")
|
| 93 |
+
glucose = gr.Textbox(label="Glucose (mg/dL, fasting)", value="160")
|
| 94 |
+
crp = gr.Textbox(label="CRP (mg/L)", value="2.5")
|
| 95 |
+
mcv = gr.Textbox(label="MCV (fL)", value="150")
|
| 96 |
+
rdw = gr.Textbox(label="RDW (%)", value="15")
|
| 97 |
+
alp = gr.Textbox(label="ALP (U/L)", value="146")
|
| 98 |
+
wbc = gr.Textbox(label="WBC (10^3/μL)", value="10.5")
|
| 99 |
+
lymphocytes = gr.Textbox(label="Lymphocytes (%)", value="38")
|
| 100 |
+
|
| 101 |
+
with gr.Column():
|
| 102 |
+
age = gr.Textbox(label="Age (years)", value="30")
|
| 103 |
+
gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
|
| 104 |
+
height = gr.Textbox(label="Height (cm)", value="170")
|
| 105 |
+
weight = gr.Textbox(label="Weight (kg)", value="60")
|
| 106 |
|
| 107 |
+
output = gr.Textbox(label="AI Health Report", lines=30)
|
| 108 |
+
btn = gr.Button("Generate Report")
|
| 109 |
|
| 110 |
+
btn.click(
|
| 111 |
+
respond,
|
| 112 |
+
inputs=[albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc, lymphocytes, age, gender, height, weight],
|
| 113 |
+
outputs=output
|
| 114 |
+
)
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
if __name__ == "__main__":
|
| 117 |
+
demo.launch()
|