DheivaCodes commited on
Commit
9c4e54a
Β·
verified Β·
1 Parent(s): 2082bee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +310 -356
app.py CHANGED
@@ -31,7 +31,7 @@ DOMAIN_WEIGHTS = {
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())
@@ -42,69 +42,117 @@ def clean_df_cols(df: pd.DataFrame) -> pd.DataFrame:
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]
48
  if not avail:
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]
58
- for d in DOMAIN_WEIGHTS if f"{d}_SEV" in df
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
  # ─────────────────────────────────────────────────────────────
@@ -113,7 +161,6 @@ def load_image_model():
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(),
@@ -121,6 +168,7 @@ IMG_TRANSFORM = transforms.Compose([
121
  std =[0.229, 0.224, 0.225]),
122
  ])
123
 
 
124
  # ─────────────────────────────────────────────────────────────
125
  # CLINICAL PREDICTION
126
  # ─────────────────────────────────────────────────────────────
@@ -133,147 +181,141 @@ def predict_clinical(
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
@@ -282,175 +324,125 @@ def predict_image(image):
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
 
@@ -458,150 +450,112 @@ def make_bar_chart(base_probs: dict, ensemble_prob: float):
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)
 
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())
 
42
  return df
43
 
44
  def apply_severity(domain_models, stats, X_sc: pd.DataFrame) -> pd.DataFrame:
45
+ out = 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]
48
  if not avail:
49
+ out[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
+ out[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
55
+ out = out.fillna(0)
56
+ out["OVERALL_SEV"] = sum(
57
+ out[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
58
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in out
59
  )
60
+ return out
61
+
62
+
63
+ # ─────────────────────────────────────────────────────────────
64
+ # SAFE IMPUTATION
65
+ # Replaces MICE.transform() which breaks when sklearn versions
66
+ # differ between training env and deployment env.
67
+ # Uses RobustScaler's center_ (training medians) to fill NaNs.
68
+ # ─────────────────────────────────────────────────────────────
69
+ def safe_impute(X: pd.DataFrame, scaler) -> pd.DataFrame:
70
+ X_imp = X.copy().astype(float)
71
+ num_cols = X_imp.select_dtypes(include=np.number).columns.tolist()
72
+
73
+ if hasattr(scaler, "center_") and scaler.center_ is not None:
74
+ scaler_cols = getattr(scaler, "feature_names_in_", None)
75
+ if scaler_cols is not None:
76
+ median_map = dict(zip(scaler_cols, scaler.center_))
77
+ else:
78
+ median_map = dict(zip(num_cols, scaler.center_))
79
+ for col in num_cols:
80
+ if X_imp[col].isna().any():
81
+ X_imp[col] = X_imp[col].fillna(median_map.get(col, 0.0))
82
+ else:
83
+ X_imp = X_imp.fillna(0)
84
+
85
+ return X_imp
86
+
87
 
88
  # ─────────────────────────────────────────────────────────────
89
  # LOAD TABULAR MODELS
90
  # ─────────────────────────────────────────────────────────────
91
  def load_tabular_models():
92
  try:
93
+ meta_model = joblib.load(f"{MODELS_DIR}/ensemble_meta.pkl")
94
+ base_models = joblib.load(f"{MODELS_DIR}/base_models.pkl")
95
+ domain_models = joblib.load(f"{MODELS_DIR}/domain_models.pkl")
96
+ train_stats = joblib.load(f"{MODELS_DIR}/train_stats.pkl")
97
+ scaler = joblib.load(f"{MODELS_DIR}/scaler.pkl")
98
+ feature_cols = joblib.load(f"{MODELS_DIR}/feature_columns.pkl")
99
+ best_threshold = joblib.load(f"{MODELS_DIR}/best_threshold.pkl")
100
+
101
+ # MICE is optional β€” load but don't crash if version-incompatible
102
+ mice_imputer = None
103
+ try:
104
+ mice_imputer = joblib.load(f"{MODELS_DIR}/mice_imputer.pkl")
105
+ print("βœ… MICE imputer loaded")
106
+ except Exception as e:
107
+ print(f"⚠️ MICE imputer skipped ({e}) β€” using median fallback")
108
+
109
  print("βœ… Tabular models loaded")
110
+ return (meta_model, base_models, domain_models, train_stats,
111
+ mice_imputer, scaler, feature_cols, best_threshold)
112
+
113
  except Exception as e:
114
  print(f"❌ Tabular model load error: {e}")
115
  return None, None, None, None, None, None, None, None
116
 
117
+
118
  # ─────────────────────────────────────────────────────────────
119
  # LOAD IMAGE MODEL
120
  # ─────────────────────────────────────────────────────────────
121
  def load_image_model():
122
+ candidates = [
123
+ f"{MODELS_DIR}/efficientnetb0.pth",
124
+ f"{MODELS_DIR}/best_model.pth",
125
+ f"{MODELS_DIR}/EfficientNetB0.pth",
126
+ ]
127
+ pth_path = next((p for p in candidates if os.path.exists(p)), None)
128
+
129
+ if pth_path is None:
130
+ folder_files = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else "folder missing"
131
+ print(f"❌ Image model not found. models/ contains: {folder_files}")
132
  return None
133
+
134
  try:
135
  model = models.efficientnet_b0(weights=None)
136
  in_features = model.classifier[1].in_features
137
  model.classifier[1] = nn.Linear(in_features, 2)
138
+
139
+ state = torch.load(pth_path, map_location=DEVICE, weights_only=False)
140
+ if isinstance(state, dict):
141
+ for key in ("model_state_dict", "state_dict", "model"):
142
+ if key in state:
143
+ state = state[key]
144
+ break
145
+
146
+ model.load_state_dict(state, strict=False)
147
  model.eval()
148
+ print(f"βœ… Image model loaded from {pth_path}")
149
  return model
150
+
151
  except Exception as e:
152
  print(f"❌ Image model load error: {e}")
153
  return None
154
 
155
+
156
  # ─────────────────────────────────────────────────────────────
157
  # GLOBAL MODEL LOADING
158
  # ─────────────────────────────────────────────────────────────
 
161
 
162
  IMAGE_MODEL = load_image_model()
163
 
 
164
  IMG_TRANSFORM = transforms.Compose([
165
  transforms.Resize((IMG_SIZE, IMG_SIZE)),
166
  transforms.ToTensor(),
 
168
  std =[0.229, 0.224, 0.225]),
169
  ])
170
 
171
+
172
  # ─────────────────────────────────────────────────────────────
173
  # CLINICAL PREDICTION
174
  # ─────────────────────────────────────────────────────────────
 
181
  fast_food, exercise, hb, pulse, rr
182
  ):
183
  if META_MODEL is None:
184
+ return "❌ Tabular models not loaded. Check that all .pkl files are in the models/ folder.", None, None
185
 
186
  try:
187
+ fsh_f = float(fsh); lh_f = float(lh); amh_f = float(amh)
188
+ bmi_f = float(bmi); waist_f = float(waist); hip_f = float(hip)
189
+
190
  raw = {
191
+ "Age (yrs)" : float(age),
192
+ "BMI" : bmi_f,
193
+ "Weight (Kg)" : float(weight),
194
+ "Waist(inch)" : waist_f,
195
+ "Hip(inch)" : hip_f,
196
+ "Cycle(R/I)" : 1 if cycle == "Irregular" else 0,
197
+ "Cycle length(days)" : float(cycle_len),
198
+ "FSH(mIU/mL)" : fsh_f,
199
+ "LH(mIU/mL)" : lh_f,
200
+ "AMH(ng/mL)" : amh_f,
201
+ "PRG(ng/mL)" : float(prg),
202
+ "PRL(ng/mL)" : float(prl),
203
+ "TSH (mIU/L)" : float(tsh),
204
+ "Vit D3 (ng/mL)" : float(vit_d3),
205
+ "Follicle No. (L)" : float(follicle_l),
206
+ "Follicle No. (R)" : float(follicle_r),
207
+ "Endometrium (mm)" : float(endometrium),
208
+ "RBS(mg/dl)" : float(rbs),
209
+ "BP _Systolic (mmHg)" : float(bp_sys),
210
+ "BP _Diastolic (mmHg)": float(bp_dia),
211
+ "Weight gain(Y/N)" : int(bool(weight_gain)),
212
+ "hair growth(Y/N)" : int(bool(hair_growth)),
213
+ "Skin darkening (Y/N)": int(bool(skin_dark)),
214
+ "Hair loss(Y/N)" : int(bool(hair_loss)),
215
+ "Pimples(Y/N)" : int(bool(pimples)),
216
+ "Fast food (Y/N)" : int(bool(fast_food)),
217
+ "Reg.Exercise(Y/N)" : int(bool(exercise)),
218
+ "Hb(g/dl)" : float(hb),
219
+ "Pulse rate(bpm)" : float(pulse),
220
+ "RR (breaths/min)" : float(rr),
221
+ # Engineered (load_and_engineer)
222
+ "FSH/LH" : fsh_f / (lh_f + 1e-6),
223
+ "Waist:Hip Ratio" : waist_f / (hip_f + 1e-6),
224
+ "FSH_LH_Ratio" : fsh_f / (lh_f + 1e-6),
225
+ "Total_Follicles" : float(follicle_l) + float(follicle_r),
226
+ "AMH_FSH_Ratio" : amh_f / (fsh_f + 1e-6),
227
+ "BMI_Waist_Ratio" : bmi_f / (waist_f + 1e-6),
228
+ "Androgenic_Score" : (int(bool(hair_growth)) + int(bool(skin_dark))
229
+ + int(bool(hair_loss)) + int(bool(pimples))),
230
+ "Avg. F size (L) (mm)": np.nan, # not collected β€” imputed
231
+ "Avg. F size (R) (mm)": np.nan,
232
  }
233
 
234
+ df_clean = clean_df_cols(pd.DataFrame([raw]))
 
235
 
236
+ # Separate base vs SEV columns
237
+ base_fc = [c for c in FEATURE_COLS if not c.endswith("_SEV")]
 
 
238
 
239
+ X_base = pd.DataFrame(index=[0], columns=base_fc, dtype=float)
 
240
  for col in base_fc:
241
+ X_base[col] = df_clean[col].values[0] if col in df_clean.columns else np.nan
242
+
243
+ # Imputation β€” MICE with median fallback
244
+ if MICE_IMPUTER is not None:
245
+ try:
246
+ arr = MICE_IMPUTER.transform(X_base.values)
247
+ X_imp = pd.DataFrame(arr, columns=base_fc)
248
+ except Exception:
249
+ X_imp = safe_impute(X_base, SCALER)
250
+ else:
251
+ X_imp = safe_impute(X_base, SCALER)
252
 
253
+ # Scaling
254
  num_cols = X_imp.select_dtypes(include=np.number).columns
255
  X_sc = X_imp.copy()
256
  X_sc[num_cols] = SCALER.transform(X_imp[num_cols])
257
 
258
+ # Domain severity
 
259
  sev_df = apply_severity(DOMAIN_MODELS, TRAIN_STATS, X_sc)
260
 
261
+ # Concat β†’ exact feature_cols order
262
+ X_final = pd.concat([X_sc.reset_index(drop=True),
263
+ sev_df.reset_index(drop=True)], axis=1)
264
  for col in FEATURE_COLS:
265
  if col not in X_final.columns:
266
  X_final[col] = 0.0
267
  X_final = X_final[FEATURE_COLS]
268
 
269
+ # Base + ensemble predictions
270
+ meta_input = pd.DataFrame(index=[0])
271
+ for name, mdl in BASE_MODELS.items():
272
+ meta_input[name] = mdl.predict_proba(X_final)[:, 1]
273
 
 
274
  prob = float(META_MODEL.predict_proba(meta_input)[:, 1][0])
275
+ pred = int(prob >= float(BEST_THRESHOLD))
276
  label = "πŸ”΄ PCOS Detected" if pred == 1 else "🟒 No PCOS"
277
+ risk = ("Low Risk" if prob < 0.33
278
+ else "Moderate Risk" if prob < 0.66
279
+ else "High Risk")
280
 
281
+ def sev_val(col):
282
+ return float(sev_df[col].iloc[0]) if col in sev_df.columns else 0.0
 
 
 
 
 
283
 
 
284
  sev_vals = {
285
+ "Metabolic" : sev_val("METABOLIC_SEV"),
286
+ "Reproductive" : sev_val("REPRODUCTIVE_SEV"),
287
+ "Hyperandrogenic": sev_val("HYPERANDROGENIC_SEV"),
288
+ "General" : sev_val("GENERAL_SEV"),
289
  }
290
 
291
  result_text = (
292
+ f"## Diagnosis: {label}\n\n"
293
+ f"**PCOS Probability:** {prob*100:.1f}% \n"
294
+ f"**Risk Level:** {risk} \n"
295
+ f"**Threshold (Youden-J):** {float(BEST_THRESHOLD):.4f}\n\n"
296
+ f"### Domain Severity\n"
297
+ + "\n".join(f"- **{k}:** {v*100:.1f}%" for k, v in sev_vals.items())
298
+ + f"\n- **Overall:** {sev_val('OVERALL_SEV')*100:.1f}%"
299
  )
300
 
301
+ return result_text, make_radar_chart(sev_vals, prob), make_bar_chart(meta_input.iloc[0].to_dict(), prob)
 
 
 
 
 
 
302
 
303
  except Exception as e:
304
  import traceback
305
+ return f"❌ Prediction error: {e}\n\n```\n{traceback.format_exc()}\n```", None, None
306
 
307
 
308
  # ─────────────────────────────────────────────────────────────
309
+ # IMAGE PREDICTION + GRAD-CAM
310
  # ─────────────────────────────────────────────────────────────
311
  def predict_image(image):
312
  if IMAGE_MODEL is None:
313
+ files = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else "folder missing"
314
+ return (
315
+ f"❌ Image model not loaded.\n\n"
316
+ f"Files in `models/`: `{files}`\n\n"
317
+ "Upload `efficientnetb0.pth` (or `best_model.pth`) to the models/ folder."
318
+ ), None
319
 
320
  if image is None:
321
  return "⚠️ Please upload an ultrasound image.", None
 
324
  if not isinstance(image, Image.Image):
325
  image = Image.fromarray(image)
326
  image_rgb = image.convert("RGB")
 
327
  tensor = IMG_TRANSFORM(image_rgb).unsqueeze(0).to(DEVICE)
328
 
 
329
  IMAGE_MODEL.eval()
330
  with torch.no_grad():
331
+ logits = IMAGE_MODEL(tensor)
332
+ probs_t = torch.softmax(logits, dim=1)
333
+ pcos_p = float(probs_t[0, 1])
 
334
 
335
+ pred = int(pcos_p >= 0.5)
336
  label = "πŸ”΄ PCOS Detected" if pred == 1 else "🟒 No PCOS"
337
+ conf = pcos_p if pred == 1 else (1 - pcos_p)
338
+ risk = ("Low Risk" if pcos_p < 0.33
339
+ else "Moderate Risk" if pcos_p < 0.66
340
+ else "High Risk")
 
 
 
 
341
 
342
  result_text = (
343
+ f"## Diagnosis: {label}\n\n"
344
+ f"**PCOS Probability:** {pcos_p*100:.1f}% \n"
345
+ f"**Non-PCOS Probability:** {(1-pcos_p)*100:.1f}% \n"
346
+ f"**Confidence:** {conf*100:.1f}% \n"
347
+ f"**Risk Level:** {risk}\n\n"
348
+ "*Model: EfficientNetB0 (fine-tuned on PCOS ultrasound dataset)*"
349
  )
350
 
351
+ return result_text, compute_gradcam(image_rgb, tensor, pcos_p)
 
 
 
352
 
353
  except Exception as e:
354
  import traceback
355
+ return f"❌ Image prediction error: {e}\n\n```\n{traceback.format_exc()}\n```", None
356
 
357
 
358
  def compute_gradcam(orig_img, tensor, prob):
 
359
  try:
360
+ grads = []; acts = []
 
 
 
 
 
 
 
361
 
362
+ def save_grad(g): grads.append(g.detach())
363
+ def fwd_hook(m, i, o):
364
+ acts.append(o)
365
+ o.register_hook(save_grad)
 
366
 
367
+ handle = IMAGE_MODEL.features[-1].register_forward_hook(fwd_hook)
368
  IMAGE_MODEL.eval()
369
+ IMAGE_MODEL(tensor)[0, 1].backward()
 
 
 
 
370
  handle.remove()
371
 
372
+ if not grads or not acts:
373
  return None
374
 
375
+ grad = grads[0].squeeze(0).cpu().numpy()
376
+ act = acts[0].squeeze(0).detach().cpu().numpy()
377
+ w = grad.mean(axis=(1, 2))
378
+ cam = np.zeros(act.shape[1:], dtype=np.float32)
379
+ for i, wi in enumerate(w):
380
+ cam += wi * act[i]
 
 
381
  cam = np.maximum(cam, 0)
382
  if cam.max() > 0:
383
+ cam /= cam.max()
 
 
 
 
 
 
 
384
 
385
+ cam_np = np.array(
386
+ Image.fromarray((cam * 255).astype(np.uint8)).resize(
387
+ (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
388
+ ) / 255.0
389
 
390
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4.5), facecolor="#0e1117")
391
+ orig_r = orig_img.resize((IMG_SIZE, IMG_SIZE))
 
392
 
393
+ axes[0].imshow(orig_r); axes[0].set_title("Original", color="white", fontsize=12); axes[0].axis("off")
394
+ axes[1].imshow(cam_np, cmap="jet"); axes[1].set_title("Grad-CAM Heatmap", color="white", fontsize=12); axes[1].axis("off")
395
+ overlay = np.clip(0.55 * np.array(orig_r) / 255. + 0.45 * cm.jet(cam_np)[:,:,:3], 0, 1)
396
+ axes[2].imshow(overlay); axes[2].set_title(f"Overlay (PCOS: {prob*100:.1f}%)", color="white", fontsize=12); axes[2].axis("off")
397
 
398
+ for ax in axes: ax.set_facecolor("#0e1117")
399
+ plt.suptitle("EfficientNetB0 β€” Grad-CAM", color="white", fontsize=13, fontweight="bold")
 
 
 
 
 
 
400
  plt.tight_layout()
401
  return fig
402
 
403
  except Exception as e:
404
+ print(f"Grad-CAM error (non-fatal): {e}")
405
  return None
406
 
407
 
408
  # ─────────────────────────────────────────────────────────────
409
+ # CHARTS
410
  # ─────────────────────────────────────────────────────────────
411
+ def make_radar_chart(sev_vals, overall_prob):
412
  domains = list(sev_vals.keys())
413
+ values = list(sev_vals.values())
414
  N = len(domains)
415
+ angles = [n / float(N) * 2 * np.pi for n in range(N)] + [0]
416
+ vp = values + values[:1]
 
417
 
418
+ fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True), facecolor="#0e1117")
419
  ax.set_facecolor("#0e1117")
420
+ ax.plot(angles, vp, "o-", lw=2, color="#e040fb")
421
+ ax.fill(angles, vp, alpha=0.3, color="#e040fb")
422
+ ax.set_xticks(angles[:-1]); ax.set_xticklabels(domains, color="white", fontsize=10)
423
+ ax.set_ylim(0, 1); ax.set_yticks([0.25, 0.5, 0.75, 1]); ax.set_yticklabels(["25%","50%","75%","100%"], color="gray", fontsize=7)
424
+ ax.tick_params(colors="white"); ax.spines["polar"].set_color("gray"); ax.grid(color="gray", alpha=0.3)
425
+ ax.set_title(f"Domain Severity (PCOS prob: {overall_prob*100:.1f}%)", color="white", fontsize=10, pad=15)
 
 
 
 
 
 
 
 
426
  return fig
427
 
428
 
429
+ def make_bar_chart(base_probs, ensemble_prob):
430
+ labels = list(base_probs.keys()) + ["Ensemble"]
431
+ vals = list(base_probs.values()) + [ensemble_prob]
432
+ colors = ["#42a5f5"] * len(base_probs) + ["#e040fb"]
 
 
433
 
434
+ fig, ax = plt.subplots(figsize=(6, 3.5), facecolor="#0e1117")
435
  ax.set_facecolor("#0e1117")
436
+ bars = ax.barh(labels, vals, color=colors, height=0.5)
437
+ ax.axvline(0.5, color="white", ls="--", alpha=0.5, lw=1)
438
+ ax.set_xlim(0, 1.05); ax.set_xlabel("PCOS Probability", color="white", fontsize=10)
439
+ ax.set_title("Model-wise Predictions", color="white", fontsize=11)
 
 
 
440
  ax.tick_params(colors="white")
441
+ for sp in ["top","right"]: ax.spines[sp].set_visible(False)
442
+ for sp in ["bottom","left"]: ax.spines[sp].set_color("gray")
443
+ for bar, v in zip(bars, vals):
444
+ ax.text(min(v+0.02, 0.97), bar.get_y()+bar.get_height()/2,
445
+ f"{v*100:.1f}%", va="center", color="white", fontsize=9)
 
 
446
  plt.tight_layout()
447
  return fig
448
 
 
450
  # ─────────────────────────────────────────────────────────────
451
  # GRADIO UI
452
  # ─────────────────────────────────────────────────────────────
453
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple"), title="PCOS Detection System") as demo:
 
 
 
 
 
 
 
454
 
455
  gr.Markdown("""
456
  # 🩺 PCOS Detection System
457
+ **AI-powered Polycystic Ovary Syndrome detection β€” Clinical Features & Ultrasound Images**
458
  > ⚠️ For research/educational purposes only. Not a substitute for professional medical advice.
459
  """)
460
 
461
  with gr.Tabs():
462
 
 
463
  with gr.TabItem("πŸ”¬ Clinical Feature Analysis"):
464
  gr.Markdown("### Enter Patient Clinical Data")
 
465
  with gr.Row():
466
  with gr.Column(scale=1):
467
+ gr.Markdown("#### πŸ“ Anthropometric")
468
+ age = gr.Slider(18, 50, value=28, step=1, label="Age (yrs)")
469
+ bmi = gr.Slider(15, 50, value=24.0, step=0.1, label="BMI (kg/mΒ²)")
470
+ weight = gr.Slider(30, 130, value=60.0, step=0.5, label="Weight (Kg)")
471
+ waist = gr.Slider(20, 60, value=32.0, step=0.5, label="Waist (inch)")
472
+ hip = gr.Slider(25, 70, value=38.0, step=0.5, label="Hip (inch)")
 
473
  gr.Markdown("#### 🩸 Vitals")
474
+ bp_sys = gr.Slider(80, 180, value=120, step=1, label="BP Systolic (mmHg)")
475
+ bp_dia = gr.Slider(50, 120, value=80, step=1, label="BP Diastolic (mmHg)")
476
+ pulse = gr.Slider(50, 120, value=72, step=1, label="Pulse Rate (bpm)")
477
+ rr = gr.Slider(10, 30, value=18, step=1, label="RR (breaths/min)")
478
+ hb = gr.Slider(7, 18, value=12.5, step=0.1, label="Hb (g/dl)")
479
+ rbs = gr.Slider(60, 300, value=95, step=1, label="RBS (mg/dl)")
480
 
481
  with gr.Column(scale=1):
482
  gr.Markdown("#### πŸ”¬ Hormones")
483
+ fsh = gr.Slider(0, 30, value=6.0, step=0.1, label="FSH (mIU/mL)")
484
+ lh = gr.Slider(0, 50, value=8.0, step=0.1, label="LH (mIU/mL)")
485
+ amh = gr.Slider(0, 20, value=3.5, step=0.1, label="AMH (ng/mL)")
486
+ prg = gr.Slider(0, 30, value=0.8, step=0.1, label="Progesterone (ng/mL)")
487
+ prl = gr.Slider(0, 100, value=15.0, step=0.5, label="Prolactin (ng/mL)")
488
+ tsh = gr.Slider(0, 10, value=2.5, step=0.1, label="TSH (mIU/L)")
489
+ vit_d3 = gr.Slider(0, 100, value=25.0, step=0.5, label="Vit D3 (ng/mL)")
 
490
  gr.Markdown("#### πŸ”„ Cycle & Follicles")
491
+ cycle = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle Type")
492
+ cycle_len = gr.Slider(21, 45, value=28, step=1, label="Cycle Length (days)")
493
+ follicle_l = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Left)")
494
+ follicle_r = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Right)")
495
+ endometrium = gr.Slider(3, 20, value=8, step=0.1, label="Endometrium (mm)")
496
 
497
  with gr.Column(scale=1):
498
+ gr.Markdown("#### 🧬 Symptoms")
499
  weight_gain = gr.Checkbox(label="Weight Gain")
500
+ hair_growth = gr.Checkbox(label="Excess Hair Growth (Hirsutism)")
501
+ skin_dark = gr.Checkbox(label="Skin Darkening (Acanthosis)")
502
+ hair_loss = gr.Checkbox(label="Hair Loss / Thinning")
503
  pimples = gr.Checkbox(label="Pimples / Acne")
504
+ fast_food = gr.Checkbox(label="Regular Fast Food Consumption")
505
  exercise = gr.Checkbox(label="Regular Exercise", value=True)
 
506
  gr.Markdown("---")
507
+ predict_btn = gr.Button("πŸ” Predict PCOS", variant="primary", size="lg")
508
 
509
  with gr.Row():
510
+ clinical_result = gr.Markdown()
 
511
  with gr.Row():
512
  radar_plot = gr.Plot(label="Domain Severity Radar")
513
+ bar_plot = gr.Plot(label="Model Confidence Breakdown")
514
 
515
+ predict_btn.click(
516
  fn=predict_clinical,
517
+ inputs=[age, bmi, weight, waist, hip, cycle, cycle_len,
518
+ fsh, lh, amh, prg, prl, tsh, vit_d3,
519
+ follicle_l, follicle_r, endometrium, rbs,
520
+ bp_sys, bp_dia,
521
+ weight_gain, hair_growth, skin_dark, hair_loss, pimples,
522
+ fast_food, exercise, hb, pulse, rr],
523
+ outputs=[clinical_result, radar_plot, bar_plot],
 
 
524
  )
525
 
 
526
  with gr.TabItem("πŸ–ΌοΈ Ultrasound Image Analysis"):
527
  gr.Markdown("### Upload Ovarian Ultrasound Image")
 
528
  with gr.Row():
529
  with gr.Column(scale=1):
530
+ img_input = gr.Image(label="Upload Ultrasound (PNG / JPG)", type="pil", height=300)
531
+ image_btn = gr.Button("πŸ” Analyze Image", variant="primary", size="lg")
532
+ gr.Markdown("**Model:** EfficientNetB0 fine-tuned on PCOS dataset \n**Visualization:** Grad-CAM attention map")
 
 
 
 
 
 
 
 
 
 
533
  with gr.Column(scale=2):
534
+ img_result = gr.Markdown()
535
  gradcam_plot = gr.Plot(label="Grad-CAM Visualization")
536
 
537
+ image_btn.click(fn=predict_image, inputs=[img_input], outputs=[img_result, gradcam_plot])
 
 
 
 
538
 
 
539
  with gr.TabItem("ℹ️ About"):
540
  gr.Markdown("""
541
+ ## About This System
542
+
543
+ ### πŸ”¬ Clinical Pipeline
544
+ | Step | Method |
545
+ |------|--------|
546
+ | Imputation | MICE β†’ median fallback (sklearn version-safe) |
547
+ | Scaling | RobustScaler |
548
+ | Severity | Domain GBM (OOF on train) |
549
+ | Ensemble | LR + RF + GBM + CatBoost β†’ CalibratedLogisticRegressionCV |
550
+ | Threshold | Youden-J optimal |
551
+
552
+ **Domain Severity Weights:** Reproductive 40% Β· Metabolic 35% Β· Hyperandrogenic 20% Β· General 5%
553
+
554
+ ### πŸ–ΌοΈ Image Pipeline
555
+ EfficientNetB0 (ImageNet pretrained, fine-tuned) Β· 224Γ—224 RGB Β· Grad-CAM visualization
556
+
557
+ ### ⚠️ Disclaimer
558
+ For **research and educational purposes only**. Consult a qualified healthcare professional for medical decisions.
 
 
 
 
 
 
559
  """)
560
 
561
  demo.launch(server_name="0.0.0.0", server_port=7860)