aneesqumar commited on
Commit
c6aced4
·
verified ·
1 Parent(s): 61bd172

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +329 -0
app.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import joblib
3
+ import pandas as pd
4
+ import os
5
+ from groq import Groq
6
+
7
+ from reportlab.platypus import (
8
+ SimpleDocTemplate, Paragraph, Spacer,
9
+ Table, TableStyle
10
+ )
11
+ from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
12
+ from reportlab.lib import colors
13
+ from reportlab.lib.units import inch
14
+
15
+ # ===============================
16
+ # LOAD MODEL
17
+ # ===============================
18
+ model = joblib.load("typhoidguard_model_reduced.pkl")
19
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
20
+
21
+ last_llm_report = ""
22
+ last_basic_data = {}
23
+
24
+ # ===============================
25
+ # LLM FUNCTION
26
+ # ===============================
27
+ def generate_llm_report(patient_info, prob_pct, risk_label, recommendation, factors):
28
+
29
+ prompt = f"""
30
+ You are a responsible medical AI assistant helping rural healthcare units in Pakistan.
31
+
32
+ Patient Details:
33
+ {patient_info}
34
+
35
+ Predicted Risk: {prob_pct}%
36
+ Risk Category: {risk_label}
37
+
38
+ Clinical Risk Factors:
39
+ {", ".join(factors) if factors else "None"}
40
+
41
+ Agent Recommendation:
42
+ {recommendation}
43
+
44
+ Generate structured sections:
45
+ Clinical Interpretation
46
+ Possible Complications
47
+ Immediate Precautions
48
+ Preventative Measures
49
+ Follow-up Recommendations
50
+
51
+ Keep headings clear.
52
+ End with reminder to consult qualified doctor.
53
+ """
54
+
55
+ response = client.chat.completions.create(
56
+ model="llama-3.3-70b-versatile",
57
+ messages=[{"role": "user", "content": prompt}],
58
+ temperature=0.4,
59
+ )
60
+
61
+ return response.choices[0].message.content
62
+
63
+
64
+ # ===============================
65
+ # BASIC PREDICTION
66
+ # ===============================
67
+ def predict_basic(name, age, gender, platelets, hb, duration,
68
+ blood_bacteria, severity, medication):
69
+
70
+ global last_basic_data, last_llm_report
71
+ last_llm_report = ""
72
+
73
+ data = pd.DataFrame([{
74
+ "Age": age,
75
+ "Platelet Count": platelets,
76
+ "Hemoglobin (g/dL)": hb,
77
+ "Treatment Duration": duration,
78
+ "Gender": gender,
79
+ "Blood Culture Bacteria": blood_bacteria,
80
+ "Symptoms Severity": severity,
81
+ "Current Medication": medication
82
+ }])
83
+
84
+ prob = model.predict_proba(data)[0][1]
85
+ prob_pct = round(prob * 100, 2)
86
+
87
+ low_platelets = platelets < 150000
88
+ low_hb = hb < 10
89
+
90
+ if low_platelets or low_hb:
91
+ prob_pct = 90.0
92
+ risk_label = "HIGH RISK"
93
+ color = "#b00020"
94
+ recommendation = "Immediate referral to secondary care facility recommended."
95
+ elif prob >= 0.65:
96
+ risk_label = "HIGH RISK"
97
+ color = "#b00020"
98
+ recommendation = "Urgent clinical evaluation required."
99
+ elif prob >= 0.35:
100
+ risk_label = "MODERATE RISK"
101
+ color = "#f57c00"
102
+ recommendation = "Close monitoring advised."
103
+ else:
104
+ risk_label = "LOW RISK"
105
+ color = "#2e7d32"
106
+ recommendation = "Continue standard treatment protocol."
107
+
108
+ factors = []
109
+ if low_platelets:
110
+ factors.append("Low Platelet Count")
111
+ if low_hb:
112
+ factors.append("Low Hemoglobin")
113
+
114
+ last_basic_data = {
115
+ "name": name,
116
+ "age": age,
117
+ "gender": gender,
118
+ "platelets": platelets,
119
+ "hb": hb,
120
+ "duration": duration,
121
+ "bacteria": blood_bacteria,
122
+ "severity": severity,
123
+ "medication": medication,
124
+ "prob_pct": prob_pct,
125
+ "risk_label": risk_label,
126
+ "recommendation": recommendation,
127
+ "factors": factors
128
+ }
129
+
130
+ urdu = f"""
131
+ <div style='background:#eef3fb;padding:10px;border-radius:8px;'>
132
+ <b>اردو خلاصہ:</b><br>
133
+ علاج ناکامی کا خطرہ <b>{prob_pct}%</b> ہے۔ درجہ: <b>{risk_label}</b>۔<br>
134
+ ڈاکٹر سے مشورہ ضرور کریں۔
135
+ </div>
136
+ """
137
+
138
+ return f"""
139
+ <div style="font-family:Arial;padding:15px;">
140
+ <h2 style="color:{color};">Patient: {name}</h2>
141
+ <h3>Risk of Treatment Failure: {prob_pct}%</h3>
142
+ <h3>Status: {risk_label}</h3>
143
+
144
+ <h4>Clinical Risk Factors:</h4>
145
+ <ul>
146
+ {''.join([f"<li>{f}</li>" for f in factors]) if factors else "<li>None</li>"}
147
+ </ul>
148
+
149
+ <h4>Agent Recommendation:</h4>
150
+ <p><b>{recommendation}</b></p>
151
+
152
+ {urdu}
153
+ </div>
154
+ """
155
+
156
+
157
+ # ===============================
158
+ # DETAILED BUTTON
159
+ # ===============================
160
+ def generate_detailed(*inputs):
161
+ global last_basic_data, last_llm_report
162
+
163
+ basic_html = predict_basic(*inputs)
164
+
165
+ d = last_basic_data
166
+
167
+ patient_info = f"""
168
+ Age: {d['age']}
169
+ Gender: {d['gender']}
170
+ Platelets: {d['platelets']}
171
+ Hemoglobin: {d['hb']}
172
+ Duration: {d['duration']}
173
+ Bacteria: {d['bacteria']}
174
+ Severity: {d['severity']}
175
+ Medication: {d['medication']}
176
+ """
177
+
178
+ last_llm_report = generate_llm_report(
179
+ patient_info,
180
+ d["prob_pct"],
181
+ d["risk_label"],
182
+ d["recommendation"],
183
+ d["factors"]
184
+ )
185
+
186
+ formatted = last_llm_report.replace("\n", "<br>")
187
+
188
+ return basic_html + f"""
189
+ <hr>
190
+ <h3 style="color:#003366;">Detailed AI Report & Recommendations</h3>
191
+ <div style="background:#f9f9f9;padding:15px;border-radius:8px;">
192
+ {formatted}
193
+ </div>
194
+ """
195
+
196
+
197
+ # ===============================
198
+ # PDF GENERATION (PROFESSIONAL)
199
+ # ===============================
200
+ def generate_pdf(*inputs):
201
+
202
+ global last_basic_data, last_llm_report
203
+
204
+ d = last_basic_data
205
+ file_path = f"{d['name']}_Typhoid_Report.pdf"
206
+ doc = SimpleDocTemplate(file_path)
207
+ elements = []
208
+ styles = getSampleStyleSheet()
209
+
210
+ # Title
211
+ elements.append(Paragraph("<b>TyphoidGuard AI Clinical Report</b>", styles["Title"]))
212
+ elements.append(Spacer(1, 0.3 * inch))
213
+
214
+ # ---- TABLE ----
215
+ table_data = [
216
+ ["Patient Name", d["name"]],
217
+ ["Age", d["age"]],
218
+ ["Gender", d["gender"]],
219
+ ["Platelet Count", d["platelets"]],
220
+ ["Hemoglobin", d["hb"]],
221
+ ["Treatment Duration", d["duration"]],
222
+ ["Bacteria", d["bacteria"]],
223
+ ["Severity", d["severity"]],
224
+ ["Medication", d["medication"]],
225
+ ["Predicted Risk %", d["prob_pct"]],
226
+ ["Risk Level", d["risk_label"]],
227
+ ]
228
+
229
+ table = Table(table_data, colWidths=[2.5*inch, 3*inch])
230
+ table.setStyle(TableStyle([
231
+ ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
232
+ ('GRID',(0,0),(-1,-1),1,colors.grey),
233
+ ('FONTNAME',(0,0),(-1,-1),'Helvetica')
234
+ ]))
235
+
236
+ elements.append(table)
237
+ elements.append(Spacer(1,0.4*inch))
238
+
239
+ # ---- BASIC RECOMMENDATION ----
240
+ elements.append(Paragraph("<b>Agent Recommendation</b>", styles["Heading2"]))
241
+ elements.append(Spacer(1,0.2*inch))
242
+ elements.append(Paragraph(d["recommendation"], styles["Normal"]))
243
+ elements.append(Spacer(1,0.4*inch))
244
+
245
+ # ---- LLM SECTION ----
246
+ if last_llm_report:
247
+ elements.append(Paragraph("<b>Detailed AI Report & Recommendations</b>", styles["Heading2"]))
248
+ elements.append(Spacer(1,0.2*inch))
249
+ elements.append(Paragraph(last_llm_report.replace("\n","<br/>"), styles["Normal"]))
250
+ elements.append(Spacer(1,0.4*inch))
251
+
252
+ # Disclaimer
253
+ elements.append(Paragraph(
254
+ "<i>This report is AI-generated. Final medical decisions must be made by a qualified doctor.</i>",
255
+ styles["Normal"]
256
+ ))
257
+
258
+ # Team Footer
259
+ elements.append(Spacer(1,0.5*inch))
260
+ elements.append(Paragraph("<b>Team Chinar AI (AJK)</b>", styles["Normal"]))
261
+ elements.append(Paragraph(
262
+ "Anees Qumar Abbasi | Sharafat Hussain | Salma Asghar | "
263
+ "Kaleem Hussain | Munazza Zahra | Kokub Khurishid",
264
+ styles["Normal"]
265
+ ))
266
+
267
+ doc.build(elements)
268
+ return file_path
269
+
270
+
271
+ # ===============================
272
+ # INTERFACE
273
+ # ===============================
274
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
275
+
276
+ gr.Markdown("""
277
+ # 🏥 TyphoidGuard AI
278
+ ### HEC Generative AI Hackathon – Pakistan
279
+ #### Team Chinar AI (AJK)
280
+ """)
281
+
282
+ with gr.Row():
283
+ name = gr.Textbox(label="Patient Name")
284
+ age = gr.Number(label="Age")
285
+ gender = gr.Radio(["Male", "Female"], label="Gender")
286
+
287
+ with gr.Row():
288
+ platelets = gr.Number(label="Platelet Count")
289
+ hb = gr.Number(label="Hemoglobin (g/dL)")
290
+ duration = gr.Number(label="Treatment Duration (Days)")
291
+
292
+ with gr.Row():
293
+ blood_bacteria = gr.Dropdown(
294
+ ["Escherichia coli","Salmonella typhi","Unknown","Staphylococcus"],
295
+ label="Blood Culture Bacteria"
296
+ )
297
+ severity = gr.Dropdown(
298
+ ["Low","Moderate","High","Unknown"],
299
+ label="Symptoms Severity"
300
+ )
301
+ medication = gr.Dropdown(
302
+ ["Amoxicillin","Ceftriaxone","Azithromycin"],
303
+ label="Current Medication"
304
+ )
305
+
306
+ # ---- BUTTONS ABOVE OUTPUT ----
307
+ with gr.Row():
308
+ predict_btn = gr.Button("Basic Risk Assessment", variant="primary")
309
+ detailed_btn = gr.Button("Detailed Report & Recommendations", variant="secondary")
310
+ pdf_btn = gr.Button("Generate PDF Report")
311
+
312
+ output = gr.HTML()
313
+
314
+ predict_btn.click(predict_basic,
315
+ inputs=[name,age,gender,platelets,hb,duration,
316
+ blood_bacteria,severity,medication],
317
+ outputs=output)
318
+
319
+ detailed_btn.click(generate_detailed,
320
+ inputs=[name,age,gender,platelets,hb,duration,
321
+ blood_bacteria,severity,medication],
322
+ outputs=output)
323
+
324
+ pdf_btn.click(generate_pdf,
325
+ inputs=[name,age,gender,platelets,hb,duration,
326
+ blood_bacteria,severity,medication],
327
+ outputs=gr.File())
328
+
329
+ demo.launch()