Doctor_Twin / app.py
isana25's picture
Update app.py
aec8fe3 verified
import gradio as gr
from transformers import pipeline
import random
import threading
import time
# Load pretrained QA model once
qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2")
# Simulated vitals state
vitals = {
"heart_rate": 70,
"blood_pressure": 120
}
# Function to simulate vitals update
def simulate_vitals():
while True:
vitals["heart_rate"] = max(50, min(110, vitals["heart_rate"] + random.randint(-3, 3)))
vitals["blood_pressure"] = max(90, min(150, vitals["blood_pressure"] + random.randint(-4, 4)))
time.sleep(3)
# Start vitals simulation in a background thread
thread = threading.Thread(target=simulate_vitals, daemon=True)
thread.start()
def answer_question(question, context):
if not question.strip():
return "❗ Please enter a valid health-related question to get an answer."
input_data = {"question": question, "context": context if context.strip() else "medical symptoms and health conditions"}
result = qa_pipeline(input_data)
answer = result['answer']
score = result['score']
return f"🩺 Answer:\n{answer}\n\nπŸ” Confidence Score: {score:.2f}"
def get_vitals():
hr = vitals["heart_rate"]
bp = vitals["blood_pressure"]
alerts = []
if hr > 100:
alerts.append("⚠️ High heart rate detected!")
if bp > 140:
alerts.append("⚠️ High blood pressure detected!")
alert_text = "\n".join(alerts) if alerts else "βœ… Vitals are within normal range."
return f"πŸ’“ Heart Rate: {hr} bpm\n🩸 Blood Pressure (Systolic): {bp} mmHg\n\n{alert_text}"
with gr.Blocks(title="Doctor TWIN – Virtual Healthcare Companion") as demo:
gr.Markdown("# 🧠 Doctor TWIN – Your Virtual Healthcare Companion")
gr.Markdown(
"Welcome! This app helps you get instant answers to your health questions "
"and simulates monitoring of vital signs like heart rate and blood pressure.\n\n"
"**Use the tabs below to navigate between:**\n"
"- **Virtual Consultation:** Ask health-related questions and get AI-generated answers.\n"
"- **Monitoring & Alerts:** See simulated live vital signs and get alerts if values are out of range."
)
with gr.Tabs():
with gr.TabItem("Virtual Consultation"):
gr.Markdown(
"**How to use Virtual Consultation:**\n"
"1. Type a clear, health-related question.\n"
"2. Optionally provide additional context (like symptoms or relevant info).\n"
"3. Click **Get Answer** to receive an AI-generated response."
)
question_input = gr.Textbox(label="Your Health Question", lines=2, placeholder="e.g., What are common causes of fatigue?")
context_input = gr.Textbox(label="Additional Context (optional)", lines=4, placeholder="e.g., I feel tired mostly in the afternoon and have trouble sleeping.")
answer_output = gr.Textbox(label="Answer", lines=6, interactive=False)
submit_btn = gr.Button("Get Answer")
submit_btn.click(answer_question, inputs=[question_input, context_input], outputs=answer_output)
with gr.TabItem("Monitoring & Alerts"):
gr.Markdown(
"**Simulated Monitoring & Alerts:**\n"
"This section shows simulated vital signs data updating every few seconds.\n"
"Click **Refresh Vitals** to update the values.\n"
"Watch for alerts indicating if vitals exceed safe thresholds."
)
vitals_output = gr.Textbox(label="Simulated Vitals & Alerts", lines=6, interactive=False)
refresh_btn = gr.Button("Refresh Vitals")
refresh_btn.click(get_vitals, outputs=vitals_output)
# Initialize vitals output on load
vitals_output.value = get_vitals()
demo.launch()