Dacthex commited on
Commit
a58a0a2
·
verified ·
1 Parent(s): 344a069

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -58
app.py CHANGED
@@ -1,33 +1,27 @@
1
  import gradio as gr
 
 
2
 
3
  # ===========================
4
  # Malaria Symptom Rules
5
  # ===========================
6
  malaria_rules = {
7
- "fever": {
8
- "diagnosis": ["Patient may have malaria.", "Consider differential: viral infection, bacterial infection."],
9
- "treatment": ["Recommend antimalarial therapy as appropriate."],
10
- "prognosis": ["Mild if treated early."]
11
- },
12
- "chills": {
13
- "diagnosis": ["Chills often accompany malaria fever.", "Monitor for shaking chills indicating severe malaria."],
14
- "treatment": ["Supportive care, hydration, and antipyretics as needed."],
15
- "prognosis": ["Typically resolves with treatment."]
16
- },
17
- "headache": {"diagnosis": ["Common in malaria patients."], "treatment": ["Analgesics as needed."], "prognosis": ["Improves with treatment."]},
18
- "nausea": {"diagnosis": ["May indicate malaria or gastrointestinal infection."], "treatment": ["Anti-nausea medications if severe."], "prognosis": ["Resolves with malaria treatment."]},
19
- "vomiting": {"diagnosis": ["May indicate severe malaria if combined with fever."], "treatment": ["Consider oral or IV hydration."], "prognosis": ["Monitor for dehydration."]},
20
- "muscle_aches": {"diagnosis": ["Common symptom of malaria."], "treatment": ["Analgesics if necessary."], "prognosis": ["Improves with antimalarial therapy."]},
21
- "fatigue": {"diagnosis": ["Common symptom, may persist during recovery."], "treatment": ["Rest and supportive care."], "prognosis": ["Gradual improvement expected."]},
22
- "sweating": {"diagnosis": ["Sweating often follows fever spikes."], "treatment": ["Supportive care."], "prognosis": ["Normalizes with treatment."]},
23
- "anemia": {"diagnosis": ["Severe malaria can cause hemolytic anemia."], "treatment": ["Monitor hemoglobin; blood transfusion if critical."], "prognosis": ["Serious if untreated."]},
24
- "jaundice": {"diagnosis": ["May indicate liver involvement; risk for severe malaria."], "treatment": ["Monitor liver function, supportive care."], "prognosis": ["Can be severe if untreated."]},
25
- "seizures": {"diagnosis": ["Cerebral malaria, medical emergency."], "treatment": ["Immediate hospitalization, IV antimalarials."], "prognosis": ["Life-threatening without prompt care."]},
26
  # Combined symptom rules
27
- ("fever", "chills"): {"diagnosis": ["Classic malaria presentation."], "treatment": ["Prompt antimalarial therapy."], "prognosis": ["Good if treated early."]},
28
- ("fever", "vomiting"): {"diagnosis": ["Possible severe malaria."], "treatment": ["Monitor hydration, antimalarials."], "prognosis": ["Serious if untreated."]},
29
- ("jaundice", "anemia"): {"diagnosis": ["Severe malaria with liver involvement."], "treatment": ["Hospitalization recommended."], "prognosis": ["Severe, close monitoring required."]},
30
- ("seizures", "fever"): {"diagnosis": ["Cerebral malaria; emergency."], "treatment": ["Immediate IV therapy and ICU support."], "prognosis": ["Life-threatening."]},
31
  }
32
 
33
  # ===========================
@@ -37,57 +31,71 @@ def analyze_malaria(symptoms):
37
  diagnosis = set()
38
  treatment = set()
39
  prognosis = set()
40
- # Check combined symptoms first
41
  for combo in [k for k in malaria_rules if isinstance(k, tuple)]:
42
  if all(sym in symptoms for sym in combo):
43
  diagnosis.update(malaria_rules[combo]["diagnosis"])
44
  treatment.update(malaria_rules[combo]["treatment"])
45
  prognosis.update(malaria_rules[combo]["prognosis"])
46
- # Check single symptoms
47
  for sym in symptoms:
48
  if sym in malaria_rules:
49
  diagnosis.update(malaria_rules[sym]["diagnosis"])
50
  treatment.update(malaria_rules[sym]["treatment"])
51
  prognosis.update(malaria_rules[sym]["prognosis"])
52
- return {"Diagnosis": "\n".join(diagnosis) if diagnosis else "No malaria-related diagnosis detected.",
53
- "Treatment": "\n".join(treatment) if treatment else "No treatment recommended.",
54
- "Prognosis": "\n".join(prognosis) if prognosis else "No prognosis available."}
 
 
55
 
56
- def run_analysis(age, gender, location, travel, travel_details, symptoms_list,
57
- temperature, blood_pressure, heart_rate, previous_malaria, medications, additional_notes):
 
 
 
58
 
59
- symptoms = symptoms_list
60
- result = analyze_malaria(symptoms)
61
-
62
- severity = "Mild"
63
- color = "#10B981"
64
- if all(sym in symptoms for sym in ["seizures", "fever"]):
65
- severity = "Life-threatening"
66
- color = "#EF4444"
67
- elif all(sym in symptoms for sym in ["jaundice", "anemia"]):
68
- severity = "Severe"
69
- color = "#F97316"
70
-
71
- alert_banner = f"<div style='border-radius:0.5rem; padding:1rem; background-color:{color}; color:white; font-weight:bold; margin-bottom:1rem;'>⚠️ Severity Alert: {severity}</div>"
 
 
 
 
 
 
72
 
73
- diag_output = f"{alert_banner}<b>Diagnosis:</b><br>{result['Diagnosis'].replace(chr(10), '<br>')}"
74
- treat_output = f"{alert_banner}<b>Treatment:</b><br>{result['Treatment'].replace(chr(10), '<br>')}"
75
- prog_output = f"{alert_banner}<b>Prognosis:</b><br>{result['Prognosis'].replace(chr(10), '<br>')}"
76
 
77
  return diag_output, treat_output, prog_output
78
 
79
  # ===========================
80
- # Gradio UI (Tailwind-inspired)
81
  # ===========================
82
- symptoms_options = ["fever", "chills", "headache", "nausea", "vomiting",
83
- "muscle_aches", "fatigue", "sweating", "anemia", "jaundice", "seizures"]
84
 
85
  with gr.Blocks(css="""
86
- body {background-color:#F9FAFB;}
87
- .card {border-radius:1rem; box-shadow:0 10px 25px rgba(0,0,0,0.1); background:white; padding:1.5rem;}
88
- .header {background:linear-gradient(135deg,#667eea 0%,#764ba2 100%); color:white; padding:2rem; text-align:center; border-radius:1rem; margin-bottom:1rem;}
89
- .btn {background-color:#5D5CDE; color:white; padding:0.75rem 1.5rem; border-radius:0.75rem; font-weight:bold;}
 
 
 
90
  """) as demo:
 
91
  gr.HTML("<div class='header'><h1 class='text-4xl font-bold'>🦟 Malaria AI Assistant</h1><p>Advanced diagnostic, treatment, and prognostic analysis</p></div>")
92
 
93
  with gr.Row():
@@ -98,7 +106,7 @@ with gr.Blocks(css="""
98
  location = gr.Textbox(label="Location")
99
  travel = gr.Checkbox(label="Recent Travel to Endemic Areas")
100
  travel_details = gr.Textbox(label="Travel Details")
101
- symptoms_list = gr.CheckboxGroup(symptoms_options, label="Symptoms")
102
  temperature = gr.Number(label="Temperature (°C)")
103
  blood_pressure = gr.Textbox(label="Blood Pressure")
104
  heart_rate = gr.Number(label="Heart Rate")
@@ -108,13 +116,13 @@ with gr.Blocks(css="""
108
 
109
  with gr.Column(scale=1):
110
  with gr.Group(elem_classes="card"):
111
- diag_output = gr.HTML(label="Diagnosis")
112
- treat_output = gr.HTML(label="Treatment")
113
- prog_output = gr.HTML(label="Prognosis")
114
 
115
  run_btn = gr.Button("Run Analysis", elem_classes="btn")
116
  run_btn.click(
117
- run_analysis,
118
  inputs=[age, gender, location, travel, travel_details, symptoms_list,
119
  temperature, blood_pressure, heart_rate, previous_malaria,
120
  medications, additional_notes],
 
1
  import gradio as gr
2
+ import time
3
+ from threading import Thread
4
 
5
  # ===========================
6
  # Malaria Symptom Rules
7
  # ===========================
8
  malaria_rules = {
9
+ "fever": {"diagnosis":["Patient may have malaria."],"treatment":["Recommend antimalarial therapy."],"prognosis":["Mild if treated early."]},
10
+ "chills": {"diagnosis":["Chills often accompany malaria fever."],"treatment":["Supportive care, hydration, antipyretics."],"prognosis":["Typically resolves with treatment."]},
11
+ "headache": {"diagnosis":["Common in malaria patients."],"treatment":["Analgesics as needed."],"prognosis":["Improves with treatment."]},
12
+ "nausea": {"diagnosis":["May indicate malaria or gastrointestinal infection."],"treatment":["Anti-nausea medications if severe."],"prognosis":["Resolves with malaria treatment."]},
13
+ "vomiting": {"diagnosis":["May indicate severe malaria if combined with fever."],"treatment":["Consider oral or IV hydration."],"prognosis":["Monitor for dehydration."]},
14
+ "muscle_aches": {"diagnosis":["Common symptom of malaria."],"treatment":["Analgesics if necessary."],"prognosis":["Improves with antimalarial therapy."]},
15
+ "fatigue": {"diagnosis":["Common symptom, may persist during recovery."],"treatment":["Rest and supportive care."],"prognosis":["Gradual improvement expected."]},
16
+ "sweating": {"diagnosis":["Sweating often follows fever spikes."],"treatment":["Supportive care."],"prognosis":["Normalizes with treatment."]},
17
+ "anemia": {"diagnosis":["Severe malaria can cause hemolytic anemia."],"treatment":["Monitor hemoglobin; blood transfusion if critical."],"prognosis":["Serious if untreated."]},
18
+ "jaundice": {"diagnosis":["May indicate liver involvement; risk for severe malaria."],"treatment":["Monitor liver function, supportive care."],"prognosis":["Can be severe if untreated."]},
19
+ "seizures": {"diagnosis":["Cerebral malaria, medical emergency."],"treatment":["Immediate hospitalization, IV antimalarials."],"prognosis":["Life-threatening without prompt care."]},
 
 
 
 
 
 
 
 
20
  # Combined symptom rules
21
+ ("fever","chills"): {"diagnosis":["Classic malaria presentation."],"treatment":["Prompt antimalarial therapy."],"prognosis":["Good if treated early."]},
22
+ ("fever","vomiting"): {"diagnosis":["Possible severe malaria."],"treatment":["Monitor hydration, antimalarials."],"prognosis":["Serious if untreated."]},
23
+ ("jaundice","anemia"): {"diagnosis":["Severe malaria with liver involvement."],"treatment":["Hospitalization recommended."],"prognosis":["Severe, close monitoring required."]},
24
+ ("seizures","fever"): {"diagnosis":["Cerebral malaria; emergency."],"treatment":["Immediate IV therapy and ICU support."],"prognosis":["Life-threatening."]}
25
  }
26
 
27
  # ===========================
 
31
  diagnosis = set()
32
  treatment = set()
33
  prognosis = set()
34
+ # Combined symptoms first
35
  for combo in [k for k in malaria_rules if isinstance(k, tuple)]:
36
  if all(sym in symptoms for sym in combo):
37
  diagnosis.update(malaria_rules[combo]["diagnosis"])
38
  treatment.update(malaria_rules[combo]["treatment"])
39
  prognosis.update(malaria_rules[combo]["prognosis"])
40
+ # Single symptoms
41
  for sym in symptoms:
42
  if sym in malaria_rules:
43
  diagnosis.update(malaria_rules[sym]["diagnosis"])
44
  treatment.update(malaria_rules[sym]["treatment"])
45
  prognosis.update(malaria_rules[sym]["prognosis"])
46
+ return {
47
+ "Diagnosis": "\n".join(diagnosis) if diagnosis else "No malaria-related diagnosis detected.",
48
+ "Treatment": "\n".join(treatment) if treatment else "No treatment recommended.",
49
+ "Prognosis": "\n".join(prognosis) if prognosis else "No prognosis available."
50
+ }
51
 
52
+ def run_analysis_with_loading(age, gender, location, travel, travel_details, symptoms_list,
53
+ temperature, blood_pressure, heart_rate, previous_malaria, medications, additional_notes):
54
+ # Show loading dots first
55
+ loading_html = "<div style='text-align:center; font-size:1.5rem;'><div>🤖 AI is analyzing patient data<span id='dots'>...</span></div></div>"
56
+ diag_output = treat_output = prog_output = loading_html
57
 
58
+ # Run the actual analysis in a thread to simulate loading
59
+ def compute():
60
+ nonlocal diag_output, treat_output, prog_output
61
+ time.sleep(2) # simulate AI processing time
62
+ symptoms = symptoms_list
63
+ result = analyze_malaria(symptoms)
64
+ severity = "Mild"
65
+ color = "#10B981"
66
+ if all(sym in symptoms for sym in ["seizures","fever"]):
67
+ severity = "Life-threatening"
68
+ color = "#EF4444"
69
+ elif all(sym in symptoms for sym in ["jaundice","anemia"]):
70
+ severity = "Severe"
71
+ color = "#F97316"
72
+
73
+ alert_banner = f"<div style='border-radius:0.5rem; padding:1rem; background-color:{color}; color:white; font-weight:bold; margin-bottom:1rem;'>⚠️ Severity Alert: {severity}</div>"
74
+ diag_output = f"{alert_banner}<b>Diagnosis:</b><br>{result['Diagnosis'].replace(chr(10),'<br>')}"
75
+ treat_output = f"{alert_banner}<b>Treatment:</b><br>{result['Treatment'].replace(chr(10),'<br>')}"
76
+ prog_output = f"{alert_banner}<b>Prognosis:</b><br>{result['Prognosis'].replace(chr(10),'<br>')}"
77
 
78
+ thread = Thread(target=compute)
79
+ thread.start()
80
+ thread.join()
81
 
82
  return diag_output, treat_output, prog_output
83
 
84
  # ===========================
85
+ # Gradio UI
86
  # ===========================
87
+ symptoms_options = ["fever","chills","headache","nausea","vomiting","muscle_aches","fatigue","sweating","anemia","jaundice","seizures"]
 
88
 
89
  with gr.Blocks(css="""
90
+ body {background-color:#F9FAFB; font-family:sans-serif;}
91
+ .header {background:linear-gradient(135deg,#667eea 0%,#764ba2 100%); color:white; padding:2rem; text-align:center; border-radius:1rem; margin-bottom:1rem;}
92
+ .card {border-radius:1rem; box-shadow:0 10px 25px rgba(0,0,0,0.1); background:white; padding:1.5rem; margin-bottom:1rem;}
93
+ .btn {background-color:#5D5CDE; color:white; padding:0.75rem 1.5rem; border-radius:0.75rem; font-weight:bold; cursor:pointer;}
94
+ .btn:hover {background-color:#4B4AC8;}
95
+ .checkbox-group label {display:block; padding:0.5rem; border-radius:0.5rem; cursor:pointer; transition:0.2s;}
96
+ .checkbox-group label:hover {background-color:#E0E7FF;}
97
  """) as demo:
98
+
99
  gr.HTML("<div class='header'><h1 class='text-4xl font-bold'>🦟 Malaria AI Assistant</h1><p>Advanced diagnostic, treatment, and prognostic analysis</p></div>")
100
 
101
  with gr.Row():
 
106
  location = gr.Textbox(label="Location")
107
  travel = gr.Checkbox(label="Recent Travel to Endemic Areas")
108
  travel_details = gr.Textbox(label="Travel Details")
109
+ symptoms_list = gr.CheckboxGroup(symptoms_options, label="Symptoms", elem_classes="checkbox-group")
110
  temperature = gr.Number(label="Temperature (°C)")
111
  blood_pressure = gr.Textbox(label="Blood Pressure")
112
  heart_rate = gr.Number(label="Heart Rate")
 
116
 
117
  with gr.Column(scale=1):
118
  with gr.Group(elem_classes="card"):
119
+ diag_output = gr.HTML(label="Diagnosis", value="<div style='text-align:center;'>🤖 Waiting for input...</div>")
120
+ treat_output = gr.HTML(label="Treatment", value="<div style='text-align:center;'>🤖 Waiting for input...</div>")
121
+ prog_output = gr.HTML(label="Prognosis", value="<div style='text-align:center;'>🤖 Waiting for input...</div>")
122
 
123
  run_btn = gr.Button("Run Analysis", elem_classes="btn")
124
  run_btn.click(
125
+ run_analysis_with_loading,
126
  inputs=[age, gender, location, travel, travel_details, symptoms_list,
127
  temperature, blood_pressure, heart_rate, previous_malaria,
128
  medications, additional_notes],