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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +243 -478
app.py CHANGED
@@ -1,9 +1,6 @@
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
@@ -17,432 +14,238 @@ import gradio as gr
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
- 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
- # ─────────────────────────────────────────────────────────────
159
- (META_MODEL, BASE_MODELS, DOMAIN_MODELS, TRAIN_STATS,
160
- MICE_IMPUTER, SCALER, FEATURE_COLS, BEST_THRESHOLD) = load_tabular_models()
161
-
162
- IMAGE_MODEL = load_image_model()
163
-
164
- IMG_TRANSFORM = transforms.Compose([
165
- transforms.Resize((IMG_SIZE, IMG_SIZE)),
166
- transforms.ToTensor(),
167
- transforms.Normalize(mean=[0.485, 0.456, 0.406],
168
- std =[0.229, 0.224, 0.225]),
169
- ])
170
 
171
 
172
  # ─────────────────────────────────────────────────────────────
173
- # CLINICAL PREDICTION
174
  # ─────────────────────────────────────────────────────────────
175
- def predict_clinical(
176
- age, bmi, weight, waist, hip, cycle, cycle_len,
177
- fsh, lh, amh, prg, prl, tsh, vit_d3,
178
- follicle_l, follicle_r, endometrium, rbs,
179
- bp_sys, bp_dia,
180
- weight_gain, hair_growth, skin_dark, hair_loss, pimples,
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
322
 
323
  try:
 
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,112 +253,74 @@ def make_bar_chart(base_probs, ensemble_prob):
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)
 
1
  import os
 
2
  import warnings
3
  import numpy as np
 
 
4
  import torch
5
  import torch.nn as nn
6
  from torchvision import models, transforms
 
14
  warnings.filterwarnings("ignore")
15
 
16
  # ─────────────────────────────────────────────────────────────
17
+ # CONFIG β€” mirrors pipeline exactly
18
  # ─────────────────────────────────────────────────────────────
19
  MODELS_DIR = "models"
20
  IMG_SIZE = 224
21
  DEVICE = torch.device("cpu")
22
 
23
+ # ImageFolder sorts alphabetically: ['not_pcos', 'pcos']
24
+ # β†’ index 0 = not_pcos, index 1 = pcos
25
+ CLASS_NAMES = ["Not PCOS", "PCOS"] # index 0, 1
26
+ PCOS_IDX = 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Val/test transform β€” no augmentation, same as pipeline
29
+ VAL_TRANSFORM = transforms.Compose([
30
+ transforms.Resize((IMG_SIZE, IMG_SIZE)),
31
+ transforms.ToTensor(),
32
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
33
+ std =[0.229, 0.224, 0.225]),
34
+ ])
35
 
36
  # ─────────────────────────────────────────────────────────────
37
+ # MODEL LOADING
38
+ # checkpoint format: {"model_state": ..., "epoch": ..., ...}
39
  # ─────────────────────────────────────────────────────────────
40
+ def load_model():
41
  candidates = [
42
+ os.path.join(MODELS_DIR, "best_model.pth"),
43
+ os.path.join(MODELS_DIR, "efficientnetb0.pth"),
44
+ os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
45
  ]
46
+ pth = next((p for p in candidates if os.path.exists(p)), None)
47
 
48
+ if pth is None:
49
+ existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else []
50
+ print(f"❌ No model file found. models/ contains: {existing}")
51
+ return None, None
52
 
53
  try:
54
+ net = models.efficientnet_b0(weights=None)
55
+ net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
56
+
57
+ ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
58
+
59
+ # Handle all checkpoint formats from pipeline
60
+ if isinstance(ckpt, dict):
61
+ if "model_state" in ckpt: # pipeline format
62
+ state = ckpt["model_state"]
63
+ elif "model_state_dict" in ckpt:
64
+ state = ckpt["model_state_dict"]
65
+ elif "state_dict" in ckpt:
66
+ state = ckpt["state_dict"]
67
+ else:
68
+ state = ckpt # raw state dict
69
+ else:
70
+ state = ckpt
71
 
72
+ net.load_state_dict(state, strict=True)
73
+ net.to(DEVICE).eval()
74
+ print(f"βœ… Model loaded from {pth}")
75
+ return net, pth
76
  except Exception as e:
77
+ print(f"❌ Model load error: {e}")
78
+ return None, None
79
 
80
 
81
+ MODEL, MODEL_PATH = load_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
 
84
  # ─────────────────────────────────────────────────────────────
85
+ # GRAD-CAM
86
  # ─────────────────────────────────────────────────────────────
87
+ def compute_gradcam(image_rgb: Image.Image, tensor: torch.Tensor, target_class: int):
88
+ """
89
+ Grad-CAM on EfficientNetB0 features[-1] (last conv block).
90
+ Returns overlaid figure.
91
+ """
92
+ grads, acts = [], []
 
 
 
 
93
 
94
+ def fwd_hook(m, inp, out):
95
+ acts.append(out.detach())
96
+ out.register_hook(lambda g: grads.append(g.detach()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ handle = MODEL.features[-1].register_forward_hook(fwd_hook)
99
 
100
+ MODEL.zero_grad()
101
+ output = MODEL(tensor)
102
+ output[0, target_class].backward()
103
+ handle.remove()
104
+
105
+ if not grads or not acts:
106
+ return None
107
+
108
+ # weights = global average pooled gradients
109
+ w = grads[0].squeeze(0).mean(dim=(1, 2)) # (C,)
110
+ act = acts[0].squeeze(0).cpu().numpy() # (C, H, W)
111
+ cam = np.zeros(act.shape[1:], dtype=np.float32)
112
+ for i, wi in enumerate(w.cpu().numpy()):
113
+ cam += wi * act[i]
114
+
115
+ cam = np.maximum(cam, 0)
116
+ if cam.max() > 1e-8:
117
+ cam /= cam.max()
118
+
119
+ cam_up = np.array(
120
+ Image.fromarray((cam * 255).astype(np.uint8)).resize(
121
+ (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
122
+ ) / 255.0
123
+
124
+ orig_r = image_rgb.resize((IMG_SIZE, IMG_SIZE))
125
+ heat = cm.jet(cam_up)[:, :, :3]
126
+ overlay = np.clip(0.55 * np.array(orig_r) / 255.0 + 0.45 * heat, 0, 1)
127
+
128
+ fig, axes = plt.subplots(1, 3, figsize=(15, 5), facecolor="#111827")
129
+ titles = ["Original Image", "Grad-CAM Heatmap", "Overlay"]
130
+ imgs = [orig_r, cam_up, overlay]
131
+ cmaps = [None, "jet", None]
132
+
133
+ for ax, title, img, cmap in zip(axes, titles, imgs, cmaps):
134
+ ax.set_facecolor("#111827")
135
+ ax.imshow(img, cmap=cmap)
136
+ ax.set_title(title, color="white", fontsize=12, fontweight="bold", pad=8)
137
+ ax.axis("off")
138
+
139
+ label = CLASS_NAMES[target_class]
140
+ plt.suptitle(
141
+ f"Grad-CAM β€” Model attention for: {label}",
142
+ color="white", fontsize=13, fontweight="bold", y=1.02
143
+ )
144
+ plt.tight_layout()
145
+ return fig
146
 
147
 
148
  # ─────────────────────────────────────────────────────────────
149
+ # MAIN PREDICTION FUNCTION
150
  # ─────────────────────────────────────────────────────────────
151
+ def predict(image):
152
+ if MODEL is None:
153
+ existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else "folder missing"
154
+ msg = (
155
+ "## ❌ Model not loaded\n\n"
156
+ f"Files found in `models/`: `{existing}`\n\n"
157
+ "**Fix:** Upload `best_model.pth` to the `models/` folder on HuggingFace."
158
+ )
159
+ return msg, None, None
160
 
161
  if image is None:
162
+ return "## ⚠️ Please upload an ultrasound image.", None, None
163
 
164
  try:
165
+ # ── Preprocess ───────────────────────────────────────────
166
  if not isinstance(image, Image.Image):
167
  image = Image.fromarray(image)
168
+ img_rgb = image.convert("RGB")
169
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
170
 
171
+ # ── Forward pass ─────────────────────────────────────────
172
+ MODEL.eval()
173
  with torch.no_grad():
174
+ logits = MODEL(tensor)
175
+ probs = torch.softmax(logits, dim=1)[0]
176
+
177
+ pcos_prob = float(probs[PCOS_IDX])
178
+ notpcos_prob = float(probs[1 - PCOS_IDX])
179
+ pred_idx = int(probs.argmax())
180
+ pred_label = CLASS_NAMES[pred_idx]
181
+ confidence = float(probs[pred_idx])
182
+
183
+ # ── Risk tier ─────────────────────────────────────────────
184
+ if pcos_prob < 0.33:
185
+ risk, risk_color = "🟒 Low Risk", "green"
186
+ elif pcos_prob < 0.66:
187
+ risk, risk_color = "🟑 Moderate Risk", "orange"
188
+ else:
189
+ risk, risk_color = "πŸ”΄ High Risk", "red"
190
+
191
+ diagnosis_icon = "πŸ”΄" if pred_idx == PCOS_IDX else "🟒"
192
+
193
+ # ── Result markdown ───────────────────────────────────────
194
+ result = (
195
+ f"## {diagnosis_icon} Diagnosis: **{pred_label}**\n\n"
196
+ f"| Metric | Value |\n"
197
+ f"|--------|-------|\n"
198
+ f"| PCOS Probability | **{pcos_prob*100:.1f}%** |\n"
199
+ f"| Not PCOS Probability | **{notpcos_prob*100:.1f}%** |\n"
200
+ f"| Model Confidence | **{confidence*100:.1f}%** |\n"
201
+ f"| Risk Level | **{risk}** |\n\n"
202
+ f"*Model: EfficientNetB0 Β· Input: 224Γ—224 RGB Β· Threshold: 0.50*\n\n"
203
+ f"> ⚠️ For research purposes only. Consult a qualified clinician."
204
  )
205
 
206
+ # ── Probability bar chart ─────────────────────────────────
207
+ bar_fig = make_prob_chart(pcos_prob, notpcos_prob)
208
 
209
+ # ── Grad-CAM (use predicted class) ───────────────────────
210
+ # Re-run with grad enabled
211
+ tensor_grad = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
212
+ tensor_grad.requires_grad_(False)
213
+ gradcam_fig = compute_gradcam(img_rgb, tensor_grad, pred_idx)
214
 
215
+ return result, bar_fig, gradcam_fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
  except Exception as e:
218
+ import traceback
219
+ return f"## ❌ Prediction error\n\n```\n{traceback.format_exc()}\n```", None, None
220
 
221
 
222
  # ─────────────────────────────────────────────────────────────
223
+ # PROBABILITY BAR CHART
224
  # ─────────────────────────────────────────────────────────────
225
+ def make_prob_chart(pcos_prob: float, notpcos_prob: float):
226
+ fig, ax = plt.subplots(figsize=(6, 2.8), facecolor="#111827")
227
+ ax.set_facecolor("#111827")
228
+
229
+ labels = ["Not PCOS", "PCOS"]
230
+ vals = [notpcos_prob, pcos_prob]
231
+ colors = ["#22c55e", "#ef4444"]
232
+
233
+ bars = ax.barh(labels, vals, color=colors, height=0.45, edgecolor="none")
234
+ ax.axvline(0.5, color="white", lw=1, ls="--", alpha=0.5)
235
+ ax.set_xlim(0, 1.08)
236
+ ax.set_xlabel("Probability", color="#9ca3af", fontsize=10)
237
+ ax.set_title("Class Probabilities", color="white", fontsize=12, fontweight="bold", pad=10)
238
+ ax.tick_params(colors="white", labelsize=11)
239
+ for sp in ax.spines.values():
240
+ sp.set_visible(False)
241
+
242
+ for bar, val in zip(bars, vals):
243
+ ax.text(
244
+ min(val + 0.025, 1.0), bar.get_y() + bar.get_height() / 2,
245
+ f"{val*100:.1f}%", va="center", color="white",
246
+ fontsize=11, fontweight="bold"
247
+ )
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  plt.tight_layout()
250
  return fig
251
 
 
253
  # ─────────────────────────────────────────────────────────────
254
  # GRADIO UI
255
  # ─────────────────────────────────────────────────────────────
256
+ with gr.Blocks(
257
+ theme=gr.themes.Soft(primary_hue="purple", neutral_hue="slate"),
258
+ title="PCOS Ultrasound Detection"
259
+ ) as demo:
260
 
261
  gr.Markdown("""
262
+ # 🩺 PCOS Ultrasound Image Detection
263
+ **EfficientNetB0 Β· Fine-tuned on PCOS ovarian ultrasound dataset Β· Grad-CAM visualization**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
+ Upload an ovarian ultrasound image to detect PCOS. The model will highlight which regions
266
+ influenced its decision using Grad-CAM.
 
 
 
 
 
 
 
 
267
 
268
+ > ⚠️ **Disclaimer:** For research/educational purposes only. Not a substitute for professional medical diagnosis.
269
+ """)
270
 
271
+ with gr.Row():
272
+ # ── Left: upload + button ──────────────────────────────────
273
+ with gr.Column(scale=1, min_width=280):
274
+ img_input = gr.Image(
275
+ label="Upload Ovarian Ultrasound (PNG / JPG)",
276
+ type="pil",
277
+ height=300,
278
+ )
279
+ analyze_btn = gr.Button(
280
+ "πŸ” Analyze Image",
281
+ variant="primary",
282
+ size="lg",
283
+ )
284
  gr.Markdown("""
285
+ **How to use:**
286
+ 1. Upload a clear ovarian ultrasound image
287
+ 2. Click **Analyze Image**
288
+ 3. View diagnosis, confidence, and Grad-CAM heatmap
289
+
290
+ **Class mapping (alphabetical):**
291
+ - `not_pcos` β†’ index 0
292
+ - `pcos` β†’ index 1
293
+ """)
294
 
295
+ # ── Right: result + probability chart ─────────────────────
296
+ with gr.Column(scale=1, min_width=300):
297
+ result_md = gr.Markdown(
298
+ value="*Upload an image and click Analyze.*"
299
+ )
300
+ prob_plot = gr.Plot(label="Class Probabilities")
 
 
301
 
302
+ # ── Grad-CAM full width ────────────────────────────────────────
303
+ with gr.Row():
304
+ gradcam_plot = gr.Plot(label="Grad-CAM Visualization β€” Model Attention Map")
305
 
306
+ analyze_btn.click(
307
+ fn=predict,
308
+ inputs=[img_input],
309
+ outputs=[result_md, prob_plot, gradcam_plot],
310
+ )
311
 
312
+ gr.Markdown("""
313
+ ---
314
+ ### About the Model
315
+ | Parameter | Value |
316
+ |-----------|-------|
317
+ | Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
318
+ | Input size | 224 Γ— 224 RGB |
319
+ | Normalization | ImageNet stats (mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]) |
320
+ | Checkpoint key | `model_state` |
321
+ | Classes | `not_pcos` (0), `pcos` (1) β€” alphabetical |
322
+ | Visualization | Grad-CAM on `features[-1]` |
323
+ | Saved by | Best val AUC during training |
324
+ """)
325
 
326
  demo.launch(server_name="0.0.0.0", server_port=7860)