DheivaCodes commited on
Commit
89e9482
Β·
verified Β·
1 Parent(s): 889635c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -706
app.py CHANGED
@@ -1,9 +1,9 @@
1
  """
2
  PCOS Integrated Detection System
3
- Tab 1 β€” Clinical Analysis (your stacked ensemble pipeline, trains on Excel at startup)
4
- Tab 2 β€” Single Ultrasound (EfficientNetB0 + Grad-CAM)
5
- Tab 3 β€” Batch Ultrasound (multi-image upload, summary table + chart)
6
- Tab 4 β€” About
7
  """
8
 
9
  import os, re, copy, warnings
@@ -19,16 +19,16 @@ from matplotlib.gridspec import GridSpec
19
  import matplotlib.cm as cm_mod
20
  import gradio as gr
21
 
22
- # ── torch (image pipeline) ────────────────────────────────────────────────────
23
  import torch
24
  import torch.nn as nn
25
  from torchvision import models as tv_models, transforms
26
  from PIL import Image
27
 
28
- # ── sklearn / catboost (clinical pipeline) ────────────────────────────────────
29
  from sklearn.model_selection import train_test_split, StratifiedKFold
30
  from sklearn.preprocessing import RobustScaler
31
- from sklearn.experimental import enable_iterative_imputer # noqa
32
  from sklearn.impute import IterativeImputer
33
  from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
34
  from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
@@ -36,122 +36,208 @@ from sklearn.calibration import CalibratedClassifierCV
36
  from sklearn.metrics import roc_auc_score, roc_curve
37
  from catboost import CatBoostClassifier
38
 
39
- # ══════════════════════════════════════════════════════════════════════════════
40
- # SECTION 1 β€” SHARED CONFIG
41
- # ══════════════════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  RANDOM_STATE = 42
43
  TEST_SIZE = 0.2
44
  CV_FOLDS = 5
45
- BG = "#0D0D1A"
46
- TC = "#E8E8F0"
47
- ACC = "#A855F7"
48
 
49
  DOMAIN_WEIGHTS = {
50
- "METABOLIC" : 0.35,
51
- "REPRODUCTIVE" : 0.40,
52
- "HYPERANDROGENIC": 0.20,
53
- "GENERAL" : 0.05,
54
  }
55
-
56
  FEATURE_GROUPS_BASE = {
57
- "METABOLIC": [
58
- "BMI","Weight (Kg)","Waist(inch)","Hip(inch)",
59
- "Waist:Hip Ratio","RBS(mg/dl)","Weight gain(Y/N)",
60
- "BP _Systolic (mmHg)","BP _Diastolic (mmHg)",
61
- "Fast food (Y/N)","Reg.Exercise(Y/N)",
62
- ],
63
- "REPRODUCTIVE": [
64
- "Cycle(R/I)","Cycle length(days)",
65
- "FSH(mIU/mL)","LH(mIU/mL)","FSH/LH",
66
- "AMH(ng/mL)","PRG(ng/mL)",
67
- "Follicle No. (L)","Follicle No. (R)",
68
- "Avg. F size (L) (mm)","Avg. F size (R) (mm)",
69
- "Endometrium (mm)",
70
- ],
71
- "HYPERANDROGENIC": [
72
- "hair growth(Y/N)","Skin darkening (Y/N)",
73
- "Hair loss(Y/N)","Pimples(Y/N)","PRL(ng/mL)",
74
- ],
75
- "GENERAL": [
76
- "Age (yrs)","Hb(g/dl)","Pulse rate(bpm)",
77
- "RR (breaths/min)","TSH (mIU/L)","Vit D3 (ng/mL)",
78
- ],
79
  }
80
-
81
- DROP_COLS = [
82
- "Sl. No","Patient File No.","Blood Group",
83
- "Marraige Status (Yrs)","Pregnant(Y/N)",
84
- "No. of aborptions","Unnamed: 44",
85
- ]
86
-
87
- DOMAIN_COLORS = {
88
- "Metabolic" : "#E74C3C",
89
- "Reproductive" : "#9B59B6",
90
- "Hyperandrogenic": "#E67E22",
91
- "General" : "#27AE60",
92
- }
93
-
94
  BIOMARKER_DIRECTIONS = {
95
- "FSH(mIU/mL)" : 1, "LH(mIU/mL)" : -1,
96
- "FSH/LH" : 1, "AMH(ng/mL)" : -1,
97
- "Follicle No. (L)": -1, "Follicle No. (R)" : -1,
98
- "Endometrium (mm)": -1, "PRG(ng/mL)" : -1,
99
- "Cycle(R/I)" : 1,
100
  }
101
  BIOMARKER_WEIGHTS = {
102
- "FSH(mIU/mL)" : 0.18, "LH(mIU/mL)" : 0.08,
103
- "FSH/LH" : 0.15, "AMH(ng/mL)" : 0.22,
104
- "Follicle No. (L)": 0.10, "Follicle No. (R)" : 0.10,
105
- "Endometrium (mm)": 0.08, "PRG(ng/mL)" : 0.05,
106
- "Cycle(R/I)" : 0.04,
107
  }
108
  BIOMARKER_RANGES = {
109
- "FSH(mIU/mL)" : (0.5, 22.0), "LH(mIU/mL)" : (0.2, 49.0),
110
- "FSH/LH" : (0.1, 20.0), "AMH(ng/mL)" : (0.01,18.0),
111
- "Follicle No. (L)": (0.0, 22.0), "Follicle No. (R)" : (0.0, 22.0),
112
- "Endometrium (mm)": (1.0, 15.0), "PRG(ng/mL)" : (0.1, 25.0),
113
- "Cycle(R/I)" : (2.0, 4.0),
114
- }
115
-
116
- EXAMPLE_PCOS = {
117
- "age":28,"weight":72,"height":158,"bmi":28.8,
118
- "pulse_rate":82,"rr":19,"hb":11.5,
119
- "cycle":4,"cycle_length":35,
120
- "fsh":4.8,"lh":12.5,"fsh_lh_ratio":0.38,
121
- "hip":40,"waist":36,"waist_hip":0.90,
122
- "tsh":2.8,"amh":8.5,"prl":22,"vit_d3":18,
123
- "prg":0.6,"rbs":105,
124
- "weight_gain":1,"hair_growth":1,"skin_darkening":1,
125
- "hair_loss":0,"pimples":1,"fast_food":1,"reg_exercise":0,
126
- "follicle_l":14,"follicle_r":13,
127
- "avg_f_size_l":8,"avg_f_size_r":8,"endometrium":6,
128
  }
129
- EXAMPLE_NORMAL = {
130
- "age":26,"weight":58,"height":162,"bmi":22.1,
131
- "pulse_rate":70,"rr":16,"hb":13.2,
132
- "cycle":2,"cycle_length":28,
133
- "fsh":7.2,"lh":4.8,"fsh_lh_ratio":1.5,
134
- "hip":37,"waist":28,"waist_hip":0.76,
135
- "tsh":2.1,"amh":3.2,"prl":14,"vit_d3":30,
136
- "prg":1.8,"rbs":85,
137
- "weight_gain":0,"hair_growth":0,"skin_darkening":0,
138
- "hair_loss":0,"pimples":0,"fast_food":0,"reg_exercise":1,
139
- "follicle_l":6,"follicle_r":6,
140
- "avg_f_size_l":16,"avg_f_size_r":16,"endometrium":9,
141
- }
142
-
143
- INPUT_KEYS = [
144
- "age","weight","height","bmi","pulse_rate","rr","hb",
145
- "cycle","cycle_length","fsh","lh","fsh_lh_ratio",
146
- "hip","waist","waist_hip","tsh","amh","prl","vit_d3","prg","rbs",
147
- "weight_gain","hair_growth","skin_darkening","hair_loss",
148
- "pimples","fast_food","reg_exercise",
149
- "follicle_l","follicle_r","avg_f_size_l","avg_f_size_r","endometrium",
150
- ]
151
 
152
- # ══════════════════════════════════════════════════════════════════════════════
153
- # SECTION 2 β€” CLINICAL PIPELINE (your exact code)
154
- # ══════════════════════════════════════════════════════════════════════════════
155
  def clean_name(n): return re.sub(r"[^0-9a-zA-Z_]","_",n.strip())
156
  def clean_df_cols(df):
157
  df=df.copy(); df.columns=[clean_name(c) for c in df.columns]; return df
@@ -164,278 +250,159 @@ def get_base_models():
164
  class_weight="balanced",random_state=RANDOM_STATE),
165
  "GradientBoost": GradientBoostingClassifier(n_estimators=200,learning_rate=0.05,
166
  max_depth=3,subsample=0.85,random_state=RANDOM_STATE),
167
- "CatBoost" : CatBoostClassifier(iterations=300,learning_rate=0.05,
168
- depth=6,random_seed=RANDOM_STATE,eval_metric="AUC",verbose=0),
169
  }
170
 
171
- def load_and_engineer(data_path):
172
- df = pd.read_excel(data_path)
173
- df = df.drop(columns=DROP_COLS,errors="ignore")
174
- df.columns = df.columns.str.strip()
175
- y = pd.to_numeric(df["PCOS (Y/N)"],errors="coerce")
176
- mask = y.notna()
177
- df = df.loc[mask].copy().reset_index(drop=True)
178
- y = y.loc[mask].astype(int).reset_index(drop=True)
179
  for c in df.columns:
180
  if df[c].dtype=="object" and c!="PCOS (Y/N)":
181
  df[c]=pd.to_numeric(df[c].astype(str).str.strip(),errors="coerce")
182
- df["FSH_LH_Ratio"] = df["FSH(mIU/mL)"]/(df["LH(mIU/mL)"]+1e-6)
183
- df["Total_Follicles"] = df["Follicle No. (L)"].fillna(0)+df["Follicle No. (R)"].fillna(0)
184
- df["AMH_FSH_Ratio"] = df["AMH(ng/mL)"]/(df["FSH(mIU/mL)"]+1e-6)
185
- df["BMI_Waist_Ratio"] = df["BMI"]/(df["Waist(inch)"]+1e-6)
186
  andro=[c for c in FEATURE_GROUPS_BASE["HYPERANDROGENIC"] if c in df.columns]
187
  if andro: df["Androgenic_Score"]=df[andro].sum(axis=1)
188
  FG=copy.deepcopy(FEATURE_GROUPS_BASE)
189
- FG["REPRODUCTIVE"] +=["FSH_LH_Ratio","Total_Follicles","AMH_FSH_Ratio"]
190
- FG["METABOLIC"] +=["BMI_Waist_Ratio"]
191
- FG["HYPERANDROGENIC"]+=["Androgenic_Score"]
192
- X=clean_df_cols(df.drop(columns=["PCOS (Y/N)"]))
193
- return X,y,FG
194
 
195
  def preprocess(Xtr,Xte):
196
  mice=IterativeImputer(max_iter=10,random_state=RANDOM_STATE)
197
- Xtr_imp=pd.DataFrame(mice.fit_transform(Xtr),columns=Xtr.columns,index=Xtr.index)
198
- Xte_imp=pd.DataFrame(mice.transform(Xte), columns=Xte.columns,index=Xte.index)
199
- num_cols=Xtr_imp.select_dtypes(include=np.number).columns.tolist()
200
- scaler=RobustScaler()
201
- Xtr_sc=Xtr_imp.copy(); Xte_sc=Xte_imp.copy()
202
- Xtr_sc[num_cols]=scaler.fit_transform(Xtr_imp[num_cols])
203
- Xte_sc[num_cols]=scaler.transform(Xte_imp[num_cols])
204
- return Xtr_sc,Xte_sc,mice,scaler,num_cols
205
-
206
- def compute_oof_severity(Xtr,ytr,Xtr_sc,FG):
207
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
208
- sev=pd.DataFrame(index=Xtr.index); models,stats={},{}
209
  for domain,feats in FG.items():
210
- fc=get_clean_feats(feats,Xtr_sc.columns)
211
  if len(fc)<3: continue
212
- oof=np.zeros(len(Xtr_sc))
213
- for tr,val in skf.split(Xtr_sc,ytr):
214
  m=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
215
  max_depth=3,random_state=RANDOM_STATE)
216
- m.fit(Xtr_sc.iloc[tr][fc],ytr.iloc[tr])
217
- oof[val]=m.predict_proba(Xtr_sc.iloc[val][fc])[:,1]
218
  stats[domain]={"min":oof.min(),"max":oof.max()}
219
  sev[f"{domain}_SEV"]=(oof-oof.min())/(oof.max()-oof.min()+1e-6)
220
  fm=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
221
  max_depth=3,random_state=RANDOM_STATE)
222
- fm.fit(Xtr_sc[fc],ytr); models[domain]=(fm,fc)
223
  sev["OVERALL_SEV"]=sum(sev[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
224
  for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev)
225
- return sev.fillna(0),models,stats
226
-
227
- def apply_severity(models,stats,X_sc):
228
- df_sev=pd.DataFrame(index=X_sc.index)
229
- for d,(model,fc) in models.items():
230
- fc_a=[f for f in fc if f in X_sc.columns]
231
- p=model.predict_proba(X_sc[fc_a])[:,1]
232
- df_sev[f"{d}_SEV"]=np.clip((p-stats[d]["min"])/(stats[d]["max"]-stats[d]["min"]+1e-6),0,1)
233
- df_sev=df_sev.fillna(0)
234
- df_sev["OVERALL_SEV"]=sum(df_sev[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
235
- for d in DOMAIN_WEIGHTS if f"{d}_SEV" in df_sev)
236
- return df_sev
237
-
238
- def build_pipeline(data_path):
239
  print("πŸ”„ Training clinical pipeline...")
240
- X,y,FG=load_and_engineer(data_path)
241
- Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=TEST_SIZE,
242
- stratify=y,random_state=RANDOM_STATE)
243
- Xtr_sc,Xte_sc,mice,scaler,num_cols=preprocess(Xtr,Xte)
244
- sev_tr,domain_models,stats=compute_oof_severity(Xtr,ytr,Xtr_sc,FG)
245
- sev_te=apply_severity(domain_models,stats,Xte_sc)
246
- Xtr_f=pd.concat([Xtr_sc,sev_tr],axis=1)
247
- Xte_f=pd.concat([Xte_sc,sev_te],axis=1)
248
-
249
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
250
- oof_meta=pd.DataFrame(index=Xtr_f.index)
251
- test_meta=pd.DataFrame(index=Xte_f.index)
252
- trained_base={}
253
-
254
  for name,model in get_base_models().items():
255
- oof=np.zeros(len(Xtr_f))
256
- for tr_i,val_i in skf.split(Xtr_f,ytr):
257
- model.fit(Xtr_f.iloc[tr_i],ytr.iloc[tr_i])
258
- oof[val_i]=model.predict_proba(Xtr_f.iloc[val_i])[:,1]
259
- model.fit(Xtr_f,ytr)
260
- oof_meta[name]=oof
261
- test_meta[name]=model.predict_proba(Xte_f)[:,1]
262
- trained_base[name]=model
263
- print(f" βœ… {name} AUC: {roc_auc_score(ytr,oof):.4f}")
264
-
265
- meta=CalibratedClassifierCV(
266
- LogisticRegressionCV(cv=5,class_weight={0:1,1:3}),method="isotonic")
267
- meta.fit(oof_meta,ytr)
268
- ens_probs=meta.predict_proba(test_meta)[:,1]
269
- fpr,tpr,thresholds=roc_curve(yte,ens_probs)
270
- best_t=float(thresholds[np.argmax(tpr-fpr)])
271
- auc=roc_auc_score(yte,ens_probs)
272
- print(f" βœ… Ensemble AUC:{auc:.4f} threshold:{best_t:.4f}")
273
- return dict(meta=meta,base=trained_base,domain_models=domain_models,
274
- stats=stats,mice=mice,scaler=scaler,num_cols=num_cols,
275
- scaled_cols=list(Xtr_sc.columns),feature_cols=list(Xtr_f.columns),
276
- threshold=best_t,auc=round(auc,4))
277
-
278
- def compute_infertility_risk(patient_raw):
279
  def _v(v):
280
  try: return not np.isnan(float(v)) if v is not None else False
281
  except: return False
282
- avail={f:w for f,w in BIOMARKER_WEIGHTS.items() if f in patient_raw and _v(patient_raw[f])}
283
- if not avail: return {"score":0.5,"tier":"Unknown","breakdown":{}}
284
- tw=sum(avail.values()); score=0.0; breakdown={}
285
- for feat,w in avail.items():
286
- val=float(patient_raw[feat])
287
- lo,hi=BIOMARKER_RANGES.get(feat,(0.0,1.0))
288
- norm=np.clip((val-lo)/(hi-lo+1e-8),0.0,1.0)
289
- oriented=(1.0-norm) if BIOMARKER_DIRECTIONS.get(feat,1)==-1 else norm
290
- contrib=(w/tw)*oriented; score+=contrib
291
- breakdown[feat]={"raw":round(val,3),"oriented":round(oriented,3),
292
- "contribution":round(contrib,4),
293
- "direction":"↑ risk" if BIOMARKER_DIRECTIONS.get(feat,1)==1 else "↓ protective"}
294
- tier="High" if score>=0.66 else ("Moderate" if score>=0.33 else "Low")
295
- return {"score":round(score,4),"tier":tier,"breakdown":breakdown}
296
-
297
- def predict_single_clinical(pipeline, patient_raw):
298
- row={k:np.nan for k in pipeline["scaled_cols"]}
299
- for rk,val in patient_raw.items():
300
  ck=clean_name(rk)
301
  if ck in row and val is not None:
302
  try: row[ck]=float(val)
303
  except: pass
304
- X_raw=pd.DataFrame([row])
305
- for c in X_raw.columns: X_raw[c]=pd.to_numeric(X_raw[c],errors="coerce")
306
- X_imp=pd.DataFrame(pipeline["mice"].transform(X_raw),columns=X_raw.columns)
307
- X_sc=X_imp.copy()
308
- num_c=[c for c in pipeline["num_cols"] if c in X_sc.columns]
309
- X_sc[num_c]=pipeline["scaler"].transform(X_imp[num_c])
310
- sev=apply_severity(pipeline["domain_models"],pipeline["stats"],X_sc)
311
- X_f=pd.concat([X_sc.reset_index(drop=True),sev.reset_index(drop=True)],axis=1)
312
- for c in pipeline["feature_cols"]:
313
- if c not in X_f.columns: X_f[c]=0.0
314
- X_f=X_f[pipeline["feature_cols"]].clip(-10,10)
315
- base_probs={n:m.predict_proba(X_f)[:,1][0] for n,m in pipeline["base"].items()}
316
- pcos_prob=pipeline["meta"].predict_proba(pd.DataFrame([base_probs]))[:,1][0]
317
- pred=int(pcos_prob>=pipeline["threshold"])
318
- def _s(col): return float(sev[col].iloc[0]) if col in sev.columns else 0.0
319
- severity={
320
- "Metabolic":_s("METABOLIC_SEV"),"Reproductive":_s("REPRODUCTIVE_SEV"),
321
- "Hyperandrogenic":_s("HYPERANDROGENIC_SEV"),"General":_s("GENERAL_SEV"),
322
- "Overall":_s("OVERALL_SEV"),
323
- }
324
- return pcos_prob,pred,severity,base_probs
325
-
326
- # ── Startup ───────────────────────────────────────────────────────────────────
327
  DATA_PATH = os.path.join(os.path.dirname(__file__), "PCOS_data_without_infertility.xlsx")
328
  if os.path.exists(DATA_PATH):
329
  try:
330
- PIPELINE = build_pipeline(DATA_PATH)
331
- PIPELINE_READY = True
332
- print("βœ… Clinical pipeline ready")
333
  except Exception as _e:
334
  print(f"⚠️ Pipeline error: {_e}"); PIPELINE=None; PIPELINE_READY=False
335
  else:
336
  print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False
337
 
338
- # ══════════════════════════════════════════════════════════════════════════════
339
- # SECTION 3 β€” IMAGE PIPELINE (your exact EfficientNetB0 code)
340
- # ══════════════════════════════════════════════════════════════════════════════
341
- MODELS_DIR = "models"
342
- IMG_SIZE = 224
343
- DEVICE = torch.device("cpu")
344
- CLASS_NAMES = ["Not PCOS","PCOS"]
345
- PCOS_IDX = 1
346
-
347
- VAL_TRANSFORM = transforms.Compose([
348
- transforms.Resize((IMG_SIZE,IMG_SIZE)),
349
- transforms.ToTensor(),
350
- transforms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225]),
351
- ])
352
-
353
- def load_image_model():
354
- candidates=[
355
- os.path.join(MODELS_DIR,"best_model.pth"),
356
- os.path.join(MODELS_DIR,"efficientnetb0.pth"),
357
- os.path.join(MODELS_DIR,"EfficientNetB0.pth"),
358
- ]
359
- pth=next((p for p in candidates if os.path.exists(p)),None)
360
- if pth is None:
361
- print(f"⚠️ Image model not found. models/={os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else 'missing'}")
362
- return None
363
- try:
364
- net=tv_models.efficientnet_b0(weights=None)
365
- net.classifier[1]=nn.Linear(net.classifier[1].in_features,2)
366
- ckpt=torch.load(pth,map_location=DEVICE,weights_only=False)
367
- if isinstance(ckpt,dict):
368
- state=(ckpt.get("model_state") or ckpt.get("model_state_dict")
369
- or ckpt.get("state_dict") or ckpt)
370
- else:
371
- state=ckpt
372
- net.load_state_dict(state,strict=True)
373
- net.to(DEVICE).eval()
374
- print(f"βœ… Image model loaded: {pth}")
375
- return net
376
- except Exception as _img_err:
377
- print(f"⚠️ Image model failed to load ({_img_err}). "
378
- f"Re-save best_model.pth in Colab with current PyTorch and re-upload.")
379
- return None
380
-
381
- IMAGE_MODEL=load_image_model()
382
-
383
- def run_image_inference(img_rgb):
384
- tensor=VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
385
- with torch.no_grad():
386
- probs=torch.softmax(IMAGE_MODEL(tensor),dim=1)[0]
387
- return float(probs[PCOS_IDX]),float(probs[1-PCOS_IDX]),int(probs.argmax())
388
-
389
- def compute_gradcam(img_rgb,target_class):
390
- grads,acts=[],[]
391
- def fwd_hook(m,inp,out):
392
- acts.append(out.detach())
393
- out.register_hook(lambda g: grads.append(g.detach()))
394
- handle=IMAGE_MODEL.features[-1].register_forward_hook(fwd_hook)
395
- tensor=VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
396
- IMAGE_MODEL.zero_grad()
397
- IMAGE_MODEL(tensor)[0,target_class].backward()
398
- handle.remove()
399
- if not grads or not acts: return None
400
- w=grads[0].squeeze(0).mean(dim=(1,2)).cpu().numpy()
401
- act=acts[0].squeeze(0).cpu().numpy()
402
- cam=np.maximum(sum(w[i]*act[i] for i in range(len(w))),0)
403
- if cam.max()>1e-8: cam/=cam.max()
404
- cam_up=np.array(Image.fromarray((cam*255).astype(np.uint8)).resize(
405
- (IMG_SIZE,IMG_SIZE),Image.BILINEAR))/255.0
406
- orig_r=np.array(img_rgb.resize((IMG_SIZE,IMG_SIZE)))
407
- heat=cm_mod.jet(cam_up)[:,:,:3]
408
- overlay=np.clip(0.55*orig_r/255.0+0.45*heat,0,1)
409
-
410
- fig,axes=plt.subplots(1,3,figsize=(15,4.5),facecolor=BG,
411
- gridspec_kw={"wspace":0.04})
412
- panels=[(orig_r,None,"Original Image"),(cam_up,"jet","Grad-CAM Heatmap"),(overlay,None,"Activation Overlay")]
413
- for ax,(img,cmap,title) in zip(axes,panels):
414
- ax.set_facecolor(BG); ax.imshow(img,cmap=cmap); ax.axis("off")
415
- ax.set_title(title,color=TC,fontsize=11,fontweight="bold",pad=6)
416
- for sp in ax.spines.values(): sp.set_linewidth(0)
417
- fig.text(0.5,0.0,f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
418
- ha="center",color="#94a3b8",fontsize=9)
419
- plt.tight_layout(pad=0.3)
420
- return fig
421
-
422
- # ══════════════════════════════════════════════════════════════════════════════
423
- # SECTION 4 β€” CLINICAL CHARTS (your exact draw_gauge + make_result_figure)
424
- # ══════════════════════════════════════════════════════════════════════════════
425
  def draw_gauge(ax,value,title,val_label,sub_label,val_col):
426
  ax.set_facecolor(BG)
427
  theta=np.linspace(np.pi,0,300)
428
  for i in range(len(theta)-1):
429
- t=i/(len(theta)-1)
430
  ax.fill_between([np.cos(theta[i]),np.cos(theta[i+1])],
431
  [np.sin(theta[i]),np.sin(theta[i+1])],
432
- alpha=0.9,color=plt.cm.RdYlGn_r(t))
433
  angle=np.pi*(1-value)
434
  ax.annotate("",xy=(0.65*np.cos(angle),0.65*np.sin(angle)),xytext=(0,0),
435
  arrowprops=dict(arrowstyle="-|>",color="white",lw=3))
436
  ax.plot(0,0,"o",color="white",markersize=6,zorder=5)
437
  ax.text(0,-0.15,val_label,ha="center",fontsize=22,fontweight="bold",color=val_col,va="center")
438
- ax.text(0,-0.38,title,ha="center",fontsize=9,color="#AAAACC")
439
  ax.text(0,-0.58,sub_label,ha="center",fontsize=10,fontweight="bold",color=val_col)
440
  for pct,lbl in [(0,"0%"),(0.5,"50%"),(1.0,"100%")]:
441
  a=np.pi*(1-pct)
@@ -443,175 +410,109 @@ def draw_gauge(ax,value,title,val_label,sub_label,val_col):
443
  ax.set_xlim(-1.05,1.05); ax.set_ylim(-0.72,1.05); ax.axis("off")
444
  ax.set_title(title,color=TC,fontsize=12,fontweight="bold",pad=4)
445
 
446
- def make_clinical_figure(pcos_prob,pred,sev,base_probs,inf_risk,threshold):
447
  fig=plt.figure(figsize=(18,13),facecolor=BG)
448
- gs=GridSpec(3,4,figure=fig,hspace=0.58,wspace=0.45,
449
- top=0.93,bottom=0.05,left=0.05,right=0.97)
450
- ax_pg =fig.add_subplot(gs[0,0])
451
- ax_ig =fig.add_subplot(gs[0,1])
452
- ax_rad=fig.add_subplot(gs[0,2:],polar=True)
453
- ax_bar=fig.add_subplot(gs[1,:2])
454
- ax_bio=fig.add_subplot(gs[1,2:])
455
- ax_sev=fig.add_subplot(gs[2,:])
456
-
457
- risk_col="#E74C3C" if pcos_prob>0.65 else ("#F39C12" if pcos_prob>0.35 else "#2ECC71")
458
- inf_s=inf_risk["score"]; inf_t=inf_risk["tier"]
459
- inf_col="#E74C3C" if inf_t=="High" else ("#F39C12" if inf_t=="Moderate" else "#2ECC71")
460
-
461
- draw_gauge(ax_pg,pcos_prob,"PCOS Risk",f"{pcos_prob*100:.1f}%",
462
- "⚠️ PCOS Detected" if pred else "βœ… No PCOS",risk_col)
463
- draw_gauge(ax_ig,inf_s,"Infertility Risk",f"{inf_s*100:.1f}%",
464
- f"{'πŸ”΄' if inf_t=='High' else ('🟑' if inf_t=='Moderate' else '🟒')} {inf_t}",inf_col)
465
-
466
  # Radar
467
- domains=["Metabolic","Reproductive","Hyperandrogenic","General"]
468
- vals=[sev[d] for d in domains]
469
- angles=np.linspace(0,2*np.pi,len(domains),endpoint=False).tolist()
470
- v_c=vals+[vals[0]]; a_c=angles+[angles[0]]
471
- ax_rad.set_facecolor(BG)
472
- for level,alpha,color in [(1.0,0.05,"#E74C3C"),(0.65,0.08,"#F39C12"),(0.35,0.08,"#2ECC71")]:
473
- ax_rad.fill(a_c,[level]*len(a_c),alpha=alpha,color=color)
474
- ax_rad.plot(a_c,v_c,"o-",lw=2.5,color=ACC,markersize=7)
475
- ax_rad.fill(a_c,v_c,alpha=0.30,color=ACC)
476
- ax_rad.set_xticks(angles)
477
- ax_rad.set_xticklabels([f"{d}\n{vals[i]*100:.0f}%" for i,d in enumerate(domains)],
478
- color=TC,fontsize=10,fontweight="bold")
479
- ax_rad.set_ylim(0,1); ax_rad.set_yticks([0.35,0.65,1.0])
480
- ax_rad.set_yticklabels(["Low→Mod","Mod→High","Max"],color="#666",fontsize=7)
481
- ax_rad.grid(color="#333355",alpha=0.6,linewidth=0.8)
482
- ax_rad.spines["polar"].set_color("#333355")
483
- ax_rad.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
484
-
485
  # Base model bars
486
- ax_bar.set_facecolor(BG)
487
- names=list(base_probs.keys()); probs_=[base_probs[n] for n in names]
488
- colors=["#3B82F6","#10B981","#F59E0B","#EF4444"]
489
- bars=ax_bar.barh(names,probs_,color=colors[:len(names)],height=0.52,alpha=0.88)
490
  for bar,p in zip(bars,probs_):
491
- ax_bar.text(min(p+0.018,0.97),bar.get_y()+bar.get_height()/2,
492
- f"{p:.3f}",va="center",color=TC,fontsize=11,fontweight="bold")
493
- ax_bar.axvline(0.5,color="white",linestyle="--",alpha=0.3,lw=1.5)
494
- ax_bar.axvline(threshold,color=ACC,linestyle=":",alpha=0.6,lw=1.5,
495
- label=f"Youden threshold ({threshold:.2f})")
496
- ax_bar.set_xlim(0,1.12); ax_bar.tick_params(colors=TC,labelsize=11)
497
- for sp in ax_bar.spines.values(): sp.set_color("#2A2A4A")
498
- ax_bar.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
499
- ax_bar.set_xlabel("PCOS Probability",color=TC,fontsize=10)
500
- ax_bar.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
501
-
502
  # Biomarker bars
503
- ax_bio.set_facecolor(BG); ax_bio.tick_params(colors=TC,labelsize=8)
504
- for sp in ax_bio.spines.values(): sp.set_color("#2A2A4A")
505
- ax_bio.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
506
- ax_bio.set_xlabel("Weighted contribution to risk",color=TC,fontsize=9)
507
- breakdown=inf_risk.get("breakdown",{})
508
- if breakdown:
509
- bio_names=list(breakdown.keys())
510
- bio_vals=[breakdown[f]["contribution"] for f in bio_names]
511
- bio_cols=["#EF4444" if breakdown[f]["oriented"]>0.5 else "#10B981" for f in bio_names]
512
- short=[f.split("(")[0].strip()[:14] for f in bio_names]
513
- sorted_p=sorted(zip(short,bio_vals,bio_cols),key=lambda x:x[1],reverse=True)
514
- short,bio_vals,bio_cols=zip(*sorted_p)
515
- bars2=ax_bio.barh(short,bio_vals,color=bio_cols,height=0.52,alpha=0.88)
516
- for bar,val in zip(bars2,bio_vals):
517
- ax_bio.text(val+0.001,bar.get_y()+bar.get_height()/2,
518
- f"{val:.3f}",va="center",color=TC,fontsize=9)
519
- p1=mpatches.Patch(color="#EF4444",label="↑ Increases risk")
520
- p2=mpatches.Patch(color="#10B981",label="↓ Protective")
521
- ax_bio.legend(handles=[p1,p2],facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8)
522
  else:
523
- ax_bio.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values to see\nbiomarker breakdown",
524
- ha="center",va="center",color="#666",fontsize=10,transform=ax_bio.transAxes)
525
-
526
  # Domain severity bars
527
- ax_sev.set_facecolor(BG)
528
- sev_vals=[sev[d] for d in domains]
529
- sev_colors=[DOMAIN_COLORS[d] for d in domains]
530
- x_pos=np.arange(len(domains))
531
- bars3=ax_sev.bar(x_pos,sev_vals,color=sev_colors,alpha=0.88,width=0.5)
532
- for bar,val,d in zip(bars3,sev_vals,domains):
533
- lvl="High" if val>0.65 else ("Moderate" if val>0.35 else "Low")
534
- lc="#E74C3C" if lvl=="High" else ("#F39C12" if lvl=="Moderate" else "#2ECC71")
535
- ax_sev.text(bar.get_x()+bar.get_width()/2,val+0.02,f"{val*100:.1f}%",
536
- ha="center",va="bottom",color=TC,fontsize=14,fontweight="bold")
537
- ax_sev.text(bar.get_x()+bar.get_width()/2,val+0.09,f"({lvl})",
538
- ha="center",va="bottom",color=lc,fontsize=11)
539
- ax_sev.axhline(0.65,color="#E74C3C",linestyle="--",alpha=0.45,lw=1.5,label="High (65%)")
540
- ax_sev.axhline(0.35,color="#F39C12",linestyle="--",alpha=0.45,lw=1.5,label="Moderate (35%)")
541
- ax_sev.set_ylim(0,1.3); ax_sev.set_xticks(x_pos)
542
- ax_sev.set_xticklabels(domains,color=TC,fontsize=13,fontweight="bold")
543
- ax_sev.tick_params(axis="y",colors=TC,labelsize=10)
544
- for sp in ax_sev.spines.values(): sp.set_color("#2A2A4A")
545
- ax_sev.set_title("PCOS Domain Severity Breakdown",color=TC,fontsize=13,fontweight="bold")
546
- ax_sev.set_ylabel("Severity Score",color=TC,fontsize=11)
547
- ax_sev.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=9,loc="upper right")
548
-
549
  fig.patch.set_facecolor(BG)
550
  fig.suptitle("🩺 PCOS Clinical Assessment Report",color=TC,fontsize=16,fontweight="bold",y=0.97)
551
  return fig
552
 
553
- # ══════════════════════════════════════════════════════════════════════════════
554
- # SECTION 5 β€” IMAGE CHARTS
555
- # ══════════════════════════════════════════════════════════════════════════════
556
- def make_image_gauge(pcos_prob):
557
- fig,ax=plt.subplots(figsize=(5,2.6),facecolor=BG)
558
- ax.set_facecolor(BG); ax.set_xlim(0,1); ax.set_ylim(0,1); ax.axis("off")
559
- ax.barh([0.5],[1.0],height=0.30,color="#1e293b",left=0,align="center",zorder=1)
560
- color="#22c55e" if pcos_prob<0.33 else "#f59e0b" if pcos_prob<0.66 else "#ef4444"
561
- ax.barh([0.5],[pcos_prob],height=0.30,color=color,left=0,align="center",zorder=2)
562
- ax.axvline(0.5,color="white",lw=1.5,ls="--",alpha=0.7,zorder=3)
563
- ax.text(pcos_prob,0.5,f" {pcos_prob*100:.1f}%",va="center",color="white",
564
- fontsize=16,fontweight="bold",zorder=4,
565
- ha="left" if pcos_prob<0.85 else "right")
566
- for x,lbl,c in [(0.16,"Low","#22c55e"),(0.50,"Moderate","#f59e0b"),(0.83,"High","#ef4444")]:
567
- ax.text(x,0.12,lbl,color=c,fontsize=8,ha="center",alpha=0.8)
568
- ax.text(0.5,0.92,"PCOS Probability",color="#94a3b8",fontsize=9,ha="center",va="top")
569
- plt.tight_layout(pad=0.2)
570
- return fig
571
-
572
- def make_batch_chart(pcos_c,notp_c,total):
573
- fig=plt.figure(figsize=(10,4),facecolor=BG)
574
- ax1=fig.add_subplot(1,2,1); ax1.set_facecolor(BG)
575
- if total>0:
576
- wedges,texts,autotexts=ax1.pie(
577
- [pcos_c,notp_c],labels=[f"PCOS\n{pcos_c}",f"Not PCOS\n{notp_c}"],
578
- colors=["#ef4444","#22c55e"],autopct="%1.1f%%",startangle=90,
579
- textprops={"color":"white","fontsize":10},
580
- wedgeprops={"linewidth":2,"edgecolor":BG},pctdistance=0.75)
581
- for at in autotexts: at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold")
582
- ax1.set_title("Class Distribution",color=TC,fontsize=12,fontweight="bold",pad=12)
583
- ax2=fig.add_subplot(1,2,2); ax2.set_facecolor(BG)
584
- bars=ax2.bar(["Not PCOS","PCOS"],[notp_c,pcos_c],color=["#22c55e","#ef4444"],
585
- width=0.45,edgecolor=BG,linewidth=2)
586
- ax2.set_ylim(0,max(pcos_c,notp_c)*1.35+0.5)
587
- ax2.set_title("Count per Class",color=TC,fontsize=12,fontweight="bold",pad=12)
588
- ax2.tick_params(colors=TC,labelsize=11)
589
- for sp in ax2.spines.values(): sp.set_visible(False)
590
- ax2.yaxis.set_visible(False)
591
- for bar,cnt in zip(bars,[notp_c,pcos_c]):
592
- ax2.text(bar.get_x()+bar.get_width()/2,bar.get_height()+0.15,str(cnt),
593
- ha="center",color=TC,fontsize=14,fontweight="bold")
594
- fig.text(0.5,0.01,f"Total: {total} image{'s' if total>1 else ''} Β· EfficientNetB0",
595
- ha="center",color="#64748b",fontsize=9)
596
- plt.tight_layout(pad=1.5)
597
- return fig
598
-
599
- # ══════════════════════════════════════════════════════════════════════════════
600
- # SECTION 6 β€” GRADIO HANDLER FUNCTIONS
601
- # ══════════════════════════════════════════════════════════════════════════════
602
  def predict_clinical(*args):
603
  vals=dict(zip(INPUT_KEYS,args))
604
  if not PIPELINE_READY:
605
- return ("❌ Clinical pipeline not ready.\n\nUpload `PCOS_data_without_infertility.xlsx` "
606
- "to the Space root folder.",None,"")
607
  bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
608
  if (not bmi or bmi==0) and vals["weight"] and vals["height"] and vals["height"]>0:
609
  bmi=vals["weight"]/((vals["height"]/100)**2)
610
  if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"]==0) and fsh and lh:
611
  vals["fsh_lh_ratio"]=fsh/(lh+1e-6)
612
  vals["bmi"]=bmi
613
-
614
- patient_raw={
615
  "Age (yrs)":vals["age"],"Weight (Kg)":vals["weight"],"BMI":vals["bmi"],
616
  "Pulse rate(bpm)":vals["pulse_rate"],"RR (breaths/min)":vals["rr"],
617
  "Hb(g/dl)":vals["hb"],"Cycle(R/I)":vals["cycle"],
@@ -630,50 +531,45 @@ def predict_clinical(*args):
630
  "BP _Systolic (mmHg)":120,"BP _Diastolic (mmHg)":80,
631
  }
632
  try:
633
- pcos_prob,pred,sev,base_probs=predict_single_clinical(PIPELINE,patient_raw)
634
  except Exception as e:
635
- return f"❌ Prediction error: {e}",None,""
636
-
637
- inf_risk=compute_infertility_risk(patient_raw)
638
- inf_s=inf_risk["score"]; inf_t=inf_risk["tier"]
639
- inf_icon="πŸ”΄" if inf_t=="High" else ("🟑" if inf_t=="Moderate" else "🟒")
640
- pcos_tier=("HIGH RISK πŸ”΄" if pcos_prob>0.65 else
641
- ("MODERATE RISK 🟑" if pcos_prob>0.35 else "LOW RISK 🟒"))
642
  recs=[]
643
  if pred: recs.append("πŸ₯ **Consult an endocrinologist / gynaecologist immediately.**")
644
- if inf_t=="High": recs.append("🧬 **High infertility risk β€” fertility specialist evaluation recommended.**")
645
- elif inf_t=="Moderate": recs.append("πŸ”¬ Hormonal panel follow-up recommended.")
646
- if sev["Metabolic"]>0.5: recs.append("βš–οΈ Weight management and regular exercise advised.")
647
- if sev["Hyperandrogenic"]>0.5: recs.append("πŸ’Š Discuss anti-androgen therapy with your doctor.")
648
  if not recs: recs.append("βœ… Continue routine annual screening and a healthy lifestyle.")
649
-
650
  sev_rows="\n".join(
651
- f"| {d} | {sev[d]*100:.1f}% | {'πŸ”΄ High' if sev[d]>0.65 else ('🟑 Moderate' if sev[d]>0.35 else '🟒 Low')} |"
652
  for d in ["Metabolic","Reproductive","Hyperandrogenic","General"])
653
  bio_rows="\n".join(
654
  f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
655
- for f,v in inf_risk.get("breakdown",{}).items()
656
  ) or "| β€” | Enter hormonal values | β€” | β€” |"
657
  rec_text="\n".join(f"- {r}" for r in recs)
658
-
659
- summary=f"""## Clinical Assessment β€” {pcos_tier}
660
 
661
  | Metric | Value |
662
  |---|---|
663
- | **PCOS Probability** | **{pcos_prob*100:.1f}%** |
664
  | **Diagnosis** | {"⚠️ PCOS Detected" if pred else "βœ… No PCOS Detected"} |
665
- | **Overall Severity** | {sev['Overall']*100:.1f}% |
666
- | **Infertility Risk** | {inf_icon} {inf_t} ({inf_s*100:.1f}%) |
667
 
668
  ---
669
  ### PCOS Domain Severity
670
  | Domain | Score | Level |
671
- |--------|-------|-------|
672
  {sev_rows}
673
 
674
  ### Infertility Biomarker Breakdown
675
  | Biomarker | Value | Direction | Contribution |
676
- |-----------|-------|-----------|-------------|
677
  {bio_rows}
678
 
679
  ### Clinical Recommendations
@@ -681,35 +577,18 @@ def predict_clinical(*args):
681
 
682
  ---
683
  *βš•οΈ For research/educational purposes only. Not medical advice.*"""
684
-
685
- fig=make_clinical_figure(pcos_prob,pred,sev,base_probs,inf_risk,PIPELINE["threshold"])
686
- info=(f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['threshold']:.4f} | "
687
- f"Models: LR + RF + GBM + CatBoost β†’ CalibratedLogisticRegressionCV")
688
- return summary,fig,info
689
 
690
 
691
  def predict_image_single(image):
692
  if IMAGE_MODEL is None:
693
- fix = (
694
- "## ❌ Image model not loaded\n\n"
695
- "**Cause:** `best_model.pth` was saved with an old PyTorch version "
696
- "that Python 3.13 cannot unpickle (`STACK_GLOBAL requires str`).\n\n"
697
- "**Fix β€” run in Colab then re-upload `best_model_fixed.pth` β†’ rename to `best_model.pth`:**\n"
698
- "```python\n"
699
- "import torch\nfrom torchvision import models\nimport torch.nn as nn\n\n"
700
- "old = torch.load('/content/drive/MyDrive/PCOS_RESULTS/EfficientNetB0/best_model.pth',\n"
701
- " map_location='cpu', weights_only=False)\n"
702
- "net = models.efficientnet_b0(weights=None)\n"
703
- "net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)\n"
704
- "net.load_state_dict(old['model_state'])\n"
705
- "torch.save({'model_state': net.state_dict()}, '/content/best_model_fixed.pth')\n"
706
- "print('Done β€” download and upload to models/ on HF')\n"
707
- "```\n\n"
708
- "The **Clinical tab works normally** β€” only the image tabs are affected."
709
- )
710
- return fix, None, None
711
  if image is None:
712
- return "⚠️ Please upload an ultrasound image.",None,None
713
  try:
714
  img_rgb=(image if isinstance(image,Image.Image) else Image.fromarray(image)).convert("RGB")
715
  pcos_p,notp,pred=run_image_inference(img_rgb)
@@ -728,38 +607,37 @@ def predict_image_single(image):
728
 
729
  *EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
730
  > ⚠️ Research use only β€” not a clinical tool."""
731
- return result, make_image_gauge(pcos_p), compute_gradcam(img_rgb,pred)
732
  except Exception as e:
733
  import traceback
734
- return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```",None,None
735
 
736
 
737
  def predict_image_batch(files):
738
  if IMAGE_MODEL is None:
739
- return ("## ❌ Image model not loaded\n\n"
740
- "Re-save `best_model.pth` in Colab (see Single Image tab for instructions)\n\n"
741
  "The **Clinical tab works normally**."), None
742
  if not files:
743
- return "⚠️ Upload at least one image.",None
744
  rows=[]; pcos_c=0; notp_c=0
745
  for f in files:
746
  try:
747
  img=Image.open(f.name).convert("RGB")
748
  pcos_p,notp,pred=run_image_inference(img)
749
- label=CLASS_NAMES[pred]
750
- risk="Low" if pcos_p<0.33 else "Moderate" if pcos_p<0.66 else "High"
751
  icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
752
- fname=os.path.basename(f.name)
753
- rows.append({"File":fname,"Prediction":f"{icon} {label}",
754
- "PCOS%":f"{pcos_p*100:.1f}","Not PCOS%":f"{notp*100:.1f}","Risk":risk})
 
755
  if pred==PCOS_IDX: pcos_c+=1
756
  else: notp_c+=1
757
  except Exception as e:
758
  rows.append({"File":os.path.basename(f.name),"Prediction":f"❌ {e}",
759
  "PCOS%":"β€”","Not PCOS%":"β€”","Risk":"β€”"})
760
  total=len(rows)
761
- table="\n".join(f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |"
762
- for r in rows)
 
763
  summary=f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total>1 else ''}
764
 
765
  | | Count | % |
@@ -775,158 +653,123 @@ def predict_image_batch(files):
775
  |---|---|---|---|---|
776
  {table}
777
 
778
- > ⚠️ Research use only β€” not a clinical tool."""
779
- return summary, make_batch_chart(pcos_c,notp_c,total)
780
 
781
- # ══════════════════════════════════════════════════════════════════════════════
782
- # SECTION 7 β€” CSS
783
- # ══════════════════════════════════════════════════════════════════════════════
784
  CSS = """
785
- body, .gradio-container { background:#0D0D1A !important; font-family:'Inter','Segoe UI',sans-serif !important; }
786
-
787
- .app-header {
788
- background: linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
789
- border:1px solid #4338ca; border-radius:16px;
790
- padding:28px 36px; margin-bottom:18px; text-align:center;
791
- }
792
- .app-header h1 { color:#e0e7ff !important; font-size:2rem !important; font-weight:700 !important; margin:0 0 4px 0 !important; }
793
- .app-header p { color:#a5b4fc !important; font-size:0.95rem !important; margin:0 !important; }
794
-
795
- .disclaimer {
796
- background:#1c1917; border-left:4px solid #f59e0b; border-radius:8px;
797
- padding:10px 16px; color:#fbbf24 !important; font-size:0.85rem; margin-bottom:16px;
798
- }
799
- .section-label {
800
- color:#c7d2fe !important; font-size:0.75rem !important; font-weight:700 !important;
801
- letter-spacing:1.4px !important; text-transform:uppercase !important;
802
- margin:0 0 8px 0 !important; padding-bottom:6px !important;
803
- border-bottom:1px solid #334155 !important;
804
- }
805
- .info-box {
806
- background:#1e293b; border:1px solid #334155; border-radius:10px;
807
- padding:14px 18px; font-size:0.85rem; color:#94a3b8; line-height:1.7;
808
- }
809
- .info-box strong { color:#c7d2fe; }
810
- .tab-nav button { color:#94a3b8 !important; font-size:0.9rem !important; font-weight:600 !important; }
811
- .tab-nav button.selected { color:#818cf8 !important; border-bottom:2px solid #818cf8 !important; background:#1e293b !important; }
812
- button.primary {
813
- background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
814
- border:none !important; border-radius:10px !important;
815
- font-weight:700 !important; color:white !important; padding:12px 0 !important;
816
- }
817
- button.secondary { border-radius:8px !important; }
818
- table { width:100%; border-collapse:collapse; font-size:0.88rem; }
819
- th { background:#1e3a5f; color:#93c5fd; padding:8px 12px; text-align:left; font-weight:600; }
820
- td { padding:7px 12px; border-bottom:1px solid #1e293b; color:#e2e8f0; }
821
- tr:nth-child(even) td { background:#1a2540; }
822
- footer { display:none !important; }
823
  """
824
 
825
- # ══════════════════════════════════════════════════════════════════════════════
826
- # SECTION 8 β€” GRADIO UI
827
- # ══════════════════════════════════════════════════════════════════════════════
828
  with gr.Blocks(
829
- theme=gr.themes.Base(primary_hue="purple",secondary_hue="violet",
830
- neutral_hue="slate",
831
  font=[gr.themes.GoogleFont("Inter"),"sans-serif"]),
832
  css=CSS, title="PCOS Integrated Detection System"
833
  ) as demo:
834
 
835
- # ── Banner ────────────────────────────────────────────────────────────────
836
  gr.HTML("""
837
  <div class="app-header">
838
  <h1>🩺 PCOS Integrated Detection System</h1>
839
- <p>
840
- Clinical Stacked Ensemble (AUC β‰ˆ 0.95) &nbsp;Β·&nbsp;
841
- EfficientNetB0 Ultrasound Analysis &nbsp;Β·&nbsp;
842
- Infertility Risk Scoring &nbsp;Β·&nbsp;
843
- Grad-CAM Explainability
844
- </p>
845
  </div>
846
  <div class="disclaimer">
847
  ⚠️ <strong>Medical Disclaimer:</strong> For <strong>research &amp; educational purposes only</strong>.
848
  Not a certified medical device. Consult a qualified clinician for any health decisions.
849
- </div>
850
- """)
851
 
852
  with gr.Tabs(elem_classes="tab-nav"):
853
 
854
- # ══════════════════════════════════════════════════════════
855
- # TAB 1 β€” CLINICAL
856
- # ══════════════════════════════════════════════════════════
857
  with gr.TabItem("πŸ”¬ Clinical Analysis"):
858
-
859
  with gr.Row():
860
- btn_pcos = gr.Button("πŸ“‹ Load PCOS Example", variant="secondary", size="sm")
861
- btn_normal = gr.Button("πŸ“‹ Load Normal Example", variant="secondary", size="sm")
862
- btn_clear = gr.Button("πŸ—‘οΈ Clear All", variant="secondary", size="sm")
863
 
864
  with gr.Row(equal_height=False):
865
  with gr.Column(scale=1):
866
- with gr.Accordion("πŸ“‹ General & Vitals", open=True):
867
- age = gr.Number(label="Age (yrs)", value=25)
868
- weight = gr.Number(label="Weight (Kg)", value=60)
869
- height = gr.Number(label="Height (cm)", value=160)
870
- bmi = gr.Number(label="BMI (auto-computed)",value=0)
871
- pulse_rate = gr.Number(label="Pulse rate (bpm)", value=72)
872
- rr = gr.Number(label="RR (breaths/min)", value=18)
873
- hb = gr.Number(label="Hb (g/dl)", value=12)
874
- tsh = gr.Number(label="TSH (mIU/L)", value=2.5)
875
- vit_d3 = gr.Number(label="Vit D3 (ng/mL)", value=25)
876
-
877
  with gr.Column(scale=1):
878
- with gr.Accordion("πŸ”΄ Metabolic", open=True):
879
- rbs = gr.Number(label="RBS (mg/dl)", value=90)
880
- waist = gr.Number(label="Waist (inch)", value=30)
881
- hip = gr.Number(label="Hip (inch)", value=37)
882
- waist_hip = gr.Number(label="Waist:Hip Ratio", value=0.81)
883
- weight_gain = gr.Radio([0,1], label="Weight Gain", value=0)
884
- fast_food = gr.Radio([0,1], label="Fast Food (Y=1)", value=0)
885
- reg_exercise = gr.Radio([0,1], label="Exercise (Y=1)", value=1)
886
-
887
  with gr.Column(scale=1):
888
- with gr.Accordion("🟣 Reproductive & Hormonal β˜…", open=True):
889
- cycle = gr.Radio([2,4], label="Cycle Regular=2 / Irregular=4", value=2)
890
- cycle_length = gr.Number(label="Cycle length (days)", value=28)
891
- fsh = gr.Number(label="FSH (mIU/mL) β˜…", value=6.5)
892
- lh = gr.Number(label="LH (mIU/mL) β˜…", value=5.0)
893
- fsh_lh_ratio = gr.Number(label="FSH/LH (auto if 0) β˜…", value=0)
894
- amh = gr.Number(label="AMH (ng/mL) β˜…", value=2.5)
895
- prg = gr.Number(label="PRG (ng/mL) β˜…", value=1.0)
896
- endometrium = gr.Number(label="Endometrium (mm) β˜…", value=8.0)
897
- follicle_l = gr.Number(label="Follicle No. (L) β˜…", value=6)
898
- follicle_r = gr.Number(label="Follicle No. (R) β˜…", value=6)
899
- avg_f_size_l = gr.Number(label="Avg F size L (mm)", value=15)
900
- avg_f_size_r = gr.Number(label="Avg F size R (mm)", value=15)
901
- gr.HTML("<p style='color:#94a3b8;font-size:0.8rem'>β˜… Used for both PCOS + Infertility Risk</p>")
902
-
903
  with gr.Column(scale=1):
904
- with gr.Accordion("🟠 Hyperandrogenic", open=True):
905
- hair_growth = gr.Radio([0,1], label="Hair Growth (Y=1)", value=0)
906
- skin_darkening = gr.Radio([0,1], label="Skin Darkening (Y=1)", value=0)
907
- hair_loss = gr.Radio([0,1], label="Hair Loss (Y=1)", value=0)
908
- pimples = gr.Radio([0,1], label="Pimples (Y=1)", value=0)
909
- prl = gr.Number(label="PRL (ng/mL)", value=15)
910
  gr.HTML("<br>")
911
- predict_btn = gr.Button("πŸ”¬ Run Full Analysis", variant="primary", size="lg")
912
 
913
- ALL_INPUTS = [
914
- age,weight,height,bmi,pulse_rate,rr,hb,
915
- cycle,cycle_length,fsh,lh,fsh_lh_ratio,
916
- hip,waist,waist_hip,tsh,amh,prl,vit_d3,prg,rbs,
917
- weight_gain,hair_growth,skin_darkening,hair_loss,
918
- pimples,fast_food,reg_exercise,
919
- follicle_l,follicle_r,avg_f_size_l,avg_f_size_r,endometrium,
920
- ]
921
 
922
  with gr.Row():
923
  with gr.Column(scale=1):
924
- gr.HTML('<p class="section-label">πŸ“‹ Assessment Summary</p>')
925
- summary_out = gr.Markdown(value="*Fill the form and click Run Full Analysis.*")
926
- model_info = gr.Textbox(label="Pipeline info", interactive=False, lines=2)
927
  with gr.Column(scale=2):
928
- gr.HTML('<p class="section-label">πŸ“Š Assessment Charts</p>')
929
- chart_out = gr.Plot(label="", show_label=False)
930
 
931
  def load_ex(ex): return [ex[k] for k in INPUT_KEYS]
932
  def clear_all():
@@ -939,74 +782,57 @@ with gr.Blocks(
939
  return [d[k] for k in INPUT_KEYS]
940
 
941
  btn_pcos.click(fn=lambda: load_ex(EXAMPLE_PCOS), outputs=ALL_INPUTS)
942
- btn_normal.click(fn=lambda: load_ex(EXAMPLE_NORMAL), outputs=ALL_INPUTS)
943
  btn_clear.click(fn=clear_all, outputs=ALL_INPUTS)
944
- predict_btn.click(fn=predict_clinical, inputs=ALL_INPUTS,
945
  outputs=[summary_out,chart_out,model_info])
946
 
947
- # ══════════════════════════════════════════════════════════
948
- # TAB 2 β€” SINGLE IMAGE
949
- # ═════════════════════════════════════════════════════���════
950
  with gr.TabItem("πŸ–ΌοΈ Ultrasound β€” Single"):
951
-
952
  with gr.Row(equal_height=False):
953
  with gr.Column(scale=4):
954
- gr.HTML('<p class="section-label">πŸ“ Upload Image</p>')
955
- img_input = gr.Image(label="", type="pil", height=280)
956
- img_btn = gr.Button("πŸ” Analyze Image", variant="primary", size="lg")
957
- gr.HTML("""
958
- <div class="info-box" style="margin-top:12px">
959
  <strong>Model:</strong> EfficientNetB0 (fine-tuned)<br>
960
  <strong>Input:</strong> 224Γ—224 RGB Β· ImageNet normalisation<br>
961
  <strong>Classes:</strong> <code>not_pcos</code> (0) Β· <code>pcos</code> (1)<br>
962
  <strong>Checkpoint:</strong> <code>models/best_model.pth</code><br>
963
  <strong>XAI:</strong> Grad-CAM on <code>features[-1]</code>
964
  </div>""")
965
-
966
  with gr.Column(scale=6):
967
- gr.HTML('<p class="section-label">πŸ“‹ Diagnosis Result</p>')
968
- img_result = gr.Markdown(value="*Upload an image and click Analyze.*")
969
- gr.HTML('<p class="section-label" style="margin-top:14px">πŸ“Š Probability Gauge</p>')
970
- img_gauge = gr.Plot(label="", show_label=False)
971
-
972
- gr.HTML('<p class="section-label" style="margin-top:6px">πŸ”₯ Grad-CAM Explainability</p>')
973
- img_gradcam = gr.Plot(label="", show_label=False)
974
-
975
- img_btn.click(fn=predict_image_single, inputs=[img_input],
976
- outputs=[img_result, img_gauge, img_gradcam])
977
-
978
- # ══════════════════════════════════════════════════════════
979
- # TAB 3 β€” BATCH IMAGE
980
- # ══════════════════════════════════════════════════════════
981
  with gr.TabItem("πŸ“‚ Ultrasound β€” Batch"):
982
-
983
  with gr.Row(equal_height=False):
984
  with gr.Column(scale=4):
985
- gr.HTML('<p class="section-label">πŸ“ Upload Multiple Images</p>')
986
- batch_input = gr.File(label="", file_count="multiple",
987
- file_types=["image"])
988
- batch_btn = gr.Button("⚑ Run Batch Analysis", variant="primary", size="lg")
989
- gr.HTML("""
990
- <div class="info-box" style="margin-top:12px">
991
  Upload any number of ultrasound images.<br>
992
  Each is analysed independently.<br>
993
  Results shown as a summary table + distribution chart.<br><br>
994
  <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF
995
  </div>""")
996
-
997
  with gr.Column(scale=6):
998
- gr.HTML('<p class="section-label">πŸ“Š Batch Summary</p>')
999
- batch_result = gr.Markdown(value="*Upload images and click Run Batch Analysis.*")
1000
-
1001
- gr.HTML('<p class="section-label" style="margin-top:6px">πŸ“ˆ Distribution Chart</p>')
1002
- batch_chart = gr.Plot(label="", show_label=False)
1003
-
1004
- batch_btn.click(fn=predict_image_batch, inputs=[batch_input],
1005
- outputs=[batch_result, batch_chart])
1006
-
1007
- # ══════════════════════════════════════════════════════════
1008
- # TAB 4 β€” ABOUT
1009
- # ══════════════════════════════════════════════════════════
1010
  with gr.TabItem("ℹ️ About"):
1011
  gr.Markdown("""
1012
  ## About This System
@@ -1019,8 +845,8 @@ with gr.Blocks(
1019
  | Imputation | MICE (IterativeImputer, max_iter=10) |
1020
  | Scaling | RobustScaler |
1021
  | Severity scoring | OOF GBM per domain β†’ normalised 0–1 |
1022
- | Threshold | Youden-J optimal (test ROC) |
1023
- | Dataset | PCOS_data_without_infertility.xlsx |
1024
 
1025
  **Domain weights:** Reproductive 40% Β· Metabolic 35% Β· Hyperandrogenic 20% Β· General 5%
1026
 
@@ -1032,11 +858,10 @@ with gr.Blocks(
1032
  | Classes | `not_pcos` (0) Β· `pcos` (1) β€” alphabetical |
1033
  | Checkpoint key | `model_state` |
1034
  | XAI | Grad-CAM on `features[-1]` |
1035
- | Saved by | Best validation AUC |
1036
 
1037
  ### 🧬 Infertility Risk
1038
- Pure formula β€” no training needed. Weighted biomarker orientations:
1039
- AMH (0.22) Β· FSH (0.18) Β· FSH/LH (0.15) Β· Follicles L+R (0.10Γ—2) Β· Endometrium (0.08) Β· LH (0.08) Β· PRG (0.05) Β· Cycle (0.04)
1040
 
1041
  ### ⚠️ Disclaimer
1042
  For **research and educational purposes only**. Not a certified medical device.
 
1
  """
2
  PCOS Integrated Detection System
3
+ - Tab 1: Clinical Analysis (stacked ensemble, trains on Excel at startup)
4
+ - Tab 2: Ultrasound Single (EfficientNetB0 β€” exact same code that worked standalone)
5
+ - Tab 3: Ultrasound Batch (multi-image, summary table + chart)
6
+ - Tab 4: About
7
  """
8
 
9
  import os, re, copy, warnings
 
19
  import matplotlib.cm as cm_mod
20
  import gradio as gr
21
 
22
+ # ── image deps ────────────────────────────────────────────────
23
  import torch
24
  import torch.nn as nn
25
  from torchvision import models as tv_models, transforms
26
  from PIL import Image
27
 
28
+ # ── clinical deps ─────────────────────────────────────────────
29
  from sklearn.model_selection import train_test_split, StratifiedKFold
30
  from sklearn.preprocessing import RobustScaler
31
+ from sklearn.experimental import enable_iterative_imputer # noqa
32
  from sklearn.impute import IterativeImputer
33
  from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
34
  from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
 
36
  from sklearn.metrics import roc_auc_score, roc_curve
37
  from catboost import CatBoostClassifier
38
 
39
+ # ══════════════════════════════════════════════════════════════
40
+ # SECTION 1 β€” IMAGE PIPELINE (exact standalone code that worked)
41
+ # ══════════════════════════════════════════════════════════════
42
+ MODELS_DIR = "models"
43
+ IMG_SIZE = 224
44
+ DEVICE = torch.device("cpu")
45
+ CLASS_NAMES = ["Not PCOS", "PCOS"] # alphabetical: not_pcos=0, pcos=1
46
+ PCOS_IDX = 1
47
+
48
+ VAL_TRANSFORM = transforms.Compose([
49
+ transforms.Resize((IMG_SIZE, IMG_SIZE)),
50
+ transforms.ToTensor(),
51
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
52
+ std =[0.229, 0.224, 0.225]),
53
+ ])
54
+
55
+ def load_image_model():
56
+ candidates = [
57
+ os.path.join(MODELS_DIR, "best_model.pth"),
58
+ os.path.join(MODELS_DIR, "efficientnetb0.pth"),
59
+ os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
60
+ ]
61
+ pth = next((p for p in candidates if os.path.exists(p)), None)
62
+ if pth is None:
63
+ existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else []
64
+ print(f"⚠️ Image model not found. models/ contains: {existing}")
65
+ return None
66
+ try:
67
+ net = tv_models.efficientnet_b0(weights=None)
68
+ net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
69
+ ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
70
+ if isinstance(ckpt, dict):
71
+ state = (ckpt.get("model_state") or ckpt.get("model_state_dict")
72
+ or ckpt.get("state_dict") or ckpt)
73
+ else:
74
+ state = ckpt
75
+ net.load_state_dict(state, strict=True)
76
+ net.to(DEVICE).eval()
77
+ print(f"βœ… Image model loaded: {pth}")
78
+ return net
79
+ except Exception as e:
80
+ print(f"⚠️ Image model failed to load: {e}")
81
+ return None
82
+
83
+ IMAGE_MODEL = load_image_model()
84
+
85
+ def run_image_inference(img_rgb: Image.Image):
86
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
87
+ with torch.no_grad():
88
+ probs = torch.softmax(IMAGE_MODEL(tensor), dim=1)[0]
89
+ return float(probs[PCOS_IDX]), float(probs[1 - PCOS_IDX]), int(probs.argmax())
90
+
91
+ def compute_gradcam(img_rgb: Image.Image, target_class: int):
92
+ grads, acts = [], []
93
+ def fwd_hook(m, inp, out):
94
+ acts.append(out.detach())
95
+ out.register_hook(lambda g: grads.append(g.detach()))
96
+ handle = IMAGE_MODEL.features[-1].register_forward_hook(fwd_hook)
97
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
98
+ IMAGE_MODEL.zero_grad()
99
+ IMAGE_MODEL(tensor)[0, target_class].backward()
100
+ handle.remove()
101
+ if not grads or not acts:
102
+ return None
103
+ w = grads[0].squeeze(0).mean(dim=(1, 2)).cpu().numpy()
104
+ act = acts[0].squeeze(0).cpu().numpy()
105
+ cam = np.maximum(sum(w[i] * act[i] for i in range(len(w))), 0)
106
+ if cam.max() > 1e-8:
107
+ cam /= cam.max()
108
+ cam_up = np.array(
109
+ Image.fromarray((cam * 255).astype(np.uint8)).resize(
110
+ (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
111
+ ) / 255.0
112
+ orig_r = np.array(img_rgb.resize((IMG_SIZE, IMG_SIZE)))
113
+ heat = cm_mod.jet(cam_up)[:, :, :3]
114
+ overlay = np.clip(0.55 * orig_r / 255.0 + 0.45 * heat, 0, 1)
115
+
116
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4), facecolor="#0f172a",
117
+ gridspec_kw={"wspace": 0.05})
118
+ for ax, (img, cmap, title) in zip(axes, [
119
+ (orig_r, None, "Original Image"),
120
+ (cam_up, "jet", "Grad-CAM Heatmap"),
121
+ (overlay, None, "Activation Overlay"),
122
+ ]):
123
+ ax.set_facecolor("#0f172a")
124
+ ax.imshow(img, cmap=cmap)
125
+ ax.set_title(title, color="white", fontsize=11, fontweight="bold", pad=6)
126
+ ax.axis("off")
127
+ fig.text(0.5, -0.01,
128
+ f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
129
+ ha="center", color="#94a3b8", fontsize=9)
130
+ plt.tight_layout(pad=0.3)
131
+ return fig
132
+
133
+ def make_image_gauge(pcos_prob: float):
134
+ fig, ax = plt.subplots(figsize=(5, 2.6), facecolor="#0f172a")
135
+ ax.set_facecolor("#0f172a")
136
+ ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
137
+ ax.barh([0.5], [1.0], height=0.30, color="#1e293b", left=0, align="center", zorder=1)
138
+ color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
139
+ ax.barh([0.5], [pcos_prob], height=0.30, color=color, left=0, align="center", zorder=2)
140
+ ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
141
+ ax.text(pcos_prob, 0.5, f" {pcos_prob*100:.1f}%", va="center", color="white",
142
+ fontsize=16, fontweight="bold", zorder=4,
143
+ ha="left" if pcos_prob < 0.85 else "right")
144
+ for x, lbl, c in [(0.16, "Low", "#22c55e"), (0.50, "Moderate", "#f59e0b"), (0.83, "High", "#ef4444")]:
145
+ ax.text(x, 0.12, lbl, color=c, fontsize=8, ha="center", alpha=0.8)
146
+ ax.text(0.5, 0.92, "PCOS Probability", color="#94a3b8", fontsize=9, ha="center", va="top")
147
+ plt.tight_layout(pad=0.2)
148
+ return fig
149
+
150
+ def make_batch_chart(pcos_c: int, notp_c: int, total: int):
151
+ fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")
152
+ ax1 = fig.add_subplot(1, 2, 1); ax1.set_facecolor("#0f172a")
153
+ if total > 0:
154
+ _, _, autotexts = ax1.pie(
155
+ [pcos_c, notp_c],
156
+ labels=[f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"],
157
+ colors=["#ef4444", "#22c55e"], autopct="%1.1f%%", startangle=90,
158
+ textprops={"color": "white", "fontsize": 10},
159
+ wedgeprops={"linewidth": 2, "edgecolor": "#0f172a"}, pctdistance=0.75)
160
+ for at in autotexts:
161
+ at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold")
162
+ ax1.set_title("Class Distribution", color="white", fontsize=12, fontweight="bold", pad=12)
163
+ ax2 = fig.add_subplot(1, 2, 2); ax2.set_facecolor("#0f172a")
164
+ bars = ax2.bar(["Not PCOS", "PCOS"], [notp_c, pcos_c],
165
+ color=["#22c55e", "#ef4444"], width=0.45, edgecolor="#0f172a", linewidth=2)
166
+ ax2.set_ylim(0, max(pcos_c, notp_c) * 1.35 + 0.5)
167
+ ax2.set_title("Count per Class", color="white", fontsize=12, fontweight="bold", pad=12)
168
+ ax2.tick_params(colors="white", labelsize=11)
169
+ for sp in ax2.spines.values(): sp.set_visible(False)
170
+ ax2.yaxis.set_visible(False)
171
+ for bar, cnt in zip(bars, [notp_c, pcos_c]):
172
+ ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.15,
173
+ str(cnt), ha="center", color="white", fontsize=14, fontweight="bold")
174
+ fig.text(0.5, 0.01, f"Total: {total} image{'s' if total > 1 else ''} Β· EfficientNetB0",
175
+ ha="center", color="#64748b", fontsize=9)
176
+ plt.tight_layout(pad=1.5)
177
+ return fig
178
+
179
+ # ══════════════════════════════════════════════════════════════
180
+ # SECTION 2 β€” CLINICAL PIPELINE (your exact code)
181
+ # ══════════════════════════════════════════════════════════════
182
  RANDOM_STATE = 42
183
  TEST_SIZE = 0.2
184
  CV_FOLDS = 5
185
+ BG = "#0D0D1A"
186
+ TC = "#E8E8F0"
187
+ ACC = "#A855F7"
188
 
189
  DOMAIN_WEIGHTS = {
190
+ "METABOLIC": 0.35, "REPRODUCTIVE": 0.40,
191
+ "HYPERANDROGENIC": 0.20, "GENERAL": 0.05,
 
 
192
  }
 
193
  FEATURE_GROUPS_BASE = {
194
+ "METABOLIC": ["BMI","Weight (Kg)","Waist(inch)","Hip(inch)",
195
+ "Waist:Hip Ratio","RBS(mg/dl)","Weight gain(Y/N)",
196
+ "BP _Systolic (mmHg)","BP _Diastolic (mmHg)",
197
+ "Fast food (Y/N)","Reg.Exercise(Y/N)"],
198
+ "REPRODUCTIVE": ["Cycle(R/I)","Cycle length(days)","FSH(mIU/mL)","LH(mIU/mL)","FSH/LH",
199
+ "AMH(ng/mL)","PRG(ng/mL)","Follicle No. (L)","Follicle No. (R)",
200
+ "Avg. F size (L) (mm)","Avg. F size (R) (mm)","Endometrium (mm)"],
201
+ "HYPERANDROGENIC": ["hair growth(Y/N)","Skin darkening (Y/N)",
202
+ "Hair loss(Y/N)","Pimples(Y/N)","PRL(ng/mL)"],
203
+ "GENERAL": ["Age (yrs)","Hb(g/dl)","Pulse rate(bpm)",
204
+ "RR (breaths/min)","TSH (mIU/L)","Vit D3 (ng/mL)"],
 
 
 
 
 
 
 
 
 
 
 
205
  }
206
+ DROP_COLS = ["Sl. No","Patient File No.","Blood Group","Marraige Status (Yrs)",
207
+ "Pregnant(Y/N)","No. of aborptions","Unnamed: 44"]
208
+ DOMAIN_COLORS = {"Metabolic":"#E74C3C","Reproductive":"#9B59B6",
209
+ "Hyperandrogenic":"#E67E22","General":"#27AE60"}
 
 
 
 
 
 
 
 
 
 
210
  BIOMARKER_DIRECTIONS = {
211
+ "FSH(mIU/mL)":1,"LH(mIU/mL)":-1,"FSH/LH":1,"AMH(ng/mL)":-1,
212
+ "Follicle No. (L)":-1,"Follicle No. (R)":-1,"Endometrium (mm)":-1,
213
+ "PRG(ng/mL)":-1,"Cycle(R/I)":1,
 
 
214
  }
215
  BIOMARKER_WEIGHTS = {
216
+ "FSH(mIU/mL)":0.18,"LH(mIU/mL)":0.08,"FSH/LH":0.15,"AMH(ng/mL)":0.22,
217
+ "Follicle No. (L)":0.10,"Follicle No. (R)":0.10,"Endometrium (mm)":0.08,
218
+ "PRG(ng/mL)":0.05,"Cycle(R/I)":0.04,
 
 
219
  }
220
  BIOMARKER_RANGES = {
221
+ "FSH(mIU/mL)":(0.5,22.0),"LH(mIU/mL)":(0.2,49.0),"FSH/LH":(0.1,20.0),
222
+ "AMH(ng/mL)":(0.01,18.0),"Follicle No. (L)":(0.0,22.0),"Follicle No. (R)":(0.0,22.0),
223
+ "Endometrium (mm)":(1.0,15.0),"PRG(ng/mL)":(0.1,25.0),"Cycle(R/I)":(2.0,4.0),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  }
225
+ EXAMPLE_PCOS = dict(age=28,weight=72,height=158,bmi=28.8,pulse_rate=82,rr=19,hb=11.5,
226
+ cycle=4,cycle_length=35,fsh=4.8,lh=12.5,fsh_lh_ratio=0.38,hip=40,waist=36,
227
+ waist_hip=0.90,tsh=2.8,amh=8.5,prl=22,vit_d3=18,prg=0.6,rbs=105,
228
+ weight_gain=1,hair_growth=1,skin_darkening=1,hair_loss=0,pimples=1,
229
+ fast_food=1,reg_exercise=0,follicle_l=14,follicle_r=13,avg_f_size_l=8,avg_f_size_r=8,endometrium=6)
230
+ EXAMPLE_NORMAL = dict(age=26,weight=58,height=162,bmi=22.1,pulse_rate=70,rr=16,hb=13.2,
231
+ cycle=2,cycle_length=28,fsh=7.2,lh=4.8,fsh_lh_ratio=1.5,hip=37,waist=28,
232
+ waist_hip=0.76,tsh=2.1,amh=3.2,prl=14,vit_d3=30,prg=1.8,rbs=85,
233
+ weight_gain=0,hair_growth=0,skin_darkening=0,hair_loss=0,pimples=0,
234
+ fast_food=0,reg_exercise=1,follicle_l=6,follicle_r=6,avg_f_size_l=16,avg_f_size_r=16,endometrium=9)
235
+ INPUT_KEYS = ["age","weight","height","bmi","pulse_rate","rr","hb","cycle","cycle_length",
236
+ "fsh","lh","fsh_lh_ratio","hip","waist","waist_hip","tsh","amh","prl",
237
+ "vit_d3","prg","rbs","weight_gain","hair_growth","skin_darkening","hair_loss",
238
+ "pimples","fast_food","reg_exercise","follicle_l","follicle_r",
239
+ "avg_f_size_l","avg_f_size_r","endometrium"]
 
 
 
 
 
 
 
240
 
 
 
 
241
  def clean_name(n): return re.sub(r"[^0-9a-zA-Z_]","_",n.strip())
242
  def clean_df_cols(df):
243
  df=df.copy(); df.columns=[clean_name(c) for c in df.columns]; return df
 
250
  class_weight="balanced",random_state=RANDOM_STATE),
251
  "GradientBoost": GradientBoostingClassifier(n_estimators=200,learning_rate=0.05,
252
  max_depth=3,subsample=0.85,random_state=RANDOM_STATE),
253
+ "CatBoost" : CatBoostClassifier(iterations=300,learning_rate=0.05,depth=6,
254
+ random_seed=RANDOM_STATE,eval_metric="AUC",verbose=0),
255
  }
256
 
257
+ def load_and_engineer(dp):
258
+ df=pd.read_excel(dp); df=df.drop(columns=DROP_COLS,errors="ignore")
259
+ df.columns=df.columns.str.strip()
260
+ y=pd.to_numeric(df["PCOS (Y/N)"],errors="coerce"); mask=y.notna()
261
+ df=df.loc[mask].copy().reset_index(drop=True); y=y.loc[mask].astype(int).reset_index(drop=True)
 
 
 
262
  for c in df.columns:
263
  if df[c].dtype=="object" and c!="PCOS (Y/N)":
264
  df[c]=pd.to_numeric(df[c].astype(str).str.strip(),errors="coerce")
265
+ df["FSH_LH_Ratio"]=df["FSH(mIU/mL)"]/(df["LH(mIU/mL)"]+1e-6)
266
+ df["Total_Follicles"]=df["Follicle No. (L)"].fillna(0)+df["Follicle No. (R)"].fillna(0)
267
+ df["AMH_FSH_Ratio"]=df["AMH(ng/mL)"]/(df["FSH(mIU/mL)"]+1e-6)
268
+ df["BMI_Waist_Ratio"]=df["BMI"]/(df["Waist(inch)"]+1e-6)
269
  andro=[c for c in FEATURE_GROUPS_BASE["HYPERANDROGENIC"] if c in df.columns]
270
  if andro: df["Androgenic_Score"]=df[andro].sum(axis=1)
271
  FG=copy.deepcopy(FEATURE_GROUPS_BASE)
272
+ FG["REPRODUCTIVE"]+=["FSH_LH_Ratio","Total_Follicles","AMH_FSH_Ratio"]
273
+ FG["METABOLIC"]+=["BMI_Waist_Ratio"]; FG["HYPERANDROGENIC"]+=["Androgenic_Score"]
274
+ return clean_df_cols(df.drop(columns=["PCOS (Y/N)"])),y,FG
 
 
275
 
276
  def preprocess(Xtr,Xte):
277
  mice=IterativeImputer(max_iter=10,random_state=RANDOM_STATE)
278
+ Xti=pd.DataFrame(mice.fit_transform(Xtr),columns=Xtr.columns,index=Xtr.index)
279
+ Xei=pd.DataFrame(mice.transform(Xte),columns=Xte.columns,index=Xte.index)
280
+ nc=Xti.select_dtypes(include=np.number).columns.tolist(); sc=RobustScaler()
281
+ Xts=Xti.copy(); Xes=Xei.copy()
282
+ Xts[nc]=sc.fit_transform(Xti[nc]); Xes[nc]=sc.transform(Xei[nc])
283
+ return Xts,Xes,mice,sc,nc
284
+
285
+ def compute_oof_severity(Xtr,ytr,Xts,FG):
 
 
286
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
287
+ sev=pd.DataFrame(index=Xtr.index); mods,stats={},{}
288
  for domain,feats in FG.items():
289
+ fc=get_clean_feats(feats,Xts.columns)
290
  if len(fc)<3: continue
291
+ oof=np.zeros(len(Xts))
292
+ for tr,val in skf.split(Xts,ytr):
293
  m=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
294
  max_depth=3,random_state=RANDOM_STATE)
295
+ m.fit(Xts.iloc[tr][fc],ytr.iloc[tr]); oof[val]=m.predict_proba(Xts.iloc[val][fc])[:,1]
 
296
  stats[domain]={"min":oof.min(),"max":oof.max()}
297
  sev[f"{domain}_SEV"]=(oof-oof.min())/(oof.max()-oof.min()+1e-6)
298
  fm=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
299
  max_depth=3,random_state=RANDOM_STATE)
300
+ fm.fit(Xts[fc],ytr); mods[domain]=(fm,fc)
301
  sev["OVERALL_SEV"]=sum(sev[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
302
  for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev)
303
+ return sev.fillna(0),mods,stats
304
+
305
+ def apply_severity(mods,stats,Xsc):
306
+ out=pd.DataFrame(index=Xsc.index)
307
+ for d,(m,fc) in mods.items():
308
+ fca=[f for f in fc if f in Xsc.columns]
309
+ p=m.predict_proba(Xsc[fca])[:,1]
310
+ out[f"{d}_SEV"]=np.clip((p-stats[d]["min"])/(stats[d]["max"]-stats[d]["min"]+1e-6),0,1)
311
+ out=out.fillna(0)
312
+ out["OVERALL_SEV"]=sum(out[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
313
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in out)
314
+ return out
315
+
316
+ def build_pipeline(dp):
317
  print("πŸ”„ Training clinical pipeline...")
318
+ X,y,FG=load_and_engineer(dp)
319
+ Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=TEST_SIZE,stratify=y,random_state=RANDOM_STATE)
320
+ Xts,Xes,mice,sc,nc=preprocess(Xtr,Xte)
321
+ sev_tr,dm,stats=compute_oof_severity(Xtr,ytr,Xts,FG)
322
+ sev_te=apply_severity(dm,stats,Xes)
323
+ Xf=pd.concat([Xts,sev_tr],axis=1); Xef=pd.concat([Xes,sev_te],axis=1)
 
 
 
324
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
325
+ om=pd.DataFrame(index=Xf.index); tm=pd.DataFrame(index=Xef.index); tb={}
 
 
 
326
  for name,model in get_base_models().items():
327
+ oof=np.zeros(len(Xf))
328
+ for tri,vi in skf.split(Xf,ytr):
329
+ model.fit(Xf.iloc[tri],ytr.iloc[tri]); oof[vi]=model.predict_proba(Xf.iloc[vi])[:,1]
330
+ model.fit(Xf,ytr); om[name]=oof; tm[name]=model.predict_proba(Xef)[:,1]; tb[name]=model
331
+ print(f" βœ… {name} AUC:{roc_auc_score(ytr,oof):.4f}")
332
+ meta=CalibratedClassifierCV(LogisticRegressionCV(cv=5,class_weight={0:1,1:3}),method="isotonic")
333
+ meta.fit(om,ytr); ep=meta.predict_proba(tm)[:,1]
334
+ fpr,tpr,ths=roc_curve(yte,ep); bt=float(ths[np.argmax(tpr-fpr)]); auc=roc_auc_score(yte,ep)
335
+ print(f" βœ… Ensemble AUC:{auc:.4f} threshold:{bt:.4f}\nβœ… Clinical pipeline ready")
336
+ return dict(meta=meta,base=tb,dm=dm,stats=stats,mice=mice,sc=sc,nc=nc,
337
+ sc_cols=list(Xts.columns),fc=list(Xf.columns),thr=bt,auc=round(auc,4))
338
+
339
+ def compute_infertility_risk(pr):
 
 
 
 
 
 
 
 
 
 
 
340
  def _v(v):
341
  try: return not np.isnan(float(v)) if v is not None else False
342
  except: return False
343
+ av={f:w for f,w in BIOMARKER_WEIGHTS.items() if f in pr and _v(pr[f])}
344
+ if not av: return {"score":0.5,"tier":"Unknown","breakdown":{}}
345
+ tw=sum(av.values()); score=0.0; bd={}
346
+ for feat,w in av.items():
347
+ val=float(pr[feat]); lo,hi=BIOMARKER_RANGES.get(feat,(0,1))
348
+ norm=np.clip((val-lo)/(hi-lo+1e-8),0,1)
349
+ ori=(1-norm) if BIOMARKER_DIRECTIONS.get(feat,1)==-1 else norm
350
+ c=(w/tw)*ori; score+=c
351
+ bd[feat]={"raw":round(val,3),"oriented":round(ori,3),"contribution":round(c,4),
352
+ "direction":"↑ risk" if BIOMARKER_DIRECTIONS.get(feat,1)==1 else "↓ protective"}
353
+ tier="High" if score>=0.66 else("Moderate" if score>=0.33 else "Low")
354
+ return {"score":round(score,4),"tier":tier,"breakdown":bd}
355
+
356
+ def predict_clinical_single(pl,pr):
357
+ row={k:np.nan for k in pl["sc_cols"]}
358
+ for rk,val in pr.items():
 
 
359
  ck=clean_name(rk)
360
  if ck in row and val is not None:
361
  try: row[ck]=float(val)
362
  except: pass
363
+ Xr=pd.DataFrame([row])
364
+ for c in Xr.columns: Xr[c]=pd.to_numeric(Xr[c],errors="coerce")
365
+ Xi=pd.DataFrame(pl["mice"].transform(Xr),columns=Xr.columns)
366
+ Xs=Xi.copy(); ncc=[c for c in pl["nc"] if c in Xs.columns]
367
+ Xs[ncc]=pl["sc"].transform(Xi[ncc])
368
+ sev=apply_severity(pl["dm"],pl["stats"],Xs)
369
+ Xf=pd.concat([Xs.reset_index(drop=True),sev.reset_index(drop=True)],axis=1)
370
+ for c in pl["fc"]:
371
+ if c not in Xf.columns: Xf[c]=0.0
372
+ Xf=Xf[pl["fc"]].clip(-10,10)
373
+ bp={n:m.predict_proba(Xf)[:,1][0] for n,m in pl["base"].items()}
374
+ pp=pl["meta"].predict_proba(pd.DataFrame([bp]))[:,1][0]
375
+ pred=int(pp>=pl["thr"])
376
+ def _s(c): return float(sev[c].iloc[0]) if c in sev.columns else 0.0
377
+ sv={"Metabolic":_s("METABOLIC_SEV"),"Reproductive":_s("REPRODUCTIVE_SEV"),
378
+ "Hyperandrogenic":_s("HYPERANDROGENIC_SEV"),"General":_s("GENERAL_SEV"),"Overall":_s("OVERALL_SEV")}
379
+ return pp,pred,sv,bp
380
+
381
+ # ── Startup ───────────────────────────────────────────────────
 
 
 
 
382
  DATA_PATH = os.path.join(os.path.dirname(__file__), "PCOS_data_without_infertility.xlsx")
383
  if os.path.exists(DATA_PATH):
384
  try:
385
+ PIPELINE=build_pipeline(DATA_PATH); PIPELINE_READY=True
 
 
386
  except Exception as _e:
387
  print(f"⚠️ Pipeline error: {_e}"); PIPELINE=None; PIPELINE_READY=False
388
  else:
389
  print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False
390
 
391
+ # ══════════════════════════════════════════════════════════════
392
+ # SECTION 3 β€” CLINICAL CHARTS (your exact draw_gauge code)
393
+ # ══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  def draw_gauge(ax,value,title,val_label,sub_label,val_col):
395
  ax.set_facecolor(BG)
396
  theta=np.linspace(np.pi,0,300)
397
  for i in range(len(theta)-1):
 
398
  ax.fill_between([np.cos(theta[i]),np.cos(theta[i+1])],
399
  [np.sin(theta[i]),np.sin(theta[i+1])],
400
+ alpha=0.9,color=plt.cm.RdYlGn_r(i/(len(theta)-1)))
401
  angle=np.pi*(1-value)
402
  ax.annotate("",xy=(0.65*np.cos(angle),0.65*np.sin(angle)),xytext=(0,0),
403
  arrowprops=dict(arrowstyle="-|>",color="white",lw=3))
404
  ax.plot(0,0,"o",color="white",markersize=6,zorder=5)
405
  ax.text(0,-0.15,val_label,ha="center",fontsize=22,fontweight="bold",color=val_col,va="center")
 
406
  ax.text(0,-0.58,sub_label,ha="center",fontsize=10,fontweight="bold",color=val_col)
407
  for pct,lbl in [(0,"0%"),(0.5,"50%"),(1.0,"100%")]:
408
  a=np.pi*(1-pct)
 
410
  ax.set_xlim(-1.05,1.05); ax.set_ylim(-0.72,1.05); ax.axis("off")
411
  ax.set_title(title,color=TC,fontsize=12,fontweight="bold",pad=4)
412
 
413
+ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
414
  fig=plt.figure(figsize=(18,13),facecolor=BG)
415
+ gs=GridSpec(3,4,figure=fig,hspace=0.58,wspace=0.45,top=0.93,bottom=0.05,left=0.05,right=0.97)
416
+ ax_pg=fig.add_subplot(gs[0,0]); ax_ig=fig.add_subplot(gs[0,1])
417
+ ax_rd=fig.add_subplot(gs[0,2:],polar=True)
418
+ ax_br=fig.add_subplot(gs[1,:2]); ax_bi=fig.add_subplot(gs[1,2:])
419
+ ax_sv=fig.add_subplot(gs[2,:])
420
+ rc="#E74C3C" if pp>0.65 else("#F39C12" if pp>0.35 else "#2ECC71")
421
+ it=inf["tier"]; ic="#E74C3C" if it=="High" else("#F39C12" if it=="Moderate" else "#2ECC71")
422
+ draw_gauge(ax_pg,pp,"PCOS Risk",f"{pp*100:.1f}%","⚠️ PCOS Detected" if pred else "βœ… No PCOS",rc)
423
+ draw_gauge(ax_ig,inf["score"],"Infertility Risk",f"{inf['score']*100:.1f}%",
424
+ f"{'πŸ”΄' if it=='High' else('🟑' if it=='Moderate' else '🟒')} {it}",ic)
 
 
 
 
 
 
 
 
425
  # Radar
426
+ doms=["Metabolic","Reproductive","Hyperandrogenic","General"]
427
+ vals=[sv[d] for d in doms]
428
+ ang=np.linspace(0,2*np.pi,len(doms),endpoint=False).tolist()
429
+ vc=vals+[vals[0]]; ac=ang+[ang[0]]
430
+ ax_rd.set_facecolor(BG)
431
+ for lv,al,co in [(1.0,0.05,"#E74C3C"),(0.65,0.08,"#F39C12"),(0.35,0.08,"#2ECC71")]:
432
+ ax_rd.fill(ac,[lv]*len(ac),alpha=al,color=co)
433
+ ax_rd.plot(ac,vc,"o-",lw=2.5,color=ACC,markersize=7); ax_rd.fill(ac,vc,alpha=0.30,color=ACC)
434
+ ax_rd.set_xticks(ang)
435
+ ax_rd.set_xticklabels([f"{d}\n{vals[i]*100:.0f}%" for i,d in enumerate(doms)],
436
+ color=TC,fontsize=10,fontweight="bold")
437
+ ax_rd.set_ylim(0,1); ax_rd.set_yticks([0.35,0.65,1.0])
438
+ ax_rd.set_yticklabels(["Low→Mod","Mod→High","Max"],color="#666",fontsize=7)
439
+ ax_rd.grid(color="#333355",alpha=0.6,lw=0.8); ax_rd.spines["polar"].set_color("#333355")
440
+ ax_rd.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
 
 
 
441
  # Base model bars
442
+ ax_br.set_facecolor(BG)
443
+ names=list(bp.keys()); probs_=[bp[n] for n in names]
444
+ cols=["#3B82F6","#10B981","#F59E0B","#EF4444"]
445
+ bars=ax_br.barh(names,probs_,color=cols[:len(names)],height=0.52,alpha=0.88)
446
  for bar,p in zip(bars,probs_):
447
+ ax_br.text(min(p+0.018,0.97),bar.get_y()+bar.get_height()/2,
448
+ f"{p:.3f}",va="center",color=TC,fontsize=11,fontweight="bold")
449
+ ax_br.axvline(0.5,color="white",ls="--",alpha=0.3,lw=1.5)
450
+ ax_br.axvline(thr,color=ACC,ls=":",alpha=0.6,lw=1.5,label=f"Youden threshold ({thr:.2f})")
451
+ ax_br.set_xlim(0,1.12); ax_br.tick_params(colors=TC,labelsize=11)
452
+ for sp in ax_br.spines.values(): sp.set_color("#2A2A4A")
453
+ ax_br.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
454
+ ax_br.set_xlabel("PCOS Probability",color=TC,fontsize=10)
455
+ ax_br.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
 
 
456
  # Biomarker bars
457
+ ax_bi.set_facecolor(BG); ax_bi.tick_params(colors=TC,labelsize=8)
458
+ for sp in ax_bi.spines.values(): sp.set_color("#2A2A4A")
459
+ ax_bi.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
460
+ ax_bi.set_xlabel("Weighted contribution",color=TC,fontsize=9)
461
+ bd=inf.get("breakdown",{})
462
+ if bd:
463
+ fn=list(bd.keys()); fv=[bd[f]["contribution"] for f in fn]
464
+ fc_=[("#EF4444" if bd[f]["oriented"]>0.5 else "#10B981") for f in fn]
465
+ sn=[f.split("(")[0].strip()[:14] for f in fn]
466
+ sp2=sorted(zip(sn,fv,fc_),key=lambda x:x[1],reverse=True)
467
+ sn,fv,fc_=zip(*sp2)
468
+ b2=ax_bi.barh(sn,fv,color=fc_,height=0.52,alpha=0.88)
469
+ for bar,val in zip(b2,fv):
470
+ ax_bi.text(val+0.001,bar.get_y()+bar.get_height()/2,f"{val:.3f}",va="center",color=TC,fontsize=9)
471
+ ax_bi.legend(handles=[mpatches.Patch(color="#EF4444",label="↑ Increases risk"),
472
+ mpatches.Patch(color="#10B981",label="↓ Protective")],
473
+ facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8)
 
 
474
  else:
475
+ ax_bi.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values",ha="center",va="center",
476
+ color="#666",fontsize=10,transform=ax_bi.transAxes)
 
477
  # Domain severity bars
478
+ ax_sv.set_facecolor(BG)
479
+ sv_v=[sv[d] for d in doms]; sv_c=[DOMAIN_COLORS[d] for d in doms]
480
+ xp=np.arange(len(doms)); b3=ax_sv.bar(xp,sv_v,color=sv_c,alpha=0.88,width=0.5)
481
+ for bar,val,d in zip(b3,sv_v,doms):
482
+ lv="High" if val>0.65 else("Moderate" if val>0.35 else "Low")
483
+ lc="#E74C3C" if lv=="High" else("#F39C12" if lv=="Moderate" else "#2ECC71")
484
+ ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.02,f"{val*100:.1f}%",
485
+ ha="center",va="bottom",color=TC,fontsize=14,fontweight="bold")
486
+ ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.09,f"({lv})",
487
+ ha="center",va="bottom",color=lc,fontsize=11)
488
+ ax_sv.axhline(0.65,color="#E74C3C",ls="--",alpha=0.45,lw=1.5,label="High (65%)")
489
+ ax_sv.axhline(0.35,color="#F39C12",ls="--",alpha=0.45,lw=1.5,label="Moderate (35%)")
490
+ ax_sv.set_ylim(0,1.3); ax_sv.set_xticks(xp)
491
+ ax_sv.set_xticklabels(doms,color=TC,fontsize=13,fontweight="bold")
492
+ ax_sv.tick_params(axis="y",colors=TC,labelsize=10)
493
+ for sp in ax_sv.spines.values(): sp.set_color("#2A2A4A")
494
+ ax_sv.set_title("PCOS Domain Severity Breakdown",color=TC,fontsize=13,fontweight="bold")
495
+ ax_sv.set_ylabel("Severity Score",color=TC,fontsize=11)
496
+ ax_sv.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=9,loc="upper right")
 
 
 
497
  fig.patch.set_facecolor(BG)
498
  fig.suptitle("🩺 PCOS Clinical Assessment Report",color=TC,fontsize=16,fontweight="bold",y=0.97)
499
  return fig
500
 
501
+ # ══════════════════════════════════════════════════════════════
502
+ # SECTION 4 β€” GRADIO HANDLER FUNCTIONS
503
+ # ══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  def predict_clinical(*args):
505
  vals=dict(zip(INPUT_KEYS,args))
506
  if not PIPELINE_READY:
507
+ return ("❌ Clinical pipeline not ready.\nUpload `PCOS_data_without_infertility.xlsx` "
508
+ "to the Space root folder."), None, ""
509
  bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
510
  if (not bmi or bmi==0) and vals["weight"] and vals["height"] and vals["height"]>0:
511
  bmi=vals["weight"]/((vals["height"]/100)**2)
512
  if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"]==0) and fsh and lh:
513
  vals["fsh_lh_ratio"]=fsh/(lh+1e-6)
514
  vals["bmi"]=bmi
515
+ pr={
 
516
  "Age (yrs)":vals["age"],"Weight (Kg)":vals["weight"],"BMI":vals["bmi"],
517
  "Pulse rate(bpm)":vals["pulse_rate"],"RR (breaths/min)":vals["rr"],
518
  "Hb(g/dl)":vals["hb"],"Cycle(R/I)":vals["cycle"],
 
531
  "BP _Systolic (mmHg)":120,"BP _Diastolic (mmHg)":80,
532
  }
533
  try:
534
+ pp,pred,sv,bp=predict_clinical_single(PIPELINE,pr)
535
  except Exception as e:
536
+ return f"❌ Prediction error: {e}", None, ""
537
+ inf=compute_infertility_risk(pr)
538
+ it=inf["tier"]; ii="πŸ”΄" if it=="High" else("🟑" if it=="Moderate" else "🟒")
539
+ pt="HIGH RISK πŸ”΄" if pp>0.65 else("MODERATE RISK 🟑" if pp>0.35 else "LOW RISK 🟒")
 
 
 
540
  recs=[]
541
  if pred: recs.append("πŸ₯ **Consult an endocrinologist / gynaecologist immediately.**")
542
+ if it=="High": recs.append("🧬 **High infertility risk β€” fertility specialist evaluation recommended.**")
543
+ elif it=="Moderate": recs.append("πŸ”¬ Hormonal panel follow-up (FSH, LH, AMH) recommended.")
544
+ if sv["Metabolic"]>0.5: recs.append("βš–οΈ Weight management and regular exercise advised.")
545
+ if sv["Hyperandrogenic"]>0.5: recs.append("πŸ’Š Discuss anti-androgen therapy with your doctor.")
546
  if not recs: recs.append("βœ… Continue routine annual screening and a healthy lifestyle.")
 
547
  sev_rows="\n".join(
548
+ f"| {d} | {sv[d]*100:.1f}% | {'πŸ”΄ High' if sv[d]>0.65 else('🟑 Moderate' if sv[d]>0.35 else '🟒 Low')} |"
549
  for d in ["Metabolic","Reproductive","Hyperandrogenic","General"])
550
  bio_rows="\n".join(
551
  f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
552
+ for f,v in inf.get("breakdown",{}).items()
553
  ) or "| β€” | Enter hormonal values | β€” | β€” |"
554
  rec_text="\n".join(f"- {r}" for r in recs)
555
+ summary=f"""## Clinical Assessment β€” {pt}
 
556
 
557
  | Metric | Value |
558
  |---|---|
559
+ | **PCOS Probability** | **{pp*100:.1f}%** |
560
  | **Diagnosis** | {"⚠️ PCOS Detected" if pred else "βœ… No PCOS Detected"} |
561
+ | **Overall Severity** | {sv['Overall']*100:.1f}% |
562
+ | **Infertility Risk** | {ii} {it} ({inf['score']*100:.1f}%) |
563
 
564
  ---
565
  ### PCOS Domain Severity
566
  | Domain | Score | Level |
567
+ |---|---|---|
568
  {sev_rows}
569
 
570
  ### Infertility Biomarker Breakdown
571
  | Biomarker | Value | Direction | Contribution |
572
+ |---|---|---|---|
573
  {bio_rows}
574
 
575
  ### Clinical Recommendations
 
577
 
578
  ---
579
  *βš•οΈ For research/educational purposes only. Not medical advice.*"""
580
+ fig=make_clinical_figure(pp,pred,sv,bp,inf,PIPELINE["thr"])
581
+ info=f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['thr']:.4f} | LR+RF+GBM+CatBoost β†’ CalibratedLRCV"
582
+ return summary, fig, info
 
 
583
 
584
 
585
  def predict_image_single(image):
586
  if IMAGE_MODEL is None:
587
+ return ("## ❌ Image model not loaded\n\n"
588
+ "Upload `best_model.pth` to the `models/` folder on HuggingFace.\n\n"
589
+ "The **Clinical tab works normally**."), None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  if image is None:
591
+ return "⚠️ Please upload an ultrasound image.", None, None
592
  try:
593
  img_rgb=(image if isinstance(image,Image.Image) else Image.fromarray(image)).convert("RGB")
594
  pcos_p,notp,pred=run_image_inference(img_rgb)
 
607
 
608
  *EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
609
  > ⚠️ Research use only β€” not a clinical tool."""
610
+ return result, make_image_gauge(pcos_p), compute_gradcam(img_rgb, pred)
611
  except Exception as e:
612
  import traceback
613
+ return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None
614
 
615
 
616
  def predict_image_batch(files):
617
  if IMAGE_MODEL is None:
618
+ return ("## ❌ Image model not loaded\n\nUpload `best_model.pth` to `models/`.\n\n"
 
619
  "The **Clinical tab works normally**."), None
620
  if not files:
621
+ return "⚠️ Upload at least one image.", None
622
  rows=[]; pcos_c=0; notp_c=0
623
  for f in files:
624
  try:
625
  img=Image.open(f.name).convert("RGB")
626
  pcos_p,notp,pred=run_image_inference(img)
 
 
627
  icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
628
+ rows.append({"File":os.path.basename(f.name),
629
+ "Prediction":f"{icon} {CLASS_NAMES[pred]}",
630
+ "PCOS%":f"{pcos_p*100:.1f}","Not PCOS%":f"{notp*100:.1f}",
631
+ "Risk":"Low" if pcos_p<0.33 else "Moderate" if pcos_p<0.66 else "High"})
632
  if pred==PCOS_IDX: pcos_c+=1
633
  else: notp_c+=1
634
  except Exception as e:
635
  rows.append({"File":os.path.basename(f.name),"Prediction":f"❌ {e}",
636
  "PCOS%":"β€”","Not PCOS%":"β€”","Risk":"β€”"})
637
  total=len(rows)
638
+ table="\n".join(
639
+ f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |"
640
+ for r in rows)
641
  summary=f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total>1 else ''}
642
 
643
  | | Count | % |
 
653
  |---|---|---|---|---|
654
  {table}
655
 
656
+ > ⚠️ Research use only."""
657
+ return summary, make_batch_chart(pcos_c, notp_c, total)
658
 
659
+ # ══════════════════════════════════════════════════════════════
660
+ # SECTION 5 β€” CSS + UI
661
+ # ══════════════════════════════════════════════════════════════
662
  CSS = """
663
+ body,.gradio-container{background:#0D0D1A !important;font-family:'Inter','Segoe UI',sans-serif !important;}
664
+ .app-header{background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
665
+ border:1px solid #4338ca;border-radius:16px;padding:28px 36px;margin-bottom:16px;text-align:center;}
666
+ .app-header h1{color:#e0e7ff !important;font-size:2rem !important;font-weight:700 !important;margin:0 0 4px 0 !important;}
667
+ .app-header p{color:#a5b4fc !important;font-size:0.95rem !important;margin:0 !important;}
668
+ .disclaimer{background:#1c1917;border-left:4px solid #f59e0b;border-radius:8px;
669
+ padding:10px 16px;color:#fbbf24 !important;font-size:0.85rem;margin-bottom:16px;}
670
+ .sec{color:#c7d2fe !important;font-size:0.75rem !important;font-weight:700 !important;
671
+ letter-spacing:1.4px !important;text-transform:uppercase !important;
672
+ margin:0 0 8px 0 !important;padding-bottom:6px !important;border-bottom:1px solid #334155 !important;}
673
+ .info-box{background:#1e293b;border:1px solid #334155;border-radius:10px;
674
+ padding:14px 18px;font-size:0.85rem;color:#94a3b8;line-height:1.7;}
675
+ .info-box strong{color:#c7d2fe;}
676
+ .tab-nav button{color:#94a3b8 !important;font-size:0.9rem !important;font-weight:600 !important;}
677
+ .tab-nav button.selected{color:#818cf8 !important;border-bottom:2px solid #818cf8 !important;background:#1e293b !important;}
678
+ button.primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
679
+ border:none !important;border-radius:10px !important;font-weight:700 !important;
680
+ color:white !important;padding:12px 0 !important;}
681
+ table{width:100%;border-collapse:collapse;font-size:0.88rem;}
682
+ th{background:#1e3a5f;color:#93c5fd;padding:8px 12px;text-align:left;font-weight:600;}
683
+ td{padding:7px 12px;border-bottom:1px solid #1e293b;color:#e2e8f0;}
684
+ tr:nth-child(even) td{background:#1a2540;}
685
+ footer{display:none !important;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
  """
687
 
 
 
 
688
  with gr.Blocks(
689
+ theme=gr.themes.Base(primary_hue="purple",secondary_hue="violet",neutral_hue="slate",
 
690
  font=[gr.themes.GoogleFont("Inter"),"sans-serif"]),
691
  css=CSS, title="PCOS Integrated Detection System"
692
  ) as demo:
693
 
 
694
  gr.HTML("""
695
  <div class="app-header">
696
  <h1>🩺 PCOS Integrated Detection System</h1>
697
+ <p>Clinical Stacked Ensemble &nbsp;Β·&nbsp; EfficientNetB0 Ultrasound &nbsp;Β·&nbsp;
698
+ Infertility Risk &nbsp;Β·&nbsp; Grad-CAM XAI &nbsp;Β·&nbsp; Batch Analysis</p>
 
 
 
 
699
  </div>
700
  <div class="disclaimer">
701
  ⚠️ <strong>Medical Disclaimer:</strong> For <strong>research &amp; educational purposes only</strong>.
702
  Not a certified medical device. Consult a qualified clinician for any health decisions.
703
+ </div>""")
 
704
 
705
  with gr.Tabs(elem_classes="tab-nav"):
706
 
707
+ # ── TAB 1: CLINICAL ──────────────────────────────────────
 
 
708
  with gr.TabItem("πŸ”¬ Clinical Analysis"):
 
709
  with gr.Row():
710
+ btn_pcos =gr.Button("πŸ“‹ Load PCOS Example", variant="secondary",size="sm")
711
+ btn_norm =gr.Button("πŸ“‹ Load Normal Example", variant="secondary",size="sm")
712
+ btn_clear =gr.Button("πŸ—‘οΈ Clear All", variant="secondary",size="sm")
713
 
714
  with gr.Row(equal_height=False):
715
  with gr.Column(scale=1):
716
+ with gr.Accordion("πŸ“‹ General & Vitals",open=True):
717
+ age=gr.Number(label="Age (yrs)",value=25)
718
+ weight=gr.Number(label="Weight (Kg)",value=60)
719
+ height=gr.Number(label="Height (cm)",value=160)
720
+ bmi=gr.Number(label="BMI (auto-computed)",value=0)
721
+ pulse_rate=gr.Number(label="Pulse rate (bpm)",value=72)
722
+ rr=gr.Number(label="RR (breaths/min)",value=18)
723
+ hb=gr.Number(label="Hb (g/dl)",value=12)
724
+ tsh=gr.Number(label="TSH (mIU/L)",value=2.5)
725
+ vit_d3=gr.Number(label="Vit D3 (ng/mL)",value=25)
 
726
  with gr.Column(scale=1):
727
+ with gr.Accordion("πŸ”΄ Metabolic",open=True):
728
+ rbs=gr.Number(label="RBS (mg/dl)",value=90)
729
+ waist=gr.Number(label="Waist (inch)",value=30)
730
+ hip=gr.Number(label="Hip (inch)",value=37)
731
+ waist_hip=gr.Number(label="Waist:Hip Ratio",value=0.81)
732
+ weight_gain=gr.Radio([0,1],label="Weight Gain (Y=1)",value=0)
733
+ fast_food=gr.Radio([0,1],label="Fast Food (Y=1)",value=0)
734
+ reg_exercise=gr.Radio([0,1],label="Exercise (Y=1)",value=1)
 
735
  with gr.Column(scale=1):
736
+ with gr.Accordion("🟣 Reproductive & Hormonal β˜…",open=True):
737
+ cycle=gr.Radio([2,4],label="Cycle Regular=2 / Irregular=4",value=2)
738
+ cycle_length=gr.Number(label="Cycle length (days)",value=28)
739
+ fsh=gr.Number(label="FSH (mIU/mL) β˜…",value=6.5)
740
+ lh=gr.Number(label="LH (mIU/mL) β˜…",value=5.0)
741
+ fsh_lh_ratio=gr.Number(label="FSH/LH (auto if 0) β˜…",value=0)
742
+ amh=gr.Number(label="AMH (ng/mL) β˜…",value=2.5)
743
+ prg=gr.Number(label="PRG (ng/mL) β˜…",value=1.0)
744
+ endometrium=gr.Number(label="Endometrium (mm) β˜…",value=8.0)
745
+ follicle_l=gr.Number(label="Follicle No. (L) β˜…",value=6)
746
+ follicle_r=gr.Number(label="Follicle No. (R) β˜…",value=6)
747
+ avg_f_size_l=gr.Number(label="Avg F size L (mm)",value=15)
748
+ avg_f_size_r=gr.Number(label="Avg F size R (mm)",value=15)
749
+ gr.HTML("<p style='color:#94a3b8;font-size:0.8rem'>β˜… Used for PCOS + Infertility Risk</p>")
 
750
  with gr.Column(scale=1):
751
+ with gr.Accordion("🟠 Hyperandrogenic",open=True):
752
+ hair_growth=gr.Radio([0,1],label="Hair Growth (Y=1)",value=0)
753
+ skin_darkening=gr.Radio([0,1],label="Skin Darkening (Y=1)",value=0)
754
+ hair_loss=gr.Radio([0,1],label="Hair Loss (Y=1)",value=0)
755
+ pimples=gr.Radio([0,1],label="Pimples (Y=1)",value=0)
756
+ prl=gr.Number(label="PRL (ng/mL)",value=15)
757
  gr.HTML("<br>")
758
+ predict_btn=gr.Button("πŸ”¬ Run Full Analysis",variant="primary",size="lg")
759
 
760
+ ALL_INPUTS=[age,weight,height,bmi,pulse_rate,rr,hb,cycle,cycle_length,
761
+ fsh,lh,fsh_lh_ratio,hip,waist,waist_hip,tsh,amh,prl,vit_d3,prg,rbs,
762
+ weight_gain,hair_growth,skin_darkening,hair_loss,pimples,fast_food,
763
+ reg_exercise,follicle_l,follicle_r,avg_f_size_l,avg_f_size_r,endometrium]
 
 
 
 
764
 
765
  with gr.Row():
766
  with gr.Column(scale=1):
767
+ gr.HTML('<p class="sec">πŸ“‹ Assessment Summary</p>')
768
+ summary_out=gr.Markdown(value="*Fill the form and click Run Full Analysis.*")
769
+ model_info=gr.Textbox(label="Pipeline info",interactive=False,lines=2)
770
  with gr.Column(scale=2):
771
+ gr.HTML('<p class="sec">πŸ“Š Assessment Charts</p>')
772
+ chart_out=gr.Plot(label="",show_label=False)
773
 
774
  def load_ex(ex): return [ex[k] for k in INPUT_KEYS]
775
  def clear_all():
 
782
  return [d[k] for k in INPUT_KEYS]
783
 
784
  btn_pcos.click(fn=lambda: load_ex(EXAMPLE_PCOS), outputs=ALL_INPUTS)
785
+ btn_norm.click(fn=lambda: load_ex(EXAMPLE_NORMAL), outputs=ALL_INPUTS)
786
  btn_clear.click(fn=clear_all, outputs=ALL_INPUTS)
787
+ predict_btn.click(fn=predict_clinical,inputs=ALL_INPUTS,
788
  outputs=[summary_out,chart_out,model_info])
789
 
790
+ # ── TAB 2: SINGLE IMAGE ───────────────────────────────────
 
 
791
  with gr.TabItem("πŸ–ΌοΈ Ultrasound β€” Single"):
 
792
  with gr.Row(equal_height=False):
793
  with gr.Column(scale=4):
794
+ gr.HTML('<p class="sec">πŸ“ Upload Image</p>')
795
+ img_input=gr.Image(label="",type="pil",height=280)
796
+ img_btn=gr.Button("πŸ” Analyze Image",variant="primary",size="lg")
797
+ gr.HTML("""<div class="info-box" style="margin-top:12px">
 
798
  <strong>Model:</strong> EfficientNetB0 (fine-tuned)<br>
799
  <strong>Input:</strong> 224Γ—224 RGB Β· ImageNet normalisation<br>
800
  <strong>Classes:</strong> <code>not_pcos</code> (0) Β· <code>pcos</code> (1)<br>
801
  <strong>Checkpoint:</strong> <code>models/best_model.pth</code><br>
802
  <strong>XAI:</strong> Grad-CAM on <code>features[-1]</code>
803
  </div>""")
 
804
  with gr.Column(scale=6):
805
+ gr.HTML('<p class="sec">πŸ“‹ Diagnosis Result</p>')
806
+ img_result=gr.Markdown(value="*Upload an image and click Analyze.*")
807
+ gr.HTML('<p class="sec" style="margin-top:14px">πŸ“Š Probability Gauge</p>')
808
+ img_gauge=gr.Plot(label="",show_label=False)
809
+ gr.HTML('<p class="sec" style="margin-top:6px">πŸ”₯ Grad-CAM Explainability</p>')
810
+ img_gradcam=gr.Plot(label="",show_label=False)
811
+ img_btn.click(fn=predict_image_single,inputs=[img_input],
812
+ outputs=[img_result,img_gauge,img_gradcam])
813
+
814
+ # ── TAB 3: BATCH IMAGE ────────────────────────────────────
 
 
 
 
815
  with gr.TabItem("πŸ“‚ Ultrasound β€” Batch"):
 
816
  with gr.Row(equal_height=False):
817
  with gr.Column(scale=4):
818
+ gr.HTML('<p class="sec">πŸ“ Upload Multiple Images</p>')
819
+ batch_input=gr.File(label="",file_count="multiple",file_types=["image"])
820
+ batch_btn=gr.Button("⚑ Run Batch Analysis",variant="primary",size="lg")
821
+ gr.HTML("""<div class="info-box" style="margin-top:12px">
 
 
822
  Upload any number of ultrasound images.<br>
823
  Each is analysed independently.<br>
824
  Results shown as a summary table + distribution chart.<br><br>
825
  <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF
826
  </div>""")
 
827
  with gr.Column(scale=6):
828
+ gr.HTML('<p class="sec">πŸ“Š Batch Summary</p>')
829
+ batch_result=gr.Markdown(value="*Upload images and click Run Batch Analysis.*")
830
+ gr.HTML('<p class="sec" style="margin-top:6px">πŸ“ˆ Distribution Chart</p>')
831
+ batch_chart=gr.Plot(label="",show_label=False)
832
+ batch_btn.click(fn=predict_image_batch,inputs=[batch_input],
833
+ outputs=[batch_result,batch_chart])
834
+
835
+ # ── TAB 4: ABOUT ──────────────────────────────────────────
 
 
 
 
836
  with gr.TabItem("ℹ️ About"):
837
  gr.Markdown("""
838
  ## About This System
 
845
  | Imputation | MICE (IterativeImputer, max_iter=10) |
846
  | Scaling | RobustScaler |
847
  | Severity scoring | OOF GBM per domain β†’ normalised 0–1 |
848
+ | Threshold | Youden-J optimal on test ROC |
849
+ | Dataset | PCOS_data_without_infertility.xlsx (Space root) |
850
 
851
  **Domain weights:** Reproductive 40% Β· Metabolic 35% Β· Hyperandrogenic 20% Β· General 5%
852
 
 
858
  | Classes | `not_pcos` (0) Β· `pcos` (1) β€” alphabetical |
859
  | Checkpoint key | `model_state` |
860
  | XAI | Grad-CAM on `features[-1]` |
861
+ | File | `models/best_model.pth` |
862
 
863
  ### 🧬 Infertility Risk
864
+ Weighted biomarker formula (no training): AMH 0.22 Β· FSH 0.18 Β· FSH/LH 0.15 Β· Follicles 0.10Γ—2 Β· Endometrium 0.08 Β· LH 0.08 Β· PRG 0.05 Β· Cycle 0.04
 
865
 
866
  ### ⚠️ Disclaimer
867
  For **research and educational purposes only**. Not a certified medical device.