Spaces:
Sleeping

Lab13_part2 / app.py
mariamarshad's picture
Update app.py
097dfd2 verified
Raw History Blame Contribute Delete
5.86 kB
import gradio as gr
# ---------------------------------------------
# REALISTIC DISEASE DATABASE
# (Weighted symptoms: key = 2 pts, secondary = 1 pt)
# ---------------------------------------------
conditions = {
"Flu": {
"key": ["Fever", "Body Ache", "Fatigue"],
"secondary": ["Cough", "Headache", "Sore Throat", "Nasal Congestion"],
"advice": "Rest, fluids, and paracetamol. Symptoms usually improve in 3–5 days."
},
"Common Cold": {
"key": ["Cough", "Nasal Congestion", "Sore Throat"],
"secondary": ["Headache", "Fatigue"],
"advice": "Warm fluids, rest, steam inhalation, and OTC cold medicine."
},
"COVID-19": {
"key": ["Fever", "Cough", "Fatigue"],
"secondary": ["Shortness of Breath", "Body Ache", "Headache"],
"advice": "Get tested. Isolate if possible. Monitor breathing."
},
"Migraine": {
"key": ["Headache"],
"secondary": ["Nausea", "Fatigue"],
"advice": "Rest in dark room, hydrate, use paracetamol if suitable."
},
"Dengue": {
"key": ["Fever", "Body Ache", "Headache"],
"secondary": ["Nausea"],
"advice": "Seek medical evaluation, avoid ibuprofen, maintain hydration."
},
"Malaria": {
"key": ["Fever", "Fatigue"],
"secondary": ["Body Ache", "Nausea"],
"advice": "Go for a malaria test urgently if you live in mosquito-prone areas."
},
"Food Poisoning": {
"key": ["Nausea", "Diarrhea"],
"secondary": ["Fever", "Abdominal Pain"],
"advice": "Hydrate with ORS, avoid solid food until symptoms ease."
},
"Sinus Infection": {
"key": ["Headache", "Nasal Congestion"],
"secondary": ["Sore Throat", "Fatigue"],
"advice": "Steam inhalation, hydration, see doctor if symptoms persist."
}
}
symptom_list = [
"Fever", "Cough", "Headache", "Fatigue", "Sore Throat",
"Shortness of Breath", "Nausea", "Body Ache", "Diarrhea",
"Chest Pain", "Nasal Congestion", "Abdominal Pain"
]
# ---------------------------------------------
# SMART DIAGNOSIS (NO PERCENTAGES)
# ---------------------------------------------
def diagnose(symptoms):
if not symptoms:
return "Select at least one symptom.", None
scores = {}
for disease, info in conditions.items():
score = 0
# key symptoms have high weight
for s in info["key"]:
if s in symptoms:
score += 2
# secondary symptoms mild weight
for s in info["secondary"]:
if s in symptoms:
score += 1
scores[disease] = score
# get highest scoring disease
top_disease = max(scores, key=scores.get)
# determine risk level
highest_score = scores[top_disease]
if highest_score <= 2:
risk = "LOW RISK"
elif highest_score <= 5:
risk = "MODERATE RISK"
else:
risk = "HIGH RISK"
result = f"""
## Medical Diagnosis Result
### **Most likely condition:** **{top_disease}**
### **Risk Level:** {risk}
**Why this diagnosis?**
Matched symptoms:
{" , ".join([s for s in symptoms])}
### **Recommended Action:**
{conditions[top_disease]['advice']}
*This system gives general guidance only. Always consult a real doctor for serious symptoms.*
"""
return result, top_disease
# ---------------------------------------------
# DOCTOR CHAT (context-aware)
# ---------------------------------------------
def doctor_chat(history, user_message, diagnosis):
if not user_message:
return history, ""
if diagnosis is None:
reply = "Please perform an analysis first so I can understand your condition."
else:
d = diagnosis.lower()
msg = user_message.lower()
if "medicine" in msg or "take" in msg:
if d == "flu":
reply = "For flu: paracetamol for fever, rest, fluids. Avoid antibiotics unless a doctor prescribes."
elif d == "common cold":
reply = "For common cold: antihistamines, steam inhalation and hydration help."
elif d == "migraine":
reply = "For migraine: rest in a dark room and use paracetamol if suitable."
elif d in ["dengue", "malaria"]:
reply = f"{diagnosis} requires proper testing. Do NOT self-medicate — see a doctor urgently."
else:
reply = f"For {diagnosis}: follow the recommended action on the main diagnosis panel."
else:
reply = f"I can help answer questions about your diagnosis of **{diagnosis}**. Ask about medicines, care, or when to see a doctor."
history = history or []
history.append(("user", user_message))
history.append(("assistant", reply))
return history, ""
# ---------------------------------------------
# GRADIO UI
# ---------------------------------------------
with gr.Blocks() as app:
gr.Markdown("# Advanced Medical Diagnosis System")
with gr.Row():
with gr.Column(scale=2):
symptoms = gr.CheckboxGroup(symptom_list, label="Select your symptoms")
analyze = gr.Button("Analyze Symptoms")
with gr.Column(scale=3):
result_md = gr.Markdown("Results will appear here.")
diagnosis_state = gr.State()
gr.Markdown("---")
gr.Markdown("## AI Doctor Chat")
chatbox = gr.Chatbot()
msg = gr.Textbox()
send = gr.Button("Send")
# connect functions
analyze.click(
diagnose,
inputs=[symptoms],
outputs=[result_md, diagnosis_state]
)
send.click(
doctor_chat,
inputs=[chatbox, msg, diagnosis_state],
outputs=[chatbox, msg]
)
msg.submit(
doctor_chat,
inputs=[chatbox, msg, diagnosis_state],
outputs=[chatbox, msg]
)
app.launch()