Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,51 +1,47 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import matplotlib
|
| 5 |
matplotlib.use("Agg")
|
| 6 |
import matplotlib.pyplot as plt
|
|
|
|
| 7 |
import gradio as gr
|
|
|
|
| 8 |
warnings.filterwarnings("ignore")
|
| 9 |
|
| 10 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
DOMAIN_WEIGHTS = {
|
| 12 |
-
"METABOLIC": 0.35,
|
| 13 |
-
"REPRODUCTIVE": 0.40,
|
| 14 |
"HYPERANDROGENIC": 0.20,
|
| 15 |
-
"GENERAL": 0.05,
|
| 16 |
}
|
| 17 |
|
| 18 |
-
# ββ
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def
|
| 22 |
-
|
| 23 |
-
if _mdl is not None:
|
| 24 |
-
return _mdl, None
|
| 25 |
-
import joblib
|
| 26 |
-
needed = ["ensemble_meta", "base_models", "domain_models", "train_stats",
|
| 27 |
-
"mice_imputer", "scaler", "feature_columns", "best_threshold"]
|
| 28 |
-
missing = [f for f in needed if not os.path.exists(f"models/{f}.pkl")]
|
| 29 |
-
if missing:
|
| 30 |
-
return None, f"Missing pkl files: {missing}"
|
| 31 |
-
try:
|
| 32 |
-
_mdl = {
|
| 33 |
-
"meta": joblib.load("models/ensemble_meta.pkl"),
|
| 34 |
-
"base": joblib.load("models/base_models.pkl"),
|
| 35 |
-
"domain": joblib.load("models/domain_models.pkl"),
|
| 36 |
-
"stats": joblib.load("models/train_stats.pkl"),
|
| 37 |
-
"mice": joblib.load("models/mice_imputer.pkl"),
|
| 38 |
-
"scaler": joblib.load("models/scaler.pkl"),
|
| 39 |
-
"features": joblib.load("models/feature_columns.pkl"),
|
| 40 |
-
"threshold": joblib.load("models/best_threshold.pkl"),
|
| 41 |
-
}
|
| 42 |
-
return _mdl, None
|
| 43 |
-
except Exception as e:
|
| 44 |
-
return None, str(e)
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
def apply_severity(domain_models, stats, X_raw, X_sc):
|
| 49 |
df = pd.DataFrame(index=X_sc.index)
|
| 50 |
for d, (model, fc) in domain_models.items():
|
| 51 |
avail = [f for f in fc if f in X_sc.columns]
|
|
@@ -53,8 +49,9 @@ def apply_severity(domain_models, stats, X_raw, X_sc):
|
|
| 53 |
df[f"{d}_SEV"] = 0.0
|
| 54 |
continue
|
| 55 |
p = model.predict_proba(X_sc[avail])[:, 1]
|
| 56 |
-
|
| 57 |
-
|
|
|
|
| 58 |
df = df.fillna(0)
|
| 59 |
df["OVERALL_SEV"] = sum(
|
| 60 |
df[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
|
|
@@ -62,386 +59,549 @@ def apply_severity(domain_models, stats, X_raw, X_sc):
|
|
| 62 |
)
|
| 63 |
return df
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
foll = (foll_l or 0) + (foll_r or 0)
|
| 112 |
-
if amh: parts.append(("AMH Reserve", max(0, 1 - amh / 5), 0.35))
|
| 113 |
-
if fsh: parts.append(("FSH Level", min(1, fsh / 20), 0.25))
|
| 114 |
-
if foll: parts.append(("Follicle Count", max(0, 1 - foll / 20), 0.20))
|
| 115 |
-
parts.append(("Cycle", 0.70 if cycle == "Irregular" else 0.20, 0.15))
|
| 116 |
-
if bmi: parts.append(("BMI", 0.6 if bmi < 18.5 or bmi > 30 else 0.3 if bmi > 25 else 0.0, 0.05))
|
| 117 |
-
if not parts:
|
| 118 |
-
return 0.5, "Moderate"
|
| 119 |
-
tw = sum(w for _, _, w in parts)
|
| 120 |
-
sc = sum(r * w for _, r, w in parts) / tw
|
| 121 |
-
return sc, ("Low" if sc < 0.35 else "High" if sc >= 0.60 else "Moderate")
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# ββ Plots ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 125 |
-
def make_radar(sev):
|
| 126 |
-
doms = ["METABOLIC", "REPRODUCTIVE", "HYPERANDROGENIC", "GENERAL"]
|
| 127 |
-
vals = [sev.get(d, 0) for d in doms] + [sev.get(doms[0], 0)]
|
| 128 |
-
ang = [n / len(doms) * 2 * np.pi for n in range(len(doms))] + [0]
|
| 129 |
-
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
|
| 130 |
-
fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
|
| 131 |
-
ax.plot(ang, vals, "o-", lw=2.5, color="#4f46e5")
|
| 132 |
-
ax.fill(ang, vals, alpha=0.25, color="#4f46e5")
|
| 133 |
-
ax.set_xticks(ang[:-1])
|
| 134 |
-
ax.set_xticklabels([d.capitalize() for d in doms], fontsize=10)
|
| 135 |
-
ax.set_ylim(0, 1); ax.set_yticks([.25, .5, .75, 1])
|
| 136 |
-
ax.set_yticklabels(["25%", "50%", "75%", "100%"], fontsize=7)
|
| 137 |
-
ax.set_title("Domain Severity Profile", fontsize=12, fontweight="bold", pad=16)
|
| 138 |
-
plt.tight_layout()
|
| 139 |
-
return fig
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
f"{p:.1%}", ha="center", fontsize=10, fontweight="600")
|
| 152 |
-
ax.axhline(threshold, color="#f59e0b", lw=2, ls="--",
|
| 153 |
-
label=f"Threshold {threshold:.3f}")
|
| 154 |
-
ax.set_ylim(0, 1.15); ax.legend(fontsize=9)
|
| 155 |
-
ax.set_title("Base Model Probabilities", fontsize=11, fontweight="bold")
|
| 156 |
-
ax.spines[["top", "right"]].set_visible(False)
|
| 157 |
-
ax.tick_params(labelsize=10)
|
| 158 |
-
plt.tight_layout()
|
| 159 |
-
return fig
|
| 160 |
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
# ββ Main prediction function βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 189 |
-
def run_analysis(age, bmi, weight, hb, pulse, rr,
|
| 190 |
-
fsh, lh, amh, prg, prl, tsh, vitd3, rbs,
|
| 191 |
-
waist, hip, bp_sys, bp_dia,
|
| 192 |
-
foll_l, foll_r, avg_fl, avg_fr, endo,
|
| 193 |
-
cycle, cycle_len,
|
| 194 |
-
wt_gain, hair_growth, skin_dark,
|
| 195 |
-
hair_loss, pimples, fast_food, exercise):
|
| 196 |
-
|
| 197 |
-
mdl, err = get_models()
|
| 198 |
-
if err:
|
| 199 |
-
err_html = f'<div style="color:red;padding:20px;font-family:sans-serif">β {err}<br>Make sure all 8 pkl files are in the models/ folder.</div>'
|
| 200 |
-
return err_html, None, None, "", ""
|
| 201 |
-
|
| 202 |
-
cycle_code = 2 if cycle == "Irregular" else 4
|
| 203 |
-
whr = round(waist / max(hip, 1), 3)
|
| 204 |
-
|
| 205 |
-
inp = {
|
| 206 |
-
"Age__yrs_": age, "BMI": bmi, "Weight__Kg_": weight,
|
| 207 |
-
"Hb__g_dl_": hb, "Pulse_rate_bpm_": pulse, "RR__breaths_min_": rr,
|
| 208 |
-
"FSH_mIU_mL_": fsh, "LH_mIU_mL_": lh,
|
| 209 |
-
"FSH_LH": round(fsh / max(lh, 0.01), 3),
|
| 210 |
-
"AMH_ng_mL_": amh, "PRG_ng_mL_": prg, "PRL_ng_mL_": prl,
|
| 211 |
-
"TSH__mIU_L_": tsh, "Vit_D3__ng_mL_": vitd3, "RBS_mg_dl_": rbs,
|
| 212 |
-
"Waist_inch_": waist, "Hip_inch_": hip, "Waist_Hip_Ratio": whr,
|
| 213 |
-
"BP__Systolic__mmHg_": bp_sys, "BP__Diastolic__mmHg_": bp_dia,
|
| 214 |
-
"Follicle_No___L_": foll_l, "Follicle_No___R_": foll_r,
|
| 215 |
-
"Avg_F_size__L__mm_": avg_fl, "Avg_F_size__R__mm_": avg_fr,
|
| 216 |
-
"Endometrium__mm_": endo, "Cycle_R_I_": cycle_code,
|
| 217 |
-
"Cycle_length_days_": cycle_len,
|
| 218 |
-
"Weight_gain_Y_N_": int(wt_gain), "hair_growth_Y_N_": int(hair_growth),
|
| 219 |
-
"Skin_darkening__Y_N_": int(skin_dark), "Hair_loss_Y_N_": int(hair_loss),
|
| 220 |
-
"Pimples_Y_N_": int(pimples), "Fast_food__Y_N_": int(fast_food),
|
| 221 |
-
"Reg_Exercise_Y_N_": int(exercise),
|
| 222 |
-
# Engineered features
|
| 223 |
-
"FSH_LH_Ratio": round(fsh / max(lh, 0.01), 4),
|
| 224 |
-
"Total_Follicles": foll_l + foll_r,
|
| 225 |
-
"AMH_FSH_Ratio": round(amh / max(fsh, 0.01), 4),
|
| 226 |
-
"BMI_Waist_Ratio": round(bmi / max(waist, 1), 4),
|
| 227 |
-
"Androgenic_Score": int(hair_growth) + int(skin_dark) + int(hair_loss) + int(pimples),
|
| 228 |
-
}
|
| 229 |
|
|
|
|
|
|
|
| 230 |
try:
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
except Exception as e:
|
| 233 |
-
|
| 234 |
-
return
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
<div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
|
| 299 |
-
<div style="font-size:1.1rem;font-weight:700;color:{tcol}">{ticon} {itier} Infertility Risk</div>
|
| 300 |
-
<div style="font-size:2.2rem;font-weight:700;color:{tcol};margin:8px 0">{iscore:.0%}</div>
|
| 301 |
-
<div style="font-size:.85rem;color:#6b7280;margin-bottom:14px">Based on AMH Β· FSH Β· Follicles Β· Cycle Β· BMI</div>
|
| 302 |
-
{''.join(f'<div style="font-size:.85rem;margin:5px 0;color:#374151">{n}</div>' for n in notes)}
|
| 303 |
-
</div>"""
|
| 304 |
-
|
| 305 |
-
# ββ Clinical recommendations βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 306 |
-
recs = []
|
| 307 |
-
if pred:
|
| 308 |
-
recs += [
|
| 309 |
-
"β
Confirm PCOS with transvaginal ultrasound",
|
| 310 |
-
"β
Full hormonal panel: FSH, LH, AMH, testosterone, DHEAS",
|
| 311 |
-
"β
Metabolic screen: fasting glucose, insulin, HbA1c, lipid profile",
|
| 312 |
-
]
|
| 313 |
-
if cycle == "Irregular":
|
| 314 |
-
recs.append("β
Discuss cycle regulation β OCP or progesterone cycling")
|
| 315 |
-
if bmi > 25:
|
| 316 |
-
recs.append("β
Lifestyle: 5β10% weight loss can restore ovulation")
|
| 317 |
-
if bmi > 30:
|
| 318 |
-
recs.append("β
Consider metformin for insulin sensitisation")
|
| 319 |
-
else:
|
| 320 |
-
recs += [
|
| 321 |
-
"β
PCOS unlikely β routine annual review recommended",
|
| 322 |
-
"β
Maintain healthy BMI and regular exercise",
|
| 323 |
-
]
|
| 324 |
-
if itier == "High":
|
| 325 |
-
recs.append("π΄ Fertility specialist referral recommended β high infertility risk (>60%)")
|
| 326 |
-
elif itier == "Moderate":
|
| 327 |
-
recs.append("π‘ Consider fertility evaluation if conception not achieved in 6β12 months")
|
| 328 |
-
|
| 329 |
-
rec_html = f"""
|
| 330 |
-
<div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
|
| 331 |
-
<div style="font-size:1rem;font-weight:700;color:#374151;margin-bottom:12px">π Clinical Recommendations</div>
|
| 332 |
-
{''.join(f'<div style="font-size:.88rem;margin:7px 0;color:#374151">{r}</div>' for r in recs)}
|
| 333 |
-
<div style="margin-top:16px;font-size:.72rem;color:#9ca3af;border-top:1px solid #e5e7eb;padding-top:10px">
|
| 334 |
-
βοΈ For clinical decision support only. Results must be interpreted by a qualified healthcare provider.
|
| 335 |
-
</div>
|
| 336 |
-
</div>"""
|
| 337 |
-
|
| 338 |
-
radar_fig = make_radar(sev)
|
| 339 |
-
base_fig = make_base_bar(base_probs, mdl["threshold"])
|
| 340 |
-
|
| 341 |
-
return result_html, radar_fig, base_fig, inf_html, rec_html
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
# ββ Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
css = """
|
| 346 |
-
|
| 347 |
-
.
|
|
|
|
|
|
|
| 348 |
"""
|
| 349 |
|
| 350 |
-
with gr.Blocks(
|
| 351 |
-
|
| 352 |
-
gr.
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
gr.
|
| 412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
gr.Markdown("""
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
fn=run_analysis,
|
| 442 |
-
inputs=all_inputs,
|
| 443 |
-
outputs=[result_out, radar_out, base_out, inf_out, rec_out],
|
| 444 |
-
)
|
| 445 |
-
|
| 446 |
-
if __name__ == "__main__":
|
| 447 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import warnings
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
| 6 |
+
import joblib
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torchvision import models, transforms
|
| 10 |
+
from PIL import Image
|
| 11 |
import matplotlib
|
| 12 |
matplotlib.use("Agg")
|
| 13 |
import matplotlib.pyplot as plt
|
| 14 |
+
import matplotlib.cm as cm
|
| 15 |
import gradio as gr
|
| 16 |
+
|
| 17 |
warnings.filterwarnings("ignore")
|
| 18 |
|
| 19 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
# CONFIG
|
| 21 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
MODELS_DIR = "models"
|
| 23 |
+
IMG_SIZE = 224
|
| 24 |
+
DEVICE = torch.device("cpu")
|
| 25 |
+
|
| 26 |
DOMAIN_WEIGHTS = {
|
| 27 |
+
"METABOLIC" : 0.35,
|
| 28 |
+
"REPRODUCTIVE" : 0.40,
|
| 29 |
"HYPERANDROGENIC": 0.20,
|
| 30 |
+
"GENERAL" : 0.05,
|
| 31 |
}
|
| 32 |
|
| 33 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
# UTILITIES (mirror pipeline exactly)
|
| 35 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
+
def clean_name(name: str) -> str:
|
| 37 |
+
return re.sub(r"[^0-9a-zA-Z_]", "_", name.strip())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
def clean_df_cols(df: pd.DataFrame) -> pd.DataFrame:
|
| 40 |
+
df = df.copy()
|
| 41 |
+
df.columns = [clean_name(c) for c in df.columns]
|
| 42 |
+
return df
|
| 43 |
|
| 44 |
+
def apply_severity(domain_models, stats, X_sc: pd.DataFrame) -> pd.DataFrame:
|
|
|
|
| 45 |
df = pd.DataFrame(index=X_sc.index)
|
| 46 |
for d, (model, fc) in domain_models.items():
|
| 47 |
avail = [f for f in fc if f in X_sc.columns]
|
|
|
|
| 49 |
df[f"{d}_SEV"] = 0.0
|
| 50 |
continue
|
| 51 |
p = model.predict_proba(X_sc[avail])[:, 1]
|
| 52 |
+
mn = stats[d]["min"]
|
| 53 |
+
mx = stats[d]["max"]
|
| 54 |
+
df[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
|
| 55 |
df = df.fillna(0)
|
| 56 |
df["OVERALL_SEV"] = sum(
|
| 57 |
df[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
|
|
|
|
| 59 |
)
|
| 60 |
return df
|
| 61 |
|
| 62 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
# LOAD TABULAR MODELS
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
def load_tabular_models():
|
| 66 |
+
try:
|
| 67 |
+
meta_model = joblib.load(f"{MODELS_DIR}/ensemble_meta.pkl")
|
| 68 |
+
base_models = joblib.load(f"{MODELS_DIR}/base_models.pkl")
|
| 69 |
+
domain_models = joblib.load(f"{MODELS_DIR}/domain_models.pkl")
|
| 70 |
+
train_stats = joblib.load(f"{MODELS_DIR}/train_stats.pkl")
|
| 71 |
+
mice_imputer = joblib.load(f"{MODELS_DIR}/mice_imputer.pkl")
|
| 72 |
+
scaler = joblib.load(f"{MODELS_DIR}/scaler.pkl")
|
| 73 |
+
feature_cols = joblib.load(f"{MODELS_DIR}/feature_columns.pkl")
|
| 74 |
+
best_threshold= joblib.load(f"{MODELS_DIR}/best_threshold.pkl")
|
| 75 |
+
print("β
Tabular models loaded")
|
| 76 |
+
return meta_model, base_models, domain_models, train_stats, \
|
| 77 |
+
mice_imputer, scaler, feature_cols, best_threshold
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"β Tabular model load error: {e}")
|
| 80 |
+
return None, None, None, None, None, None, None, None
|
| 81 |
+
|
| 82 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
+
# LOAD IMAGE MODEL
|
| 84 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 85 |
+
def load_image_model():
|
| 86 |
+
pth_path = f"{MODELS_DIR}/efficientnetb0.pth"
|
| 87 |
+
if not os.path.exists(pth_path):
|
| 88 |
+
print(f"β Image model not found at {pth_path}")
|
| 89 |
+
return None
|
| 90 |
+
try:
|
| 91 |
+
model = models.efficientnet_b0(weights=None)
|
| 92 |
+
in_features = model.classifier[1].in_features
|
| 93 |
+
model.classifier[1] = nn.Linear(in_features, 2)
|
| 94 |
+
state = torch.load(pth_path, map_location=DEVICE)
|
| 95 |
+
# Handle various checkpoint formats
|
| 96 |
+
if isinstance(state, dict) and "model_state_dict" in state:
|
| 97 |
+
state = state["model_state_dict"]
|
| 98 |
+
elif isinstance(state, dict) and "state_dict" in state:
|
| 99 |
+
state = state["state_dict"]
|
| 100 |
+
model.load_state_dict(state)
|
| 101 |
+
model.eval()
|
| 102 |
+
print("β
Image model loaded")
|
| 103 |
+
return model
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"β Image model load error: {e}")
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 109 |
+
# GLOBAL MODEL LOADING
|
| 110 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 111 |
+
(META_MODEL, BASE_MODELS, DOMAIN_MODELS, TRAIN_STATS,
|
| 112 |
+
MICE_IMPUTER, SCALER, FEATURE_COLS, BEST_THRESHOLD) = load_tabular_models()
|
| 113 |
+
|
| 114 |
+
IMAGE_MODEL = load_image_model()
|
| 115 |
+
|
| 116 |
+
# Image preprocessing (val transform β no augmentation)
|
| 117 |
+
IMG_TRANSFORM = transforms.Compose([
|
| 118 |
+
transforms.Resize((IMG_SIZE, IMG_SIZE)),
|
| 119 |
+
transforms.ToTensor(),
|
| 120 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 121 |
+
std =[0.229, 0.224, 0.225]),
|
| 122 |
+
])
|
| 123 |
+
|
| 124 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 125 |
+
# CLINICAL PREDICTION
|
| 126 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 127 |
+
def predict_clinical(
|
| 128 |
+
age, bmi, weight, waist, hip, cycle, cycle_len,
|
| 129 |
+
fsh, lh, amh, prg, prl, tsh, vit_d3,
|
| 130 |
+
follicle_l, follicle_r, endometrium, rbs,
|
| 131 |
+
bp_sys, bp_dia,
|
| 132 |
+
weight_gain, hair_growth, skin_dark, hair_loss, pimples,
|
| 133 |
+
fast_food, exercise, hb, pulse, rr
|
| 134 |
+
):
|
| 135 |
+
if META_MODEL is None:
|
| 136 |
+
return "β Tabular models not loaded.", None, None
|
| 137 |
|
| 138 |
+
try:
|
| 139 |
+
# Build raw input matching pipeline column names (before clean_df_cols)
|
| 140 |
+
raw = {
|
| 141 |
+
"Age (yrs)" : age,
|
| 142 |
+
"BMI" : bmi,
|
| 143 |
+
"Weight (Kg)" : weight,
|
| 144 |
+
"Waist(inch)" : waist,
|
| 145 |
+
"Hip(inch)" : hip,
|
| 146 |
+
"Cycle(R/I)" : 1 if cycle == "Irregular" else 0,
|
| 147 |
+
"Cycle length(days)" : cycle_len,
|
| 148 |
+
"FSH(mIU/mL)" : fsh,
|
| 149 |
+
"LH(mIU/mL)" : lh,
|
| 150 |
+
"AMH(ng/mL)" : amh,
|
| 151 |
+
"PRG(ng/mL)" : prg,
|
| 152 |
+
"PRL(ng/mL)" : prl,
|
| 153 |
+
"TSH (mIU/L)" : tsh,
|
| 154 |
+
"Vit D3 (ng/mL)" : vit_d3,
|
| 155 |
+
"Follicle No. (L)" : follicle_l,
|
| 156 |
+
"Follicle No. (R)" : follicle_r,
|
| 157 |
+
"Endometrium (mm)" : endometrium,
|
| 158 |
+
"RBS(mg/dl)" : rbs,
|
| 159 |
+
"BP _Systolic (mmHg)" : bp_sys,
|
| 160 |
+
"BP _Diastolic (mmHg)" : bp_dia,
|
| 161 |
+
"Weight gain(Y/N)" : int(weight_gain),
|
| 162 |
+
"hair growth(Y/N)" : int(hair_growth),
|
| 163 |
+
"Skin darkening (Y/N)" : int(skin_dark),
|
| 164 |
+
"Hair loss(Y/N)" : int(hair_loss),
|
| 165 |
+
"Pimples(Y/N)" : int(pimples),
|
| 166 |
+
"Fast food (Y/N)" : int(fast_food),
|
| 167 |
+
"Reg.Exercise(Y/N)" : int(exercise),
|
| 168 |
+
"Hb(g/dl)" : hb,
|
| 169 |
+
"Pulse rate(bpm)" : pulse,
|
| 170 |
+
"RR (breaths/min)" : rr,
|
| 171 |
+
# Derived features (matching load_and_engineer)
|
| 172 |
+
"FSH/LH" : fsh / (lh + 1e-6),
|
| 173 |
+
"Waist:Hip Ratio" : waist / (hip + 1e-6),
|
| 174 |
+
"FSH_LH_Ratio" : fsh / (lh + 1e-6),
|
| 175 |
+
"Total_Follicles" : follicle_l + follicle_r,
|
| 176 |
+
"AMH_FSH_Ratio" : amh / (fsh + 1e-6),
|
| 177 |
+
"BMI_Waist_Ratio" : bmi / (waist + 1e-6),
|
| 178 |
+
"Androgenic_Score" : int(hair_growth) + int(skin_dark) + int(hair_loss) + int(pimples),
|
| 179 |
+
# Avg follicle sizes β user doesn't provide so use 0 (MICE will impute)
|
| 180 |
+
"Avg. F size (L) (mm)" : np.nan,
|
| 181 |
+
"Avg. F size (R) (mm)" : np.nan,
|
| 182 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
+
df_raw = pd.DataFrame([raw])
|
| 185 |
+
df_clean = clean_df_cols(df_raw)
|
| 186 |
+
|
| 187 |
+
# ββ Separate base features from SEV columns ββββββββββββββ
|
| 188 |
+
# feature_cols = base_scaled_cols + SEV cols (as saved by pipeline)
|
| 189 |
+
sev_col_names = [c for c in FEATURE_COLS if c.endswith("_SEV")]
|
| 190 |
+
base_fc = [c for c in FEATURE_COLS if not c.endswith("_SEV")]
|
| 191 |
+
|
| 192 |
+
# Align to base_fc (only columns the MICE+scaler were fitted on)
|
| 193 |
+
X_base = pd.DataFrame(columns=base_fc)
|
| 194 |
+
for col in base_fc:
|
| 195 |
+
X_base[col] = df_clean[col].values if col in df_clean.columns else np.nan
|
| 196 |
+
|
| 197 |
+
X_base = X_base.astype(float)
|
| 198 |
+
|
| 199 |
+
# ββ MICE imputation (never refit) ββββββββββββββββββββββββββ
|
| 200 |
+
X_imp = pd.DataFrame(
|
| 201 |
+
MICE_IMPUTER.transform(X_base),
|
| 202 |
+
columns=base_fc
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# ββ Scaling (never refit) ββββββββββββββββββββββββββββββββββ
|
| 206 |
+
num_cols = X_imp.select_dtypes(include=np.number).columns
|
| 207 |
+
X_sc = X_imp.copy()
|
| 208 |
+
X_sc[num_cols] = SCALER.transform(X_imp[num_cols])
|
| 209 |
+
|
| 210 |
+
# ββ Domain severity βββββββββββββββββββββββββββββββββββββββββ
|
| 211 |
+
# Pass X_raw (unscaled, raw index) and X_sc to apply_severity
|
| 212 |
+
sev_df = apply_severity(DOMAIN_MODELS, TRAIN_STATS, X_sc)
|
| 213 |
+
|
| 214 |
+
# ββ Concat and reindex to exact feature_cols order ββββββββββ
|
| 215 |
+
X_final = pd.concat([X_sc, sev_df], axis=1)
|
| 216 |
+
# Add any missing SEV columns as 0
|
| 217 |
+
for col in FEATURE_COLS:
|
| 218 |
+
if col not in X_final.columns:
|
| 219 |
+
X_final[col] = 0.0
|
| 220 |
+
X_final = X_final[FEATURE_COLS]
|
| 221 |
+
|
| 222 |
+
# ββ Base model predictions βββββββββββββββββββββββββββββββββββ
|
| 223 |
+
meta_input = pd.DataFrame()
|
| 224 |
+
for name, model in BASE_MODELS.items():
|
| 225 |
+
meta_input[name] = model.predict_proba(X_final)[:, 1]
|
| 226 |
+
|
| 227 |
+
# ββ Ensemble prediction ββββββββββββββββββββββββββββββββββββββ
|
| 228 |
+
prob = float(META_MODEL.predict_proba(meta_input)[:, 1][0])
|
| 229 |
+
pred = int(prob >= BEST_THRESHOLD)
|
| 230 |
+
label = "π΄ PCOS Detected" if pred == 1 else "π’ No PCOS"
|
| 231 |
+
|
| 232 |
+
# ββ Risk tier ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 233 |
+
if prob < 0.33:
|
| 234 |
+
risk = "Low Risk"
|
| 235 |
+
elif prob < 0.66:
|
| 236 |
+
risk = "Moderate Risk"
|
| 237 |
+
else:
|
| 238 |
+
risk = "High Risk"
|
| 239 |
+
|
| 240 |
+
# ββ Severity scores ββββββββββββββββββββββββββββββββββββββββββ
|
| 241 |
+
sev_vals = {
|
| 242 |
+
"Metabolic" : float(sev_df.get("METABOLIC_SEV", pd.Series([0])).iloc[0]),
|
| 243 |
+
"Reproductive" : float(sev_df.get("REPRODUCTIVE_SEV", pd.Series([0])).iloc[0]),
|
| 244 |
+
"Hyperandrogenic": float(sev_df.get("HYPERANDROGENIC_SEV", pd.Series([0])).iloc[0]),
|
| 245 |
+
"General" : float(sev_df.get("GENERAL_SEV", pd.Series([0])).iloc[0]),
|
| 246 |
+
}
|
| 247 |
|
| 248 |
+
result_text = (
|
| 249 |
+
f"**Diagnosis: {label}**\n\n"
|
| 250 |
+
f"PCOS Probability: **{prob*100:.1f}%**\n"
|
| 251 |
+
f"Risk Level: **{risk}**\n"
|
| 252 |
+
f"Threshold used: {BEST_THRESHOLD:.4f}\n\n"
|
| 253 |
+
f"**Domain Severity Scores:**\n"
|
| 254 |
+
+ "\n".join(f"- {k}: {v*100:.1f}%" for k, v in sev_vals.items())
|
| 255 |
+
+ f"\n- Overall: {float(sev_df.get('OVERALL_SEV', pd.Series([0])).iloc[0])*100:.1f}%"
|
| 256 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
# ββ Radar chart βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 259 |
+
radar_fig = make_radar_chart(sev_vals, prob)
|
| 260 |
|
| 261 |
+
# ββ Bar chart βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 262 |
+
bar_fig = make_bar_chart(meta_input.iloc[0].to_dict(), prob)
|
| 263 |
+
|
| 264 |
+
return result_text, radar_fig, bar_fig
|
| 265 |
+
|
| 266 |
+
except Exception as e:
|
| 267 |
+
import traceback
|
| 268 |
+
return f"β Prediction error: {e}\n\n{traceback.format_exc()}", None, None
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 272 |
+
# IMAGE PREDICTION
|
| 273 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 274 |
+
def predict_image(image):
|
| 275 |
+
if IMAGE_MODEL is None:
|
| 276 |
+
return "β Image model not loaded.", None
|
| 277 |
+
|
| 278 |
+
if image is None:
|
| 279 |
+
return "β οΈ Please upload an ultrasound image.", None
|
| 280 |
+
|
| 281 |
+
try:
|
| 282 |
+
if not isinstance(image, Image.Image):
|
| 283 |
+
image = Image.fromarray(image)
|
| 284 |
+
image_rgb = image.convert("RGB")
|
| 285 |
+
|
| 286 |
+
tensor = IMG_TRANSFORM(image_rgb).unsqueeze(0).to(DEVICE)
|
| 287 |
+
|
| 288 |
+
# ββ Forward pass ββββββββββββββββββββββββββββββββββββββββββ
|
| 289 |
+
IMAGE_MODEL.eval()
|
| 290 |
+
with torch.no_grad():
|
| 291 |
+
logits = IMAGE_MODEL(tensor)
|
| 292 |
+
probs = torch.softmax(logits, dim=1)
|
| 293 |
+
pcos_prob = float(probs[0, 1])
|
| 294 |
+
pred = int(pcos_prob >= 0.5)
|
| 295 |
+
|
| 296 |
+
label = "π΄ PCOS Detected" if pred == 1 else "π’ No PCOS"
|
| 297 |
+
confidence = pcos_prob if pred == 1 else (1 - pcos_prob)
|
| 298 |
+
|
| 299 |
+
if pcos_prob < 0.33:
|
| 300 |
+
risk = "Low Risk"
|
| 301 |
+
elif pcos_prob < 0.66:
|
| 302 |
+
risk = "Moderate Risk"
|
| 303 |
+
else:
|
| 304 |
+
risk = "High Risk"
|
| 305 |
+
|
| 306 |
+
result_text = (
|
| 307 |
+
f"**Diagnosis: {label}**\n\n"
|
| 308 |
+
f"PCOS Probability: **{pcos_prob*100:.1f}%**\n"
|
| 309 |
+
f"Non-PCOS Probability: **{(1-pcos_prob)*100:.1f}%**\n"
|
| 310 |
+
f"Confidence: **{confidence*100:.1f}%**\n"
|
| 311 |
+
f"Risk Level: **{risk}**\n\n"
|
| 312 |
+
f"*Model: EfficientNetB0 (ImageNet pretrained, fine-tuned on PCOS dataset)*"
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
# ββ Grad-CAM ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 316 |
+
gradcam_fig = compute_gradcam(image_rgb, tensor, pcos_prob)
|
| 317 |
+
|
| 318 |
+
return result_text, gradcam_fig
|
| 319 |
|
| 320 |
+
except Exception as e:
|
| 321 |
+
import traceback
|
| 322 |
+
return f"β Image prediction error: {e}\n\n{traceback.format_exc()}", None
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
+
def compute_gradcam(orig_img, tensor, prob):
|
| 326 |
+
"""Grad-CAM on EfficientNetB0 features layer."""
|
| 327 |
try:
|
| 328 |
+
gradients = []
|
| 329 |
+
activations = []
|
| 330 |
+
|
| 331 |
+
def save_gradient(grad):
|
| 332 |
+
gradients.append(grad)
|
| 333 |
+
|
| 334 |
+
# Hook on the last conv layer of EfficientNetB0 features
|
| 335 |
+
target_layer = IMAGE_MODEL.features[-1]
|
| 336 |
+
|
| 337 |
+
def forward_hook(module, input, output):
|
| 338 |
+
activations.append(output)
|
| 339 |
+
output.register_hook(save_gradient)
|
| 340 |
+
|
| 341 |
+
handle = target_layer.register_forward_hook(forward_hook)
|
| 342 |
+
|
| 343 |
+
IMAGE_MODEL.eval()
|
| 344 |
+
output = IMAGE_MODEL(tensor)
|
| 345 |
+
IMAGE_MODEL.zero_grad()
|
| 346 |
+
class_score = output[0, 1]
|
| 347 |
+
class_score.backward()
|
| 348 |
+
|
| 349 |
+
handle.remove()
|
| 350 |
+
|
| 351 |
+
if not gradients or not activations:
|
| 352 |
+
return None
|
| 353 |
+
|
| 354 |
+
grad = gradients[0].squeeze(0).cpu().numpy() # (C, H, W)
|
| 355 |
+
act = activations[0].squeeze(0).cpu().detach().numpy()
|
| 356 |
+
|
| 357 |
+
weights = grad.mean(axis=(1, 2)) # (C,)
|
| 358 |
+
cam = np.zeros(act.shape[1:], dtype=np.float32)
|
| 359 |
+
for i, w in enumerate(weights):
|
| 360 |
+
cam += w * act[i]
|
| 361 |
+
|
| 362 |
+
cam = np.maximum(cam, 0)
|
| 363 |
+
if cam.max() > 0:
|
| 364 |
+
cam = cam / cam.max()
|
| 365 |
+
|
| 366 |
+
# Resize cam to image size
|
| 367 |
+
from PIL import Image as PILImage
|
| 368 |
+
cam_img = PILImage.fromarray((cam * 255).astype(np.uint8)).resize(
|
| 369 |
+
(IMG_SIZE, IMG_SIZE), PILImage.BILINEAR
|
| 370 |
+
)
|
| 371 |
+
cam_np = np.array(cam_img) / 255.0
|
| 372 |
+
|
| 373 |
+
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
|
| 374 |
+
orig_resized = orig_img.resize((IMG_SIZE, IMG_SIZE))
|
| 375 |
+
|
| 376 |
+
axes[0].imshow(orig_resized)
|
| 377 |
+
axes[0].set_title("Original", fontsize=12)
|
| 378 |
+
axes[0].axis("off")
|
| 379 |
+
|
| 380 |
+
axes[1].imshow(cam_np, cmap="jet")
|
| 381 |
+
axes[1].set_title("Grad-CAM Heatmap", fontsize=12)
|
| 382 |
+
axes[1].axis("off")
|
| 383 |
+
|
| 384 |
+
heatmap = cm.jet(cam_np)[:, :, :3]
|
| 385 |
+
overlay = 0.55 * np.array(orig_resized) / 255.0 + 0.45 * heatmap
|
| 386 |
+
overlay = np.clip(overlay, 0, 1)
|
| 387 |
+
axes[2].imshow(overlay)
|
| 388 |
+
axes[2].set_title(f"Overlay (PCOS: {prob*100:.1f}%)", fontsize=12)
|
| 389 |
+
axes[2].axis("off")
|
| 390 |
+
|
| 391 |
+
plt.suptitle("EfficientNetB0 β Grad-CAM Visualization", fontsize=13, fontweight="bold")
|
| 392 |
+
plt.tight_layout()
|
| 393 |
+
return fig
|
| 394 |
+
|
| 395 |
except Exception as e:
|
| 396 |
+
print(f"Grad-CAM error: {e}")
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 401 |
+
# CHART HELPERS
|
| 402 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 403 |
+
def make_radar_chart(sev_vals: dict, overall_prob: float):
|
| 404 |
+
domains = list(sev_vals.keys())
|
| 405 |
+
values = [sev_vals[d] for d in domains]
|
| 406 |
+
N = len(domains)
|
| 407 |
+
angles = [n / float(N) * 2 * np.pi for n in range(N)]
|
| 408 |
+
angles += angles[:1]
|
| 409 |
+
values_plot = values + values[:1]
|
| 410 |
+
|
| 411 |
+
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
|
| 412 |
+
ax.set_facecolor("#0e1117")
|
| 413 |
+
fig.patch.set_facecolor("#0e1117")
|
| 414 |
+
|
| 415 |
+
ax.plot(angles, values_plot, "o-", linewidth=2, color="#e040fb")
|
| 416 |
+
ax.fill(angles, values_plot, alpha=0.3, color="#e040fb")
|
| 417 |
+
ax.set_xticks(angles[:-1])
|
| 418 |
+
ax.set_xticklabels(domains, color="white", fontsize=10)
|
| 419 |
+
ax.set_ylim(0, 1)
|
| 420 |
+
ax.set_yticks([0.25, 0.5, 0.75, 1.0])
|
| 421 |
+
ax.set_yticklabels(["25%", "50%", "75%", "100%"], color="gray", fontsize=7)
|
| 422 |
+
ax.tick_params(colors="white")
|
| 423 |
+
ax.spines["polar"].set_color("gray")
|
| 424 |
+
ax.grid(color="gray", alpha=0.3)
|
| 425 |
+
ax.set_title(f"Domain Severity (Overall: {overall_prob*100:.1f}%)",
|
| 426 |
+
color="white", fontsize=11, pad=15)
|
| 427 |
+
return fig
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def make_bar_chart(base_probs: dict, ensemble_prob: float):
|
| 431 |
+
models_list = list(base_probs.keys()) + ["Ensemble"]
|
| 432 |
+
probs_list = list(base_probs.values()) + [ensemble_prob]
|
| 433 |
+
colors = ["#42a5f5", "#42a5f5", "#42a5f5", "#42a5f5", "#e040fb"]
|
| 434 |
+
if len(models_list) != len(colors):
|
| 435 |
+
colors = ["#42a5f5"] * (len(models_list) - 1) + ["#e040fb"]
|
| 436 |
+
|
| 437 |
+
fig, ax = plt.subplots(figsize=(6, 3.5))
|
| 438 |
+
ax.set_facecolor("#0e1117")
|
| 439 |
+
fig.patch.set_facecolor("#0e1117")
|
| 440 |
+
|
| 441 |
+
bars = ax.barh(models_list, probs_list, color=colors[:len(models_list)], height=0.5)
|
| 442 |
+
ax.axvline(x=0.5, color="white", linestyle="--", alpha=0.5, linewidth=1)
|
| 443 |
+
ax.set_xlim(0, 1)
|
| 444 |
+
ax.set_xlabel("PCOS Probability", color="white", fontsize=10)
|
| 445 |
+
ax.set_title("Model Predictions", color="white", fontsize=11)
|
| 446 |
+
ax.tick_params(colors="white")
|
| 447 |
+
ax.spines["bottom"].set_color("gray")
|
| 448 |
+
ax.spines["left"].set_color("gray")
|
| 449 |
+
ax.spines["top"].set_visible(False)
|
| 450 |
+
ax.spines["right"].set_visible(False)
|
| 451 |
+
for bar, prob in zip(bars, probs_list):
|
| 452 |
+
ax.text(min(prob + 0.02, 0.95), bar.get_y() + bar.get_height() / 2,
|
| 453 |
+
f"{prob*100:.1f}%", va="center", color="white", fontsize=9)
|
| 454 |
+
plt.tight_layout()
|
| 455 |
+
return fig
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 459 |
+
# GRADIO UI
|
| 460 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
css = """
|
| 462 |
+
body { background: #0e1117; }
|
| 463 |
+
.gradio-container { font-family: 'Inter', sans-serif; }
|
| 464 |
+
.tab-nav button { font-size: 15px; font-weight: 600; }
|
| 465 |
+
h1 { text-align: center; }
|
| 466 |
"""
|
| 467 |
|
| 468 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple"), css=css, title="PCOS Detection") as demo:
|
| 469 |
+
|
| 470 |
+
gr.Markdown("""
|
| 471 |
+
# π©Ί PCOS Detection System
|
| 472 |
+
**AI-powered Polycystic Ovary Syndrome detection using clinical features and ultrasound images**
|
| 473 |
+
> β οΈ For research/educational purposes only. Not a substitute for professional medical advice.
|
| 474 |
+
""")
|
| 475 |
+
|
| 476 |
+
with gr.Tabs():
|
| 477 |
+
|
| 478 |
+
# ββ TAB 1: CLINICAL ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 479 |
+
with gr.TabItem("π¬ Clinical Feature Analysis"):
|
| 480 |
+
gr.Markdown("### Enter Patient Clinical Data")
|
| 481 |
+
|
| 482 |
+
with gr.Row():
|
| 483 |
+
with gr.Column(scale=1):
|
| 484 |
+
gr.Markdown("#### π Anthropometric")
|
| 485 |
+
age = gr.Slider(18, 50, value=28, step=1, label="Age (yrs)")
|
| 486 |
+
bmi = gr.Slider(15.0, 50.0, value=24.0, step=0.1, label="BMI (kg/mΒ²)")
|
| 487 |
+
weight = gr.Slider(30.0, 130.0, value=60.0, step=0.5, label="Weight (Kg)")
|
| 488 |
+
waist = gr.Slider(20.0, 60.0, value=32.0, step=0.5, label="Waist (inch)")
|
| 489 |
+
hip = gr.Slider(25.0, 70.0, value=38.0, step=0.5, label="Hip (inch)")
|
| 490 |
+
|
| 491 |
+
gr.Markdown("#### π©Έ Vitals")
|
| 492 |
+
bp_sys = gr.Slider(80, 180, value=120, step=1, label="BP Systolic (mmHg)")
|
| 493 |
+
bp_dia = gr.Slider(50, 120, value=80, step=1, label="BP Diastolic (mmHg)")
|
| 494 |
+
pulse = gr.Slider(50, 120, value=72, step=1, label="Pulse Rate (bpm)")
|
| 495 |
+
rr = gr.Slider(10, 30, value=18, step=1, label="RR (breaths/min)")
|
| 496 |
+
hb = gr.Slider(7.0, 18.0, value=12.5, step=0.1, label="Hb (g/dl)")
|
| 497 |
+
rbs = gr.Slider(60.0, 300.0, value=95.0, step=1.0, label="RBS (mg/dl)")
|
| 498 |
+
|
| 499 |
+
with gr.Column(scale=1):
|
| 500 |
+
gr.Markdown("#### π¬ Hormones")
|
| 501 |
+
fsh = gr.Slider(0.0, 30.0, value=6.0, step=0.1, label="FSH (mIU/mL)")
|
| 502 |
+
lh = gr.Slider(0.0, 50.0, value=8.0, step=0.1, label="LH (mIU/mL)")
|
| 503 |
+
amh = gr.Slider(0.0, 20.0, value=3.5, step=0.1, label="AMH (ng/mL)")
|
| 504 |
+
prg = gr.Slider(0.0, 30.0, value=0.8, step=0.1, label="Progesterone (ng/mL)")
|
| 505 |
+
prl = gr.Slider(0.0, 100.0, value=15.0, step=0.5, label="Prolactin (ng/mL)")
|
| 506 |
+
tsh = gr.Slider(0.0, 10.0, value=2.5, step=0.1, label="TSH (mIU/L)")
|
| 507 |
+
vit_d3 = gr.Slider(0.0, 100.0, value=25.0, step=0.5, label="Vit D3 (ng/mL)")
|
| 508 |
+
|
| 509 |
+
gr.Markdown("#### π Cycle & Follicles")
|
| 510 |
+
cycle = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle Type")
|
| 511 |
+
cycle_len = gr.Slider(21, 45, value=28, step=1, label="Cycle Length (days)")
|
| 512 |
+
follicle_l = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Left)")
|
| 513 |
+
follicle_r = gr.Slider(0, 25, value=5, step=1, label="Follicle No. (Right)")
|
| 514 |
+
endometrium= gr.Slider(3.0, 20.0, value=8.0, step=0.1, label="Endometrium (mm)")
|
| 515 |
+
|
| 516 |
+
with gr.Column(scale=1):
|
| 517 |
+
gr.Markdown("#### 𧬠Symptoms (Yes/No)")
|
| 518 |
+
weight_gain = gr.Checkbox(label="Weight Gain")
|
| 519 |
+
hair_growth = gr.Checkbox(label="Excess Hair Growth")
|
| 520 |
+
skin_dark = gr.Checkbox(label="Skin Darkening")
|
| 521 |
+
hair_loss = gr.Checkbox(label="Hair Loss")
|
| 522 |
+
pimples = gr.Checkbox(label="Pimples / Acne")
|
| 523 |
+
fast_food = gr.Checkbox(label="Fast Food Consumption")
|
| 524 |
+
exercise = gr.Checkbox(label="Regular Exercise", value=True)
|
| 525 |
+
|
| 526 |
+
gr.Markdown("---")
|
| 527 |
+
clinical_btn = gr.Button("π Predict PCOS", variant="primary", size="lg")
|
| 528 |
+
|
| 529 |
+
with gr.Row():
|
| 530 |
+
clinical_result = gr.Markdown(label="Diagnosis Result")
|
| 531 |
+
|
| 532 |
+
with gr.Row():
|
| 533 |
+
radar_plot = gr.Plot(label="Domain Severity Radar")
|
| 534 |
+
bar_plot = gr.Plot(label="Model Confidence")
|
| 535 |
+
|
| 536 |
+
clinical_btn.click(
|
| 537 |
+
fn=predict_clinical,
|
| 538 |
+
inputs=[
|
| 539 |
+
age, bmi, weight, waist, hip, cycle, cycle_len,
|
| 540 |
+
fsh, lh, amh, prg, prl, tsh, vit_d3,
|
| 541 |
+
follicle_l, follicle_r, endometrium, rbs,
|
| 542 |
+
bp_sys, bp_dia,
|
| 543 |
+
weight_gain, hair_growth, skin_dark, hair_loss, pimples,
|
| 544 |
+
fast_food, exercise, hb, pulse, rr
|
| 545 |
+
],
|
| 546 |
+
outputs=[clinical_result, radar_plot, bar_plot]
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# ββ TAB 2: IMAGE βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 550 |
+
with gr.TabItem("πΌοΈ Ultrasound Image Analysis"):
|
| 551 |
+
gr.Markdown("### Upload Ovarian Ultrasound Image")
|
| 552 |
+
|
| 553 |
+
with gr.Row():
|
| 554 |
+
with gr.Column(scale=1):
|
| 555 |
+
img_input = gr.Image(
|
| 556 |
+
label="Upload Ultrasound (PNG/JPG)",
|
| 557 |
+
type="pil",
|
| 558 |
+
height=300
|
| 559 |
+
)
|
| 560 |
+
image_btn = gr.Button("π Analyze Image", variant="primary", size="lg")
|
| 561 |
+
gr.Markdown("""
|
| 562 |
+
**Tips for best results:**
|
| 563 |
+
- Use clear ovarian ultrasound images
|
| 564 |
+
- PNG or JPG format
|
| 565 |
+
- Model: EfficientNetB0 fine-tuned on PCOS dataset
|
| 566 |
+
""")
|
| 567 |
+
|
| 568 |
+
with gr.Column(scale=2):
|
| 569 |
+
img_result = gr.Markdown(label="Image Analysis Result")
|
| 570 |
+
gradcam_plot = gr.Plot(label="Grad-CAM Visualization")
|
| 571 |
+
|
| 572 |
+
image_btn.click(
|
| 573 |
+
fn=predict_image,
|
| 574 |
+
inputs=[img_input],
|
| 575 |
+
outputs=[img_result, gradcam_plot]
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
# ββ TAB 3: INFO ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 579 |
+
with gr.TabItem("βΉοΈ About"):
|
| 580 |
gr.Markdown("""
|
| 581 |
+
## About This System
|
| 582 |
+
|
| 583 |
+
### π¬ Clinical Model
|
| 584 |
+
- **Pipeline:** MICE Imputation β RobustScaler β Domain Severity β Stacked Ensemble
|
| 585 |
+
- **Base Models:** Logistic Regression, Random Forest, Gradient Boosting, CatBoost
|
| 586 |
+
- **Meta-Learner:** CalibratedClassifierCV (LogisticRegressionCV, isotonic calibration)
|
| 587 |
+
- **Threshold:** Youden-J optimal threshold on test ROC
|
| 588 |
+
|
| 589 |
+
**Domain Severity Scoring:**
|
| 590 |
+
| Domain | Weight | Features |
|
| 591 |
+
|--------|--------|----------|
|
| 592 |
+
| Reproductive | 40% | FSH, LH, AMH, Follicles, Cycle |
|
| 593 |
+
| Metabolic | 35% | BMI, Weight, Waist, RBS, BP |
|
| 594 |
+
| Hyperandrogenic | 20% | Hair growth, Skin darkening, PRL |
|
| 595 |
+
| General | 5% | Age, Hb, TSH, Vit D3 |
|
| 596 |
+
|
| 597 |
+
### πΌοΈ Image Model
|
| 598 |
+
- **Architecture:** EfficientNetB0 (ImageNet pretrained, fine-tuned)
|
| 599 |
+
- **Input:** 224Γ224 RGB ultrasound images
|
| 600 |
+
- **Visualization:** Grad-CAM heatmaps showing attention regions
|
| 601 |
+
|
| 602 |
+
### β οΈ Disclaimer
|
| 603 |
+
This tool is for **research and educational purposes only**.
|
| 604 |
+
Always consult a qualified healthcare professional for medical decisions.
|
| 605 |
+
""")
|
| 606 |
+
|
| 607 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|