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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -73
app.py CHANGED
@@ -1,88 +1,125 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
3
- import time
4
 
5
- # --- MODEL SETUP ---
6
- # CPU-friendly LLM
7
- model_name = "google/flan-t5-small" # small enough for CPU
8
- tokenizer = AutoTokenizer.from_pretrained(model_name)
9
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
10
-
11
- generator = pipeline("text2text-generation", model=model, tokenizer=tokenizer)
12
-
13
- # --- MALARIA RULES ---
14
  malaria_rules = {
15
- "fever": {"diagnosis": "Malaria likely", "treatment": "ACT (artemisinin-based combination therapy)", "prognosis": "Good if treated early"},
16
- "chills": {"diagnosis": "Malaria likely", "treatment": "ACT", "prognosis": "Good if treated early"},
17
- "headache": {"diagnosis": "Malaria possible", "treatment": "Supportive care and ACT if confirmed", "prognosis": "Good with treatment"},
18
- "sweating": {"diagnosis": "Malaria possible", "treatment": "Monitor temperature, ACT if confirmed", "prognosis": "Good with treatment"},
19
- "nausea": {"diagnosis": "Malaria possible", "treatment": "Hydration, ACT if confirmed", "prognosis": "Good with treatment"},
20
- "vomiting": {"diagnosis": "Malaria possible", "treatment": "Hydration, ACT if confirmed", "prognosis": "Good with treatment"},
21
- "fatigue": {"diagnosis": "Malaria possible", "treatment": "Rest and ACT if confirmed", "prognosis": "Good with treatment"},
22
- "anemia": {"diagnosis": "Severe malaria possible", "treatment": "Hospitalization, blood transfusion, ACT", "prognosis": "Guarded, monitor closely"},
23
- "jaundice": {"diagnosis": "Severe malaria possible", "treatment": "Hospitalization, supportive care, ACT", "prognosis": "Guarded"},
24
- "convulsions": {"diagnosis": "Cerebral malaria possible", "treatment": "Emergency care, IV antimalarials", "prognosis": "Poor if untreated"},
25
- "respiratory distress": {"diagnosis": "Severe malaria possible", "treatment": "Oxygen therapy, IV antimalarials", "prognosis": "Guarded"},
26
- "abdominal pain": {"diagnosis": "Malaria possible", "treatment": "Supportive care, ACT if confirmed", "prognosis": "Good with treatment"},
27
- "diarrhea": {"diagnosis": "Malaria possible", "treatment": "Hydration, ACT if confirmed", "prognosis": "Good with treatment"},
28
- "muscle pain": {"diagnosis": "Malaria possible", "treatment": "Rest, analgesics, ACT if confirmed", "prognosis": "Good with treatment"},
 
 
 
 
 
 
 
 
 
 
29
  }
30
 
31
- # --- ANALYSIS FUNCTION ---
32
- def analyze_symptoms(symptoms_input):
33
- # show temporary running feedback
34
- output = "Running analysis...\n"
35
-
36
- symptoms = [s.strip().lower() for s in symptoms_input.split(",")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- diagnosis_list = []
39
- treatment_list = []
40
- prognosis_list = []
41
 
42
- for symptom in symptoms:
43
- if symptom in malaria_rules:
44
- rule = malaria_rules[symptom]
45
- diagnosis_list.append(rule["diagnosis"])
46
- treatment_list.append(rule["treatment"])
47
- prognosis_list.append(rule["prognosis"])
48
- else:
49
- diagnosis_list.append(f"No rule for '{symptom}'")
50
- treatment_list.append(f"No rule for '{symptom}'")
51
- prognosis_list.append(f"No rule for '{symptom}'")
52
 
53
- # Convert lists to readable text
54
- diagnosis_text = "\n".join(diagnosis_list)
55
- treatment_text = "\n".join(treatment_list)
56
- prognosis_text = "\n".join(prognosis_list)
57
 
58
- # Enhance outputs with LLM
59
- enhanced_diagnosis = generator(f"Summarize and explain clearly: {diagnosis_text}", max_length=150)[0]["generated_text"]
60
- enhanced_treatment = generator(f"Summarize and explain clearly: {treatment_text}", max_length=150)[0]["generated_text"]
61
- enhanced_prognosis = generator(f"Summarize and explain clearly: {prognosis_text}", max_length=150)[0]["generated_text"]
62
 
63
- return enhanced_diagnosis, enhanced_treatment, enhanced_prognosis
64
 
65
- # --- GRADIO UI ---
66
- with gr.Blocks() as demo:
67
- gr.Markdown("## Malaria Multi-Agent AI")
68
-
69
- with gr.Row():
70
- symptoms_input = gr.Textbox(label="Enter symptoms (comma-separated)", placeholder="fever, chills, headache")
71
- analyze_button = gr.Button("Run Analysis")
 
 
 
 
 
 
72
 
73
  with gr.Row():
74
- diagnosis_output = gr.Textbox(label="Diagnosis", interactive=False)
75
- treatment_output = gr.Textbox(label="Treatment", interactive=False)
76
- prognosis_output = gr.Textbox(label="Prognosis", interactive=False)
77
-
78
- def on_click(symptoms):
79
- # Show temporary running message first
80
- diagnosis_output.value = "Running analysis..."
81
- treatment_output.value = "Running analysis..."
82
- prognosis_output.value = "Running analysis..."
83
- time.sleep(0.5) # short pause to simulate processing
84
- return analyze_symptoms(symptoms)
 
 
 
 
 
 
 
 
 
85
 
86
- analyze_button.click(on_click, inputs=[symptoms_input], outputs=[diagnosis_output, treatment_output, prognosis_output])
 
 
 
 
 
 
 
87
 
88
- demo.launch()
 
 
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
+ # ===========================
34
+ # Analysis Functions
35
+ # ===========================
36
+ 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():
94
+ with gr.Column(scale=1):
95
+ with gr.Group(elem_classes="card"):
96
+ age = gr.Number(label="Age")
97
+ gender = gr.Dropdown(["male","female","other"], label="Gender")
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")
105
+ previous_malaria = gr.Checkbox(label="Previous Malaria Episodes")
106
+ medications = gr.Textbox(label="Current Medications / Allergies")
107
+ additional_notes = gr.Textbox(label="Additional Notes")
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],
121
+ outputs=[diag_output, treat_output, prog_output]
122
+ )
123
 
124
+ if __name__ == "__main__":
125
+ demo.launch()