aneesqumar commited on
Commit
b10bb59
·
verified ·
1 Parent(s): bcd867a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -116
app.py CHANGED
@@ -2,6 +2,9 @@ import gradio as gr
2
  import joblib
3
  import pandas as pd
4
  import numpy as np
 
 
 
5
  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
6
  from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
7
  from reportlab.lib import colors
@@ -12,10 +15,54 @@ from reportlab.platypus import TableStyle
12
  # Load model
13
  model = joblib.load("typhoidguard_model_reduced.pkl")
14
 
15
- # Risk & Agentic Logic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, potassium):
17
 
18
- # 1️⃣ Prepare data with exact column names
19
  data = pd.DataFrame([{
20
  "Platelet Count": platelets,
21
  "Age": age,
@@ -26,24 +73,18 @@ def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, po
26
  "Gender": gender
27
  }])
28
 
29
- # 2️⃣ Transform through preprocessor
30
  X_processed = model.named_steps["preprocessor"].transform(data)
31
-
32
- # 3️⃣ Model probability
33
  prob = model.named_steps["classifier"].predict_proba(X_processed)[0][1]
34
 
35
- # 4️⃣ Clinical thresholds
36
  low_platelets = platelets < 150000
37
  low_hb = hb < 10
38
  prolonged_treatment = duration > 7
39
 
40
- # 5️⃣ Adjust probability for extreme lab values
41
  if low_platelets or low_hb:
42
- prob_pct = 90.0 # clinically override
43
  else:
44
  prob_pct = round(prob * 100, 2)
45
 
46
- # Default risk label based on probability
47
  if prob > 0.65:
48
  risk_label = "🔴 HIGH RISK"
49
  color = "#d62828"
@@ -54,7 +95,6 @@ def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, po
54
  risk_label = "🟢 LOW RISK"
55
  color = "#2a9d8f"
56
 
57
- # Override risk for critical lab values
58
  if low_platelets or low_hb:
59
  risk_label = "🔴 HIGH RISK"
60
  color = "#d62828"
@@ -64,7 +104,6 @@ def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, po
64
  else:
65
  recommendation = "Continue standard treatment protocol."
66
 
67
- # 6️⃣ Risk factors list
68
  factors = []
69
  if low_platelets:
70
  factors.append("Low Platelet Count")
@@ -77,142 +116,78 @@ def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, po
77
  if potassium < 3.5 or potassium > 5.0:
78
  factors.append("Abnormal Potassium")
79
 
80
- # 7️⃣ Construct HTML
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  explanation = f"""
82
  <div style="font-family:Arial; padding:15px;">
83
  <h2 style="color:{color};">Patient: {name}</h2>
84
  <h3>Risk of Treatment Failure: {prob_pct}%</h3>
85
  <h3>Status: {risk_label}</h3>
 
86
  <h4>Clinical Risk Factors:</h4>
87
  <ul>
88
- {''.join([f"<li>{f}</li>" for f in factors])}
89
  </ul>
 
90
  <h4>Agent Recommendation:</h4>
91
- <p>{recommendation}</p>
 
 
 
 
 
 
 
92
  </div>
93
  """
94
 
95
  return explanation
96
 
97
 
98
- # PDF Generation
99
- # PDF Generation (with color coding & disclaimer)
 
100
  def generate_pdf(name, age, gender, platelets, hb, duration, calcium, potassium):
101
 
102
- # 1️⃣ Prepare data for model & agentic logic
103
- data = pd.DataFrame([{
104
- "Platelet Count": platelets,
105
- "Age": age,
106
- "Hemoglobin (g/dL)": hb,
107
- "Treatment Duration": duration,
108
- "Calcium (mg/dL)": calcium,
109
- "Potassium (mmol/L)": potassium,
110
- "Gender": gender
111
- }])
112
-
113
- X_processed = model.named_steps["preprocessor"].transform(data)
114
- prob = model.named_steps["classifier"].predict_proba(X_processed)[0][1]
115
 
116
- low_platelets = platelets < 150000
117
- low_hb = hb < 10
118
- prolonged_treatment = duration > 7
119
-
120
- # Adjust probability for critical lab values
121
- if low_platelets or low_hb:
122
- prob_pct = 95.0
123
- else:
124
- prob_pct = round(prob * 100, 2)
125
-
126
- # Determine status and recommendation
127
- if prob > 0.65:
128
- risk_label = "HIGH RISK"
129
- color = colors.red
130
- elif prob >= 0.35:
131
- risk_label = "MODERATE RISK"
132
- color = colors.orange
133
- else:
134
- risk_label = "LOW RISK"
135
- color = colors.green
136
-
137
- if low_platelets or low_hb:
138
- risk_label = "HIGH RISK"
139
- color = colors.red
140
- recommendation = "Immediate referral to secondary care facility recommended. Close monitoring required."
141
- elif prob >= 0.35:
142
- recommendation = "Close monitoring advised. Repeat blood tests within 48 hours."
143
- else:
144
- recommendation = "Continue standard treatment protocol."
145
-
146
- # Clinical risk factors
147
- factors = []
148
- if low_platelets:
149
- factors.append("Low Platelet Count")
150
- if low_hb:
151
- factors.append("Low Hemoglobin")
152
- if prolonged_treatment:
153
- factors.append("Prolonged Treatment Duration")
154
- if calcium < 8.5:
155
- factors.append("Low Calcium")
156
- if potassium < 3.5 or potassium > 5.0:
157
- factors.append("Abnormal Potassium")
158
-
159
- # 2️⃣ Generate PDF
160
  file_path = f"{name}_Typhoid_Report.pdf"
161
  doc = SimpleDocTemplate(file_path)
162
  elements = []
163
  styles = getSampleStyleSheet()
164
 
165
- # Title
166
  elements.append(Paragraph("<b>TyphoidGuard AI Clinical Report</b>", styles["Title"]))
167
  elements.append(Spacer(1, 0.3 * inch))
168
 
169
- # Patient Info Table
170
- patient_data = [
171
- ["Patient Name", name],
172
- ["Age", age],
173
- ["Gender", gender],
174
- ["Platelet Count", platelets],
175
- ["Hemoglobin (g/dL)", hb],
176
- ["Treatment Duration (Days)", duration],
177
- ["Calcium (mg/dL)", calcium],
178
- ["Potassium (mmol/L)", potassium],
179
- ["Risk of Treatment Failure (%)", prob_pct],
180
- ["Status", risk_label],
181
- ]
182
-
183
- table = Table(patient_data, colWidths=[200, 250])
184
- table.setStyle(TableStyle([
185
- ('BACKGROUND', (0,0), (-1,0), colors.lightblue),
186
- ('GRID', (0,0), (-1,-1), 1, colors.grey),
187
- ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
188
- ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
189
- # Color coding for risk status
190
- ('TEXTCOLOR', (-1,-1), (-1,-1), color)
191
- ]))
192
- elements.append(table)
193
- elements.append(Spacer(1, 0.3 * inch))
194
-
195
- # Clinical Risk Factors
196
- if factors:
197
- elements.append(Paragraph("<b>Clinical Risk Factors:</b>", styles["Heading3"]))
198
- for f in factors:
199
- elements.append(Paragraph(f"- {f}", styles["Normal"]))
200
- elements.append(Spacer(1, 0.2 * inch))
201
-
202
- # Agent Recommendation
203
- elements.append(Paragraph("<b>Agent Recommendation:</b>", styles["Heading3"]))
204
- elements.append(Paragraph(recommendation, styles["Normal"]))
205
  elements.append(Spacer(1, 0.3 * inch))
206
 
207
- # Footer
208
- elements.append(Paragraph("Generated under HEC Generative AI Training Hackathon", styles["Normal"]))
209
- elements.append(Paragraph("Team Chinar AI - AJK", styles["Normal"]))
210
- elements.append(Spacer(1, 0.2 * inch))
211
- elements.append(Paragraph("<i>Disclaimer: This report is AI-generated. Please consult a qualified doctor for clinical decisions.</i>", styles["Normal"]))
212
 
213
  doc.build(elements)
214
  return file_path
 
 
 
215
  # Interface
 
216
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
217
 
218
  gr.Markdown("""
@@ -237,7 +212,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
237
 
238
  output = gr.HTML()
239
 
240
- predict_btn = gr.Button("🔍 Analyze Patient")
241
  pdf_btn = gr.Button("📄 Generate PDF Report")
242
 
243
  predict_btn.click(
 
2
  import joblib
3
  import pandas as pd
4
  import numpy as np
5
+ import os
6
+ from groq import Groq
7
+
8
  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
9
  from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
10
  from reportlab.lib import colors
 
15
  # Load model
16
  model = joblib.load("typhoidguard_model_reduced.pkl")
17
 
18
+ # Groq Client (API key from HF Secrets)
19
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
20
+
21
+ # ===============================
22
+ # LLM REPORT FUNCTION
23
+ # ===============================
24
+ def generate_llm_report(patient_info, prob_pct, risk_label, recommendation, factors):
25
+
26
+ prompt = f"""
27
+ You are a responsible medical AI assistant helping rural healthcare units in Pakistan.
28
+
29
+ Patient Details:
30
+ {patient_info}
31
+
32
+ Predicted Risk of Treatment Failure: {prob_pct}%
33
+ Risk Category: {risk_label}
34
+
35
+ Clinical Risk Factors:
36
+ {", ".join(factors) if factors else "None"}
37
+
38
+ Agent Recommendation:
39
+ {recommendation}
40
+
41
+ Generate a structured detailed report including:
42
+ 1. Clinical Interpretation
43
+ 2. Possible Complications
44
+ 3. Immediate Precautions
45
+ 4. Preventative Measures
46
+ 5. Follow-up Recommendations
47
+
48
+ Use clear bullet points.
49
+ End with a reminder that final decisions must be made by a qualified doctor.
50
+ """
51
+
52
+ response = client.chat.completions.create(
53
+ model="llama-3.3-70b-versatile",
54
+ messages=[{"role": "user", "content": prompt}],
55
+ temperature=0.4,
56
+ )
57
+
58
+ return response.choices[0].message.content
59
+
60
+
61
+ # ===============================
62
+ # Risk & Agentic Logic (UNCHANGED)
63
+ # ===============================
64
  def predict_and_generate(name, age, gender, platelets, hb, duration, calcium, potassium):
65
 
 
66
  data = pd.DataFrame([{
67
  "Platelet Count": platelets,
68
  "Age": age,
 
73
  "Gender": gender
74
  }])
75
 
 
76
  X_processed = model.named_steps["preprocessor"].transform(data)
 
 
77
  prob = model.named_steps["classifier"].predict_proba(X_processed)[0][1]
78
 
 
79
  low_platelets = platelets < 150000
80
  low_hb = hb < 10
81
  prolonged_treatment = duration > 7
82
 
 
83
  if low_platelets or low_hb:
84
+ prob_pct = 90.0
85
  else:
86
  prob_pct = round(prob * 100, 2)
87
 
 
88
  if prob > 0.65:
89
  risk_label = "🔴 HIGH RISK"
90
  color = "#d62828"
 
95
  risk_label = "🟢 LOW RISK"
96
  color = "#2a9d8f"
97
 
 
98
  if low_platelets or low_hb:
99
  risk_label = "🔴 HIGH RISK"
100
  color = "#d62828"
 
104
  else:
105
  recommendation = "Continue standard treatment protocol."
106
 
 
107
  factors = []
108
  if low_platelets:
109
  factors.append("Low Platelet Count")
 
116
  if potassium < 3.5 or potassium > 5.0:
117
  factors.append("Abnormal Potassium")
118
 
119
+ # -------- LLM CALL --------
120
+ patient_info = f"""
121
+ Age: {age}
122
+ Gender: {gender}
123
+ Platelets: {platelets}
124
+ Hemoglobin: {hb}
125
+ Treatment Duration: {duration}
126
+ Calcium: {calcium}
127
+ Potassium: {potassium}
128
+ """
129
+
130
+ llm_report = generate_llm_report(
131
+ patient_info, prob_pct, risk_label, recommendation, factors
132
+ )
133
+
134
+ # -------- HTML OUTPUT --------
135
  explanation = f"""
136
  <div style="font-family:Arial; padding:15px;">
137
  <h2 style="color:{color};">Patient: {name}</h2>
138
  <h3>Risk of Treatment Failure: {prob_pct}%</h3>
139
  <h3>Status: {risk_label}</h3>
140
+
141
  <h4>Clinical Risk Factors:</h4>
142
  <ul>
143
+ {''.join([f"<li>{f}</li>" for f in factors]) if factors else "<li>None</li>"}
144
  </ul>
145
+
146
  <h4>Agent Recommendation:</h4>
147
+ <p><b>{recommendation}</b></p>
148
+
149
+ <hr>
150
+
151
+ <h3 style="color:#003366;">🧠 Detailed AI Report & Recommendations</h3>
152
+ <div style="background:#f8f9fa; padding:15px; border-radius:10px; line-height:1.6;">
153
+ {llm_report.replace("\n", "<br>")}
154
+ </div>
155
  </div>
156
  """
157
 
158
  return explanation
159
 
160
 
161
+ # ===============================
162
+ # PDF Generation (LLM Included)
163
+ # ===============================
164
  def generate_pdf(name, age, gender, platelets, hb, duration, calcium, potassium):
165
 
166
+ html_output = predict_and_generate(name, age, gender, platelets, hb, duration, calcium, potassium)
 
 
 
 
 
 
 
 
 
 
 
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  file_path = f"{name}_Typhoid_Report.pdf"
169
  doc = SimpleDocTemplate(file_path)
170
  elements = []
171
  styles = getSampleStyleSheet()
172
 
 
173
  elements.append(Paragraph("<b>TyphoidGuard AI Clinical Report</b>", styles["Title"]))
174
  elements.append(Spacer(1, 0.3 * inch))
175
 
176
+ elements.append(Paragraph(html_output.replace("<br>", "<br/>"), styles["Normal"]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  elements.append(Spacer(1, 0.3 * inch))
178
 
179
+ elements.append(Paragraph(
180
+ "<i>Disclaimer: This report is AI-generated. Please consult a qualified doctor before making clinical decisions.</i>",
181
+ styles["Normal"]
182
+ ))
 
183
 
184
  doc.build(elements)
185
  return file_path
186
+
187
+
188
+ # ===============================
189
  # Interface
190
+ # ===============================
191
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
192
 
193
  gr.Markdown("""
 
212
 
213
  output = gr.HTML()
214
 
215
+ predict_btn = gr.Button("🧠 Detailed Report and Recommendations")
216
  pdf_btn = gr.Button("📄 Generate PDF Report")
217
 
218
  predict_btn.click(