DheivaCodes commited on
Commit
d4a40e2
Β·
verified Β·
1 Parent(s): 1a6ff61

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1022 -0
app.py ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
10
+ warnings.filterwarnings("ignore")
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import matplotlib
15
+ matplotlib.use("Agg")
16
+ import matplotlib.pyplot as plt
17
+ import matplotlib.patches as mpatches
18
+ 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
35
+ 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
158
+ def get_clean_feats(fl,av): return [clean_name(f) for f in fl if clean_name(f) in av]
159
+
160
+ def get_base_models():
161
+ return {
162
+ "Logistic" : LogisticRegression(max_iter=2000,class_weight="balanced"),
163
+ "RandomForest": RandomForestClassifier(n_estimators=300,max_depth=10,
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
+ net=tv_models.efficientnet_b0(weights=None)
364
+ net.classifier[1]=nn.Linear(net.classifier[1].in_features,2)
365
+ ckpt=torch.load(pth,map_location=DEVICE,weights_only=False)
366
+ if isinstance(ckpt,dict):
367
+ state=(ckpt.get("model_state") or ckpt.get("model_state_dict")
368
+ or ckpt.get("state_dict") or ckpt)
369
+ else:
370
+ state=ckpt
371
+ net.load_state_dict(state,strict=True)
372
+ net.to(DEVICE).eval()
373
+ print(f"βœ… Image model loaded: {pth}")
374
+ return net
375
+
376
+ IMAGE_MODEL=load_image_model()
377
+
378
+ def run_image_inference(img_rgb):
379
+ tensor=VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
380
+ with torch.no_grad():
381
+ probs=torch.softmax(IMAGE_MODEL(tensor),dim=1)[0]
382
+ return float(probs[PCOS_IDX]),float(probs[1-PCOS_IDX]),int(probs.argmax())
383
+
384
+ def compute_gradcam(img_rgb,target_class):
385
+ grads,acts=[],[]
386
+ def fwd_hook(m,inp,out):
387
+ acts.append(out.detach())
388
+ out.register_hook(lambda g: grads.append(g.detach()))
389
+ handle=IMAGE_MODEL.features[-1].register_forward_hook(fwd_hook)
390
+ tensor=VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
391
+ IMAGE_MODEL.zero_grad()
392
+ IMAGE_MODEL(tensor)[0,target_class].backward()
393
+ handle.remove()
394
+ if not grads or not acts: return None
395
+ w=grads[0].squeeze(0).mean(dim=(1,2)).cpu().numpy()
396
+ act=acts[0].squeeze(0).cpu().numpy()
397
+ cam=np.maximum(sum(w[i]*act[i] for i in range(len(w))),0)
398
+ if cam.max()>1e-8: cam/=cam.max()
399
+ cam_up=np.array(Image.fromarray((cam*255).astype(np.uint8)).resize(
400
+ (IMG_SIZE,IMG_SIZE),Image.BILINEAR))/255.0
401
+ orig_r=np.array(img_rgb.resize((IMG_SIZE,IMG_SIZE)))
402
+ heat=cm_mod.jet(cam_up)[:,:,:3]
403
+ overlay=np.clip(0.55*orig_r/255.0+0.45*heat,0,1)
404
+
405
+ fig,axes=plt.subplots(1,3,figsize=(15,4.5),facecolor=BG,
406
+ gridspec_kw={"wspace":0.04})
407
+ panels=[(orig_r,None,"Original Image"),(cam_up,"jet","Grad-CAM Heatmap"),(overlay,None,"Activation Overlay")]
408
+ for ax,(img,cmap,title) in zip(axes,panels):
409
+ ax.set_facecolor(BG); ax.imshow(img,cmap=cmap); ax.axis("off")
410
+ ax.set_title(title,color=TC,fontsize=11,fontweight="bold",pad=6)
411
+ for sp in ax.spines.values(): sp.set_linewidth(0)
412
+ fig.text(0.5,0.0,f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
413
+ ha="center",color="#94a3b8",fontsize=9)
414
+ plt.tight_layout(pad=0.3)
415
+ return fig
416
+
417
+ # ══════════════════════════════════════════════════════════════════════════════
418
+ # SECTION 4 β€” CLINICAL CHARTS (your exact draw_gauge + make_result_figure)
419
+ # ══════════════════════════════════════════════════════════════════════════════
420
+ def draw_gauge(ax,value,title,val_label,sub_label,val_col):
421
+ ax.set_facecolor(BG)
422
+ theta=np.linspace(np.pi,0,300)
423
+ for i in range(len(theta)-1):
424
+ t=i/(len(theta)-1)
425
+ ax.fill_between([np.cos(theta[i]),np.cos(theta[i+1])],
426
+ [np.sin(theta[i]),np.sin(theta[i+1])],
427
+ alpha=0.9,color=plt.cm.RdYlGn_r(t))
428
+ angle=np.pi*(1-value)
429
+ ax.annotate("",xy=(0.65*np.cos(angle),0.65*np.sin(angle)),xytext=(0,0),
430
+ arrowprops=dict(arrowstyle="-|>",color="white",lw=3))
431
+ ax.plot(0,0,"o",color="white",markersize=6,zorder=5)
432
+ ax.text(0,-0.15,val_label,ha="center",fontsize=22,fontweight="bold",color=val_col,va="center")
433
+ ax.text(0,-0.38,title,ha="center",fontsize=9,color="#AAAACC")
434
+ ax.text(0,-0.58,sub_label,ha="center",fontsize=10,fontweight="bold",color=val_col)
435
+ for pct,lbl in [(0,"0%"),(0.5,"50%"),(1.0,"100%")]:
436
+ a=np.pi*(1-pct)
437
+ ax.text(0.88*np.cos(a),0.88*np.sin(a),lbl,ha="center",va="center",fontsize=6,color="#888")
438
+ ax.set_xlim(-1.05,1.05); ax.set_ylim(-0.72,1.05); ax.axis("off")
439
+ ax.set_title(title,color=TC,fontsize=12,fontweight="bold",pad=4)
440
+
441
+ def make_clinical_figure(pcos_prob,pred,sev,base_probs,inf_risk,threshold):
442
+ fig=plt.figure(figsize=(18,13),facecolor=BG)
443
+ gs=GridSpec(3,4,figure=fig,hspace=0.58,wspace=0.45,
444
+ top=0.93,bottom=0.05,left=0.05,right=0.97)
445
+ ax_pg =fig.add_subplot(gs[0,0])
446
+ ax_ig =fig.add_subplot(gs[0,1])
447
+ ax_rad=fig.add_subplot(gs[0,2:],polar=True)
448
+ ax_bar=fig.add_subplot(gs[1,:2])
449
+ ax_bio=fig.add_subplot(gs[1,2:])
450
+ ax_sev=fig.add_subplot(gs[2,:])
451
+
452
+ risk_col="#E74C3C" if pcos_prob>0.65 else ("#F39C12" if pcos_prob>0.35 else "#2ECC71")
453
+ inf_s=inf_risk["score"]; inf_t=inf_risk["tier"]
454
+ inf_col="#E74C3C" if inf_t=="High" else ("#F39C12" if inf_t=="Moderate" else "#2ECC71")
455
+
456
+ draw_gauge(ax_pg,pcos_prob,"PCOS Risk",f"{pcos_prob*100:.1f}%",
457
+ "⚠️ PCOS Detected" if pred else "βœ… No PCOS",risk_col)
458
+ draw_gauge(ax_ig,inf_s,"Infertility Risk",f"{inf_s*100:.1f}%",
459
+ f"{'πŸ”΄' if inf_t=='High' else ('🟑' if inf_t=='Moderate' else '🟒')} {inf_t}",inf_col)
460
+
461
+ # Radar
462
+ domains=["Metabolic","Reproductive","Hyperandrogenic","General"]
463
+ vals=[sev[d] for d in domains]
464
+ angles=np.linspace(0,2*np.pi,len(domains),endpoint=False).tolist()
465
+ v_c=vals+[vals[0]]; a_c=angles+[angles[0]]
466
+ ax_rad.set_facecolor(BG)
467
+ for level,alpha,color in [(1.0,0.05,"#E74C3C"),(0.65,0.08,"#F39C12"),(0.35,0.08,"#2ECC71")]:
468
+ ax_rad.fill(a_c,[level]*len(a_c),alpha=alpha,color=color)
469
+ ax_rad.plot(a_c,v_c,"o-",lw=2.5,color=ACC,markersize=7)
470
+ ax_rad.fill(a_c,v_c,alpha=0.30,color=ACC)
471
+ ax_rad.set_xticks(angles)
472
+ ax_rad.set_xticklabels([f"{d}\n{vals[i]*100:.0f}%" for i,d in enumerate(domains)],
473
+ color=TC,fontsize=10,fontweight="bold")
474
+ ax_rad.set_ylim(0,1); ax_rad.set_yticks([0.35,0.65,1.0])
475
+ ax_rad.set_yticklabels(["Low→Mod","Mod→High","Max"],color="#666",fontsize=7)
476
+ ax_rad.grid(color="#333355",alpha=0.6,linewidth=0.8)
477
+ ax_rad.spines["polar"].set_color("#333355")
478
+ ax_rad.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
479
+
480
+ # Base model bars
481
+ ax_bar.set_facecolor(BG)
482
+ names=list(base_probs.keys()); probs_=[base_probs[n] for n in names]
483
+ colors=["#3B82F6","#10B981","#F59E0B","#EF4444"]
484
+ bars=ax_bar.barh(names,probs_,color=colors[:len(names)],height=0.52,alpha=0.88)
485
+ for bar,p in zip(bars,probs_):
486
+ ax_bar.text(min(p+0.018,0.97),bar.get_y()+bar.get_height()/2,
487
+ f"{p:.3f}",va="center",color=TC,fontsize=11,fontweight="bold")
488
+ ax_bar.axvline(0.5,color="white",linestyle="--",alpha=0.3,lw=1.5)
489
+ ax_bar.axvline(threshold,color=ACC,linestyle=":",alpha=0.6,lw=1.5,
490
+ label=f"Youden threshold ({threshold:.2f})")
491
+ ax_bar.set_xlim(0,1.12); ax_bar.tick_params(colors=TC,labelsize=11)
492
+ for sp in ax_bar.spines.values(): sp.set_color("#2A2A4A")
493
+ ax_bar.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
494
+ ax_bar.set_xlabel("PCOS Probability",color=TC,fontsize=10)
495
+ ax_bar.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
496
+
497
+ # Biomarker bars
498
+ ax_bio.set_facecolor(BG); ax_bio.tick_params(colors=TC,labelsize=8)
499
+ for sp in ax_bio.spines.values(): sp.set_color("#2A2A4A")
500
+ ax_bio.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
501
+ ax_bio.set_xlabel("Weighted contribution to risk",color=TC,fontsize=9)
502
+ breakdown=inf_risk.get("breakdown",{})
503
+ if breakdown:
504
+ bio_names=list(breakdown.keys())
505
+ bio_vals=[breakdown[f]["contribution"] for f in bio_names]
506
+ bio_cols=["#EF4444" if breakdown[f]["oriented"]>0.5 else "#10B981" for f in bio_names]
507
+ short=[f.split("(")[0].strip()[:14] for f in bio_names]
508
+ sorted_p=sorted(zip(short,bio_vals,bio_cols),key=lambda x:x[1],reverse=True)
509
+ short,bio_vals,bio_cols=zip(*sorted_p)
510
+ bars2=ax_bio.barh(short,bio_vals,color=bio_cols,height=0.52,alpha=0.88)
511
+ for bar,val in zip(bars2,bio_vals):
512
+ ax_bio.text(val+0.001,bar.get_y()+bar.get_height()/2,
513
+ f"{val:.3f}",va="center",color=TC,fontsize=9)
514
+ p1=mpatches.Patch(color="#EF4444",label="↑ Increases risk")
515
+ p2=mpatches.Patch(color="#10B981",label="↓ Protective")
516
+ ax_bio.legend(handles=[p1,p2],facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8)
517
+ else:
518
+ ax_bio.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values to see\nbiomarker breakdown",
519
+ ha="center",va="center",color="#666",fontsize=10,transform=ax_bio.transAxes)
520
+
521
+ # Domain severity bars
522
+ ax_sev.set_facecolor(BG)
523
+ sev_vals=[sev[d] for d in domains]
524
+ sev_colors=[DOMAIN_COLORS[d] for d in domains]
525
+ x_pos=np.arange(len(domains))
526
+ bars3=ax_sev.bar(x_pos,sev_vals,color=sev_colors,alpha=0.88,width=0.5)
527
+ for bar,val,d in zip(bars3,sev_vals,domains):
528
+ lvl="High" if val>0.65 else ("Moderate" if val>0.35 else "Low")
529
+ lc="#E74C3C" if lvl=="High" else ("#F39C12" if lvl=="Moderate" else "#2ECC71")
530
+ ax_sev.text(bar.get_x()+bar.get_width()/2,val+0.02,f"{val*100:.1f}%",
531
+ ha="center",va="bottom",color=TC,fontsize=14,fontweight="bold")
532
+ ax_sev.text(bar.get_x()+bar.get_width()/2,val+0.09,f"({lvl})",
533
+ ha="center",va="bottom",color=lc,fontsize=11)
534
+ ax_sev.axhline(0.65,color="#E74C3C",linestyle="--",alpha=0.45,lw=1.5,label="High (65%)")
535
+ ax_sev.axhline(0.35,color="#F39C12",linestyle="--",alpha=0.45,lw=1.5,label="Moderate (35%)")
536
+ ax_sev.set_ylim(0,1.3); ax_sev.set_xticks(x_pos)
537
+ ax_sev.set_xticklabels(domains,color=TC,fontsize=13,fontweight="bold")
538
+ ax_sev.tick_params(axis="y",colors=TC,labelsize=10)
539
+ for sp in ax_sev.spines.values(): sp.set_color("#2A2A4A")
540
+ ax_sev.set_title("PCOS Domain Severity Breakdown",color=TC,fontsize=13,fontweight="bold")
541
+ ax_sev.set_ylabel("Severity Score",color=TC,fontsize=11)
542
+ ax_sev.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=9,loc="upper right")
543
+
544
+ fig.patch.set_facecolor(BG)
545
+ fig.suptitle("🩺 PCOS Clinical Assessment Report",color=TC,fontsize=16,fontweight="bold",y=0.97)
546
+ return fig
547
+
548
+ # ══════════════════════════════════════════════════════════════════════════════
549
+ # SECTION 5 β€” IMAGE CHARTS
550
+ # ══════════════════════════════════════════════════════════════════════════════
551
+ def make_image_gauge(pcos_prob):
552
+ fig,ax=plt.subplots(figsize=(5,2.6),facecolor=BG)
553
+ ax.set_facecolor(BG); ax.set_xlim(0,1); ax.set_ylim(0,1); ax.axis("off")
554
+ ax.barh([0.5],[1.0],height=0.30,color="#1e293b",left=0,align="center",zorder=1)
555
+ color="#22c55e" if pcos_prob<0.33 else "#f59e0b" if pcos_prob<0.66 else "#ef4444"
556
+ ax.barh([0.5],[pcos_prob],height=0.30,color=color,left=0,align="center",zorder=2)
557
+ ax.axvline(0.5,color="white",lw=1.5,ls="--",alpha=0.7,zorder=3)
558
+ ax.text(pcos_prob,0.5,f" {pcos_prob*100:.1f}%",va="center",color="white",
559
+ fontsize=16,fontweight="bold",zorder=4,
560
+ ha="left" if pcos_prob<0.85 else "right")
561
+ for x,lbl,c in [(0.16,"Low","#22c55e"),(0.50,"Moderate","#f59e0b"),(0.83,"High","#ef4444")]:
562
+ ax.text(x,0.12,lbl,color=c,fontsize=8,ha="center",alpha=0.8)
563
+ ax.text(0.5,0.92,"PCOS Probability",color="#94a3b8",fontsize=9,ha="center",va="top")
564
+ plt.tight_layout(pad=0.2)
565
+ return fig
566
+
567
+ def make_batch_chart(pcos_c,notp_c,total):
568
+ fig=plt.figure(figsize=(10,4),facecolor=BG)
569
+ ax1=fig.add_subplot(1,2,1); ax1.set_facecolor(BG)
570
+ if total>0:
571
+ wedges,texts,autotexts=ax1.pie(
572
+ [pcos_c,notp_c],labels=[f"PCOS\n{pcos_c}",f"Not PCOS\n{notp_c}"],
573
+ colors=["#ef4444","#22c55e"],autopct="%1.1f%%",startangle=90,
574
+ textprops={"color":"white","fontsize":10},
575
+ wedgeprops={"linewidth":2,"edgecolor":BG},pctdistance=0.75)
576
+ for at in autotexts: at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold")
577
+ ax1.set_title("Class Distribution",color=TC,fontsize=12,fontweight="bold",pad=12)
578
+ ax2=fig.add_subplot(1,2,2); ax2.set_facecolor(BG)
579
+ bars=ax2.bar(["Not PCOS","PCOS"],[notp_c,pcos_c],color=["#22c55e","#ef4444"],
580
+ width=0.45,edgecolor=BG,linewidth=2)
581
+ ax2.set_ylim(0,max(pcos_c,notp_c)*1.35+0.5)
582
+ ax2.set_title("Count per Class",color=TC,fontsize=12,fontweight="bold",pad=12)
583
+ ax2.tick_params(colors=TC,labelsize=11)
584
+ for sp in ax2.spines.values(): sp.set_visible(False)
585
+ ax2.yaxis.set_visible(False)
586
+ for bar,cnt in zip(bars,[notp_c,pcos_c]):
587
+ ax2.text(bar.get_x()+bar.get_width()/2,bar.get_height()+0.15,str(cnt),
588
+ ha="center",color=TC,fontsize=14,fontweight="bold")
589
+ fig.text(0.5,0.01,f"Total: {total} image{'s' if total>1 else ''} Β· EfficientNetB0",
590
+ ha="center",color="#64748b",fontsize=9)
591
+ plt.tight_layout(pad=1.5)
592
+ return fig
593
+
594
+ # ══════════════════════════════════════════════════════════════════════════════
595
+ # SECTION 6 β€” GRADIO HANDLER FUNCTIONS
596
+ # ══════════════════════════════════════════════════════════════════════════════
597
+ def predict_clinical(*args):
598
+ vals=dict(zip(INPUT_KEYS,args))
599
+ if not PIPELINE_READY:
600
+ return ("❌ Clinical pipeline not ready.\n\nUpload `PCOS_data_without_infertility.xlsx` "
601
+ "to the Space root folder.",None,"")
602
+ bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
603
+ if (not bmi or bmi==0) and vals["weight"] and vals["height"] and vals["height"]>0:
604
+ bmi=vals["weight"]/((vals["height"]/100)**2)
605
+ if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"]==0) and fsh and lh:
606
+ vals["fsh_lh_ratio"]=fsh/(lh+1e-6)
607
+ vals["bmi"]=bmi
608
+
609
+ patient_raw={
610
+ "Age (yrs)":vals["age"],"Weight (Kg)":vals["weight"],"BMI":vals["bmi"],
611
+ "Pulse rate(bpm)":vals["pulse_rate"],"RR (breaths/min)":vals["rr"],
612
+ "Hb(g/dl)":vals["hb"],"Cycle(R/I)":vals["cycle"],
613
+ "Cycle length(days)":vals["cycle_length"],
614
+ "FSH(mIU/mL)":vals["fsh"],"LH(mIU/mL)":vals["lh"],"FSH/LH":vals["fsh_lh_ratio"],
615
+ "Hip(inch)":vals["hip"],"Waist(inch)":vals["waist"],"Waist:Hip Ratio":vals["waist_hip"],
616
+ "TSH (mIU/L)":vals["tsh"],"AMH(ng/mL)":vals["amh"],"PRL(ng/mL)":vals["prl"],
617
+ "Vit D3 (ng/mL)":vals["vit_d3"],"PRG(ng/mL)":vals["prg"],"RBS(mg/dl)":vals["rbs"],
618
+ "Weight gain(Y/N)":vals["weight_gain"],"hair growth(Y/N)":vals["hair_growth"],
619
+ "Skin darkening (Y/N)":vals["skin_darkening"],"Hair loss(Y/N)":vals["hair_loss"],
620
+ "Pimples(Y/N)":vals["pimples"],"Fast food (Y/N)":vals["fast_food"],
621
+ "Reg.Exercise(Y/N)":vals["reg_exercise"],
622
+ "Follicle No. (L)":vals["follicle_l"],"Follicle No. (R)":vals["follicle_r"],
623
+ "Avg. F size (L) (mm)":vals["avg_f_size_l"],"Avg. F size (R) (mm)":vals["avg_f_size_r"],
624
+ "Endometrium (mm)":vals["endometrium"],
625
+ "BP _Systolic (mmHg)":120,"BP _Diastolic (mmHg)":80,
626
+ }
627
+ try:
628
+ pcos_prob,pred,sev,base_probs=predict_single_clinical(PIPELINE,patient_raw)
629
+ except Exception as e:
630
+ return f"❌ Prediction error: {e}",None,""
631
+
632
+ inf_risk=compute_infertility_risk(patient_raw)
633
+ inf_s=inf_risk["score"]; inf_t=inf_risk["tier"]
634
+ inf_icon="πŸ”΄" if inf_t=="High" else ("🟑" if inf_t=="Moderate" else "🟒")
635
+ pcos_tier=("HIGH RISK πŸ”΄" if pcos_prob>0.65 else
636
+ ("MODERATE RISK 🟑" if pcos_prob>0.35 else "LOW RISK 🟒"))
637
+ recs=[]
638
+ if pred: recs.append("πŸ₯ **Consult an endocrinologist / gynaecologist immediately.**")
639
+ if inf_t=="High": recs.append("🧬 **High infertility risk β€” fertility specialist evaluation recommended.**")
640
+ elif inf_t=="Moderate": recs.append("πŸ”¬ Hormonal panel follow-up recommended.")
641
+ if sev["Metabolic"]>0.5: recs.append("βš–οΈ Weight management and regular exercise advised.")
642
+ if sev["Hyperandrogenic"]>0.5: recs.append("πŸ’Š Discuss anti-androgen therapy with your doctor.")
643
+ if not recs: recs.append("βœ… Continue routine annual screening and a healthy lifestyle.")
644
+
645
+ sev_rows="\n".join(
646
+ f"| {d} | {sev[d]*100:.1f}% | {'πŸ”΄ High' if sev[d]>0.65 else ('🟑 Moderate' if sev[d]>0.35 else '🟒 Low')} |"
647
+ for d in ["Metabolic","Reproductive","Hyperandrogenic","General"])
648
+ bio_rows="\n".join(
649
+ f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
650
+ for f,v in inf_risk.get("breakdown",{}).items()
651
+ ) or "| β€” | Enter hormonal values | β€” | β€” |"
652
+ rec_text="\n".join(f"- {r}" for r in recs)
653
+
654
+ summary=f"""## Clinical Assessment β€” {pcos_tier}
655
+
656
+ | Metric | Value |
657
+ |---|---|
658
+ | **PCOS Probability** | **{pcos_prob*100:.1f}%** |
659
+ | **Diagnosis** | {"⚠️ PCOS Detected" if pred else "βœ… No PCOS Detected"} |
660
+ | **Overall Severity** | {sev['Overall']*100:.1f}% |
661
+ | **Infertility Risk** | {inf_icon} {inf_t} ({inf_s*100:.1f}%) |
662
+
663
+ ---
664
+ ### PCOS Domain Severity
665
+ | Domain | Score | Level |
666
+ |--------|-------|-------|
667
+ {sev_rows}
668
+
669
+ ### Infertility Biomarker Breakdown
670
+ | Biomarker | Value | Direction | Contribution |
671
+ |-----------|-------|-----------|-------------|
672
+ {bio_rows}
673
+
674
+ ### Clinical Recommendations
675
+ {rec_text}
676
+
677
+ ---
678
+ *βš•οΈ For research/educational purposes only. Not medical advice.*"""
679
+
680
+ fig=make_clinical_figure(pcos_prob,pred,sev,base_probs,inf_risk,PIPELINE["threshold"])
681
+ info=(f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['threshold']:.4f} | "
682
+ f"Models: LR + RF + GBM + CatBoost β†’ CalibratedLogisticRegressionCV")
683
+ return summary,fig,info
684
+
685
+
686
+ def predict_image_single(image):
687
+ if IMAGE_MODEL is None:
688
+ return ("❌ Image model not loaded.\n\nUpload `best_model.pth` to the `models/` folder."),None,None
689
+ if image is None:
690
+ return "⚠️ Please upload an ultrasound image.",None,None
691
+ try:
692
+ img_rgb=(image if isinstance(image,Image.Image) else Image.fromarray(image)).convert("RGB")
693
+ pcos_p,notp,pred=run_image_inference(img_rgb)
694
+ icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
695
+ label=CLASS_NAMES[pred]
696
+ conf=pcos_p if pred==PCOS_IDX else notp
697
+ risk="🟒 Low" if pcos_p<0.33 else "🟑 Moderate" if pcos_p<0.66 else "πŸ”΄ High"
698
+ result=f"""### {icon} {label}
699
+
700
+ | Metric | Value |
701
+ |---|---|
702
+ | PCOS Probability | **{pcos_p*100:.1f}%** |
703
+ | Not PCOS Probability | **{notp*100:.1f}%** |
704
+ | Confidence | **{conf*100:.1f}%** |
705
+ | Risk Level | **{risk}** |
706
+
707
+ *EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
708
+ > ⚠️ Research use only β€” not a clinical tool."""
709
+ return result, make_image_gauge(pcos_p), compute_gradcam(img_rgb,pred)
710
+ except Exception as e:
711
+ import traceback
712
+ return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```",None,None
713
+
714
+
715
+ def predict_image_batch(files):
716
+ if IMAGE_MODEL is None:
717
+ return "❌ Image model not loaded.",None
718
+ if not files:
719
+ return "⚠️ Upload at least one image.",None
720
+ rows=[]; pcos_c=0; notp_c=0
721
+ for f in files:
722
+ try:
723
+ img=Image.open(f.name).convert("RGB")
724
+ pcos_p,notp,pred=run_image_inference(img)
725
+ label=CLASS_NAMES[pred]
726
+ risk="Low" if pcos_p<0.33 else "Moderate" if pcos_p<0.66 else "High"
727
+ icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
728
+ fname=os.path.basename(f.name)
729
+ rows.append({"File":fname,"Prediction":f"{icon} {label}",
730
+ "PCOS%":f"{pcos_p*100:.1f}","Not PCOS%":f"{notp*100:.1f}","Risk":risk})
731
+ if pred==PCOS_IDX: pcos_c+=1
732
+ else: notp_c+=1
733
+ except Exception as e:
734
+ rows.append({"File":os.path.basename(f.name),"Prediction":f"❌ {e}",
735
+ "PCOS%":"β€”","Not PCOS%":"β€”","Risk":"β€”"})
736
+ total=len(rows)
737
+ table="\n".join(f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |"
738
+ for r in rows)
739
+ summary=f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total>1 else ''}
740
+
741
+ | | Count | % |
742
+ |---|---|---|
743
+ | πŸ”΄ PCOS | **{pcos_c}** | **{pcos_c/total*100:.1f}%** |
744
+ | 🟒 Not PCOS | **{notp_c}** | **{notp_c/total*100:.1f}%** |
745
+ | Total | **{total}** | 100% |
746
+
747
+ ---
748
+ ### Per-Image Results
749
+
750
+ | File | Prediction | PCOS% | Not PCOS% | Risk |
751
+ |---|---|---|---|---|
752
+ {table}
753
+
754
+ > ⚠️ Research use only β€” not a clinical tool."""
755
+ return summary, make_batch_chart(pcos_c,notp_c,total)
756
+
757
+ # ══════════════════════════════════════════════════════════════════════════════
758
+ # SECTION 7 β€” CSS
759
+ # ══════════════════════════════════════════════════════════════════════════════
760
+ CSS = """
761
+ body, .gradio-container { background:#0D0D1A !important; font-family:'Inter','Segoe UI',sans-serif !important; }
762
+
763
+ .app-header {
764
+ background: linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
765
+ border:1px solid #4338ca; border-radius:16px;
766
+ padding:28px 36px; margin-bottom:18px; text-align:center;
767
+ }
768
+ .app-header h1 { color:#e0e7ff !important; font-size:2rem !important; font-weight:700 !important; margin:0 0 4px 0 !important; }
769
+ .app-header p { color:#a5b4fc !important; font-size:0.95rem !important; margin:0 !important; }
770
+
771
+ .disclaimer {
772
+ background:#1c1917; border-left:4px solid #f59e0b; border-radius:8px;
773
+ padding:10px 16px; color:#fbbf24 !important; font-size:0.85rem; margin-bottom:16px;
774
+ }
775
+ .section-label {
776
+ color:#c7d2fe !important; font-size:0.75rem !important; font-weight:700 !important;
777
+ letter-spacing:1.4px !important; text-transform:uppercase !important;
778
+ margin:0 0 8px 0 !important; padding-bottom:6px !important;
779
+ border-bottom:1px solid #334155 !important;
780
+ }
781
+ .info-box {
782
+ background:#1e293b; border:1px solid #334155; border-radius:10px;
783
+ padding:14px 18px; font-size:0.85rem; color:#94a3b8; line-height:1.7;
784
+ }
785
+ .info-box strong { color:#c7d2fe; }
786
+ .tab-nav button { color:#94a3b8 !important; font-size:0.9rem !important; font-weight:600 !important; }
787
+ .tab-nav button.selected { color:#818cf8 !important; border-bottom:2px solid #818cf8 !important; background:#1e293b !important; }
788
+ button.primary {
789
+ background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
790
+ border:none !important; border-radius:10px !important;
791
+ font-weight:700 !important; color:white !important; padding:12px 0 !important;
792
+ }
793
+ button.secondary { border-radius:8px !important; }
794
+ table { width:100%; border-collapse:collapse; font-size:0.88rem; }
795
+ th { background:#1e3a5f; color:#93c5fd; padding:8px 12px; text-align:left; font-weight:600; }
796
+ td { padding:7px 12px; border-bottom:1px solid #1e293b; color:#e2e8f0; }
797
+ tr:nth-child(even) td { background:#1a2540; }
798
+ footer { display:none !important; }
799
+ """
800
+
801
+ # ══════════════════════════════════════════════════════════════════════════════
802
+ # SECTION 8 β€” GRADIO UI
803
+ # ══════════════════════════════════════════════════════════════════════════════
804
+ with gr.Blocks(
805
+ theme=gr.themes.Base(primary_hue="purple",secondary_hue="violet",
806
+ neutral_hue="slate",
807
+ font=[gr.themes.GoogleFont("Inter"),"sans-serif"]),
808
+ css=CSS, title="PCOS Integrated Detection System"
809
+ ) as demo:
810
+
811
+ # ── Banner ────────────────────────────────────────────────────────────────
812
+ gr.HTML("""
813
+ <div class="app-header">
814
+ <h1>🩺 PCOS Integrated Detection System</h1>
815
+ <p>
816
+ Clinical Stacked Ensemble (AUC β‰ˆ 0.95) &nbsp;Β·&nbsp;
817
+ EfficientNetB0 Ultrasound Analysis &nbsp;Β·&nbsp;
818
+ Infertility Risk Scoring &nbsp;Β·&nbsp;
819
+ Grad-CAM Explainability
820
+ </p>
821
+ </div>
822
+ <div class="disclaimer">
823
+ ⚠️ <strong>Medical Disclaimer:</strong> For <strong>research &amp; educational purposes only</strong>.
824
+ Not a certified medical device. Consult a qualified clinician for any health decisions.
825
+ </div>
826
+ """)
827
+
828
+ with gr.Tabs(elem_classes="tab-nav"):
829
+
830
+ # ══════════════════════════════════════════════════════════
831
+ # TAB 1 β€” CLINICAL
832
+ # ══════════════════════════════════════════════════════════
833
+ with gr.TabItem("πŸ”¬ Clinical Analysis"):
834
+
835
+ with gr.Row():
836
+ btn_pcos = gr.Button("πŸ“‹ Load PCOS Example", variant="secondary", size="sm")
837
+ btn_normal = gr.Button("πŸ“‹ Load Normal Example", variant="secondary", size="sm")
838
+ btn_clear = gr.Button("πŸ—‘οΈ Clear All", variant="secondary", size="sm")
839
+
840
+ with gr.Row(equal_height=False):
841
+ with gr.Column(scale=1):
842
+ with gr.Accordion("πŸ“‹ General & Vitals", open=True):
843
+ age = gr.Number(label="Age (yrs)", value=25)
844
+ weight = gr.Number(label="Weight (Kg)", value=60)
845
+ height = gr.Number(label="Height (cm)", value=160)
846
+ bmi = gr.Number(label="BMI (auto-computed)",value=0)
847
+ pulse_rate = gr.Number(label="Pulse rate (bpm)", value=72)
848
+ rr = gr.Number(label="RR (breaths/min)", value=18)
849
+ hb = gr.Number(label="Hb (g/dl)", value=12)
850
+ tsh = gr.Number(label="TSH (mIU/L)", value=2.5)
851
+ vit_d3 = gr.Number(label="Vit D3 (ng/mL)", value=25)
852
+
853
+ with gr.Column(scale=1):
854
+ with gr.Accordion("πŸ”΄ Metabolic", open=True):
855
+ rbs = gr.Number(label="RBS (mg/dl)", value=90)
856
+ waist = gr.Number(label="Waist (inch)", value=30)
857
+ hip = gr.Number(label="Hip (inch)", value=37)
858
+ waist_hip = gr.Number(label="Waist:Hip Ratio", value=0.81)
859
+ weight_gain = gr.Radio([0,1], label="Weight Gain", value=0)
860
+ fast_food = gr.Radio([0,1], label="Fast Food (Y=1)", value=0)
861
+ reg_exercise = gr.Radio([0,1], label="Exercise (Y=1)", value=1)
862
+
863
+ with gr.Column(scale=1):
864
+ with gr.Accordion("🟣 Reproductive & Hormonal β˜…", open=True):
865
+ cycle = gr.Radio([2,4], label="Cycle Regular=2 / Irregular=4", value=2)
866
+ cycle_length = gr.Number(label="Cycle length (days)", value=28)
867
+ fsh = gr.Number(label="FSH (mIU/mL) β˜…", value=6.5)
868
+ lh = gr.Number(label="LH (mIU/mL) β˜…", value=5.0)
869
+ fsh_lh_ratio = gr.Number(label="FSH/LH (auto if 0) β˜…", value=0)
870
+ amh = gr.Number(label="AMH (ng/mL) β˜…", value=2.5)
871
+ prg = gr.Number(label="PRG (ng/mL) β˜…", value=1.0)
872
+ endometrium = gr.Number(label="Endometrium (mm) β˜…", value=8.0)
873
+ follicle_l = gr.Number(label="Follicle No. (L) β˜…", value=6)
874
+ follicle_r = gr.Number(label="Follicle No. (R) β˜…", value=6)
875
+ avg_f_size_l = gr.Number(label="Avg F size L (mm)", value=15)
876
+ avg_f_size_r = gr.Number(label="Avg F size R (mm)", value=15)
877
+ gr.HTML("<p style='color:#94a3b8;font-size:0.8rem'>β˜… Used for both PCOS + Infertility Risk</p>")
878
+
879
+ with gr.Column(scale=1):
880
+ with gr.Accordion("🟠 Hyperandrogenic", open=True):
881
+ hair_growth = gr.Radio([0,1], label="Hair Growth (Y=1)", value=0)
882
+ skin_darkening = gr.Radio([0,1], label="Skin Darkening (Y=1)", value=0)
883
+ hair_loss = gr.Radio([0,1], label="Hair Loss (Y=1)", value=0)
884
+ pimples = gr.Radio([0,1], label="Pimples (Y=1)", value=0)
885
+ prl = gr.Number(label="PRL (ng/mL)", value=15)
886
+ gr.HTML("<br>")
887
+ predict_btn = gr.Button("πŸ”¬ Run Full Analysis", variant="primary", size="lg")
888
+
889
+ ALL_INPUTS = [
890
+ age,weight,height,bmi,pulse_rate,rr,hb,
891
+ cycle,cycle_length,fsh,lh,fsh_lh_ratio,
892
+ hip,waist,waist_hip,tsh,amh,prl,vit_d3,prg,rbs,
893
+ weight_gain,hair_growth,skin_darkening,hair_loss,
894
+ pimples,fast_food,reg_exercise,
895
+ follicle_l,follicle_r,avg_f_size_l,avg_f_size_r,endometrium,
896
+ ]
897
+
898
+ with gr.Row():
899
+ with gr.Column(scale=1):
900
+ gr.HTML('<p class="section-label">πŸ“‹ Assessment Summary</p>')
901
+ summary_out = gr.Markdown(value="*Fill the form and click Run Full Analysis.*")
902
+ model_info = gr.Textbox(label="Pipeline info", interactive=False, lines=2)
903
+ with gr.Column(scale=2):
904
+ gr.HTML('<p class="section-label">πŸ“Š Assessment Charts</p>')
905
+ chart_out = gr.Plot(label="", show_label=False)
906
+
907
+ def load_ex(ex): return [ex[k] for k in INPUT_KEYS]
908
+ def clear_all():
909
+ d=dict(age=25,weight=60,height=160,bmi=0,pulse_rate=72,rr=18,hb=12,
910
+ cycle=2,cycle_length=28,fsh=6.5,lh=5.0,fsh_lh_ratio=0,
911
+ hip=37,waist=30,waist_hip=0.81,tsh=2.5,amh=2.5,prl=15,
912
+ vit_d3=25,prg=1.0,rbs=90,weight_gain=0,hair_growth=0,
913
+ skin_darkening=0,hair_loss=0,pimples=0,fast_food=0,reg_exercise=1,
914
+ follicle_l=6,follicle_r=6,avg_f_size_l=15,avg_f_size_r=15,endometrium=8)
915
+ return [d[k] for k in INPUT_KEYS]
916
+
917
+ btn_pcos.click(fn=lambda: load_ex(EXAMPLE_PCOS), outputs=ALL_INPUTS)
918
+ btn_normal.click(fn=lambda: load_ex(EXAMPLE_NORMAL), outputs=ALL_INPUTS)
919
+ btn_clear.click(fn=clear_all, outputs=ALL_INPUTS)
920
+ predict_btn.click(fn=predict_clinical, inputs=ALL_INPUTS,
921
+ outputs=[summary_out,chart_out,model_info])
922
+
923
+ # ══════════════════════════════════════════════════════════
924
+ # TAB 2 β€” SINGLE IMAGE
925
+ # ══════════════════════════════════════════════════════════
926
+ with gr.TabItem("πŸ–ΌοΈ Ultrasound β€” Single"):
927
+
928
+ with gr.Row(equal_height=False):
929
+ with gr.Column(scale=4):
930
+ gr.HTML('<p class="section-label">πŸ“ Upload Image</p>')
931
+ img_input = gr.Image(label="", type="pil", height=280)
932
+ img_btn = gr.Button("πŸ” Analyze Image", variant="primary", size="lg")
933
+ gr.HTML("""
934
+ <div class="info-box" style="margin-top:12px">
935
+ <strong>Model:</strong> EfficientNetB0 (fine-tuned)<br>
936
+ <strong>Input:</strong> 224Γ—224 RGB Β· ImageNet normalisation<br>
937
+ <strong>Classes:</strong> <code>not_pcos</code> (0) Β· <code>pcos</code> (1)<br>
938
+ <strong>Checkpoint:</strong> <code>models/best_model.pth</code><br>
939
+ <strong>XAI:</strong> Grad-CAM on <code>features[-1]</code>
940
+ </div>""")
941
+
942
+ with gr.Column(scale=6):
943
+ gr.HTML('<p class="section-label">πŸ“‹ Diagnosis Result</p>')
944
+ img_result = gr.Markdown(value="*Upload an image and click Analyze.*")
945
+ gr.HTML('<p class="section-label" style="margin-top:14px">πŸ“Š Probability Gauge</p>')
946
+ img_gauge = gr.Plot(label="", show_label=False)
947
+
948
+ gr.HTML('<p class="section-label" style="margin-top:6px">πŸ”₯ Grad-CAM Explainability</p>')
949
+ img_gradcam = gr.Plot(label="", show_label=False)
950
+
951
+ img_btn.click(fn=predict_image_single, inputs=[img_input],
952
+ outputs=[img_result, img_gauge, img_gradcam])
953
+
954
+ # ══════════════════════════════════════════════════════════
955
+ # TAB 3 β€” BATCH IMAGE
956
+ # ══════════════════════════════════════════════════════════
957
+ with gr.TabItem("πŸ“‚ Ultrasound β€” Batch"):
958
+
959
+ with gr.Row(equal_height=False):
960
+ with gr.Column(scale=4):
961
+ gr.HTML('<p class="section-label">πŸ“ Upload Multiple Images</p>')
962
+ batch_input = gr.File(label="", file_count="multiple",
963
+ file_types=["image"])
964
+ batch_btn = gr.Button("⚑ Run Batch Analysis", variant="primary", size="lg")
965
+ gr.HTML("""
966
+ <div class="info-box" style="margin-top:12px">
967
+ Upload any number of ultrasound images.<br>
968
+ Each is analysed independently.<br>
969
+ Results shown as a summary table + distribution chart.<br><br>
970
+ <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF
971
+ </div>""")
972
+
973
+ with gr.Column(scale=6):
974
+ gr.HTML('<p class="section-label">πŸ“Š Batch Summary</p>')
975
+ batch_result = gr.Markdown(value="*Upload images and click Run Batch Analysis.*")
976
+
977
+ gr.HTML('<p class="section-label" style="margin-top:6px">πŸ“ˆ Distribution Chart</p>')
978
+ batch_chart = gr.Plot(label="", show_label=False)
979
+
980
+ batch_btn.click(fn=predict_image_batch, inputs=[batch_input],
981
+ outputs=[batch_result, batch_chart])
982
+
983
+ # ══════════════════════════════════════════════════════════
984
+ # TAB 4 β€” ABOUT
985
+ # ══════════════════════════════════════════════════════════
986
+ with gr.TabItem("ℹ️ About"):
987
+ gr.Markdown("""
988
+ ## About This System
989
+
990
+ ### πŸ”¬ Clinical Pipeline
991
+ | Component | Detail |
992
+ |---|---|
993
+ | Base models | Logistic Regression Β· Random Forest Β· Gradient Boosting Β· CatBoost |
994
+ | Meta-learner | CalibratedClassifierCV (LogisticRegressionCV, isotonic) |
995
+ | Imputation | MICE (IterativeImputer, max_iter=10) |
996
+ | Scaling | RobustScaler |
997
+ | Severity scoring | OOF GBM per domain β†’ normalised 0–1 |
998
+ | Threshold | Youden-J optimal (test ROC) |
999
+ | Dataset | PCOS_data_without_infertility.xlsx |
1000
+
1001
+ **Domain weights:** Reproductive 40% Β· Metabolic 35% Β· Hyperandrogenic 20% Β· General 5%
1002
+
1003
+ ### πŸ–ΌοΈ Image Pipeline
1004
+ | Component | Detail |
1005
+ |---|---|
1006
+ | Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
1007
+ | Input | 224Γ—224 RGB Β· ImageNet normalisation |
1008
+ | Classes | `not_pcos` (0) Β· `pcos` (1) β€” alphabetical |
1009
+ | Checkpoint key | `model_state` |
1010
+ | XAI | Grad-CAM on `features[-1]` |
1011
+ | Saved by | Best validation AUC |
1012
+
1013
+ ### 🧬 Infertility Risk
1014
+ Pure formula β€” no training needed. Weighted biomarker orientations:
1015
+ 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)
1016
+
1017
+ ### ⚠️ Disclaimer
1018
+ For **research and educational purposes only**. Not a certified medical device.
1019
+ Always consult a qualified healthcare professional for clinical decisions.
1020
+ """)
1021
+
1022
+ demo.launch(server_name="0.0.0.0", server_port=7860)