DheivaCodes commited on
Commit
686a400
·
verified ·
1 Parent(s): d5c0f75

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +869 -0
app.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PCOS Integrated Detection System
3
+ - Tab 1: Clinical Analysis (stacked ensemble, trains on Excel at startup)
4
+ - Tab 2: Ultrasound Single (DenseNet121 — best model by MCC/ValAUC/LogLoss)
5
+ - Tab 3: Ultrasound Batch (multi-image, 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
+ # ── 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
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 — IMAGE PIPELINE (DenseNet121)
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, "densenet121.pth"),
59
+ os.path.join(MODELS_DIR, "DenseNet121.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
+ # ── DenseNet121: classifier is a single Linear, not classifier[1] ──
68
+ net = tv_models.densenet121(weights=None)
69
+ in_features = net.classifier.in_features
70
+ net.classifier = nn.Linear(in_features, 2)
71
+
72
+ ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
73
+ if isinstance(ckpt, dict):
74
+ state = (ckpt.get("model_state") or ckpt.get("model_state_dict")
75
+ or ckpt.get("state_dict") or ckpt)
76
+ else:
77
+ state = ckpt
78
+ net.load_state_dict(state, strict=True)
79
+ net.to(DEVICE).eval()
80
+ print(f"✅ DenseNet121 loaded: {pth}")
81
+ return net
82
+ except Exception as e:
83
+ print(f"⚠️ Image model failed to load: {e}")
84
+ return None
85
+
86
+ IMAGE_MODEL = load_image_model()
87
+
88
+ def run_image_inference(img_rgb: Image.Image):
89
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
90
+ with torch.no_grad():
91
+ probs = torch.softmax(IMAGE_MODEL(tensor), dim=1)[0]
92
+ return float(probs[PCOS_IDX]), float(probs[1 - PCOS_IDX]), int(probs.argmax())
93
+
94
+ def compute_gradcam(img_rgb: Image.Image, target_class: int):
95
+ grads, acts = [], []
96
+
97
+ def fwd_hook(m, inp, out):
98
+ acts.append(out.detach())
99
+ out.register_hook(lambda g: grads.append(g.detach()))
100
+
101
+ # ── DenseNet121: target layer is features.denseblock4 (not features[-1]) ──
102
+ handle = IMAGE_MODEL.features.denseblock4.register_forward_hook(fwd_hook)
103
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
104
+ IMAGE_MODEL.zero_grad()
105
+
106
+ # Enable gradients for Grad-CAM
107
+ for param in IMAGE_MODEL.parameters():
108
+ param.requires_grad_(True)
109
+
110
+ output = IMAGE_MODEL(tensor)
111
+ output[0, target_class].backward()
112
+ handle.remove()
113
+
114
+ if not grads or not acts:
115
+ return None
116
+
117
+ w = grads[0].squeeze(0).mean(dim=(1, 2)).cpu().numpy()
118
+ act = acts[0].squeeze(0).cpu().numpy()
119
+ cam = np.maximum(sum(w[i] * act[i] for i in range(len(w))), 0)
120
+ if cam.max() > 1e-8:
121
+ cam /= cam.max()
122
+
123
+ cam_up = np.array(
124
+ Image.fromarray((cam * 255).astype(np.uint8)).resize(
125
+ (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
126
+ ) / 255.0
127
+ orig_r = np.array(img_rgb.resize((IMG_SIZE, IMG_SIZE)))
128
+ heat = cm_mod.jet(cam_up)[:, :, :3]
129
+ overlay = np.clip(0.55 * orig_r / 255.0 + 0.45 * heat, 0, 1)
130
+
131
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4), facecolor="#0f172a",
132
+ gridspec_kw={"wspace": 0.05})
133
+ for ax, (img, cmap, title) in zip(axes, [
134
+ (orig_r, None, "Original Image"),
135
+ (cam_up, "jet", "Grad-CAM Heatmap"),
136
+ (overlay, None, "Activation Overlay"),
137
+ ]):
138
+ ax.set_facecolor("#0f172a")
139
+ ax.imshow(img, cmap=cmap)
140
+ ax.set_title(title, color="white", fontsize=11, fontweight="bold", pad=6)
141
+ ax.axis("off")
142
+ fig.text(0.5, -0.01,
143
+ f"Grad-CAM · DenseNet121 · features.denseblock4 · Predicted: {CLASS_NAMES[target_class]}",
144
+ ha="center", color="#94a3b8", fontsize=9)
145
+ plt.tight_layout(pad=0.3)
146
+ return fig
147
+
148
+ def make_image_gauge(pcos_prob: float):
149
+ fig, ax = plt.subplots(figsize=(5, 2.6), facecolor="#0f172a")
150
+ ax.set_facecolor("#0f172a")
151
+ ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
152
+ ax.barh([0.5], [1.0], height=0.30, color="#1e293b", left=0, align="center", zorder=1)
153
+ color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
154
+ ax.barh([0.5], [pcos_prob], height=0.30, color=color, left=0, align="center", zorder=2)
155
+ ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
156
+ ax.text(pcos_prob, 0.5, f" {pcos_prob*100:.1f}%", va="center", color="white",
157
+ fontsize=16, fontweight="bold", zorder=4,
158
+ ha="left" if pcos_prob < 0.85 else "right")
159
+ for x, lbl, c in [(0.16, "Low", "#22c55e"), (0.50, "Moderate", "#f59e0b"), (0.83, "High", "#ef4444")]:
160
+ ax.text(x, 0.12, lbl, color=c, fontsize=8, ha="center", alpha=0.8)
161
+ ax.text(0.5, 0.92, "PCOS Probability", color="#94a3b8", fontsize=9, ha="center", va="top")
162
+ plt.tight_layout(pad=0.2)
163
+ return fig
164
+
165
+ def make_batch_chart(pcos_c: int, notp_c: int, total: int):
166
+ fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")
167
+ ax1 = fig.add_subplot(1, 2, 1); ax1.set_facecolor("#0f172a")
168
+ if total > 0:
169
+ _, _, autotexts = ax1.pie(
170
+ [pcos_c, notp_c],
171
+ labels=[f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"],
172
+ colors=["#ef4444", "#22c55e"], autopct="%1.1f%%", startangle=90,
173
+ textprops={"color": "white", "fontsize": 10},
174
+ wedgeprops={"linewidth": 2, "edgecolor": "#0f172a"}, pctdistance=0.75)
175
+ for at in autotexts:
176
+ at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold")
177
+ ax1.set_title("Class Distribution", color="white", fontsize=12, fontweight="bold", pad=12)
178
+ ax2 = fig.add_subplot(1, 2, 2); ax2.set_facecolor("#0f172a")
179
+ bars = ax2.bar(["Not PCOS", "PCOS"], [notp_c, pcos_c],
180
+ color=["#22c55e", "#ef4444"], width=0.45, edgecolor="#0f172a", linewidth=2)
181
+ ax2.set_ylim(0, max(pcos_c, notp_c) * 1.35 + 0.5)
182
+ ax2.set_title("Count per Class", color="white", fontsize=12, fontweight="bold", pad=12)
183
+ ax2.tick_params(colors="white", labelsize=11)
184
+ for sp in ax2.spines.values(): sp.set_visible(False)
185
+ ax2.yaxis.set_visible(False)
186
+ for bar, cnt in zip(bars, [notp_c, pcos_c]):
187
+ ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.15,
188
+ str(cnt), ha="center", color="white", fontsize=14, fontweight="bold")
189
+ fig.text(0.5, 0.01, f"Total: {total} image{'s' if total > 1 else ''} · DenseNet121",
190
+ ha="center", color="#64748b", fontsize=9)
191
+ plt.tight_layout(pad=1.5)
192
+ return fig
193
+
194
+ # ══════════════════════════════════════════════════════════════
195
+ # SECTION 2 — CLINICAL PIPELINE (unchanged)
196
+ # ══════════════════════════════════════════════════════════════
197
+ RANDOM_STATE = 42
198
+ TEST_SIZE = 0.2
199
+ CV_FOLDS = 5
200
+ BG = "#0D0D1A"
201
+ TC = "#E8E8F0"
202
+ ACC = "#A855F7"
203
+
204
+ DOMAIN_WEIGHTS = {
205
+ "METABOLIC": 0.35, "REPRODUCTIVE": 0.40,
206
+ "HYPERANDROGENIC": 0.20, "GENERAL": 0.05,
207
+ }
208
+ FEATURE_GROUPS_BASE = {
209
+ "METABOLIC": ["BMI","Weight (Kg)","Waist(inch)","Hip(inch)",
210
+ "Waist:Hip Ratio","RBS(mg/dl)","Weight gain(Y/N)",
211
+ "BP _Systolic (mmHg)","BP _Diastolic (mmHg)",
212
+ "Fast food (Y/N)","Reg.Exercise(Y/N)"],
213
+ "REPRODUCTIVE": ["Cycle(R/I)","Cycle length(days)","FSH(mIU/mL)","LH(mIU/mL)","FSH/LH",
214
+ "AMH(ng/mL)","PRG(ng/mL)","Follicle No. (L)","Follicle No. (R)",
215
+ "Avg. F size (L) (mm)","Avg. F size (R) (mm)","Endometrium (mm)"],
216
+ "HYPERANDROGENIC": ["hair growth(Y/N)","Skin darkening (Y/N)",
217
+ "Hair loss(Y/N)","Pimples(Y/N)","PRL(ng/mL)"],
218
+ "GENERAL": ["Age (yrs)","Hb(g/dl)","Pulse rate(bpm)",
219
+ "RR (breaths/min)","TSH (mIU/L)","Vit D3 (ng/mL)"],
220
+ }
221
+ DROP_COLS = ["Sl. No","Patient File No.","Blood Group","Marraige Status (Yrs)",
222
+ "Pregnant(Y/N)","No. of aborptions","Unnamed: 44"]
223
+ DOMAIN_COLORS = {"Metabolic":"#E74C3C","Reproductive":"#9B59B6",
224
+ "Hyperandrogenic":"#E67E22","General":"#27AE60"}
225
+ BIOMARKER_DIRECTIONS = {
226
+ "FSH(mIU/mL)":1,"LH(mIU/mL)":-1,"FSH/LH":1,"AMH(ng/mL)":-1,
227
+ "Follicle No. (L)":-1,"Follicle No. (R)":-1,"Endometrium (mm)":-1,
228
+ "PRG(ng/mL)":-1,"Cycle(R/I)":1,
229
+ }
230
+ BIOMARKER_WEIGHTS = {
231
+ "FSH(mIU/mL)":0.18,"LH(mIU/mL)":0.08,"FSH/LH":0.15,"AMH(ng/mL)":0.22,
232
+ "Follicle No. (L)":0.10,"Follicle No. (R)":0.10,"Endometrium (mm)":0.08,
233
+ "PRG(ng/mL)":0.05,"Cycle(R/I)":0.04,
234
+ }
235
+ BIOMARKER_RANGES = {
236
+ "FSH(mIU/mL)":(0.5,22.0),"LH(mIU/mL)":(0.2,49.0),"FSH/LH":(0.1,20.0),
237
+ "AMH(ng/mL)":(0.01,18.0),"Follicle No. (L)":(0.0,22.0),"Follicle No. (R)":(0.0,22.0),
238
+ "Endometrium (mm)":(1.0,15.0),"PRG(ng/mL)":(0.1,25.0),"Cycle(R/I)":(2.0,4.0),
239
+ }
240
+ EXAMPLE_PCOS = dict(age=28,weight=72,height=158,bmi=28.8,pulse_rate=82,rr=19,hb=11.5,
241
+ cycle=4,cycle_length=35,fsh=4.8,lh=12.5,fsh_lh_ratio=0.38,hip=40,waist=36,
242
+ waist_hip=0.90,tsh=2.8,amh=8.5,prl=22,vit_d3=18,prg=0.6,rbs=105,
243
+ weight_gain=1,hair_growth=1,skin_darkening=1,hair_loss=0,pimples=1,
244
+ fast_food=1,reg_exercise=0,follicle_l=14,follicle_r=13,avg_f_size_l=8,avg_f_size_r=8,endometrium=6)
245
+ EXAMPLE_NORMAL = dict(age=26,weight=58,height=162,bmi=22.1,pulse_rate=70,rr=16,hb=13.2,
246
+ cycle=2,cycle_length=28,fsh=7.2,lh=4.8,fsh_lh_ratio=1.5,hip=37,waist=28,
247
+ waist_hip=0.76,tsh=2.1,amh=3.2,prl=14,vit_d3=30,prg=1.8,rbs=85,
248
+ weight_gain=0,hair_growth=0,skin_darkening=0,hair_loss=0,pimples=0,
249
+ fast_food=0,reg_exercise=1,follicle_l=6,follicle_r=6,avg_f_size_l=16,avg_f_size_r=16,endometrium=9)
250
+ INPUT_KEYS = ["age","weight","height","bmi","pulse_rate","rr","hb","cycle","cycle_length",
251
+ "fsh","lh","fsh_lh_ratio","hip","waist","waist_hip","tsh","amh","prl",
252
+ "vit_d3","prg","rbs","weight_gain","hair_growth","skin_darkening","hair_loss",
253
+ "pimples","fast_food","reg_exercise","follicle_l","follicle_r",
254
+ "avg_f_size_l","avg_f_size_r","endometrium"]
255
+
256
+ def clean_name(n): return re.sub(r"[^0-9a-zA-Z_]","_",n.strip())
257
+ def clean_df_cols(df):
258
+ df=df.copy(); df.columns=[clean_name(c) for c in df.columns]; return df
259
+ def get_clean_feats(fl,av): return [clean_name(f) for f in fl if clean_name(f) in av]
260
+
261
+ def get_base_models():
262
+ return {
263
+ "Logistic" : LogisticRegression(max_iter=2000,class_weight="balanced"),
264
+ "RandomForest": RandomForestClassifier(n_estimators=300,max_depth=10,
265
+ class_weight="balanced",random_state=RANDOM_STATE),
266
+ "GradientBoost": GradientBoostingClassifier(n_estimators=200,learning_rate=0.05,
267
+ max_depth=3,subsample=0.85,random_state=RANDOM_STATE),
268
+ "CatBoost" : CatBoostClassifier(iterations=300,learning_rate=0.05,depth=6,
269
+ random_seed=RANDOM_STATE,eval_metric="AUC",verbose=0),
270
+ }
271
+
272
+ def load_and_engineer(dp):
273
+ df=pd.read_excel(dp); df=df.drop(columns=DROP_COLS,errors="ignore")
274
+ df.columns=df.columns.str.strip()
275
+ y=pd.to_numeric(df["PCOS (Y/N)"],errors="coerce"); mask=y.notna()
276
+ df=df.loc[mask].copy().reset_index(drop=True); y=y.loc[mask].astype(int).reset_index(drop=True)
277
+ for c in df.columns:
278
+ if df[c].dtype=="object" and c!="PCOS (Y/N)":
279
+ df[c]=pd.to_numeric(df[c].astype(str).str.strip(),errors="coerce")
280
+ df["FSH_LH_Ratio"]=df["FSH(mIU/mL)"]/(df["LH(mIU/mL)"]+1e-6)
281
+ df["Total_Follicles"]=df["Follicle No. (L)"].fillna(0)+df["Follicle No. (R)"].fillna(0)
282
+ df["AMH_FSH_Ratio"]=df["AMH(ng/mL)"]/(df["FSH(mIU/mL)"]+1e-6)
283
+ df["BMI_Waist_Ratio"]=df["BMI"]/(df["Waist(inch)"]+1e-6)
284
+ andro=[c for c in FEATURE_GROUPS_BASE["HYPERANDROGENIC"] if c in df.columns]
285
+ if andro: df["Androgenic_Score"]=df[andro].sum(axis=1)
286
+ FG=copy.deepcopy(FEATURE_GROUPS_BASE)
287
+ FG["REPRODUCTIVE"]+=["FSH_LH_Ratio","Total_Follicles","AMH_FSH_Ratio"]
288
+ FG["METABOLIC"]+=["BMI_Waist_Ratio"]; FG["HYPERANDROGENIC"]+=["Androgenic_Score"]
289
+ return clean_df_cols(df.drop(columns=["PCOS (Y/N)"])),y,FG
290
+
291
+ def preprocess(Xtr,Xte):
292
+ mice=IterativeImputer(max_iter=10,random_state=RANDOM_STATE)
293
+ Xti=pd.DataFrame(mice.fit_transform(Xtr),columns=Xtr.columns,index=Xtr.index)
294
+ Xei=pd.DataFrame(mice.transform(Xte),columns=Xte.columns,index=Xte.index)
295
+ nc=Xti.select_dtypes(include=np.number).columns.tolist(); sc=RobustScaler()
296
+ Xts=Xti.copy(); Xes=Xei.copy()
297
+ Xts[nc]=sc.fit_transform(Xti[nc]); Xes[nc]=sc.transform(Xei[nc])
298
+ return Xts,Xes,mice,sc,nc
299
+
300
+ def compute_oof_severity(Xtr,ytr,Xts,FG):
301
+ skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
302
+ sev=pd.DataFrame(index=Xtr.index); mods,stats={},{}
303
+ for domain,feats in FG.items():
304
+ fc=get_clean_feats(feats,Xts.columns)
305
+ if len(fc)<3: continue
306
+ oof=np.zeros(len(Xts))
307
+ for tr,val in skf.split(Xts,ytr):
308
+ m=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
309
+ max_depth=3,random_state=RANDOM_STATE)
310
+ m.fit(Xts.iloc[tr][fc],ytr.iloc[tr]); oof[val]=m.predict_proba(Xts.iloc[val][fc])[:,1]
311
+ stats[domain]={"min":oof.min(),"max":oof.max()}
312
+ sev[f"{domain}_SEV"]=(oof-oof.min())/(oof.max()-oof.min()+1e-6)
313
+ fm=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
314
+ max_depth=3,random_state=RANDOM_STATE)
315
+ fm.fit(Xts[fc],ytr); mods[domain]=(fm,fc)
316
+ sev["OVERALL_SEV"]=sum(sev[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
317
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev)
318
+ return sev.fillna(0),mods,stats
319
+
320
+ def apply_severity(mods,stats,Xsc):
321
+ out=pd.DataFrame(index=Xsc.index)
322
+ for d,(m,fc) in mods.items():
323
+ fca=[f for f in fc if f in Xsc.columns]
324
+ p=m.predict_proba(Xsc[fca])[:,1]
325
+ out[f"{d}_SEV"]=np.clip((p-stats[d]["min"])/(stats[d]["max"]-stats[d]["min"]+1e-6),0,1)
326
+ out=out.fillna(0)
327
+ out["OVERALL_SEV"]=sum(out[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
328
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in out)
329
+ return out
330
+
331
+ def build_pipeline(dp):
332
+ print("🔄 Training clinical pipeline...")
333
+ X,y,FG=load_and_engineer(dp)
334
+ Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=TEST_SIZE,stratify=y,random_state=RANDOM_STATE)
335
+ Xts,Xes,mice,sc,nc=preprocess(Xtr,Xte)
336
+ sev_tr,dm,stats=compute_oof_severity(Xtr,ytr,Xts,FG)
337
+ sev_te=apply_severity(dm,stats,Xes)
338
+ Xf=pd.concat([Xts,sev_tr],axis=1); Xef=pd.concat([Xes,sev_te],axis=1)
339
+ skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
340
+ om=pd.DataFrame(index=Xf.index); tm=pd.DataFrame(index=Xef.index); tb={}
341
+ for name,model in get_base_models().items():
342
+ oof=np.zeros(len(Xf))
343
+ for tri,vi in skf.split(Xf,ytr):
344
+ model.fit(Xf.iloc[tri],ytr.iloc[tri]); oof[vi]=model.predict_proba(Xf.iloc[vi])[:,1]
345
+ model.fit(Xf,ytr); om[name]=oof; tm[name]=model.predict_proba(Xef)[:,1]; tb[name]=model
346
+ print(f" ✅ {name} AUC:{roc_auc_score(ytr,oof):.4f}")
347
+ meta=CalibratedClassifierCV(LogisticRegressionCV(cv=5,class_weight={0:1,1:3}),method="isotonic")
348
+ meta.fit(om,ytr); ep=meta.predict_proba(tm)[:,1]
349
+ fpr,tpr,ths=roc_curve(yte,ep); bt=float(ths[np.argmax(tpr-fpr)]); auc=roc_auc_score(yte,ep)
350
+ print(f" ✅ Ensemble AUC:{auc:.4f} threshold:{bt:.4f}\n✅ Clinical pipeline ready")
351
+ return dict(meta=meta,base=tb,dm=dm,stats=stats,mice=mice,sc=sc,nc=nc,
352
+ sc_cols=list(Xts.columns),fc=list(Xf.columns),thr=bt,auc=round(auc,4))
353
+
354
+ def compute_infertility_risk(pr):
355
+ def _v(v):
356
+ try: return not np.isnan(float(v)) if v is not None else False
357
+ except: return False
358
+ av={f:w for f,w in BIOMARKER_WEIGHTS.items() if f in pr and _v(pr[f])}
359
+ if not av: return {"score":0.5,"tier":"Unknown","breakdown":{}}
360
+ tw=sum(av.values()); score=0.0; bd={}
361
+ for feat,w in av.items():
362
+ val=float(pr[feat]); lo,hi=BIOMARKER_RANGES.get(feat,(0,1))
363
+ norm=np.clip((val-lo)/(hi-lo+1e-8),0,1)
364
+ ori=(1-norm) if BIOMARKER_DIRECTIONS.get(feat,1)==-1 else norm
365
+ c=(w/tw)*ori; score+=c
366
+ bd[feat]={"raw":round(val,3),"oriented":round(ori,3),"contribution":round(c,4),
367
+ "direction":"↑ risk" if BIOMARKER_DIRECTIONS.get(feat,1)==1 else "↓ protective"}
368
+ tier="High" if score>=0.66 else("Moderate" if score>=0.33 else "Low")
369
+ return {"score":round(score,4),"tier":tier,"breakdown":bd}
370
+
371
+ def predict_clinical_single(pl,pr):
372
+ row={k:np.nan for k in pl["sc_cols"]}
373
+ for rk,val in pr.items():
374
+ ck=clean_name(rk)
375
+ if ck in row and val is not None:
376
+ try: row[ck]=float(val)
377
+ except: pass
378
+ Xr=pd.DataFrame([row])
379
+ for c in Xr.columns: Xr[c]=pd.to_numeric(Xr[c],errors="coerce")
380
+ Xi=pd.DataFrame(pl["mice"].transform(Xr),columns=Xr.columns)
381
+ Xs=Xi.copy(); ncc=[c for c in pl["nc"] if c in Xs.columns]
382
+ Xs[ncc]=pl["sc"].transform(Xi[ncc])
383
+ sev=apply_severity(pl["dm"],pl["stats"],Xs)
384
+ Xf=pd.concat([Xs.reset_index(drop=True),sev.reset_index(drop=True)],axis=1)
385
+ for c in pl["fc"]:
386
+ if c not in Xf.columns: Xf[c]=0.0
387
+ Xf=Xf[pl["fc"]].clip(-10,10)
388
+ bp={n:m.predict_proba(Xf)[:,1][0] for n,m in pl["base"].items()}
389
+ pp=pl["meta"].predict_proba(pd.DataFrame([bp]))[:,1][0]
390
+ pred=int(pp>=pl["thr"])
391
+ def _s(c): return float(sev[c].iloc[0]) if c in sev.columns else 0.0
392
+ sv={"Metabolic":_s("METABOLIC_SEV"),"Reproductive":_s("REPRODUCTIVE_SEV"),
393
+ "Hyperandrogenic":_s("HYPERANDROGENIC_SEV"),"General":_s("GENERAL_SEV"),"Overall":_s("OVERALL_SEV")}
394
+ return pp,pred,sv,bp
395
+
396
+ # ── Startup ───────────────────────────────────────────────────
397
+ DATA_PATH = os.path.join(os.path.dirname(__file__), "PCOS_data_without_infertility.xlsx")
398
+ if os.path.exists(DATA_PATH):
399
+ try:
400
+ PIPELINE=build_pipeline(DATA_PATH); PIPELINE_READY=True
401
+ except Exception as _e:
402
+ print(f"⚠️ Pipeline error: {_e}"); PIPELINE=None; PIPELINE_READY=False
403
+ else:
404
+ print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False
405
+
406
+ # ══════════════════════════════════════════════════════════════
407
+ # SECTION 3 — CLINICAL CHARTS
408
+ # ══════════════════════════════════════════════════════════════
409
+ def draw_gauge(ax,value,title,val_label,sub_label,val_col):
410
+ ax.set_facecolor(BG)
411
+ theta=np.linspace(np.pi,0,300)
412
+ for i in range(len(theta)-1):
413
+ ax.fill_between([np.cos(theta[i]),np.cos(theta[i+1])],
414
+ [np.sin(theta[i]),np.sin(theta[i+1])],
415
+ alpha=0.9,color=plt.cm.RdYlGn_r(i/(len(theta)-1)))
416
+ angle=np.pi*(1-value)
417
+ ax.annotate("",xy=(0.65*np.cos(angle),0.65*np.sin(angle)),xytext=(0,0),
418
+ arrowprops=dict(arrowstyle="-|>",color="white",lw=3))
419
+ ax.plot(0,0,"o",color="white",markersize=6,zorder=5)
420
+ ax.text(0,-0.15,val_label,ha="center",fontsize=22,fontweight="bold",color=val_col,va="center")
421
+ ax.text(0,-0.58,sub_label,ha="center",fontsize=10,fontweight="bold",color=val_col)
422
+ for pct,lbl in [(0,"0%"),(0.5,"50%"),(1.0,"100%")]:
423
+ a=np.pi*(1-pct)
424
+ ax.text(0.88*np.cos(a),0.88*np.sin(a),lbl,ha="center",va="center",fontsize=6,color="#888")
425
+ ax.set_xlim(-1.05,1.05); ax.set_ylim(-0.72,1.05); ax.axis("off")
426
+ ax.set_title(title,color=TC,fontsize=12,fontweight="bold",pad=4)
427
+
428
+ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
429
+ fig=plt.figure(figsize=(18,13),facecolor=BG)
430
+ gs=GridSpec(3,4,figure=fig,hspace=0.58,wspace=0.45,top=0.93,bottom=0.05,left=0.05,right=0.97)
431
+ ax_pg=fig.add_subplot(gs[0,0]); ax_ig=fig.add_subplot(gs[0,1])
432
+ ax_rd=fig.add_subplot(gs[0,2:],polar=True)
433
+ ax_br=fig.add_subplot(gs[1,:2]); ax_bi=fig.add_subplot(gs[1,2:])
434
+ ax_sv=fig.add_subplot(gs[2,:])
435
+ rc="#E74C3C" if pp>0.65 else("#F39C12" if pp>0.35 else "#2ECC71")
436
+ it=inf["tier"]; ic="#E74C3C" if it=="High" else("#F39C12" if it=="Moderate" else "#2ECC71")
437
+ draw_gauge(ax_pg,pp,"PCOS Risk",f"{pp*100:.1f}%","⚠️ PCOS Detected" if pred else "✅ No PCOS",rc)
438
+ draw_gauge(ax_ig,inf["score"],"Infertility Risk",f"{inf['score']*100:.1f}%",
439
+ f"{'🔴' if it=='High' else('🟡' if it=='Moderate' else '🟢')} {it}",ic)
440
+ doms=["Metabolic","Reproductive","Hyperandrogenic","General"]
441
+ vals=[sv[d] for d in doms]
442
+ ang=np.linspace(0,2*np.pi,len(doms),endpoint=False).tolist()
443
+ vc=vals+[vals[0]]; ac=ang+[ang[0]]
444
+ ax_rd.set_facecolor(BG)
445
+ for lv,al,co in [(1.0,0.05,"#E74C3C"),(0.65,0.08,"#F39C12"),(0.35,0.08,"#2ECC71")]:
446
+ ax_rd.fill(ac,[lv]*len(ac),alpha=al,color=co)
447
+ ax_rd.plot(ac,vc,"o-",lw=2.5,color=ACC,markersize=7); ax_rd.fill(ac,vc,alpha=0.30,color=ACC)
448
+ ax_rd.set_xticks(ang)
449
+ ax_rd.set_xticklabels([f"{d}\n{vals[i]*100:.0f}%" for i,d in enumerate(doms)],
450
+ color=TC,fontsize=10,fontweight="bold")
451
+ ax_rd.set_ylim(0,1); ax_rd.set_yticks([0.35,0.65,1.0])
452
+ ax_rd.set_yticklabels(["Low→Mod","Mod→High","Max"],color="#666",fontsize=7)
453
+ ax_rd.grid(color="#333355",alpha=0.6,lw=0.8); ax_rd.spines["polar"].set_color("#333355")
454
+ ax_rd.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
455
+ ax_br.set_facecolor(BG)
456
+ names=list(bp.keys()); probs_=[bp[n] for n in names]
457
+ cols=["#3B82F6","#10B981","#F59E0B","#EF4444"]
458
+ bars=ax_br.barh(names,probs_,color=cols[:len(names)],height=0.52,alpha=0.88)
459
+ for bar,p in zip(bars,probs_):
460
+ ax_br.text(min(p+0.018,0.97),bar.get_y()+bar.get_height()/2,
461
+ f"{p:.3f}",va="center",color=TC,fontsize=11,fontweight="bold")
462
+ ax_br.axvline(0.5,color="white",ls="--",alpha=0.3,lw=1.5)
463
+ ax_br.axvline(thr,color=ACC,ls=":",alpha=0.6,lw=1.5,label=f"Youden threshold ({thr:.2f})")
464
+ ax_br.set_xlim(0,1.12); ax_br.tick_params(colors=TC,labelsize=11)
465
+ for sp in ax_br.spines.values(): sp.set_color("#2A2A4A")
466
+ ax_br.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
467
+ ax_br.set_xlabel("PCOS Probability",color=TC,fontsize=10)
468
+ ax_br.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
469
+ ax_bi.set_facecolor(BG); ax_bi.tick_params(colors=TC,labelsize=8)
470
+ for sp in ax_bi.spines.values(): sp.set_color("#2A2A4A")
471
+ ax_bi.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
472
+ ax_bi.set_xlabel("Weighted contribution",color=TC,fontsize=9)
473
+ bd=inf.get("breakdown",{})
474
+ if bd:
475
+ fn=list(bd.keys()); fv=[bd[f]["contribution"] for f in fn]
476
+ fc_=[("#10B981" if bd[f]["oriented"]>0.5 else "#EF4444") for f in fn]
477
+ sn=[f.split("(")[0].strip()[:14] for f in fn]
478
+ sp2=sorted(zip(sn,fv,fc_),key=lambda x:x[1],reverse=True)
479
+ sn,fv,fc_=zip(*sp2)
480
+ b2=ax_bi.barh(sn,fv,color=fc_,height=0.52,alpha=0.88)
481
+ for bar,val in zip(b2,fv):
482
+ ax_bi.text(val+0.001,bar.get_y()+bar.get_height()/2,f"{val:.3f}",va="center",color=TC,fontsize=9)
483
+ ax_bi.legend(handles=[mpatches.Patch(color="#EF4444",label="↑ Increases risk"),
484
+ mpatches.Patch(color="#10B981",label="↓ Protective")],
485
+ facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8)
486
+ else:
487
+ ax_bi.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values",ha="center",va="center",
488
+ color="#666",fontsize=10,transform=ax_bi.transAxes)
489
+ ax_sv.set_facecolor(BG)
490
+ sv_v=[sv[d] for d in doms]; sv_c=[DOMAIN_COLORS[d] for d in doms]
491
+ xp=np.arange(len(doms)); b3=ax_sv.bar(xp,sv_v,color=sv_c,alpha=0.88,width=0.5)
492
+ for bar,val,d in zip(b3,sv_v,doms):
493
+ lv="High" if val>0.65 else("Moderate" if val>0.35 else "Low")
494
+ lc="#E74C3C" if lv=="High" else("#F39C12" if lv=="Moderate" else "#2ECC71")
495
+ ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.02,f"{val*100:.1f}%",
496
+ ha="center",va="bottom",color=TC,fontsize=14,fontweight="bold")
497
+ ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.09,f"({lv})",
498
+ ha="center",va="bottom",color=lc,fontsize=11)
499
+ ax_sv.axhline(0.65,color="#E74C3C",ls="--",alpha=0.45,lw=1.5,label="High (65%)")
500
+ ax_sv.axhline(0.35,color="#F39C12",ls="--",alpha=0.45,lw=1.5,label="Moderate (35%)")
501
+ ax_sv.set_ylim(0,1.3); ax_sv.set_xticks(xp)
502
+ ax_sv.set_xticklabels(doms,color=TC,fontsize=13,fontweight="bold")
503
+ ax_sv.tick_params(axis="y",colors=TC,labelsize=10)
504
+ for sp in ax_sv.spines.values(): sp.set_color("#2A2A4A")
505
+ ax_sv.set_title("PCOS Domain Severity Breakdown",color=TC,fontsize=13,fontweight="bold")
506
+ ax_sv.set_ylabel("Severity Score",color=TC,fontsize=11)
507
+ ax_sv.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=9,loc="upper right")
508
+ fig.patch.set_facecolor(BG)
509
+ fig.suptitle("🩺 PCOS Clinical Assessment Report",color=TC,fontsize=16,fontweight="bold",y=0.97)
510
+ return fig
511
+
512
+ # ══════════════════════════════════════════════════════════════
513
+ # SECTION 4 — GRADIO HANDLER FUNCTIONS
514
+ # ══════════════════════════════════════════════════════════════
515
+ def predict_clinical(*args):
516
+ vals=dict(zip(INPUT_KEYS,args))
517
+ if not PIPELINE_READY:
518
+ return ("❌ Clinical pipeline not ready.\nUpload `PCOS_data_without_infertility.xlsx` "
519
+ "to the Space root folder."), None, ""
520
+ bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
521
+ if (not bmi or bmi==0) and vals["weight"] and vals["height"] and vals["height"]>0:
522
+ bmi=vals["weight"]/((vals["height"]/100)**2)
523
+ if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"]==0) and fsh and lh:
524
+ vals["fsh_lh_ratio"]=fsh/(lh+1e-6)
525
+ vals["bmi"]=bmi
526
+ pr={
527
+ "Age (yrs)":vals["age"],"Weight (Kg)":vals["weight"],"BMI":vals["bmi"],
528
+ "Pulse rate(bpm)":vals["pulse_rate"],"RR (breaths/min)":vals["rr"],
529
+ "Hb(g/dl)":vals["hb"],"Cycle(R/I)":vals["cycle"],
530
+ "Cycle length(days)":vals["cycle_length"],
531
+ "FSH(mIU/mL)":vals["fsh"],"LH(mIU/mL)":vals["lh"],"FSH/LH":vals["fsh_lh_ratio"],
532
+ "Hip(inch)":vals["hip"],"Waist(inch)":vals["waist"],"Waist:Hip Ratio":vals["waist_hip"],
533
+ "TSH (mIU/L)":vals["tsh"],"AMH(ng/mL)":vals["amh"],"PRL(ng/mL)":vals["prl"],
534
+ "Vit D3 (ng/mL)":vals["vit_d3"],"PRG(ng/mL)":vals["prg"],"RBS(mg/dl)":vals["rbs"],
535
+ "Weight gain(Y/N)":vals["weight_gain"],"hair growth(Y/N)":vals["hair_growth"],
536
+ "Skin darkening (Y/N)":vals["skin_darkening"],"Hair loss(Y/N)":vals["hair_loss"],
537
+ "Pimples(Y/N)":vals["pimples"],"Fast food (Y/N)":vals["fast_food"],
538
+ "Reg.Exercise(Y/N)":vals["reg_exercise"],
539
+ "Follicle No. (L)":vals["follicle_l"],"Follicle No. (R)":vals["follicle_r"],
540
+ "Avg. F size (L) (mm)":vals["avg_f_size_l"],"Avg. F size (R) (mm)":vals["avg_f_size_r"],
541
+ "Endometrium (mm)":vals["endometrium"],
542
+ "BP _Systolic (mmHg)":120,"BP _Diastolic (mmHg)":80,
543
+ }
544
+ try:
545
+ pp,pred,sv,bp=predict_clinical_single(PIPELINE,pr)
546
+ except Exception as e:
547
+ return f"❌ Prediction error: {e}", None, ""
548
+ inf=compute_infertility_risk(pr)
549
+ it=inf["tier"]; ii="🔴" if it=="High" else("🟡" if it=="Moderate" else "🟢")
550
+ pt="HIGH RISK 🔴" if pp>0.65 else("MODERATE RISK 🟡" if pp>0.35 else "LOW RISK 🟢")
551
+ recs=[]
552
+ if pred: recs.append("🏥 **Consult an endocrinologist / gynaecologist immediately.**")
553
+ if it=="High": recs.append("🧬 **High infertility risk — fertility specialist evaluation recommended.**")
554
+ elif it=="Moderate": recs.append("🔬 Hormonal panel follow-up (FSH, LH, AMH) recommended.")
555
+ if sv["Metabolic"]>0.5: recs.append("⚖️ Weight management and regular exercise advised.")
556
+ if sv["Hyperandrogenic"]>0.5: recs.append("💊 Discuss anti-androgen therapy with your doctor.")
557
+ if not recs: recs.append("✅ Continue routine annual screening and a healthy lifestyle.")
558
+ sev_rows="\n".join(
559
+ f"| {d} | {sv[d]*100:.1f}% | {'🔴 High' if sv[d]>0.65 else('🟡 Moderate' if sv[d]>0.35 else '🟢 Low')} |"
560
+ for d in ["Metabolic","Reproductive","Hyperandrogenic","General"])
561
+ bio_rows="\n".join(
562
+ f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
563
+ for f,v in inf.get("breakdown",{}).items()
564
+ ) or "| — | Enter hormonal values | — | — |"
565
+ rec_text="\n".join(f"- {r}" for r in recs)
566
+ summary=f"""## Clinical Assessment — {pt}
567
+ | Metric | Value |
568
+ |---|---|
569
+ | **PCOS Probability** | **{pp*100:.1f}%** |
570
+ | **Diagnosis** | {"⚠️ PCOS Detected" if pred else "✅ No PCOS Detected"} |
571
+ | **Overall Severity** | {sv['Overall']*100:.1f}% |
572
+ | **Infertility Risk** | {ii} {it} ({inf['score']*100:.1f}%) |
573
+ ---
574
+ ### PCOS Domain Severity
575
+ | Domain | Score | Level |
576
+ |---|---|---|
577
+ {sev_rows}
578
+ ### Infertility Biomarker Breakdown
579
+ | Biomarker | Value | Direction | Contribution |
580
+ |---|---|---|---|
581
+ {bio_rows}
582
+ ### Clinical Recommendations
583
+ {rec_text}
584
+ ---
585
+ *⚕️ For research/educational purposes only. Not medical advice.*"""
586
+ fig=make_clinical_figure(pp,pred,sv,bp,inf,PIPELINE["thr"])
587
+ info=f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['thr']:.4f} | LR+RF+GBM+CatBoost → CalibratedLRCV"
588
+ return summary, fig, info
589
+
590
+
591
+ def predict_image_single(image):
592
+ if IMAGE_MODEL is None:
593
+ return ("## ❌ Image model not loaded\n\n"
594
+ "Upload `best_model.pth` to the `models/` folder on HuggingFace.\n\n"
595
+ "The **Clinical tab works normally**."), None, None
596
+ if image is None:
597
+ return "⚠️ Please upload an ultrasound image.", None, None
598
+ try:
599
+ img_rgb=(image if isinstance(image,Image.Image) else Image.fromarray(image)).convert("RGB")
600
+ pcos_p,notp,pred=run_image_inference(img_rgb)
601
+ icon="🔴" if pred==PCOS_IDX else "🟢"
602
+ label=CLASS_NAMES[pred]
603
+ conf=pcos_p if pred==PCOS_IDX else notp
604
+ risk="🟢 Low" if pcos_p<0.33 else "🟡 Moderate" if pcos_p<0.66 else "🔴 High"
605
+ result=f"""### {icon} {label}
606
+ | Metric | Value |
607
+ |---|---|
608
+ | PCOS Probability | **{pcos_p*100:.1f}%** |
609
+ | Not PCOS Probability | **{notp*100:.1f}%** |
610
+ | Confidence | **{conf*100:.1f}%** |
611
+ | Risk Level | **{risk}** |
612
+ *DenseNet121 · 224×224 · ImageNet normalisation · Val AUC: 0.9998 · MCC: 0.9648*
613
+ > ⚠️ Research use only — not a clinical tool."""
614
+ return result, make_image_gauge(pcos_p), compute_gradcam(img_rgb, pred)
615
+ except Exception as e:
616
+ import traceback
617
+ return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None
618
+
619
+
620
+ def predict_image_batch(files):
621
+ if IMAGE_MODEL is None:
622
+ return ("## ❌ Image model not loaded\n\nUpload `best_model.pth` to `models/`.\n\n"
623
+ "The **Clinical tab works normally**."), None
624
+ if not files:
625
+ return "⚠️ Upload at least one image.", None
626
+ rows=[]; pcos_c=0; notp_c=0
627
+ for f in files:
628
+ try:
629
+ img=Image.open(f.name).convert("RGB")
630
+ pcos_p,notp,pred=run_image_inference(img)
631
+ icon="🔴" if pred==PCOS_IDX else "🟢"
632
+ rows.append({"File":os.path.basename(f.name),
633
+ "Prediction":f"{icon} {CLASS_NAMES[pred]}",
634
+ "PCOS%":f"{pcos_p*100:.1f}","Not PCOS%":f"{notp*100:.1f}",
635
+ "Risk":"Low" if pcos_p<0.33 else "Moderate" if pcos_p<0.66 else "High"})
636
+ if pred==PCOS_IDX: pcos_c+=1
637
+ else: notp_c+=1
638
+ except Exception as e:
639
+ rows.append({"File":os.path.basename(f.name),"Prediction":f"❌ {e}",
640
+ "PCOS%":"—","Not PCOS%":"—","Risk":"—"})
641
+ total=len(rows)
642
+ table="\n".join(
643
+ f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |"
644
+ for r in rows)
645
+ summary=f"""### 📊 Batch Summary — {total} image{'s' if total>1 else ''}
646
+ | | Count | % |
647
+ |---|---|---|
648
+ | 🔴 PCOS | **{pcos_c}** | **{pcos_c/total*100:.1f}%** |
649
+ | 🟢 Not PCOS | **{notp_c}** | **{notp_c/total*100:.1f}%** |
650
+ | Total | **{total}** | 100% |
651
+ ---
652
+ ### Per-Image Results
653
+ | File | Prediction | PCOS% | Not PCOS% | Risk |
654
+ |---|---|---|---|---|
655
+ {table}
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; DenseNet121 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():
776
+ d=dict(age=25,weight=60,height=160,bmi=0,pulse_rate=72,rr=18,hb=12,
777
+ cycle=2,cycle_length=28,fsh=6.5,lh=5.0,fsh_lh_ratio=0,
778
+ hip=37,waist=30,waist_hip=0.81,tsh=2.5,amh=2.5,prl=15,
779
+ vit_d3=25,prg=1.0,rbs=90,weight_gain=0,hair_growth=0,
780
+ skin_darkening=0,hair_loss=0,pimples=0,fast_food=0,reg_exercise=1,
781
+ follicle_l=6,follicle_r=6,avg_f_size_l=15,avg_f_size_r=15,endometrium=8)
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> DenseNet121 (fine-tuned · best model)<br>
799
+ <strong>Selection:</strong> Highest MCC (0.9648) · Val AUC (0.9998) · Lowest Log Loss (0.0357)<br>
800
+ <strong>Input:</strong> 224×224 RGB · ImageNet normalisation<br>
801
+ <strong>Classes:</strong> <code>not_pcos</code> (0) · <code>pcos</code> (1)<br>
802
+ <strong>Checkpoint:</strong> <code>models/best_model.pth</code><br>
803
+ <strong>XAI:</strong> Grad-CAM on <code>features.denseblock4</code>
804
+ </div>""")
805
+ with gr.Column(scale=6):
806
+ gr.HTML('<p class="sec">📋 Diagnosis Result</p>')
807
+ img_result=gr.Markdown(value="*Upload an image and click Analyze.*")
808
+ gr.HTML('<p class="sec" style="margin-top:14px">📊 Probability Gauge</p>')
809
+ img_gauge=gr.Plot(label="",show_label=False)
810
+ gr.HTML('<p class="sec" style="margin-top:6px">🔥 Grad-CAM Explainability</p>')
811
+ img_gradcam=gr.Plot(label="",show_label=False)
812
+ img_btn.click(fn=predict_image_single,inputs=[img_input],
813
+ outputs=[img_result,img_gauge,img_gradcam])
814
+
815
+ # ── TAB 3: BATCH IMAGE ────────────────────────────────────
816
+ with gr.TabItem("📂 Ultrasound — Batch"):
817
+ with gr.Row(equal_height=False):
818
+ with gr.Column(scale=4):
819
+ gr.HTML('<p class="sec">📁 Upload Multiple Images</p>')
820
+ batch_input=gr.File(label="",file_count="multiple",file_types=["image"])
821
+ batch_btn=gr.Button("⚡ Run Batch Analysis",variant="primary",size="lg")
822
+ gr.HTML("""<div class="info-box" style="margin-top:12px">
823
+ Upload any number of ultrasound images.<br>
824
+ Each is analysed independently using DenseNet121.<br>
825
+ Results shown as a summary table + distribution chart.<br><br>
826
+ <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF
827
+ </div>""")
828
+ with gr.Column(scale=6):
829
+ gr.HTML('<p class="sec">📊 Batch Summary</p>')
830
+ batch_result=gr.Markdown(value="*Upload images and click Run Batch Analysis.*")
831
+ gr.HTML('<p class="sec" style="margin-top:6px">📈 Distribution Chart</p>')
832
+ batch_chart=gr.Plot(label="",show_label=False)
833
+ batch_btn.click(fn=predict_image_batch,inputs=[batch_input],
834
+ outputs=[batch_result,batch_chart])
835
+
836
+ # ── TAB 4: ABOUT ──────────────────────────────────────────
837
+ with gr.TabItem("ℹ️ About"):
838
+ gr.Markdown("""
839
+ ## About This System
840
+ ### 🖼️ Image Pipeline — DenseNet121
841
+ | Component | Detail |
842
+ |---|---|
843
+ | Architecture | DenseNet121 (ImageNet pretrained, fine-tuned) |
844
+ | Why selected | Best MCC (0.9648) · Val AUC (0.9998) · Lowest Log Loss (0.0357) · Best Specificity (0.9918) |
845
+ | Input | 224×224 RGB · ImageNet normalisation |
846
+ | Classes | `not_pcos` (0) · `pcos` (1) — alphabetical |
847
+ | Checkpoint key | `model_state` |
848
+ | XAI | Grad-CAM on `features.denseblock4` |
849
+ | File | `models/best_model.pth` |
850
+ | Test ROC-AUC | 0.9994 · F1: 0.9926 · Accuracy: 0.9883 |
851
+ ### 🔬 Clinical Pipeline
852
+ | Component | Detail |
853
+ |---|---|
854
+ | Base models | Logistic Regression · Random Forest · Gradient Boosting · CatBoost |
855
+ | Meta-learner | CalibratedClassifierCV (LogisticRegressionCV, isotonic) |
856
+ | Imputation | MICE (IterativeImputer, max_iter=10) |
857
+ | Scaling | RobustScaler |
858
+ | Severity scoring | OOF GBM per domain → normalised 0–1 |
859
+ | Threshold | Youden-J optimal on test ROC |
860
+ | Dataset | PCOS_data_without_infertility.xlsx (Space root) |
861
+ **Domain weights:** Reproductive 40% · Metabolic 35% · Hyperandrogenic 20% · General 5%
862
+ ### 🧬 Infertility Risk
863
+ 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
864
+ ### ⚠️ Disclaimer
865
+ For **research and educational purposes only**. Not a certified medical device.
866
+ Always consult a qualified healthcare professional for clinical decisions.
867
+ """)
868
+
869
+ demo.launch(server_name="0.0.0.0", server_port=7860)