DheivaCodes's picture
Create app.py
f3974a4 verified
Raw History Blame Contribute Delete
41.8 kB
"""
PCOS Detection App β€” Enhanced Gradio UI (Hugging Face Spaces)
Dual Pipeline: PCOS Classification + Infertility Risk Scoring
Dataset: PCOS_data_without_infertility.xlsx (place in Space root)
"""
import os, re, copy, warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.gridspec import GridSpec
import gradio as gr
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.preprocessing import RobustScaler
from sklearn.experimental import enable_iterative_imputer # noqa
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import roc_auc_score, roc_curve
from catboost import CatBoostClassifier
# ─────────────────────────────────────────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────────────────────────────────────────
RANDOM_STATE = 42
TEST_SIZE = 0.2
CV_FOLDS = 5
DOMAIN_WEIGHTS = {
"METABOLIC" : 0.35,
"REPRODUCTIVE" : 0.40,
"HYPERANDROGENIC": 0.20,
"GENERAL" : 0.05,
}
FEATURE_GROUPS_BASE = {
"METABOLIC": [
"BMI", "Weight (Kg)", "Waist(inch)", "Hip(inch)",
"Waist:Hip Ratio", "RBS(mg/dl)", "Weight gain(Y/N)",
"BP _Systolic (mmHg)", "BP _Diastolic (mmHg)",
"Fast food (Y/N)", "Reg.Exercise(Y/N)",
],
"REPRODUCTIVE": [
"Cycle(R/I)", "Cycle length(days)",
"FSH(mIU/mL)", "LH(mIU/mL)", "FSH/LH",
"AMH(ng/mL)", "PRG(ng/mL)",
"Follicle No. (L)", "Follicle No. (R)",
"Avg. F size (L) (mm)", "Avg. F size (R) (mm)",
"Endometrium (mm)",
],
"HYPERANDROGENIC": [
"hair growth(Y/N)", "Skin darkening (Y/N)",
"Hair loss(Y/N)", "Pimples(Y/N)", "PRL(ng/mL)",
],
"GENERAL": [
"Age (yrs)", "Hb(g/dl)", "Pulse rate(bpm)",
"RR (breaths/min)", "TSH (mIU/L)", "Vit D3 (ng/mL)",
],
}
DROP_COLS = [
"Sl. No", "Patient File No.", "Blood Group",
"Marraige Status (Yrs)", "Pregnant(Y/N)",
"No. of aborptions", "Unnamed: 44",
]
BIOMARKER_DIRECTIONS = {
"FSH(mIU/mL)" : 1,
"LH(mIU/mL)" : -1,
"FSH/LH" : 1,
"AMH(ng/mL)" : -1,
"Follicle No. (L)" : -1,
"Follicle No. (R)" : -1,
"Endometrium (mm)" : -1,
"PRG(ng/mL)" : -1,
"Cycle(R/I)" : 1,
}
BIOMARKER_WEIGHTS = {
"FSH(mIU/mL)" : 0.18,
"LH(mIU/mL)" : 0.08,
"FSH/LH" : 0.15,
"AMH(ng/mL)" : 0.22,
"Follicle No. (L)" : 0.10,
"Follicle No. (R)" : 0.10,
"Endometrium (mm)" : 0.08,
"PRG(ng/mL)" : 0.05,
"Cycle(R/I)" : 0.04,
}
BIOMARKER_RANGES = {
"FSH(mIU/mL)" : (0.5, 22.0),
"LH(mIU/mL)" : (0.2, 49.0),
"FSH/LH" : (0.1, 20.0),
"AMH(ng/mL)" : (0.01, 18.0),
"Follicle No. (L)" : (0.0, 22.0),
"Follicle No. (R)" : (0.0, 22.0),
"Endometrium (mm)" : (1.0, 15.0),
"PRG(ng/mL)" : (0.1, 25.0),
"Cycle(R/I)" : (2.0, 4.0),
}
DOMAIN_COLORS = {
"Metabolic" : "#E74C3C",
"Reproductive" : "#9B59B6",
"Hyperandrogenic": "#E67E22",
"General" : "#27AE60",
}
# ── Example patients ─────────────────────────────────────────────────────────
EXAMPLE_PCOS = {
"age": 28, "weight": 72, "height": 158, "bmi": 28.8,
"pulse_rate": 82, "rr": 19, "hb": 11.5,
"cycle": 4, "cycle_length": 35,
"fsh": 4.8, "lh": 12.5, "fsh_lh_ratio": 0.38,
"hip": 40, "waist": 36, "waist_hip": 0.90,
"tsh": 2.8, "amh": 8.5, "prl": 22, "vit_d3": 18,
"prg": 0.6, "rbs": 105,
"weight_gain": 1, "hair_growth": 1, "skin_darkening": 1,
"hair_loss": 0, "pimples": 1, "fast_food": 1, "reg_exercise": 0,
"follicle_l": 14, "follicle_r": 13,
"avg_f_size_l": 8, "avg_f_size_r": 8, "endometrium": 6,
}
EXAMPLE_NORMAL = {
"age": 26, "weight": 58, "height": 162, "bmi": 22.1,
"pulse_rate": 70, "rr": 16, "hb": 13.2,
"cycle": 2, "cycle_length": 28,
"fsh": 7.2, "lh": 4.8, "fsh_lh_ratio": 1.5,
"hip": 37, "waist": 28, "waist_hip": 0.76,
"tsh": 2.1, "amh": 3.2, "prl": 14, "vit_d3": 30,
"prg": 1.8, "rbs": 85,
"weight_gain": 0, "hair_growth": 0, "skin_darkening": 0,
"hair_loss": 0, "pimples": 0, "fast_food": 0, "reg_exercise": 1,
"follicle_l": 6, "follicle_r": 6,
"avg_f_size_l": 16, "avg_f_size_r": 16, "endometrium": 9,
}
# ─────────────────────────────────────────────────────────────────────────────
# UTILITIES
# ─────────────────────────────────────────────────────────────────────────────
def clean_name(name: str) -> str:
return re.sub(r"[^0-9a-zA-Z_]", "_", name.strip())
def clean_df_cols(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
df.columns = [clean_name(c) for c in df.columns]
return df
def get_clean_feats(feat_list, available):
return [clean_name(f) for f in feat_list if clean_name(f) in available]
# ─────────────────────────────────────────────────────────────────────────────
# INFERTILITY RISK (pure formula β€” no training needed)
# ─────────────────────────────────────────────────────────────────────────────
def compute_infertility_risk(patient_raw: dict) -> dict:
def _valid(v):
if v is None:
return False
try:
return not np.isnan(float(v))
except (TypeError, ValueError):
return False
available = {f: w for f, w in BIOMARKER_WEIGHTS.items()
if f in patient_raw and _valid(patient_raw[f])}
if not available:
return {"score": 0.5, "tier": "Unknown", "breakdown": {}}
total_weight = sum(available.values())
score = 0.0
breakdown = {}
for feat, w in available.items():
val = float(patient_raw[feat])
lo, hi = BIOMARKER_RANGES.get(feat, (0.0, 1.0))
norm = np.clip((val - lo) / (hi - lo + 1e-8), 0.0, 1.0)
oriented = (1.0 - norm) if BIOMARKER_DIRECTIONS.get(feat, 1) == -1 else norm
contribution = (w / total_weight) * oriented
score += contribution
breakdown[feat] = {
"raw" : round(val, 3),
"oriented" : round(oriented, 3),
"contribution": round(contribution, 4),
"direction" : "↑ risk" if BIOMARKER_DIRECTIONS.get(feat, 1) == 1 else "↓ protective",
}
tier = "High" if score >= 0.66 else ("Moderate" if score >= 0.33 else "Low")
return {"score": round(score, 4), "tier": tier, "breakdown": breakdown}
# ─────────────────────────────────────────────────────────────────────────────
# PCOS PIPELINE
# ─────────────────────────────────────────────────────────────────────────────
def get_base_models():
return {
"Logistic" : LogisticRegression(max_iter=2000, class_weight="balanced"),
"RandomForest": RandomForestClassifier(
n_estimators=300, max_depth=10,
class_weight="balanced", random_state=RANDOM_STATE),
"GradientBoost": GradientBoostingClassifier(
n_estimators=200, learning_rate=0.05,
max_depth=3, subsample=0.85, random_state=RANDOM_STATE),
"CatBoost" : CatBoostClassifier(
iterations=300, learning_rate=0.05,
depth=6, random_seed=RANDOM_STATE,
eval_metric="AUC", verbose=0),
}
def load_and_engineer(data_path):
df = pd.read_excel(data_path)
df = df.drop(columns=DROP_COLS, errors="ignore")
df.columns = df.columns.str.strip()
y = pd.to_numeric(df["PCOS (Y/N)"], errors="coerce")
mask = y.notna()
df = df.loc[mask].copy().reset_index(drop=True)
y = y.loc[mask].astype(int).reset_index(drop=True)
for c in df.columns:
if df[c].dtype == "object" and c != "PCOS (Y/N)":
df[c] = pd.to_numeric(df[c].astype(str).str.strip(), errors="coerce")
df["FSH_LH_Ratio"] = df["FSH(mIU/mL)"] / (df["LH(mIU/mL)"] + 1e-6)
df["Total_Follicles"] = df["Follicle No. (L)"].fillna(0) + df["Follicle No. (R)"].fillna(0)
df["AMH_FSH_Ratio"] = df["AMH(ng/mL)"] / (df["FSH(mIU/mL)"] + 1e-6)
df["BMI_Waist_Ratio"] = df["BMI"] / (df["Waist(inch)"] + 1e-6)
andro = [c for c in FEATURE_GROUPS_BASE["HYPERANDROGENIC"] if c in df.columns]
if andro:
df["Androgenic_Score"] = df[andro].sum(axis=1)
FG = copy.deepcopy(FEATURE_GROUPS_BASE)
FG["REPRODUCTIVE"] += ["FSH_LH_Ratio", "Total_Follicles", "AMH_FSH_Ratio"]
FG["METABOLIC"] += ["BMI_Waist_Ratio"]
FG["HYPERANDROGENIC"] += ["Androgenic_Score"]
X = clean_df_cols(df.drop(columns=["PCOS (Y/N)"]))
return X, y, FG
def preprocess(Xtr, Xte):
mice = IterativeImputer(max_iter=10, random_state=RANDOM_STATE)
Xtr_imp = pd.DataFrame(mice.fit_transform(Xtr), columns=Xtr.columns, index=Xtr.index)
Xte_imp = pd.DataFrame(mice.transform(Xte), columns=Xte.columns, index=Xte.index)
num_cols = Xtr_imp.select_dtypes(include=np.number).columns.tolist()
scaler = RobustScaler()
Xtr_sc = Xtr_imp.copy(); Xte_sc = Xte_imp.copy()
Xtr_sc[num_cols] = scaler.fit_transform(Xtr_imp[num_cols])
Xte_sc[num_cols] = scaler.transform(Xte_imp[num_cols])
return Xtr_sc, Xte_sc, mice, scaler, num_cols
def compute_oof_severity(Xtr, ytr, Xtr_sc, FG):
skf = StratifiedKFold(CV_FOLDS, shuffle=True, random_state=RANDOM_STATE)
sev = pd.DataFrame(index=Xtr.index)
models, stats = {}, {}
for domain, feats in FG.items():
fc = get_clean_feats(feats, Xtr_sc.columns)
if len(fc) < 3: continue
oof = np.zeros(len(Xtr_sc))
for tr, val in skf.split(Xtr_sc, ytr):
m = GradientBoostingClassifier(n_estimators=100, learning_rate=0.05,
max_depth=3, random_state=RANDOM_STATE)
m.fit(Xtr_sc.iloc[tr][fc], ytr.iloc[tr])
oof[val] = m.predict_proba(Xtr_sc.iloc[val][fc])[:, 1]
stats[domain] = {"min": oof.min(), "max": oof.max()}
sev[f"{domain}_SEV"] = (oof - oof.min()) / (oof.max() - oof.min() + 1e-6)
fm = GradientBoostingClassifier(n_estimators=100, learning_rate=0.05,
max_depth=3, random_state=RANDOM_STATE)
fm.fit(Xtr_sc[fc], ytr)
models[domain] = (fm, fc)
sev["OVERALL_SEV"] = sum(sev[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev)
return sev.fillna(0), models, stats
def apply_severity(models, stats, X_sc):
df_sev = pd.DataFrame(index=X_sc.index)
for d, (model, fc) in models.items():
fc_a = [f for f in fc if f in X_sc.columns]
p = model.predict_proba(X_sc[fc_a])[:, 1]
df_sev[f"{d}_SEV"] = np.clip(
(p - stats[d]["min"]) / (stats[d]["max"] - stats[d]["min"] + 1e-6), 0, 1)
df_sev = df_sev.fillna(0)
df_sev["OVERALL_SEV"] = sum(df_sev[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
for d in DOMAIN_WEIGHTS if f"{d}_SEV" in df_sev)
return df_sev
def build_pipeline(data_path):
print("πŸ”„ Training PCOS pipeline...")
X, y, FG = load_and_engineer(data_path)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=TEST_SIZE,
stratify=y, random_state=RANDOM_STATE)
Xtr_sc, Xte_sc, mice, scaler, num_cols = preprocess(Xtr, Xte)
sev_tr, domain_models, stats = compute_oof_severity(Xtr, ytr, Xtr_sc, FG)
sev_te = apply_severity(domain_models, stats, Xte_sc)
Xtr_f = pd.concat([Xtr_sc, sev_tr], axis=1)
Xte_f = pd.concat([Xte_sc, sev_te], axis=1)
skf = StratifiedKFold(CV_FOLDS, shuffle=True, random_state=RANDOM_STATE)
oof_meta = pd.DataFrame(index=Xtr_f.index)
test_meta = pd.DataFrame(index=Xte_f.index)
trained_base = {}
for name, model in get_base_models().items():
oof = np.zeros(len(Xtr_f))
for tr_i, val_i in skf.split(Xtr_f, ytr):
model.fit(Xtr_f.iloc[tr_i], ytr.iloc[tr_i])
oof[val_i] = model.predict_proba(Xtr_f.iloc[val_i])[:, 1]
model.fit(Xtr_f, ytr)
oof_meta[name] = oof
test_meta[name] = model.predict_proba(Xte_f)[:, 1]
trained_base[name] = model
print(f" βœ… {name} β€” CV AUC: {roc_auc_score(ytr, oof):.4f}")
meta = CalibratedClassifierCV(
LogisticRegressionCV(cv=5, class_weight={0: 1, 1: 3}), method="isotonic")
meta.fit(oof_meta, ytr)
ens_probs = meta.predict_proba(test_meta)[:, 1]
fpr, tpr, thresholds = roc_curve(yte, ens_probs)
best_t = float(thresholds[np.argmax(tpr - fpr)])
auc = roc_auc_score(yte, ens_probs)
print(f" βœ… Ensemble AUC: {auc:.4f} | threshold: {best_t:.4f}")
print("βœ… Pipeline ready!")
return dict(meta=meta, base=trained_base, domain_models=domain_models,
stats=stats, mice=mice, scaler=scaler, num_cols=num_cols,
scaled_cols=list(Xtr_sc.columns), feature_cols=list(Xtr_f.columns),
threshold=best_t, auc=round(auc, 4))
# ── Startup ──────────────────────────────────────────────────────────────────
DATA_PATH = os.path.join(os.path.dirname(__file__), "PCOS_data_without_infertility.xlsx")
print("πŸš€ Initialising pipeline...")
if os.path.exists(DATA_PATH):
try:
PIPELINE = build_pipeline(DATA_PATH)
PIPELINE_READY = True
except Exception as e:
print(f"⚠️ {e}"); PIPELINE_READY = False; PIPELINE = None
else:
print(f"⚠️ Dataset not found at {DATA_PATH}"); PIPELINE_READY = False; PIPELINE = None
# ─────────────────────────────────────────────────────────────────────────────
# INFERENCE
# ─────────────────────────────────────────────────────────────────────────────
def predict_single(pipeline, patient_dict):
row = {k: np.nan for k in pipeline["scaled_cols"]}
for raw_key, val in patient_dict.items():
ck = clean_name(raw_key)
if ck in row and val is not None:
try: row[ck] = float(val)
except (TypeError, ValueError): pass
X_raw = pd.DataFrame([row])
for c in X_raw.columns:
X_raw[c] = pd.to_numeric(X_raw[c], errors="coerce")
X_imp = pd.DataFrame(pipeline["mice"].transform(X_raw), columns=X_raw.columns)
X_sc = X_imp.copy()
num_c = [c for c in pipeline["num_cols"] if c in X_sc.columns]
X_sc[num_c] = pipeline["scaler"].transform(X_imp[num_c])
sev = apply_severity(pipeline["domain_models"], pipeline["stats"], X_sc)
X_f = pd.concat([X_sc.reset_index(drop=True), sev.reset_index(drop=True)], axis=1)
for c in pipeline["feature_cols"]:
if c not in X_f.columns: X_f[c] = 0.0
X_f = X_f[pipeline["feature_cols"]].clip(-10, 10)
base_probs = {name: model.predict_proba(X_f)[:, 1][0]
for name, model in pipeline["base"].items()}
pcos_prob = pipeline["meta"].predict_proba(pd.DataFrame([base_probs]))[:, 1][0]
pred = int(pcos_prob >= pipeline["threshold"])
def _s(col): return float(sev[col].iloc[0]) if col in sev.columns else 0.0
severity = {
"Metabolic" : _s("METABOLIC_SEV"),
"Reproductive" : _s("REPRODUCTIVE_SEV"),
"Hyperandrogenic": _s("HYPERANDROGENIC_SEV"),
"General" : _s("GENERAL_SEV"),
"Overall" : _s("OVERALL_SEV"),
}
return pcos_prob, pred, severity, base_probs
# ─────────────────────────────────────────────────────────────────────────────
# ENHANCED VISUALISATION
# ─────────────────────────────────────────────────────────────────────────────
BG = "#0D0D1A"
TC = "#E8E8F0"
ACC = "#A855F7" # purple accent
def draw_gauge(ax, value, title, val_label, sub_label, val_col):
ax.set_facecolor(BG)
theta = np.linspace(np.pi, 0, 300)
for i in range(len(theta) - 1):
t = i / (len(theta) - 1)
color = plt.cm.RdYlGn_r(t)
ax.fill_between([np.cos(theta[i]), np.cos(theta[i+1])],
[np.sin(theta[i]), np.sin(theta[i+1])],
alpha=0.9, color=color)
# Needle
angle = np.pi * (1 - value)
ax.annotate("", xy=(0.65*np.cos(angle), 0.65*np.sin(angle)),
xytext=(0, 0),
arrowprops=dict(arrowstyle="-|>", color="white", lw=3))
ax.plot(0, 0, "o", color="white", markersize=6, zorder=5)
# Labels
ax.text(0, -0.15, val_label, ha="center", fontsize=22,
fontweight="bold", color=val_col, va="center")
ax.text(0, -0.38, title, ha="center", fontsize=9, color="#AAAACC")
ax.text(0, -0.58, sub_label, ha="center", fontsize=10,
fontweight="bold", color=val_col)
# Scale ticks
for pct, lbl in [(0, "0%"), (0.5, "50%"), (1.0, "100%")]:
a = np.pi * (1 - pct)
ax.text(0.88*np.cos(a), 0.88*np.sin(a), lbl,
ha="center", va="center", fontsize=6, color="#888")
ax.set_xlim(-1.05, 1.05); ax.set_ylim(-0.72, 1.05)
ax.axis("off")
ax.set_title(title, color=TC, fontsize=12, fontweight="bold", pad=4)
def make_result_figure(pcos_prob, pred, sev, base_probs, inf_risk):
fig = plt.figure(figsize=(18, 13), facecolor=BG)
gs = GridSpec(3, 4, figure=fig, hspace=0.58, wspace=0.45,
top=0.93, bottom=0.05, left=0.05, right=0.97)
ax_pg = fig.add_subplot(gs[0, 0]) # PCOS gauge
ax_ig = fig.add_subplot(gs[0, 1]) # Infertility gauge
ax_rad = fig.add_subplot(gs[0, 2:], polar=True) # Radar (wider)
ax_bar = fig.add_subplot(gs[1, :2]) # Base model bars
ax_bio = fig.add_subplot(gs[1, 2:]) # Biomarker contributions
ax_sev = fig.add_subplot(gs[2, :]) # Domain severity
risk_col = "#E74C3C" if pcos_prob > 0.65 else ("#F39C12" if pcos_prob > 0.35 else "#2ECC71")
inf_s = inf_risk["score"]
inf_t = inf_risk["tier"]
inf_col = "#E74C3C" if inf_t == "High" else ("#F39C12" if inf_t == "Moderate" else "#2ECC71")
# ── PCOS Gauge ────────────────────────────────────────────────────────────
draw_gauge(ax_pg, pcos_prob,
"PCOS Risk",
f"{pcos_prob*100:.1f}%",
"⚠️ PCOS Detected" if pred else "βœ… No PCOS",
risk_col)
# ── Infertility Gauge ─────────────────────────────────────────────────────
draw_gauge(ax_ig, inf_s,
"Infertility Risk",
f"{inf_s*100:.1f}%",
f"{'πŸ”΄' if inf_t=='High' else ('🟑' if inf_t=='Moderate' else '🟒')} {inf_t}",
inf_col)
# ── Radar β€” larger, better labels ────────────────────────────────────────
domains = ["Metabolic", "Reproductive", "Hyperandrogenic", "General"]
vals = [sev[d] for d in domains]
angles = np.linspace(0, 2*np.pi, len(domains), endpoint=False).tolist()
v_c = vals + [vals[0]]; a_c = angles + [angles[0]]
ax_rad.set_facecolor(BG)
# Shade zones
for level, alpha, color in [(1.0, 0.05, "#E74C3C"), (0.65, 0.08, "#F39C12"),
(0.35, 0.08, "#2ECC71")]:
ax_rad.fill(a_c, [level]*len(a_c), alpha=alpha, color=color)
ax_rad.plot(a_c, v_c, "o-", lw=2.5, color=ACC, markersize=7)
ax_rad.fill(a_c, v_c, alpha=0.30, color=ACC)
ax_rad.set_xticks(angles)
ax_rad.set_xticklabels(
[f"{d}\n{vals[i]*100:.0f}%" for i, d in enumerate(domains)],
color=TC, fontsize=10, fontweight="bold")
ax_rad.set_ylim(0, 1)
ax_rad.set_yticks([0.35, 0.65, 1.0])
ax_rad.set_yticklabels(["Low→Mod", "Mod→High", "Max"],
color="#666", fontsize=7)
ax_rad.grid(color="#333355", alpha=0.6, linewidth=0.8)
ax_rad.spines["polar"].set_color("#333355")
ax_rad.set_title("Domain Severity Radar", color=TC,
fontsize=13, fontweight="bold", pad=22)
# ── Base model bars ───────────────────────────────────────────────────────
ax_bar.set_facecolor(BG)
names = list(base_probs.keys())
probs = [base_probs[n] for n in names]
colors = ["#3B82F6", "#10B981", "#F59E0B", "#EF4444"]
bars = ax_bar.barh(names, probs, color=colors[:len(names)],
height=0.52, alpha=0.88)
for bar, p in zip(bars, probs):
ax_bar.text(min(p + 0.018, 0.97), bar.get_y() + bar.get_height()/2,
f"{p:.3f}", va="center", color=TC, fontsize=11, fontweight="bold")
ax_bar.axvline(0.5, color="white", linestyle="--", alpha=0.3, lw=1.5,
label="Decision boundary (0.5)")
# Highlight ensemble threshold
ax_bar.axvline(PIPELINE["threshold"] if PIPELINE_READY else 0.5,
color="#A855F7", linestyle=":", alpha=0.5, lw=1.5,
label=f"Youden threshold ({PIPELINE['threshold']:.2f})" if PIPELINE_READY else "")
ax_bar.set_xlim(0, 1.12)
ax_bar.tick_params(colors=TC, labelsize=11)
for sp in ax_bar.spines.values(): sp.set_color("#2A2A4A")
ax_bar.set_title("Base Model Probabilities", color=TC, fontsize=12, fontweight="bold")
ax_bar.set_xlabel("PCOS Probability", color=TC, fontsize=10)
ax_bar.legend(facecolor="#1A1A2E", edgecolor="#333355", labelcolor=TC,
fontsize=8, loc="lower right")
# ── Biomarker contributions ───────────────────────────────────────────────
ax_bio.set_facecolor(BG)
ax_bio.tick_params(colors=TC, labelsize=8)
for sp in ax_bio.spines.values(): sp.set_color("#2A2A4A")
ax_bio.set_title("Infertility Biomarker Contributions", color=TC,
fontsize=12, fontweight="bold")
ax_bio.set_xlabel("Weighted contribution to risk", color=TC, fontsize=9)
breakdown = inf_risk.get("breakdown", {})
if breakdown:
bio_names = list(breakdown.keys())
bio_vals = [breakdown[f]["contribution"] for f in bio_names]
bio_cols = ["#EF4444" if breakdown[f]["oriented"] > 0.5 else "#10B981"
for f in bio_names]
short_names = [f.split("(")[0].strip()[:14] for f in bio_names]
# Sort by contribution descending
sorted_pairs = sorted(zip(short_names, bio_vals, bio_cols),
key=lambda x: x[1], reverse=True)
short_names, bio_vals, bio_cols = zip(*sorted_pairs)
bars2 = ax_bio.barh(short_names, bio_vals, color=bio_cols,
height=0.52, alpha=0.88)
for bar, val in zip(bars2, bio_vals):
ax_bio.text(val + 0.001, bar.get_y() + bar.get_height()/2,
f"{val:.3f}", va="center", color=TC, fontsize=9)
p1 = mpatches.Patch(color="#EF4444", label="↑ Increases risk")
p2 = mpatches.Patch(color="#10B981", label="↓ Protective")
ax_bio.legend(handles=[p1, p2], facecolor="#1A1A2E",
edgecolor="#333355", labelcolor=TC, fontsize=8)
else:
ax_bio.text(0.5, 0.5, "Enter FSH, LH, AMH, follicle\ncount values to see\nbiomarker breakdown",
ha="center", va="center", color="#666",
fontsize=10, transform=ax_bio.transAxes)
# ── Domain severity bars ──────────────────────────────────────────────────
ax_sev.set_facecolor(BG)
sev_vals = [sev[d] for d in domains]
sev_colors = [DOMAIN_COLORS[d] for d in domains]
x_pos = np.arange(len(domains))
bars3 = ax_sev.bar(x_pos, sev_vals, color=sev_colors, alpha=0.88, width=0.5)
for bar, val, d in zip(bars3, sev_vals, domains):
lvl = "High" if val > 0.65 else ("Moderate" if val > 0.35 else "Low")
lvl_col = "#E74C3C" if lvl=="High" else ("#F39C12" if lvl=="Moderate" else "#2ECC71")
ax_sev.text(bar.get_x() + bar.get_width()/2, val + 0.02,
f"{val*100:.1f}%", ha="center", va="bottom",
color=TC, fontsize=14, fontweight="bold")
ax_sev.text(bar.get_x() + bar.get_width()/2, val + 0.08,
f"({lvl})", ha="center", va="bottom",
color=lvl_col, fontsize=11)
ax_sev.axhline(0.65, color="#E74C3C", linestyle="--", alpha=0.45,
lw=1.5, label="High threshold (65%)")
ax_sev.axhline(0.35, color="#F39C12", linestyle="--", alpha=0.45,
lw=1.5, label="Moderate threshold (35%)")
ax_sev.set_ylim(0, 1.3)
ax_sev.set_xticks(x_pos)
ax_sev.set_xticklabels(domains, color=TC, fontsize=13, fontweight="bold")
ax_sev.tick_params(axis="y", colors=TC, labelsize=10)
for sp in ax_sev.spines.values(): sp.set_color("#2A2A4A")
ax_sev.set_title("PCOS Domain Severity Breakdown", color=TC,
fontsize=13, fontweight="bold")
ax_sev.set_ylabel("Severity Score", color=TC, fontsize=11)
ax_sev.legend(facecolor="#1A1A2E", edgecolor="#333355",
labelcolor=TC, fontsize=9, loc="upper right")
fig.patch.set_facecolor(BG)
fig.suptitle("🩺 PCOS Clinical Assessment Report", color=TC,
fontsize=16, fontweight="bold", y=0.97)
return fig
# ─────────────────────────────────────────────────────────────────────────────
# MAIN PREDICT FUNCTION
# ─────────────────────────────────────────────────────────────────────────────
INPUT_KEYS = [
"age","weight","height","bmi","pulse_rate","rr","hb",
"cycle","cycle_length","fsh","lh","fsh_lh_ratio",
"hip","waist","waist_hip","tsh","amh","prl","vit_d3","prg","rbs",
"weight_gain","hair_growth","skin_darkening","hair_loss",
"pimples","fast_food","reg_exercise",
"follicle_l","follicle_r","avg_f_size_l","avg_f_size_r","endometrium",
]
def predict(*args):
vals = dict(zip(INPUT_KEYS, args))
if not PIPELINE_READY:
return "❌ Pipeline not ready. Upload `PCOS_data_without_infertility.xlsx` to Space root.", None, ""
age=vals["age"]; weight=vals["weight"]; height=vals["height"]
bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
if (not bmi or bmi == 0) and weight and height and height > 0:
bmi = weight / ((height / 100) ** 2)
if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"] == 0) and fsh and lh:
vals["fsh_lh_ratio"] = fsh / (lh + 1e-6)
vals["bmi"] = bmi
patient_raw = {
"Age (yrs)" : vals["age"],
"Weight (Kg)" : vals["weight"],
"BMI" : vals["bmi"],
"Pulse rate(bpm)" : vals["pulse_rate"],
"RR (breaths/min)" : vals["rr"],
"Hb(g/dl)" : vals["hb"],
"Cycle(R/I)" : vals["cycle"],
"Cycle length(days)" : vals["cycle_length"],
"FSH(mIU/mL)" : vals["fsh"],
"LH(mIU/mL)" : vals["lh"],
"FSH/LH" : vals["fsh_lh_ratio"],
"Hip(inch)" : vals["hip"],
"Waist(inch)" : vals["waist"],
"Waist:Hip Ratio" : vals["waist_hip"],
"TSH (mIU/L)" : vals["tsh"],
"AMH(ng/mL)" : vals["amh"],
"PRL(ng/mL)" : vals["prl"],
"Vit D3 (ng/mL)" : vals["vit_d3"],
"PRG(ng/mL)" : vals["prg"],
"RBS(mg/dl)" : vals["rbs"],
"Weight gain(Y/N)" : vals["weight_gain"],
"hair growth(Y/N)" : vals["hair_growth"],
"Skin darkening (Y/N)" : vals["skin_darkening"],
"Hair loss(Y/N)" : vals["hair_loss"],
"Pimples(Y/N)" : vals["pimples"],
"Fast food (Y/N)" : vals["fast_food"],
"Reg.Exercise(Y/N)" : vals["reg_exercise"],
"Follicle No. (L)" : vals["follicle_l"],
"Follicle No. (R)" : vals["follicle_r"],
"Avg. F size (L) (mm)" : vals["avg_f_size_l"],
"Avg. F size (R) (mm)" : vals["avg_f_size_r"],
"Endometrium (mm)" : vals["endometrium"],
"BP _Systolic (mmHg)" : 120,
"BP _Diastolic (mmHg)" : 80,
}
try:
pcos_prob, pred, sev, base_probs = predict_single(PIPELINE, patient_raw)
except Exception as e:
return f"❌ Prediction error: {e}", None, ""
inf_risk = compute_infertility_risk(patient_raw)
inf_score = inf_risk["score"]
inf_tier = inf_risk["tier"]
inf_icon = "πŸ”΄" if inf_tier == "High" else ("🟑" if inf_tier == "Moderate" else "🟒")
pcos_tier = ("HIGH RISK πŸ”΄" if pcos_prob > 0.65 else
("MODERATE RISK 🟑" if pcos_prob > 0.35 else "LOW RISK 🟒"))
# Recommendations
recs = []
if pred:
recs.append("πŸ₯ **Consult an endocrinologist / gynaecologist immediately.**")
if inf_tier == "High":
recs.append("🧬 **High infertility risk β€” fertility specialist evaluation recommended.**")
elif inf_tier == "Moderate":
recs.append("πŸ”¬ Hormonal panel follow-up (FSH, LH, AMH) recommended.")
if sev["Metabolic"] > 0.5:
recs.append("βš–οΈ Weight management, balanced diet, and regular exercise advised.")
if sev["Hyperandrogenic"] > 0.5:
recs.append("πŸ’Š Discuss anti-androgen therapy options with your doctor.")
if not recs:
recs.append("βœ… Continue routine annual screening and a healthy lifestyle.")
divergence = ""
if (pcos_prob > 0.5 and inf_tier == "Low") or (pcos_prob < 0.3 and inf_tier in ["Moderate","High"]):
divergence = (
"\n> ℹ️ **Why do PCOS probability and infertility risk differ?** \n"
"> These scores measure different biology (r = βˆ’0.633 in research). \n"
"> PCOS probability = full hormonal + metabolic picture. \n"
"> Infertility risk = ovarian reserve biomarkers (AMH, FSH, follicle count). \n"
"> A patient can have PCOS but good ovarian reserve β€” or vice versa.\n"
)
sev_rows = "\n".join(
f"| {d} | {sev[d]*100:.1f}% | {'πŸ”΄ High' if sev[d]>0.65 else ('🟑 Moderate' if sev[d]>0.35 else '🟒 Low')} |"
for d in ["Metabolic", "Reproductive", "Hyperandrogenic", "General"]
)
bio_rows = "\n".join(
f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
for f, v in inf_risk.get("breakdown", {}).items()
) or "| β€” | Enter hormonal values | β€” | β€” |"
summary = f"""## PCOS Assessment β€” {pcos_tier}
| | |
|---|---|
| **PCOS Probability** | **{pcos_prob*100:.1f}%** |
| **Diagnosis** | {"⚠️ PCOS Detected" if pred else "βœ… No PCOS Detected"} |
| **Overall Severity** | {sev['Overall']*100:.1f}% |
---
## Infertility Risk β€” {inf_icon} {inf_tier}
| | |
|---|---|
| **Risk Score** | **{inf_score*100:.1f}%** |
| **Tier** | {inf_icon} {inf_tier} |
{divergence}
---
### PCOS Domain Severity
| Domain | Score | Level |
|--------|-------|-------|
{sev_rows}
### Infertility Biomarker Breakdown
| Biomarker | Value | Direction | Contribution |
|-----------|-------|-----------|-------------|
{bio_rows}
### Clinical Recommendations
{" ".join(chr(10) + "- " + r for r in recs)}
---
*βš•οΈ For research/educational purposes only. Not medical advice.*"""
fig = make_result_figure(pcos_prob, pred, sev, base_probs, inf_risk)
info = (f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['threshold']:.4f} | "
f"Infertility biomarker weights β€” AMH:0.22, FSH:0.18, FSH/LH:0.15, Follicles:0.10Γ—2")
return summary, fig, info
# ─────────────────────────────────────────────────────────────────────────────
# GRADIO UI
# ─────────────────────────────────────────────────────────────────────────────
CSS = """
.gr-button-primary { background: linear-gradient(135deg, #7C3AED, #A855F7) !important; }
.gr-button { border-radius: 8px !important; }
footer { display: none !important; }
"""
with gr.Blocks(
theme=gr.themes.Base(
primary_hue="purple", secondary_hue="violet",
neutral_hue="slate",
font=[gr.themes.GoogleFont("Inter"), "sans-serif"],
),
css=CSS,
title="PCOS Detection App"
) as demo:
gr.Markdown("""
# 🩺 PCOS Clinical Detection System
**Dual Pipeline** Β· PCOS Classification (Stacked Ensemble Β· AUC β‰ˆ 0.95) + Infertility Risk (Biomarker-Weighted)
*All fields optional β€” missing values are imputed automatically from training distribution*
""")
# ── Example patient buttons ───────────────────────────────────────────────
with gr.Row():
btn_pcos = gr.Button("πŸ“‹ Load PCOS Patient Example", variant="secondary")
btn_normal = gr.Button("πŸ“‹ Load Normal Patient Example", variant="secondary")
btn_clear = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
# ── Input form β€” accordion sections ──────────────────────────────────────
with gr.Row():
with gr.Column(scale=1):
with gr.Accordion("πŸ“‹ General & Vitals", open=True):
age = gr.Number(label="Age (yrs)", value=25, minimum=10, maximum=60)
weight = gr.Number(label="Weight (Kg)", value=60)
height = gr.Number(label="Height (cm)", value=160)
bmi = gr.Number(label="BMI (auto-computed)", value=0)
pulse_rate = gr.Number(label="Pulse rate (bpm)", value=72)
rr = gr.Number(label="RR (breaths/min)", value=18)
hb = gr.Number(label="Hb (g/dl)", value=12)
tsh = gr.Number(label="TSH (mIU/L)", value=2.5)
vit_d3 = gr.Number(label="Vit D3 (ng/mL)", value=25)
with gr.Column(scale=1):
with gr.Accordion("πŸ”΄ Metabolic", open=True):
rbs = gr.Number(label="RBS (mg/dl)", value=90)
waist = gr.Number(label="Waist (inch)", value=30)
hip = gr.Number(label="Hip (inch)", value=37)
waist_hip = gr.Number(label="Waist:Hip Ratio", value=0.81)
weight_gain = gr.Radio([0,1], label="Weight Gain", value=0)
fast_food = gr.Radio([0,1], label="Fast Food (Y=1)",value=0)
reg_exercise = gr.Radio([0,1], label="Exercise (Y=1)", value=1)
with gr.Column(scale=1):
with gr.Accordion("🟣 Reproductive & Hormonal β˜…", open=True):
cycle = gr.Radio([2,4], label="Cycle: Regular=2 / Irregular=4", value=2)
cycle_length = gr.Number(label="Cycle length (days)", value=28)
fsh = gr.Number(label="FSH (mIU/mL) β˜…", value=6.5)
lh = gr.Number(label="LH (mIU/mL) β˜…", value=5.0)
fsh_lh_ratio = gr.Number(label="FSH/LH (auto if 0) β˜…",value=0)
amh = gr.Number(label="AMH (ng/mL) β˜…", value=2.5)
prg = gr.Number(label="PRG (ng/mL) β˜…", value=1.0)
endometrium = gr.Number(label="Endometrium (mm) β˜…", value=8.0)
follicle_l = gr.Number(label="Follicle No. (L) β˜…", value=6)
follicle_r = gr.Number(label="Follicle No. (R) β˜…", value=6)
avg_f_size_l = gr.Number(label="Avg. F size L (mm)", value=15)
avg_f_size_r = gr.Number(label="Avg. F size R (mm)", value=15)
gr.Markdown("*β˜… Used for both PCOS + Infertility Risk*")
with gr.Column(scale=1):
with gr.Accordion("🟠 Hyperandrogenic", open=True):
hair_growth = gr.Radio([0,1], label="Hair Growth (Y=1)", value=0)
skin_darkening = gr.Radio([0,1], label="Skin Darkening (Y=1)", value=0)
hair_loss = gr.Radio([0,1], label="Hair Loss (Y=1)", value=0)
pimples = gr.Radio([0,1], label="Pimples (Y=1)", value=0)
prl = gr.Number(label="PRL (ng/mL)", value=15)
ALL_INPUTS = [
age, weight, height, bmi, pulse_rate, rr, hb,
cycle, cycle_length, fsh, lh, fsh_lh_ratio,
hip, waist, waist_hip, tsh, amh, prl, vit_d3, prg, rbs,
weight_gain, hair_growth, skin_darkening, hair_loss,
pimples, fast_food, reg_exercise,
follicle_l, follicle_r, avg_f_size_l, avg_f_size_r, endometrium,
]
predict_btn = gr.Button("πŸ”¬ Run Full Analysis", variant="primary", size="lg")
# ── Outputs ───────────────────────────────────────────────────────────────
with gr.Row():
with gr.Column(scale=1):
summary_out = gr.Markdown()
model_info = gr.Textbox(label="Pipeline info", interactive=False, lines=2)
with gr.Column(scale=2):
chart_out = gr.Plot(label="Assessment Charts")
# ── Button actions ────────────────────────────────────────────────────────
def load_example(ex):
return [ex[k] for k in INPUT_KEYS]
def clear_all():
defaults = dict(
age=25, weight=60, height=160, bmi=0, pulse_rate=72, rr=18, hb=12,
cycle=2, cycle_length=28, fsh=6.5, lh=5.0, fsh_lh_ratio=0,
hip=37, waist=30, waist_hip=0.81, tsh=2.5, amh=2.5, prl=15,
vit_d3=25, prg=1.0, rbs=90,
weight_gain=0, hair_growth=0, skin_darkening=0, hair_loss=0,
pimples=0, fast_food=0, reg_exercise=1,
follicle_l=6, follicle_r=6, avg_f_size_l=15, avg_f_size_r=15, endometrium=8,
)
return [defaults[k] for k in INPUT_KEYS]
btn_pcos.click(fn=lambda: load_example(EXAMPLE_PCOS), outputs=ALL_INPUTS)
btn_normal.click(fn=lambda: load_example(EXAMPLE_NORMAL), outputs=ALL_INPUTS)
btn_clear.click(fn=clear_all, outputs=ALL_INPUTS)
predict_btn.click(
fn=predict, inputs=ALL_INPUTS,
outputs=[summary_out, chart_out, model_info],
)
gr.Markdown("---\n*βš•οΈ For research/educational purposes only. Not medical advice.*")
if __name__ == "__main__":
demo.launch()