Spaces:
Sleeping

File size: 5,858 Bytes
553274c
 
739d512
 
 
 
553274c
 
739d512
 
 
553274c
739d512
 
 
 
553274c
739d512
 
 
 
553274c
4a9bf12
739d512
 
 
553274c
 
739d512
 
 
553274c
 
739d512
 
 
4a9bf12
739d512
 
 
 
4a9bf12
739d512
 
 
 
553274c
 
 
4a9bf12
553274c
 
4a9bf12
553274c
 
 
739d512
 
 
 
 
097dfd2
553274c
739d512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097dfd2
739d512
097dfd2
4a9bf12
097dfd2
4a9bf12
739d512
097dfd2
739d512
 
7328357
739d512
 
4a9bf12
739d512
4a9bf12
739d512
 
4a9bf12
097dfd2
739d512
7328357
739d512
7328357
 
739d512
 
 
 
55b1062
739d512
7328357
739d512
 
55b1062
739d512
 
 
 
 
 
 
 
 
 
 
 
55b1062
739d512
55b1062
739d512
553274c
739d512
 
 
553274c
739d512
553274c
 
739d512
 
 
55b1062
097dfd2
7328357
55b1062
 
739d512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a9bf12
553274c
739d512
 
 
 
 
 
 
 
 
 
55b1062
4a9bf12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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()