DheivaCodes commited on
Commit
071b854
Β·
verified Β·
1 Parent(s): 7094b3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +565 -405
app.py CHANGED
@@ -1,51 +1,47 @@
1
- import os, re, warnings
 
 
2
  import numpy as np
3
  import pandas as pd
 
 
 
 
 
4
  import matplotlib
5
  matplotlib.use("Agg")
6
  import matplotlib.pyplot as plt
 
7
  import gradio as gr
 
8
  warnings.filterwarnings("ignore")
9
 
10
- # ── Domain weights (must match pipeline exactly) ───────────────────────────────
 
 
 
 
 
 
11
  DOMAIN_WEIGHTS = {
12
- "METABOLIC": 0.35,
13
- "REPRODUCTIVE": 0.40,
14
  "HYPERANDROGENIC": 0.20,
15
- "GENERAL": 0.05,
16
  }
17
 
18
- # ── Model loading ──────────────────────────────────────────────────────────────
19
- _mdl = None
20
-
21
- def get_models():
22
- global _mdl
23
- if _mdl is not None:
24
- return _mdl, None
25
- import joblib
26
- needed = ["ensemble_meta", "base_models", "domain_models", "train_stats",
27
- "mice_imputer", "scaler", "feature_columns", "best_threshold"]
28
- missing = [f for f in needed if not os.path.exists(f"models/{f}.pkl")]
29
- if missing:
30
- return None, f"Missing pkl files: {missing}"
31
- try:
32
- _mdl = {
33
- "meta": joblib.load("models/ensemble_meta.pkl"),
34
- "base": joblib.load("models/base_models.pkl"),
35
- "domain": joblib.load("models/domain_models.pkl"),
36
- "stats": joblib.load("models/train_stats.pkl"),
37
- "mice": joblib.load("models/mice_imputer.pkl"),
38
- "scaler": joblib.load("models/scaler.pkl"),
39
- "features": joblib.load("models/feature_columns.pkl"),
40
- "threshold": joblib.load("models/best_threshold.pkl"),
41
- }
42
- return _mdl, None
43
- except Exception as e:
44
- return None, str(e)
45
 
 
 
 
 
46
 
47
- # ── Exact pipeline apply_severity(models, stats, X_raw, X_sc) ─────────────────
48
- def apply_severity(domain_models, stats, X_raw, X_sc):
49
  df = pd.DataFrame(index=X_sc.index)
50
  for d, (model, fc) in domain_models.items():
51
  avail = [f for f in fc if f in X_sc.columns]
@@ -53,8 +49,9 @@ def apply_severity(domain_models, stats, X_raw, X_sc):
53
  df[f"{d}_SEV"] = 0.0
54
  continue
55
  p = model.predict_proba(X_sc[avail])[:, 1]
56
- lo, hi = stats[d]["min"], stats[d]["max"]
57
- df[f"{d}_SEV"] = np.clip((p - lo) / (hi - lo + 1e-6), 0, 1)
 
58
  df = df.fillna(0)
59
  df["OVERALL_SEV"] = sum(
60
  df[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
@@ -62,386 +59,549 @@ def apply_severity(domain_models, stats, X_raw, X_sc):
62
  )
63
  return df
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- # ── Full inference matching pipeline deployment_config.json steps ─────────────
67
- def predict(inp, mdl):
68
- all_fc = mdl["features"]
69
- # Split feature_columns into base features and SEV columns
70
- base_fc = [c for c in all_fc if not c.endswith("_SEV")]
71
-
72
- # Step 1: raw row (base features only β€” SEV cols added later)
73
- row_raw = pd.DataFrame([{c: inp.get(c, np.nan) for c in base_fc}])
74
-
75
- # Step 2: MICE impute (never refit)
76
- row_imp = pd.DataFrame(
77
- mdl["mice"].transform(row_raw),
78
- columns=base_fc, index=row_raw.index)
79
-
80
- # Step 3: Scale (never refit)
81
- row_sc = pd.DataFrame(
82
- mdl["scaler"].transform(row_imp),
83
- columns=base_fc, index=row_raw.index)
84
-
85
- # Step 4: Domain severity
86
- sev_df = apply_severity(mdl["domain"], mdl["stats"], row_raw, row_sc)
87
-
88
- # Step 5: Concat + reindex to exact feature_columns order
89
- X_final = pd.concat([row_sc, sev_df], axis=1).reindex(columns=all_fc, fill_value=0)
90
-
91
- # Step 6+7: Base probs β†’ meta-learner
92
- base_probs = pd.DataFrame(
93
- {name: m.predict_proba(X_final)[:, 1]
94
- for name, m in mdl["base"].items()})
95
- prob = mdl["meta"].predict_proba(base_probs)[:, 1][0]
96
-
97
- # Step 8: Threshold
98
- pred = int(prob >= mdl["threshold"])
99
-
100
- sev_scores = {
101
- d: float(sev_df[f"{d}_SEV"].iloc[0])
102
- for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev_df
103
- }
104
- sev_scores["OVERALL"] = float(sev_df["OVERALL_SEV"].iloc[0])
105
- return pred, float(prob), sev_scores, base_probs
106
-
107
-
108
- # ── Infertility risk score ────────────────────────────────────────────────────��
109
- def infertility_risk(amh, fsh, foll_l, foll_r, cycle, bmi):
110
- parts = []
111
- foll = (foll_l or 0) + (foll_r or 0)
112
- if amh: parts.append(("AMH Reserve", max(0, 1 - amh / 5), 0.35))
113
- if fsh: parts.append(("FSH Level", min(1, fsh / 20), 0.25))
114
- if foll: parts.append(("Follicle Count", max(0, 1 - foll / 20), 0.20))
115
- parts.append(("Cycle", 0.70 if cycle == "Irregular" else 0.20, 0.15))
116
- if bmi: parts.append(("BMI", 0.6 if bmi < 18.5 or bmi > 30 else 0.3 if bmi > 25 else 0.0, 0.05))
117
- if not parts:
118
- return 0.5, "Moderate"
119
- tw = sum(w for _, _, w in parts)
120
- sc = sum(r * w for _, r, w in parts) / tw
121
- return sc, ("Low" if sc < 0.35 else "High" if sc >= 0.60 else "Moderate")
122
-
123
-
124
- # ── Plots ──────────────────────────────────────────────────────────────────────
125
- def make_radar(sev):
126
- doms = ["METABOLIC", "REPRODUCTIVE", "HYPERANDROGENIC", "GENERAL"]
127
- vals = [sev.get(d, 0) for d in doms] + [sev.get(doms[0], 0)]
128
- ang = [n / len(doms) * 2 * np.pi for n in range(len(doms))] + [0]
129
- fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
130
- fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
131
- ax.plot(ang, vals, "o-", lw=2.5, color="#4f46e5")
132
- ax.fill(ang, vals, alpha=0.25, color="#4f46e5")
133
- ax.set_xticks(ang[:-1])
134
- ax.set_xticklabels([d.capitalize() for d in doms], fontsize=10)
135
- ax.set_ylim(0, 1); ax.set_yticks([.25, .5, .75, 1])
136
- ax.set_yticklabels(["25%", "50%", "75%", "100%"], fontsize=7)
137
- ax.set_title("Domain Severity Profile", fontsize=12, fontweight="bold", pad=16)
138
- plt.tight_layout()
139
- return fig
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
- def make_base_bar(base_probs, threshold):
143
- names = list(base_probs.columns)
144
- probs = [float(base_probs[n].iloc[0]) for n in names]
145
- cols = ["#ef4444" if p >= threshold else "#10b981" for p in probs]
146
- fig, ax = plt.subplots(figsize=(6, 3))
147
- fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
148
- bars = ax.bar(names, probs, color=cols, edgecolor="white", width=0.5)
149
- for b, p in zip(bars, probs):
150
- ax.text(b.get_x() + b.get_width() / 2, p + 0.02,
151
- f"{p:.1%}", ha="center", fontsize=10, fontweight="600")
152
- ax.axhline(threshold, color="#f59e0b", lw=2, ls="--",
153
- label=f"Threshold {threshold:.3f}")
154
- ax.set_ylim(0, 1.15); ax.legend(fontsize=9)
155
- ax.set_title("Base Model Probabilities", fontsize=11, fontweight="bold")
156
- ax.spines[["top", "right"]].set_visible(False)
157
- ax.tick_params(labelsize=10)
158
- plt.tight_layout()
159
- return fig
160
 
 
 
161
 
162
- def make_inf_bar(amh, fsh, foll_l, foll_r, cycle, bmi):
163
- foll = (foll_l or 0) + (foll_r or 0)
164
- parts = []
165
- if amh: parts.append(("AMH Reserve", max(0, 1 - amh / 5)))
166
- if fsh: parts.append(("FSH Level", min(1, fsh / 20)))
167
- if foll: parts.append(("Follicle Count", max(0, 1 - foll / 20)))
168
- parts.append(("Cycle", 0.70 if cycle == "Irregular" else 0.20))
169
- if bmi: parts.append(("BMI", 0.6 if bmi < 18.5 or bmi > 30 else 0.3 if bmi > 25 else 0.0))
170
- if not parts:
171
- return None
172
- labels = [p[0] for p in parts]
173
- vals = [p[1] for p in parts]
174
- colors = ["#ef4444" if v > 0.6 else "#f59e0b" if v > 0.35 else "#10b981" for v in vals]
175
- fig, ax = plt.subplots(figsize=(6, 3))
176
- fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
177
- bars = ax.barh(labels, vals, color=colors, height=0.5, edgecolor="white")
178
- for b, v in zip(bars, vals):
179
- ax.text(v + 0.02, b.get_y() + b.get_height() / 2,
180
- f"{v:.0%}", va="center", fontsize=9)
181
- ax.set_xlim(0, 1.15)
182
- ax.spines[["top", "right"]].set_visible(False)
183
- ax.set_title("Infertility Risk Factors", fontsize=11, fontweight="bold")
184
- plt.tight_layout()
185
- return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
 
 
 
187
 
188
- # ── Main prediction function ───────────────────────────────────────────────────
189
- def run_analysis(age, bmi, weight, hb, pulse, rr,
190
- fsh, lh, amh, prg, prl, tsh, vitd3, rbs,
191
- waist, hip, bp_sys, bp_dia,
192
- foll_l, foll_r, avg_fl, avg_fr, endo,
193
- cycle, cycle_len,
194
- wt_gain, hair_growth, skin_dark,
195
- hair_loss, pimples, fast_food, exercise):
196
-
197
- mdl, err = get_models()
198
- if err:
199
- err_html = f'<div style="color:red;padding:20px;font-family:sans-serif">❌ {err}<br>Make sure all 8 pkl files are in the models/ folder.</div>'
200
- return err_html, None, None, "", ""
201
-
202
- cycle_code = 2 if cycle == "Irregular" else 4
203
- whr = round(waist / max(hip, 1), 3)
204
-
205
- inp = {
206
- "Age__yrs_": age, "BMI": bmi, "Weight__Kg_": weight,
207
- "Hb__g_dl_": hb, "Pulse_rate_bpm_": pulse, "RR__breaths_min_": rr,
208
- "FSH_mIU_mL_": fsh, "LH_mIU_mL_": lh,
209
- "FSH_LH": round(fsh / max(lh, 0.01), 3),
210
- "AMH_ng_mL_": amh, "PRG_ng_mL_": prg, "PRL_ng_mL_": prl,
211
- "TSH__mIU_L_": tsh, "Vit_D3__ng_mL_": vitd3, "RBS_mg_dl_": rbs,
212
- "Waist_inch_": waist, "Hip_inch_": hip, "Waist_Hip_Ratio": whr,
213
- "BP__Systolic__mmHg_": bp_sys, "BP__Diastolic__mmHg_": bp_dia,
214
- "Follicle_No___L_": foll_l, "Follicle_No___R_": foll_r,
215
- "Avg_F_size__L__mm_": avg_fl, "Avg_F_size__R__mm_": avg_fr,
216
- "Endometrium__mm_": endo, "Cycle_R_I_": cycle_code,
217
- "Cycle_length_days_": cycle_len,
218
- "Weight_gain_Y_N_": int(wt_gain), "hair_growth_Y_N_": int(hair_growth),
219
- "Skin_darkening__Y_N_": int(skin_dark), "Hair_loss_Y_N_": int(hair_loss),
220
- "Pimples_Y_N_": int(pimples), "Fast_food__Y_N_": int(fast_food),
221
- "Reg_Exercise_Y_N_": int(exercise),
222
- # Engineered features
223
- "FSH_LH_Ratio": round(fsh / max(lh, 0.01), 4),
224
- "Total_Follicles": foll_l + foll_r,
225
- "AMH_FSH_Ratio": round(amh / max(fsh, 0.01), 4),
226
- "BMI_Waist_Ratio": round(bmi / max(waist, 1), 4),
227
- "Androgenic_Score": int(hair_growth) + int(skin_dark) + int(hair_loss) + int(pimples),
228
- }
229
 
 
 
230
  try:
231
- pred, prob, sev, base_probs = predict(inp, mdl)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  except Exception as e:
233
- err_html = f'<div style="color:red;padding:20px;font-family:sans-serif">❌ Prediction error: {e}</div>'
234
- return err_html, None, None, "", ""
235
-
236
- # ── Diagnosis HTML ─────────────────────────────────────────────────────────
237
- diag = "πŸ”΄ PCOS DETECTED" if pred else "🟒 NO PCOS DETECTED"
238
- dcol = "#ef4444" if pred else "#10b981"
239
- conf = prob if pred else 1 - prob
240
- ov = sev.get("OVERALL", 0)
241
- svlbl = "Severe" if ov > 0.7 else "Moderate" if ov > 0.4 else "Mild"
242
-
243
- dom_bars = ""
244
- for d in ["METABOLIC", "REPRODUCTIVE", "HYPERANDROGENIC", "GENERAL"]:
245
- v = sev.get(d, 0)
246
- bc = "#ef4444" if v > 0.7 else "#f59e0b" if v > 0.4 else "#10b981"
247
- dom_bars += f"""
248
- <div style="display:flex;align-items:center;gap:10px;margin:6px 0">
249
- <span style="width:130px;font-size:.82rem;color:#374151">{d.capitalize()}</span>
250
- <div style="flex:1;background:#e5e7eb;border-radius:4px;height:10px">
251
- <div style="width:{v*100:.0f}%;background:{bc};height:10px;border-radius:4px"></div>
252
- </div>
253
- <span style="width:38px;text-align:right;font-size:.82rem;font-weight:600;color:{bc}">{v:.0%}</span>
254
- </div>"""
255
-
256
- result_html = f"""
257
- <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
258
- <div style="font-size:1.7rem;font-weight:700;color:{dcol};margin-bottom:16px">{diag}</div>
259
- <div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:20px">
260
- <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
261
- box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid #4f46e5">
262
- <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">PCOS Probability</div>
263
- <div style="font-size:1.7rem;font-weight:700;color:#4f46e5">{prob:.1%}</div>
264
- <div style="font-size:.75rem;color:#6b7280">Threshold: {mdl['threshold']:.3f}</div>
265
- </div>
266
- <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
267
- box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid {dcol}">
268
- <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">Confidence</div>
269
- <div style="font-size:1.7rem;font-weight:700;color:{dcol}">{conf:.1%}</div>
270
- <div style="font-size:.75rem;color:#6b7280">{'Positive' if pred else 'Negative'}</div>
271
- </div>
272
- <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
273
- box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid #f59e0b">
274
- <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">Overall Severity</div>
275
- <div style="font-size:1.7rem;font-weight:700;color:#f59e0b">{ov:.1%}</div>
276
- <div style="font-size:.75rem;color:#6b7280">{svlbl}</div>
277
- </div>
278
- </div>
279
- <div style="background:white;border-radius:10px;padding:16px 20px;box-shadow:0 2px 8px rgba(0,0,0,.07)">
280
- <div style="font-weight:700;margin-bottom:10px;color:#374151">Domain Severity Breakdown</div>
281
- {dom_bars}
282
- </div>
283
- </div>"""
284
-
285
- # ── Infertility risk HTML ──────────────────────────────────────────────────
286
- iscore, itier = infertility_risk(amh, fsh, foll_l, foll_r, cycle, bmi)
287
- tcol = {"Low": "#10b981", "Moderate": "#f59e0b", "High": "#ef4444"}[itier]
288
- ticon = {"Low": "🟒", "Moderate": "🟑", "High": "πŸ”΄"}[itier]
289
-
290
- notes = []
291
- if amh and amh < 1.0: notes.append("⚠️ Very low AMH β€” reduced ovarian reserve")
292
- if amh and amh > 6.0: notes.append("ℹ️ High AMH β€” polycystic morphology likely")
293
- if fsh and fsh > 10: notes.append("⚠️ Elevated FSH β€” diminished ovarian reserve")
294
- if (foll_l + foll_r) >= 20: notes.append("ℹ️ High follicle count β€” consistent with PCOS")
295
- if cycle == "Irregular": notes.append("⚠️ Irregular cycle β€” impacts conception")
296
-
297
- inf_html = f"""
298
- <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
299
- <div style="font-size:1.1rem;font-weight:700;color:{tcol}">{ticon} {itier} Infertility Risk</div>
300
- <div style="font-size:2.2rem;font-weight:700;color:{tcol};margin:8px 0">{iscore:.0%}</div>
301
- <div style="font-size:.85rem;color:#6b7280;margin-bottom:14px">Based on AMH Β· FSH Β· Follicles Β· Cycle Β· BMI</div>
302
- {''.join(f'<div style="font-size:.85rem;margin:5px 0;color:#374151">{n}</div>' for n in notes)}
303
- </div>"""
304
-
305
- # ── Clinical recommendations ───────────────────────────────────────────────
306
- recs = []
307
- if pred:
308
- recs += [
309
- "βœ… Confirm PCOS with transvaginal ultrasound",
310
- "βœ… Full hormonal panel: FSH, LH, AMH, testosterone, DHEAS",
311
- "βœ… Metabolic screen: fasting glucose, insulin, HbA1c, lipid profile",
312
- ]
313
- if cycle == "Irregular":
314
- recs.append("βœ… Discuss cycle regulation β€” OCP or progesterone cycling")
315
- if bmi > 25:
316
- recs.append("βœ… Lifestyle: 5–10% weight loss can restore ovulation")
317
- if bmi > 30:
318
- recs.append("βœ… Consider metformin for insulin sensitisation")
319
- else:
320
- recs += [
321
- "βœ… PCOS unlikely β€” routine annual review recommended",
322
- "βœ… Maintain healthy BMI and regular exercise",
323
- ]
324
- if itier == "High":
325
- recs.append("πŸ”΄ Fertility specialist referral recommended β€” high infertility risk (>60%)")
326
- elif itier == "Moderate":
327
- recs.append("🟑 Consider fertility evaluation if conception not achieved in 6–12 months")
328
-
329
- rec_html = f"""
330
- <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
331
- <div style="font-size:1rem;font-weight:700;color:#374151;margin-bottom:12px">πŸ“‹ Clinical Recommendations</div>
332
- {''.join(f'<div style="font-size:.88rem;margin:7px 0;color:#374151">{r}</div>' for r in recs)}
333
- <div style="margin-top:16px;font-size:.72rem;color:#9ca3af;border-top:1px solid #e5e7eb;padding-top:10px">
334
- βš•οΈ For clinical decision support only. Results must be interpreted by a qualified healthcare provider.
335
- </div>
336
- </div>"""
337
-
338
- radar_fig = make_radar(sev)
339
- base_fig = make_base_bar(base_probs, mdl["threshold"])
340
-
341
- return result_html, radar_fig, base_fig, inf_html, rec_html
342
-
343
-
344
- # ── Gradio UI ──────────────────────────────────────────────────────────────────
345
  css = """
346
- .gradio-container{background:#f0f4ff !important;}
347
- .gr-button-primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;border:none !important;}
 
 
348
  """
349
 
350
- with gr.Blocks(title="PCOS Detection & Risk Assessment", css=css) as demo:
351
-
352
- gr.HTML("""
353
- <div style="background:linear-gradient(135deg,#4f46e5,#7c3aed);border-radius:16px;
354
- padding:28px 32px;color:white;margin-bottom:20px">
355
- <h1 style="margin:0 0 6px;font-size:1.8rem">🩺 PCOS Detection & Risk Assessment</h1>
356
- <p style="margin:0;opacity:.88;font-size:.92rem">
357
- Stacked Ensemble (LR Β· RF Β· GradientBoost Β· CatBoost) &nbsp;|&nbsp;
358
- Domain Severity Scoring &nbsp;|&nbsp; Infertility Risk Stratification
359
- </p>
360
- </div>""")
361
-
362
- with gr.Row():
363
- # ── Column 1: General + Measurements ──────────────────────────────────
364
- with gr.Column():
365
- gr.Markdown("### πŸ‘€ General")
366
- age = gr.Slider(15, 60, value=28, step=1, label="Age (yrs)")
367
- bmi = gr.Slider(10, 60, value=22.0, step=0.1, label="BMI (kg/mΒ²)")
368
- weight = gr.Slider(30, 150, value=60.0, step=0.5, label="Weight (kg)")
369
- hb = gr.Slider(5, 18, value=13.0, step=0.1, label="Hb (g/dL)")
370
- pulse = gr.Slider(40, 120, value=72, step=1, label="Pulse (bpm)")
371
- rr = gr.Slider(10, 30, value=16, step=1, label="Resp Rate (breaths/min)")
372
-
373
- gr.Markdown("### πŸ“ Measurements")
374
- waist = gr.Slider(20, 60, value=32.0, step=0.5, label="Waist (inch)")
375
- hip = gr.Slider(25, 70, value=38.0, step=0.5, label="Hip (inch)")
376
- bp_sys = gr.Slider(80, 200, value=120, step=1, label="BP Systolic (mmHg)")
377
- bp_dia = gr.Slider(50, 130, value=80, step=1, label="BP Diastolic (mmHg)")
378
-
379
- # ── Column 2: Hormones + Follicles ────────────────────────────────────
380
- with gr.Column():
381
- gr.Markdown("### 🩸 Hormones & Labs")
382
- fsh = gr.Slider(0, 50, value=7.0, step=0.1, label="FSH (mIU/mL)")
383
- lh = gr.Slider(0, 50, value=5.0, step=0.1, label="LH (mIU/mL)")
384
- amh = gr.Slider(0, 20, value=3.5, step=0.1, label="AMH (ng/mL)")
385
- prg = gr.Slider(0, 30, value=1.0, step=0.1, label="Progesterone (ng/mL)")
386
- prl = gr.Slider(0, 100, value=15.0, step=0.5, label="Prolactin (ng/mL)")
387
- tsh = gr.Slider(0, 10, value=2.0, step=0.1, label="TSH (mIU/L)")
388
- vitd3 = gr.Slider(0, 100, value=25.0, step=0.5, label="Vit D3 (ng/mL)")
389
- rbs = gr.Slider(50, 400, value=90.0, step=1.0, label="RBS (mg/dL)")
390
-
391
- gr.Markdown("### 🫘 Follicles & Cycle")
392
- foll_l = gr.Slider(0, 30, value=6, step=1, label="Follicles Left")
393
- foll_r = gr.Slider(0, 30, value=6, step=1, label="Follicles Right")
394
- avg_fl = gr.Slider(0, 30, value=8.0, step=0.5, label="Avg Follicle Size L (mm)")
395
- avg_fr = gr.Slider(0, 30, value=8.0, step=0.5, label="Avg Follicle Size R (mm)")
396
- endo = gr.Slider(0, 20, value=8.0, step=0.5, label="Endometrium (mm)")
397
- cycle = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle Type")
398
- cycle_len = gr.Slider(20, 60, value=28, step=1, label="Cycle Length (days)")
399
-
400
- # ── Column 3: Symptoms + Run button ───────────────────────────────────
401
- with gr.Column():
402
- gr.Markdown("### βš•οΈ Symptoms & Lifestyle")
403
- wt_gain = gr.Checkbox(label="Weight Gain")
404
- hair_growth = gr.Checkbox(label="Excess Hair Growth")
405
- skin_dark = gr.Checkbox(label="Skin Darkening")
406
- hair_loss = gr.Checkbox(label="Hair Loss")
407
- pimples = gr.Checkbox(label="Pimples")
408
- fast_food = gr.Checkbox(label="Fast Food Regularly")
409
- exercise = gr.Checkbox(label="Regular Exercise")
410
-
411
- gr.Markdown("---")
412
- run_btn = gr.Button("β–Ά Run Analysis", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  gr.Markdown("""
414
- <div style="font-size:.8rem;color:#6b7280;margin-top:8px">
415
- Fill all inputs then click <b>Run Analysis</b>.
416
- Models load automatically from the <code>models/</code> folder.
417
- </div>""")
418
-
419
- gr.Markdown("---")
420
- gr.Markdown("## πŸ“Š Results")
421
-
422
- result_out = gr.HTML(label="Diagnosis & Severity")
423
-
424
- with gr.Row():
425
- radar_out = gr.Plot(label="Domain Severity Radar")
426
- base_out = gr.Plot(label="Base Model Probabilities")
427
-
428
- with gr.Row():
429
- inf_out = gr.HTML(label="Infertility Risk")
430
- rec_out = gr.HTML(label="Clinical Recommendations")
431
-
432
- all_inputs = [
433
- age, bmi, weight, hb, pulse, rr,
434
- fsh, lh, amh, prg, prl, tsh, vitd3, rbs,
435
- waist, hip, bp_sys, bp_dia,
436
- foll_l, foll_r, avg_fl, avg_fr, endo, cycle, cycle_len,
437
- wt_gain, hair_growth, skin_dark, hair_loss, pimples, fast_food, exercise,
438
- ]
439
-
440
- run_btn.click(
441
- fn=run_analysis,
442
- inputs=all_inputs,
443
- outputs=[result_out, radar_out, base_out, inf_out, rec_out],
444
- )
445
-
446
- if __name__ == "__main__":
447
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ import os
2
+ import re
3
+ import warnings
4
  import numpy as np
5
  import pandas as pd
6
+ import joblib
7
+ import torch
8
+ import torch.nn as nn
9
+ from torchvision import models, transforms
10
+ from PIL import Image
11
  import matplotlib
12
  matplotlib.use("Agg")
13
  import matplotlib.pyplot as plt
14
+ import matplotlib.cm as cm
15
  import gradio as gr
16
+
17
  warnings.filterwarnings("ignore")
18
 
19
+ # ─────────────────────────────────────────────────────────────
20
+ # CONFIG
21
+ # ─────────────────────────────────────────────────────────────
22
+ MODELS_DIR = "models"
23
+ IMG_SIZE = 224
24
+ DEVICE = torch.device("cpu")
25
+
26
  DOMAIN_WEIGHTS = {
27
+ "METABOLIC" : 0.35,
28
+ "REPRODUCTIVE" : 0.40,
29
  "HYPERANDROGENIC": 0.20,
30
+ "GENERAL" : 0.05,
31
  }
32
 
33
+ # ─────────────────────────────────────────────────────────────
34
+ # UTILITIES (mirror pipeline exactly)
35
+ # ─────────────────────────────────────────────────────────────
36
+ def clean_name(name: str) -> str:
37
+ return re.sub(r"[^0-9a-zA-Z_]", "_", name.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ def clean_df_cols(df: pd.DataFrame) -> pd.DataFrame:
40
+ df = df.copy()
41
+ df.columns = [clean_name(c) for c in df.columns]
42
+ return df
43
 
44
+ def apply_severity(domain_models, stats, X_sc: pd.DataFrame) -> pd.DataFrame:
 
45
  df = pd.DataFrame(index=X_sc.index)
46
  for d, (model, fc) in domain_models.items():
47
  avail = [f for f in fc if f in X_sc.columns]
 
49
  df[f"{d}_SEV"] = 0.0
50
  continue
51
  p = model.predict_proba(X_sc[avail])[:, 1]
52
+ mn = stats[d]["min"]
53
+ mx = stats[d]["max"]
54
+ df[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
55
  df = df.fillna(0)
56
  df["OVERALL_SEV"] = sum(
57
  df[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
 
59
  )
60
  return df
61
 
62
+ # ─────────────────────────────────────────────────────────────
63
+ # LOAD TABULAR MODELS
64
+ # ─────────────────────────────────────────────────────────────
65
+ def load_tabular_models():
66
+ try:
67
+ meta_model = joblib.load(f"{MODELS_DIR}/ensemble_meta.pkl")
68
+ base_models = joblib.load(f"{MODELS_DIR}/base_models.pkl")
69
+ domain_models = joblib.load(f"{MODELS_DIR}/domain_models.pkl")
70
+ train_stats = joblib.load(f"{MODELS_DIR}/train_stats.pkl")
71
+ mice_imputer = joblib.load(f"{MODELS_DIR}/mice_imputer.pkl")
72
+ scaler = joblib.load(f"{MODELS_DIR}/scaler.pkl")
73
+ feature_cols = joblib.load(f"{MODELS_DIR}/feature_columns.pkl")
74
+ best_threshold= joblib.load(f"{MODELS_DIR}/best_threshold.pkl")
75
+ print("βœ… Tabular models loaded")
76
+ return meta_model, base_models, domain_models, train_stats, \
77
+ mice_imputer, scaler, feature_cols, best_threshold
78
+ except Exception as e:
79
+ print(f"❌ Tabular model load error: {e}")
80
+ return None, None, None, None, None, None, None, None
81
+
82
+ # ─────────────────────────────────────────────────────────────
83
+ # LOAD IMAGE MODEL
84
+ # ─────────────────────────────────────────────────────────────
85
+ def load_image_model():
86
+ pth_path = f"{MODELS_DIR}/efficientnetb0.pth"
87
+ if not os.path.exists(pth_path):
88
+ print(f"❌ Image model not found at {pth_path}")
89
+ return None
90
+ try:
91
+ model = models.efficientnet_b0(weights=None)
92
+ in_features = model.classifier[1].in_features
93
+ model.classifier[1] = nn.Linear(in_features, 2)
94
+ state = torch.load(pth_path, map_location=DEVICE)
95
+ # Handle various checkpoint formats
96
+ if isinstance(state, dict) and "model_state_dict" in state:
97
+ state = state["model_state_dict"]
98
+ elif isinstance(state, dict) and "state_dict" in state:
99
+ state = state["state_dict"]
100
+ model.load_state_dict(state)
101
+ model.eval()
102
+ print("βœ… Image model loaded")
103
+ return model
104
+ except Exception as e:
105
+ print(f"❌ Image model load error: {e}")
106
+ return None
107
+
108
+ # ─────────────────────────────────────────────────────────────
109
+ # GLOBAL MODEL LOADING
110
+ # ─────────────────────────────────────────────────────────────
111
+ (META_MODEL, BASE_MODELS, DOMAIN_MODELS, TRAIN_STATS,
112
+ MICE_IMPUTER, SCALER, FEATURE_COLS, BEST_THRESHOLD) = load_tabular_models()
113
+
114
+ IMAGE_MODEL = load_image_model()
115
+
116
+ # Image preprocessing (val transform β€” no augmentation)
117
+ IMG_TRANSFORM = transforms.Compose([
118
+ transforms.Resize((IMG_SIZE, IMG_SIZE)),
119
+ transforms.ToTensor(),
120
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
121
+ std =[0.229, 0.224, 0.225]),
122
+ ])
123
+
124
+ # ─────────────────────────────────────────────────────────────
125
+ # CLINICAL PREDICTION
126
+ # ─────────────────────────────────────────────────────────────
127
+ def predict_clinical(
128
+ age, bmi, weight, waist, hip, cycle, cycle_len,
129
+ fsh, lh, amh, prg, prl, tsh, vit_d3,
130
+ follicle_l, follicle_r, endometrium, rbs,
131
+ bp_sys, bp_dia,
132
+ weight_gain, hair_growth, skin_dark, hair_loss, pimples,
133
+ fast_food, exercise, hb, pulse, rr
134
+ ):
135
+ if META_MODEL is None:
136
+ return "❌ Tabular models not loaded.", None, None
137
 
138
+ try:
139
+ # Build raw input matching pipeline column names (before clean_df_cols)
140
+ raw = {
141
+ "Age (yrs)" : age,
142
+ "BMI" : bmi,
143
+ "Weight (Kg)" : weight,
144
+ "Waist(inch)" : waist,
145
+ "Hip(inch)" : hip,
146
+ "Cycle(R/I)" : 1 if cycle == "Irregular" else 0,
147
+ "Cycle length(days)" : cycle_len,
148
+ "FSH(mIU/mL)" : fsh,
149
+ "LH(mIU/mL)" : lh,
150
+ "AMH(ng/mL)" : amh,
151
+ "PRG(ng/mL)" : prg,
152
+ "PRL(ng/mL)" : prl,
153
+ "TSH (mIU/L)" : tsh,
154
+ "Vit D3 (ng/mL)" : vit_d3,
155
+ "Follicle No. (L)" : follicle_l,
156
+ "Follicle No. (R)" : follicle_r,
157
+ "Endometrium (mm)" : endometrium,
158
+ "RBS(mg/dl)" : rbs,
159
+ "BP _Systolic (mmHg)" : bp_sys,
160
+ "BP _Diastolic (mmHg)" : bp_dia,
161
+ "Weight gain(Y/N)" : int(weight_gain),
162
+ "hair growth(Y/N)" : int(hair_growth),
163
+ "Skin darkening (Y/N)" : int(skin_dark),
164
+ "Hair loss(Y/N)" : int(hair_loss),
165
+ "Pimples(Y/N)" : int(pimples),
166
+ "Fast food (Y/N)" : int(fast_food),
167
+ "Reg.Exercise(Y/N)" : int(exercise),
168
+ "Hb(g/dl)" : hb,
169
+ "Pulse rate(bpm)" : pulse,
170
+ "RR (breaths/min)" : rr,
171
+ # Derived features (matching load_and_engineer)
172
+ "FSH/LH" : fsh / (lh + 1e-6),
173
+ "Waist:Hip Ratio" : waist / (hip + 1e-6),
174
+ "FSH_LH_Ratio" : fsh / (lh + 1e-6),
175
+ "Total_Follicles" : follicle_l + follicle_r,
176
+ "AMH_FSH_Ratio" : amh / (fsh + 1e-6),
177
+ "BMI_Waist_Ratio" : bmi / (waist + 1e-6),
178
+ "Androgenic_Score" : int(hair_growth) + int(skin_dark) + int(hair_loss) + int(pimples),
179
+ # Avg follicle sizes β€” user doesn't provide so use 0 (MICE will impute)
180
+ "Avg. F size (L) (mm)" : np.nan,
181
+ "Avg. F size (R) (mm)" : np.nan,
182
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
+ df_raw = pd.DataFrame([raw])
185
+ df_clean = clean_df_cols(df_raw)
186
+
187
+ # ── Separate base features from SEV columns ──────────────
188
+ # feature_cols = base_scaled_cols + SEV cols (as saved by pipeline)
189
+ sev_col_names = [c for c in FEATURE_COLS if c.endswith("_SEV")]
190
+ base_fc = [c for c in FEATURE_COLS if not c.endswith("_SEV")]
191
+
192
+ # Align to base_fc (only columns the MICE+scaler were fitted on)
193
+ X_base = pd.DataFrame(columns=base_fc)
194
+ for col in base_fc:
195
+ X_base[col] = df_clean[col].values if col in df_clean.columns else np.nan
196
+
197
+ X_base = X_base.astype(float)
198
+
199
+ # ── MICE imputation (never refit) ──────────────────────────
200
+ X_imp = pd.DataFrame(
201
+ MICE_IMPUTER.transform(X_base),
202
+ columns=base_fc
203
+ )
204
+
205
+ # ── Scaling (never refit) ──────────────────────────────────
206
+ num_cols = X_imp.select_dtypes(include=np.number).columns
207
+ X_sc = X_imp.copy()
208
+ X_sc[num_cols] = SCALER.transform(X_imp[num_cols])
209
+
210
+ # ── Domain severity ─────────────────────────────────────────
211
+ # Pass X_raw (unscaled, raw index) and X_sc to apply_severity
212
+ sev_df = apply_severity(DOMAIN_MODELS, TRAIN_STATS, X_sc)
213
+
214
+ # ── Concat and reindex to exact feature_cols order ──────────
215
+ X_final = pd.concat([X_sc, sev_df], axis=1)
216
+ # Add any missing SEV columns as 0
217
+ for col in FEATURE_COLS:
218
+ if col not in X_final.columns:
219
+ X_final[col] = 0.0
220
+ X_final = X_final[FEATURE_COLS]
221
+
222
+ # ── Base model predictions ───────────────────────────────────
223
+ meta_input = pd.DataFrame()
224
+ for name, model in BASE_MODELS.items():
225
+ meta_input[name] = model.predict_proba(X_final)[:, 1]
226
+
227
+ # ── Ensemble prediction ──────────────────────────────────────
228
+ prob = float(META_MODEL.predict_proba(meta_input)[:, 1][0])
229
+ pred = int(prob >= BEST_THRESHOLD)
230
+ label = "πŸ”΄ PCOS Detected" if pred == 1 else "🟒 No PCOS"
231
+
232
+ # ── Risk tier ────────────────────────────────────────────────
233
+ if prob < 0.33:
234
+ risk = "Low Risk"
235
+ elif prob < 0.66:
236
+ risk = "Moderate Risk"
237
+ else:
238
+ risk = "High Risk"
239
+
240
+ # ── Severity scores ──────────────────────────────────────────
241
+ sev_vals = {
242
+ "Metabolic" : float(sev_df.get("METABOLIC_SEV", pd.Series([0])).iloc[0]),
243
+ "Reproductive" : float(sev_df.get("REPRODUCTIVE_SEV", pd.Series([0])).iloc[0]),
244
+ "Hyperandrogenic": float(sev_df.get("HYPERANDROGENIC_SEV", pd.Series([0])).iloc[0]),
245
+ "General" : float(sev_df.get("GENERAL_SEV", pd.Series([0])).iloc[0]),
246
+ }
247
 
248
+ result_text = (
249
+ f"**Diagnosis: {label}**\n\n"
250
+ f"PCOS Probability: **{prob*100:.1f}%**\n"
251
+ f"Risk Level: **{risk}**\n"
252
+ f"Threshold used: {BEST_THRESHOLD:.4f}\n\n"
253
+ f"**Domain Severity Scores:**\n"
254
+ + "\n".join(f"- {k}: {v*100:.1f}%" for k, v in sev_vals.items())
255
+ + f"\n- Overall: {float(sev_df.get('OVERALL_SEV', pd.Series([0])).iloc[0])*100:.1f}%"
256
+ )
 
 
 
 
 
 
 
 
 
257
 
258
+ # ── Radar chart ───────────────────────────────────────────────
259
+ radar_fig = make_radar_chart(sev_vals, prob)
260
 
261
+ # ── Bar chart ─────────────────────────────────────────────────
262
+ bar_fig = make_bar_chart(meta_input.iloc[0].to_dict(), prob)
263
+
264
+ return result_text, radar_fig, bar_fig
265
+
266
+ except Exception as e:
267
+ import traceback
268
+ return f"❌ Prediction error: {e}\n\n{traceback.format_exc()}", None, None
269
+
270
+
271
+ # ─────────────────────────────────────────────────────────────
272
+ # IMAGE PREDICTION
273
+ # ─────────────────────────────────────────────────────────────
274
+ def predict_image(image):
275
+ if IMAGE_MODEL is None:
276
+ return "❌ Image model not loaded.", None
277
+
278
+ if image is None:
279
+ return "⚠️ Please upload an ultrasound image.", None
280
+
281
+ try:
282
+ if not isinstance(image, Image.Image):
283
+ image = Image.fromarray(image)
284
+ image_rgb = image.convert("RGB")
285
+
286
+ tensor = IMG_TRANSFORM(image_rgb).unsqueeze(0).to(DEVICE)
287
+
288
+ # ── Forward pass ──────────────────────────────────────────
289
+ IMAGE_MODEL.eval()
290
+ with torch.no_grad():
291
+ logits = IMAGE_MODEL(tensor)
292
+ probs = torch.softmax(logits, dim=1)
293
+ pcos_prob = float(probs[0, 1])
294
+ pred = int(pcos_prob >= 0.5)
295
+
296
+ label = "πŸ”΄ PCOS Detected" if pred == 1 else "🟒 No PCOS"
297
+ confidence = pcos_prob if pred == 1 else (1 - pcos_prob)
298
+
299
+ if pcos_prob < 0.33:
300
+ risk = "Low Risk"
301
+ elif pcos_prob < 0.66:
302
+ risk = "Moderate Risk"
303
+ else:
304
+ risk = "High Risk"
305
+
306
+ result_text = (
307
+ f"**Diagnosis: {label}**\n\n"
308
+ f"PCOS Probability: **{pcos_prob*100:.1f}%**\n"
309
+ f"Non-PCOS Probability: **{(1-pcos_prob)*100:.1f}%**\n"
310
+ f"Confidence: **{confidence*100:.1f}%**\n"
311
+ f"Risk Level: **{risk}**\n\n"
312
+ f"*Model: EfficientNetB0 (ImageNet pretrained, fine-tuned on PCOS dataset)*"
313
+ )
314
+
315
+ # ── Grad-CAM ──────────────────────────────────────────────
316
+ gradcam_fig = compute_gradcam(image_rgb, tensor, pcos_prob)
317
+
318
+ return result_text, gradcam_fig
319
 
320
+ except Exception as e:
321
+ import traceback
322
+ return f"❌ Image prediction error: {e}\n\n{traceback.format_exc()}", None
323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
 
325
+ def compute_gradcam(orig_img, tensor, prob):
326
+ """Grad-CAM on EfficientNetB0 features layer."""
327
  try:
328
+ gradients = []
329
+ activations = []
330
+
331
+ def save_gradient(grad):
332
+ gradients.append(grad)
333
+
334
+ # Hook on the last conv layer of EfficientNetB0 features
335
+ target_layer = IMAGE_MODEL.features[-1]
336
+
337
+ def forward_hook(module, input, output):
338
+ activations.append(output)
339
+ output.register_hook(save_gradient)
340
+
341
+ handle = target_layer.register_forward_hook(forward_hook)
342
+
343
+ IMAGE_MODEL.eval()
344
+ output = IMAGE_MODEL(tensor)
345
+ IMAGE_MODEL.zero_grad()
346
+ class_score = output[0, 1]
347
+ class_score.backward()
348
+
349
+ handle.remove()
350
+
351
+ if not gradients or not activations:
352
+ return None
353
+
354
+ grad = gradients[0].squeeze(0).cpu().numpy() # (C, H, W)
355
+ act = activations[0].squeeze(0).cpu().detach().numpy()
356
+
357
+ weights = grad.mean(axis=(1, 2)) # (C,)
358
+ cam = np.zeros(act.shape[1:], dtype=np.float32)
359
+ for i, w in enumerate(weights):
360
+ cam += w * act[i]
361
+
362
+ cam = np.maximum(cam, 0)
363
+ if cam.max() > 0:
364
+ cam = cam / cam.max()
365
+
366
+ # Resize cam to image size
367
+ from PIL import Image as PILImage
368
+ cam_img = PILImage.fromarray((cam * 255).astype(np.uint8)).resize(
369
+ (IMG_SIZE, IMG_SIZE), PILImage.BILINEAR
370
+ )
371
+ cam_np = np.array(cam_img) / 255.0
372
+
373
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4))
374
+ orig_resized = orig_img.resize((IMG_SIZE, IMG_SIZE))
375
+
376
+ axes[0].imshow(orig_resized)
377
+ axes[0].set_title("Original", fontsize=12)
378
+ axes[0].axis("off")
379
+
380
+ axes[1].imshow(cam_np, cmap="jet")
381
+ axes[1].set_title("Grad-CAM Heatmap", fontsize=12)
382
+ axes[1].axis("off")
383
+
384
+ heatmap = cm.jet(cam_np)[:, :, :3]
385
+ overlay = 0.55 * np.array(orig_resized) / 255.0 + 0.45 * heatmap
386
+ overlay = np.clip(overlay, 0, 1)
387
+ axes[2].imshow(overlay)
388
+ axes[2].set_title(f"Overlay (PCOS: {prob*100:.1f}%)", fontsize=12)
389
+ axes[2].axis("off")
390
+
391
+ plt.suptitle("EfficientNetB0 β€” Grad-CAM Visualization", fontsize=13, fontweight="bold")
392
+ plt.tight_layout()
393
+ return fig
394
+
395
  except Exception as e:
396
+ print(f"Grad-CAM error: {e}")
397
+ return None
398
+
399
+
400
+ # ─────────────────────────────────────────────────────────────
401
+ # CHART HELPERS
402
+ # ─────────────────────────────────────────────────────────────
403
+ def make_radar_chart(sev_vals: dict, overall_prob: float):
404
+ domains = list(sev_vals.keys())
405
+ values = [sev_vals[d] for d in domains]
406
+ N = len(domains)
407
+ angles = [n / float(N) * 2 * np.pi for n in range(N)]
408
+ angles += angles[:1]
409
+ values_plot = values + values[:1]
410
+
411
+ fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
412
+ ax.set_facecolor("#0e1117")
413
+ fig.patch.set_facecolor("#0e1117")
414
+
415
+ ax.plot(angles, values_plot, "o-", linewidth=2, color="#e040fb")
416
+ ax.fill(angles, values_plot, alpha=0.3, color="#e040fb")
417
+ ax.set_xticks(angles[:-1])
418
+ ax.set_xticklabels(domains, color="white", fontsize=10)
419
+ ax.set_ylim(0, 1)
420
+ ax.set_yticks([0.25, 0.5, 0.75, 1.0])
421
+ ax.set_yticklabels(["25%", "50%", "75%", "100%"], color="gray", fontsize=7)
422
+ ax.tick_params(colors="white")
423
+ ax.spines["polar"].set_color("gray")
424
+ ax.grid(color="gray", alpha=0.3)
425
+ ax.set_title(f"Domain Severity (Overall: {overall_prob*100:.1f}%)",
426
+ color="white", fontsize=11, pad=15)
427
+ return fig
428
+
429
+
430
+ def make_bar_chart(base_probs: dict, ensemble_prob: float):
431
+ models_list = list(base_probs.keys()) + ["Ensemble"]
432
+ probs_list = list(base_probs.values()) + [ensemble_prob]
433
+ colors = ["#42a5f5", "#42a5f5", "#42a5f5", "#42a5f5", "#e040fb"]
434
+ if len(models_list) != len(colors):
435
+ colors = ["#42a5f5"] * (len(models_list) - 1) + ["#e040fb"]
436
+
437
+ fig, ax = plt.subplots(figsize=(6, 3.5))
438
+ ax.set_facecolor("#0e1117")
439
+ fig.patch.set_facecolor("#0e1117")
440
+
441
+ bars = ax.barh(models_list, probs_list, color=colors[:len(models_list)], height=0.5)
442
+ ax.axvline(x=0.5, color="white", linestyle="--", alpha=0.5, linewidth=1)
443
+ ax.set_xlim(0, 1)
444
+ ax.set_xlabel("PCOS Probability", color="white", fontsize=10)
445
+ ax.set_title("Model Predictions", color="white", fontsize=11)
446
+ ax.tick_params(colors="white")
447
+ ax.spines["bottom"].set_color("gray")
448
+ ax.spines["left"].set_color("gray")
449
+ ax.spines["top"].set_visible(False)
450
+ ax.spines["right"].set_visible(False)
451
+ for bar, prob in zip(bars, probs_list):
452
+ ax.text(min(prob + 0.02, 0.95), bar.get_y() + bar.get_height() / 2,
453
+ f"{prob*100:.1f}%", va="center", color="white", fontsize=9)
454
+ plt.tight_layout()
455
+ return fig
456
+
457
+
458
+ # ─────────────────────────────────────────────────────────────
459
+ # GRADIO UI
460
+ # ─────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  css = """
462
+ body { background: #0e1117; }
463
+ .gradio-container { font-family: 'Inter', sans-serif; }
464
+ .tab-nav button { font-size: 15px; font-weight: 600; }
465
+ h1 { text-align: center; }
466
  """
467
 
468
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple"), css=css, title="PCOS Detection") as demo:
469
+
470
+ gr.Markdown("""
471
+ # 🩺 PCOS Detection System
472
+ **AI-powered Polycystic Ovary Syndrome detection using clinical features and ultrasound images**
473
+ > ⚠️ For research/educational purposes only. Not a substitute for professional medical advice.
474
+ """)
475
+
476
+ with gr.Tabs():
477
+
478
+ # ── TAB 1: CLINICAL ──────────────────────────────────────────────────
479
+ with gr.TabItem("πŸ”¬ Clinical Feature Analysis"):
480
+ gr.Markdown("### Enter Patient Clinical Data")
481
+
482
+ with gr.Row():
483
+ with gr.Column(scale=1):
484
+ gr.Markdown("#### πŸ“Š Anthropometric")
485
+ age = gr.Slider(18, 50, value=28, step=1, label="Age (yrs)")
486
+ bmi = gr.Slider(15.0, 50.0, value=24.0, step=0.1, label="BMI (kg/mΒ²)")
487
+ weight = gr.Slider(30.0, 130.0, value=60.0, step=0.5, label="Weight (Kg)")
488
+ waist = gr.Slider(20.0, 60.0, value=32.0, step=0.5, label="Waist (inch)")
489
+ hip = gr.Slider(25.0, 70.0, value=38.0, step=0.5, label="Hip (inch)")
490
+
491
+ gr.Markdown("#### 🩸 Vitals")
492
+ bp_sys = gr.Slider(80, 180, value=120, step=1, label="BP Systolic (mmHg)")
493
+ bp_dia = gr.Slider(50, 120, value=80, step=1, label="BP Diastolic (mmHg)")
494
+ pulse = gr.Slider(50, 120, value=72, step=1, label="Pulse Rate (bpm)")
495
+ rr = gr.Slider(10, 30, value=18, step=1, label="RR (breaths/min)")
496
+ hb = gr.Slider(7.0, 18.0, value=12.5, step=0.1, label="Hb (g/dl)")
497
+ rbs = gr.Slider(60.0, 300.0, value=95.0, step=1.0, label="RBS (mg/dl)")
498
+
499
+ with gr.Column(scale=1):
500
+ gr.Markdown("#### πŸ”¬ Hormones")
501
+ fsh = gr.Slider(0.0, 30.0, value=6.0, step=0.1, label="FSH (mIU/mL)")
502
+ lh = gr.Slider(0.0, 50.0, value=8.0, step=0.1, label="LH (mIU/mL)")
503
+ amh = gr.Slider(0.0, 20.0, value=3.5, step=0.1, label="AMH (ng/mL)")
504
+ prg = gr.Slider(0.0, 30.0, value=0.8, step=0.1, label="Progesterone (ng/mL)")
505
+ prl = gr.Slider(0.0, 100.0, value=15.0, step=0.5, label="Prolactin (ng/mL)")
506
+ tsh = gr.Slider(0.0, 10.0, value=2.5, step=0.1, label="TSH (mIU/L)")
507
+ vit_d3 = gr.Slider(0.0, 100.0, value=25.0, step=0.5, label="Vit D3 (ng/mL)")
508
+
509
+ gr.Markdown("#### πŸ”„ Cycle & Follicles")
510
+ cycle = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle Type")
511
+ cycle_len = gr.Slider(21, 45, value=28, step=1, label="Cycle Length (days)")
512
+ follicle_l = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Left)")
513
+ follicle_r = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Right)")
514
+ endometrium= gr.Slider(3.0, 20.0, value=8.0, step=0.1, label="Endometrium (mm)")
515
+
516
+ with gr.Column(scale=1):
517
+ gr.Markdown("#### 🧬 Symptoms (Yes/No)")
518
+ weight_gain = gr.Checkbox(label="Weight Gain")
519
+ hair_growth = gr.Checkbox(label="Excess Hair Growth")
520
+ skin_dark = gr.Checkbox(label="Skin Darkening")
521
+ hair_loss = gr.Checkbox(label="Hair Loss")
522
+ pimples = gr.Checkbox(label="Pimples / Acne")
523
+ fast_food = gr.Checkbox(label="Fast Food Consumption")
524
+ exercise = gr.Checkbox(label="Regular Exercise", value=True)
525
+
526
+ gr.Markdown("---")
527
+ clinical_btn = gr.Button("πŸ” Predict PCOS", variant="primary", size="lg")
528
+
529
+ with gr.Row():
530
+ clinical_result = gr.Markdown(label="Diagnosis Result")
531
+
532
+ with gr.Row():
533
+ radar_plot = gr.Plot(label="Domain Severity Radar")
534
+ bar_plot = gr.Plot(label="Model Confidence")
535
+
536
+ clinical_btn.click(
537
+ fn=predict_clinical,
538
+ inputs=[
539
+ age, bmi, weight, waist, hip, cycle, cycle_len,
540
+ fsh, lh, amh, prg, prl, tsh, vit_d3,
541
+ follicle_l, follicle_r, endometrium, rbs,
542
+ bp_sys, bp_dia,
543
+ weight_gain, hair_growth, skin_dark, hair_loss, pimples,
544
+ fast_food, exercise, hb, pulse, rr
545
+ ],
546
+ outputs=[clinical_result, radar_plot, bar_plot]
547
+ )
548
+
549
+ # ── TAB 2: IMAGE ─────────────────────────────────────────────────────
550
+ with gr.TabItem("πŸ–ΌοΈ Ultrasound Image Analysis"):
551
+ gr.Markdown("### Upload Ovarian Ultrasound Image")
552
+
553
+ with gr.Row():
554
+ with gr.Column(scale=1):
555
+ img_input = gr.Image(
556
+ label="Upload Ultrasound (PNG/JPG)",
557
+ type="pil",
558
+ height=300
559
+ )
560
+ image_btn = gr.Button("πŸ” Analyze Image", variant="primary", size="lg")
561
+ gr.Markdown("""
562
+ **Tips for best results:**
563
+ - Use clear ovarian ultrasound images
564
+ - PNG or JPG format
565
+ - Model: EfficientNetB0 fine-tuned on PCOS dataset
566
+ """)
567
+
568
+ with gr.Column(scale=2):
569
+ img_result = gr.Markdown(label="Image Analysis Result")
570
+ gradcam_plot = gr.Plot(label="Grad-CAM Visualization")
571
+
572
+ image_btn.click(
573
+ fn=predict_image,
574
+ inputs=[img_input],
575
+ outputs=[img_result, gradcam_plot]
576
+ )
577
+
578
+ # ── TAB 3: INFO ──────────────────────────────────────────────────────
579
+ with gr.TabItem("ℹ️ About"):
580
  gr.Markdown("""
581
+ ## About This System
582
+
583
+ ### πŸ”¬ Clinical Model
584
+ - **Pipeline:** MICE Imputation β†’ RobustScaler β†’ Domain Severity β†’ Stacked Ensemble
585
+ - **Base Models:** Logistic Regression, Random Forest, Gradient Boosting, CatBoost
586
+ - **Meta-Learner:** CalibratedClassifierCV (LogisticRegressionCV, isotonic calibration)
587
+ - **Threshold:** Youden-J optimal threshold on test ROC
588
+
589
+ **Domain Severity Scoring:**
590
+ | Domain | Weight | Features |
591
+ |--------|--------|----------|
592
+ | Reproductive | 40% | FSH, LH, AMH, Follicles, Cycle |
593
+ | Metabolic | 35% | BMI, Weight, Waist, RBS, BP |
594
+ | Hyperandrogenic | 20% | Hair growth, Skin darkening, PRL |
595
+ | General | 5% | Age, Hb, TSH, Vit D3 |
596
+
597
+ ### πŸ–ΌοΈ Image Model
598
+ - **Architecture:** EfficientNetB0 (ImageNet pretrained, fine-tuned)
599
+ - **Input:** 224Γ—224 RGB ultrasound images
600
+ - **Visualization:** Grad-CAM heatmaps showing attention regions
601
+
602
+ ### ⚠️ Disclaimer
603
+ This tool is for **research and educational purposes only**.
604
+ Always consult a qualified healthcare professional for medical decisions.
605
+ """)
606
+
607
+ demo.launch(server_name="0.0.0.0", server_port=7860)