Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line8889909192939495969798991001011021031041051061071081091101111121131141151161171181192 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165import gradio as grfrom fpdf import FPDF# -----------------------------# Disease & Symptom Database# -----------------------------conditions = {"COVID-19": {"symptoms": {"Fever": 2, "Cough": 2, "Shortness of Breath": 3, "Fatigue": 1, "Body Ache": 1},"recommendation": "Get tested immediately and isolate."},"Flu": {"symptoms": {"Fever": 2, "Cough": 2, "Headache": 1, "Fatigue": 1, "Body Ache": 2},"recommendation": "Rest, hydration, and OTC flu medicine."},"Pneumonia": {"symptoms": {"Fever": 2, "Cough": 2, "Shortness of Breath": 3, "Chest Pain": 3, "Fatigue": 1},"recommendation": "Seek medical evaluation immediately."},"Sinus Infection": {"symptoms": {"Headache": 2, "Nasal Congestion": 3, "Sore Throat": 1},"recommendation": "Steam inhalation and nasal spray."},"Allergy": {"symptoms": {"Nasal Congestion": 2, "Sore Throat": 1, "Fatigue": 1},"recommendation": "Take antihistamines if needed."},"Migraine": {"symptoms": {"Headache": 3, "Nausea": 2, "Fatigue": 1},"recommendation": "Rest in a dark room and hydrate."},"Food Poisoning": {"symptoms": {"Nausea": 2, "Diarrhea": 3, "Fever": 1},"recommendation": "Hydrate and avoid solid foods temporarily."},"Dengue": {"symptoms": {"Fever": 3, "Body Ache": 3, "Headache": 2, "Nausea": 2},"recommendation": "Seek medical care (avoid ibuprofen)."},"Malaria": {"symptoms": {"Fever": 3, "Fatigue": 2, "Nausea": 2, "Body Ache": 3},"recommendation": "Urgent medical testing required."},"Gastritis": {"symptoms": {"Nausea": 2, "Abdominal Pain": 3, "Fatigue": 1},"recommendation": "Avoid spicy foods and caffeine."},"Common Cold": {"symptoms": {"Cough": 1, "Sore Throat": 1, "Nasal Congestion": 2},"recommendation": "Rest, warm fluids, and vitamin C."},"Stress / Fatigue": {"symptoms": {"Fatigue": 3, "Headache": 1, "Body Ache": 1},"recommendation": "Rest, hydrate, relax."}}symptom_list = ["Fever", "Cough", "Headache", "Fatigue", "Sore Throat","Shortness of Breath", "Nausea", "Body Ache", "Diarrhea","Chest Pain", "Nasal Congestion", "Abdominal Pain"]# -----------------------------# Diagnosis Function# -----------------------------def diagnose(*values):# values = list of slider severities in same order as symptom_listuser_symptoms = dict(zip(symptom_list, values))scores = {}for cond, info in conditions.items():total_weight = sum(info["symptoms"].values())score = 0for symptom, weight in info["symptoms"].items():score += user_symptoms.get(symptom, 0) * weightscores[cond] = round((score / total_weight) * 100, 1)sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)best_cond, best_score = sorted_scores[0]if best_score < 25:risk = "π’ LOW RISK"elif best_score < 60:1 unmodified lineelse:risk = "π΄ HIGH RISK"output = f"## π©Ί Diagnosis Results\n"output += f"### Overall Risk Level: **{risk}**\n\n"output += "### Top Possible Conditions:\n"for cond, score in sorted_scores[:4]:output += f"- **{cond}** β {score}%\n"output += f"\n### Recommendation:\n**{conditions[best_cond]['recommendation']}**"# Save full text for PDFreturn output, output# -----------------------------# Chatbot Function# -----------------------------def doctor_chat(history, message):reply = {"role": "assistant","content": f"Based on your earlier diagnosis, here is my advice:\n\n{message}\n\nAlways consult a real doctor if symptoms worsen."}history.append({"role": "user", "content": message})history.append(reply)return history, ""# -----------------------------# PDF Report# -----------------------------def generate_pdf(text):pdf = FPDF()pdf.add_page()2 unmodified linesfor line in text.split("\n"):pdf.multi_cell(0, 8, line)path = "/tmp/report.pdf"pdf.output(path)return path# -----------------------------# Gradio Interface# -----------------------------with gr.Blocks() as app:gr.Markdown("# π₯ Advanced Medical Diagnosis System")# Sliderssliders = []for s in symptom_list:sliders.append(gr.Slider(0, 3, step=1, label=s))diagnose_btn = gr.Button("π Diagnose")diagnosis_md = gr.Markdown()pdf_btn = gr.Button("π Download PDF Report")pdf_file = gr.File(label="Your PDF Diagnosis")# Chatbotchatbot = gr.Chatbot(type="messages", label="AI Medical Assistant")chat_input = gr.Textbox(placeholder="Ask a question...")send_btn = gr.Button("Send")# Logicdiagnose_btn.click(diagnose,inputs=sliders,outputs=[diagnosis_md, gr.State()])pdf_btn.click(generate_pdf,inputs=diagnosis_md,outputs=pdf_file)send_btn.click(doctor_chat,123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251262 unmodified lines129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import gradio as grfrom fpdf import FPDF# ----------------------------------------# Disease Database# ----------------------------------------conditions = {"COVID-19": {"symptoms": ["Fever", "Cough", "Shortness of Breath", "Fatigue", "Body Ache"],"recommendation": "Get tested immediately and isolate."},"Flu": {"symptoms": ["Fever", "Cough", "Headache", "Fatigue", "Body Ache"],"recommendation": "Rest, hydration, and OTC flu medicine."},"Pneumonia": {"symptoms": ["Fever", "Cough", "Shortness of Breath", "Chest Pain", "Fatigue"],"recommendation": "Seek medical evaluation immediately."},"Sinus Infection": {"symptoms": ["Headache", "Nasal Congestion", "Sore Throat"],"recommendation": "Steam inhalation and nasal spray."},"Allergy": {"symptoms": ["Nasal Congestion", "Sore Throat", "Fatigue"],"recommendation": "Take antihistamines if needed."},"Migraine": {"symptoms": ["Headache", "Nausea", "Fatigue"],"recommendation": "Rest in a dark room and hydrate."},"Food Poisoning": {"symptoms": ["Nausea", "Diarrhea", "Fever"],"recommendation": "Hydrate and avoid solid foods temporarily."},"Dengue": {"symptoms": ["Fever", "Body Ache", "Headache", "Nausea"],"recommendation": "Seek medical care (avoid ibuprofen)."},"Malaria": {"symptoms": ["Fever", "Fatigue", "Nausea", "Body Ache"],"recommendation": "Urgent medical testing required."},"Gastritis": {"symptoms": ["Nausea", "Abdominal Pain", "Fatigue"],"recommendation": "Avoid spicy foods and caffeine."},"Common Cold": {"symptoms": ["Cough", "Sore Throat", "Nasal Congestion"],"recommendation": "Rest, warm fluids, and vitamin C."},"Stress / Fatigue": {"symptoms": ["Fatigue", "Headache", "Body Ache"],"recommendation": "Rest, hydrate, relax."}}# All symptom optionssymptom_list = ["Fever", "Cough", "Headache", "Fatigue", "Sore Throat","Shortness of Breath", "Nausea", "Body Ache", "Diarrhea","Chest Pain", "Nasal Congestion", "Abdominal Pain"]# ----------------------------------------# Diagnosis Logic# ----------------------------------------def diagnose(selected_symptoms):if not selected_symptoms:return "β οΈ Please select at least one symptom.", ""scores = {}for disease, info in conditions.items():total = len(info["symptoms"])match = len(set(selected_symptoms) & set(info["symptoms"]))score = round((match / total) * 100, 1) # Now max = 100%scores[disease] = scoresorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)best_disease, best_score = sorted_scores[0]# Risk Levelsif best_score < 25:risk = "π’ LOW RISK"elif best_score < 60:1 unmodified lineelse:risk = "π΄ HIGH RISK"output = "## π©Ί Diagnosis Results\n"output += f"### Overall Risk Level: **{risk}**\n\n"output += "### Top Possible Conditions:\n"for cond, score in sorted_scores[:4]:output += f"- **{cond}** β {score}%\n"output += f"\n### Recommendation:\n**{conditions[best_disease]['recommendation']}**"return output, output# ----------------------------------------# Chatbot Logic# ----------------------------------------def doctor_chat(history, message):if not message:return history, ""reply = {"role": "assistant","content": "Based on your condition: " +"\n\n" + message +"\n\nβοΈ Always consult a real doctor for serious symptoms."}history.append({"role": "user", "content": message})history.append(reply)return history, ""# ----------------------------------------# PDF Generator# ----------------------------------------def generate_pdf(text):pdf = FPDF()pdf.add_page()2 unmodified linesfor line in text.split("\n"):pdf.multi_cell(0, 8, line)path = "/tmp/diagnosis_report.pdf"pdf.output(path)return path# ----------------------------------------# Gradio App UI# ----------------------------------------with gr.Blocks() as app:gr.Markdown("# π₯ Advanced Medical Diagnosis System")symptom_box = gr.CheckboxGroup(symptom_list,label="Select Symptoms",info="Choose all symptoms that apply.")diagnose_btn = gr.Button("π Diagnose")diagnosis_md = gr.Markdown()pdf_btn = gr.Button("π Download PDF Report")pdf_file = gr.File(label="Your PDF")gr.Markdown("## π€ AI Medical Assistant Chat")chatbot = gr.Chatbot(type="messages")chat_input = gr.Textbox(placeholder="Ask the AI doctor...")send_btn = gr.Button("Send")diagnose_btn.click(diagnose, inputs=symptom_box, outputs=[diagnosis_md, gr.State()])pdf_btn.click(generate_pdf, inputs=diagnosis_md, outputs=pdf_file)send_btn.click(doctor_chat,
app.py+64-65