Spaces:
Sleeping
Sleeping
Upload 16 files
Browse files- README.md +14 -7
- app.py +371 -0
- models/base_models.pkl +3 -0
- models/best_threshold.pkl +3 -0
- models/deployment_config.json +43 -0
- models/domain_models.pkl +3 -0
- models/efficientnetb0.pth +3 -0
- models/ensemble_meta.pkl +3 -0
- models/feature_columns.pkl +3 -0
- models/mice_imputer.pkl +3 -0
- models/scaler.pkl +3 -0
- models/train_stats.pkl +3 -0
- requirements.txt +11 -0
- utils/__init__.py +0 -0
- utils/image_predictor.py +95 -0
- utils/tabular_predictor.py +141 -0
README.md
CHANGED
|
@@ -1,13 +1,20 @@
|
|
| 1 |
---
|
| 2 |
-
title: PCOS Detection
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
-
pinned:
|
| 10 |
-
short_description: PCOD Detection
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: PCOS Detection App
|
| 3 |
+
emoji: 🩺
|
| 4 |
+
colorFrom: purple
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.23.0
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: true
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# PCOS Detection & Risk Assessment System
|
| 13 |
+
|
| 14 |
+
Dual-modal AI system for PCOS detection using ultrasound images and clinical features.
|
| 15 |
+
|
| 16 |
+
- **Image model**: EfficientNetB0 + Grad-CAM
|
| 17 |
+
- **Clinical model**: Stacked Ensemble (LR + RF + GB + CatBoost) — AUC 0.953
|
| 18 |
+
- **Infertility risk scoring** from biomarkers
|
| 19 |
+
|
| 20 |
+
For research purposes only.
|
app.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, warnings
|
| 2 |
+
warnings.filterwarnings("ignore")
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import matplotlib
|
| 6 |
+
matplotlib.use("Agg")
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, os.path.dirname(__file__))
|
| 12 |
+
|
| 13 |
+
# ── Load models ───────────────────────────────────────────────────────────────
|
| 14 |
+
image_model = None
|
| 15 |
+
tabular_arts = None
|
| 16 |
+
|
| 17 |
+
def load_models():
|
| 18 |
+
global image_model, tabular_arts
|
| 19 |
+
|
| 20 |
+
path = os.path.join("models", "efficientnetb0.pth")
|
| 21 |
+
if os.path.exists(path):
|
| 22 |
+
try:
|
| 23 |
+
from utils.image_predictor import load_image_model
|
| 24 |
+
image_model = load_image_model(path)
|
| 25 |
+
print("Image model loaded")
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Image model error: {e}")
|
| 28 |
+
else:
|
| 29 |
+
print("efficientnetb0.pth not found in models/")
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
from utils.tabular_predictor import load_tabular_artifacts
|
| 33 |
+
arts = load_tabular_artifacts()
|
| 34 |
+
if arts.get("meta") is not None:
|
| 35 |
+
tabular_arts = arts
|
| 36 |
+
print("Tabular model loaded")
|
| 37 |
+
else:
|
| 38 |
+
print("Tabular pkl files not found in models/")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"Tabular error: {e}")
|
| 41 |
+
|
| 42 |
+
load_models()
|
| 43 |
+
|
| 44 |
+
# ── Plots ─────────────────────────────────────────────────────────────────────
|
| 45 |
+
def severity_plot(domain_scores, overall):
|
| 46 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
|
| 47 |
+
domains = list(domain_scores.keys())
|
| 48 |
+
values = list(domain_scores.values())
|
| 49 |
+
colors = ["#e74c3c" if v > 0.66 else "#f39c12" if v > 0.33 else "#2ecc71" for v in values]
|
| 50 |
+
axes[0].bar(domains, values, color=colors, alpha=0.85, edgecolor="white")
|
| 51 |
+
axes[0].axhline(overall, color="navy", ls="--", lw=2, label=f"Overall: {overall:.3f}")
|
| 52 |
+
axes[0].set(title="Domain Severity", ylabel="Score (0-1)", ylim=(0, 1.1))
|
| 53 |
+
axes[0].legend(); axes[0].grid(alpha=0.3, axis="y")
|
| 54 |
+
for i, v in enumerate(values):
|
| 55 |
+
axes[0].text(i, v + 0.02, f"{v:.2f}", ha="center", fontsize=10, fontweight="bold")
|
| 56 |
+
N = len(domains)
|
| 57 |
+
angles = [n / float(N) * 2 * np.pi for n in range(N)] + [0]
|
| 58 |
+
vals = values + [values[0]]
|
| 59 |
+
axes[1].remove()
|
| 60 |
+
ax_r = fig.add_subplot(122, polar=True)
|
| 61 |
+
ax_r.plot(angles, vals, "o-", lw=2, color="#667eea")
|
| 62 |
+
ax_r.fill(angles, vals, alpha=0.25, color="#667eea")
|
| 63 |
+
ax_r.set_xticks(angles[:-1]); ax_r.set_xticklabels(domains, fontsize=9)
|
| 64 |
+
ax_r.set_ylim(0, 1); ax_r.set_title("Severity Radar", pad=20)
|
| 65 |
+
plt.tight_layout()
|
| 66 |
+
return fig
|
| 67 |
+
|
| 68 |
+
def base_model_plot(base_probs):
|
| 69 |
+
fig, ax = plt.subplots(figsize=(6, 3))
|
| 70 |
+
names = list(base_probs.keys())
|
| 71 |
+
probs = list(base_probs.values())
|
| 72 |
+
colors = ["#e74c3c" if p >= 0.5 else "#2ecc71" for p in probs]
|
| 73 |
+
bars = ax.barh(names, probs, color=colors, alpha=0.8)
|
| 74 |
+
ax.axvline(0.5, color="k", ls="--", lw=1.5, alpha=0.5, label="Decision line")
|
| 75 |
+
for bar, val in zip(bars, probs):
|
| 76 |
+
ax.text(val + 0.01, bar.get_y() + bar.get_height()/2,
|
| 77 |
+
f"{val:.3f}", va="center", fontsize=9)
|
| 78 |
+
ax.set(title="Base Model Probabilities", xlabel="P(PCOS)", xlim=(0, 1.15))
|
| 79 |
+
ax.legend(); ax.grid(alpha=0.3, axis="x")
|
| 80 |
+
plt.tight_layout()
|
| 81 |
+
return fig
|
| 82 |
+
|
| 83 |
+
# ── Analysis function ─────────────────────────────────────────────────────────
|
| 84 |
+
def analyze(mode, image,
|
| 85 |
+
age, bmi, weight, waist, hip,
|
| 86 |
+
cycle_type, cycle_len,
|
| 87 |
+
fsh, lh, amh, prg, prl, tsh, vitd,
|
| 88 |
+
foll_l, foll_r, endo, rbs, bp_sys, bp_dia,
|
| 89 |
+
hair_growth, skin_dark, hair_loss, pimples,
|
| 90 |
+
weight_gain, fast_food, exercise):
|
| 91 |
+
|
| 92 |
+
use_image = "Image" in mode or "Combined" in mode
|
| 93 |
+
use_clinical = "Clinical" in mode or "Combined" in mode
|
| 94 |
+
|
| 95 |
+
html = ""
|
| 96 |
+
orig = None
|
| 97 |
+
heatmap = None
|
| 98 |
+
overlay = None
|
| 99 |
+
sev_fig = None
|
| 100 |
+
prob_fig = None
|
| 101 |
+
img_res = None
|
| 102 |
+
tab_res = None
|
| 103 |
+
|
| 104 |
+
TIER_COLOR = {"Low": "#27ae60", "Moderate": "#f39c12", "High": "#e74c3c"}
|
| 105 |
+
|
| 106 |
+
# ── IMAGE ─────────────────────────────────────────────────────────────────
|
| 107 |
+
if use_image:
|
| 108 |
+
if image is None:
|
| 109 |
+
html += "<p style='color:orange;'>⚠️ Please upload an ultrasound image.</p>"
|
| 110 |
+
elif image_model is None:
|
| 111 |
+
html += "<p style='color:red;'>❌ Image model not loaded. Add efficientnetb0.pth to models/ folder.</p>"
|
| 112 |
+
else:
|
| 113 |
+
try:
|
| 114 |
+
from utils.image_predictor import predict_image, generate_gradcam_overlay
|
| 115 |
+
pil = Image.fromarray(image).convert("RGB")
|
| 116 |
+
img_res = predict_image(image_model, pil)
|
| 117 |
+
r = img_res
|
| 118 |
+
c = TIER_COLOR[r["risk_category"]]
|
| 119 |
+
html += f"""
|
| 120 |
+
<div style='padding:1rem;border-radius:10px;border:1px solid #ddd;margin-bottom:1rem;'>
|
| 121 |
+
<h3>🖼️ Image Analysis</h3>
|
| 122 |
+
<div style='display:flex;gap:2rem;align-items:center;'>
|
| 123 |
+
<div>
|
| 124 |
+
<div style='font-size:2.5rem;font-weight:bold;color:{c};'>{r['prob_pcos']:.1%}</div>
|
| 125 |
+
<div style='color:{c};font-size:1.1rem;font-weight:600;'>{r['risk_category']} Risk — {r['pred_label']}</div>
|
| 126 |
+
<div style='color:#555;'>Not PCOS probability: {r['prob_not_pcos']:.1%}</div>
|
| 127 |
+
</div>
|
| 128 |
+
</div>
|
| 129 |
+
<div style='margin-top:0.75rem;padding:0.75rem;background:#f8f8f8;border-radius:6px;'>
|
| 130 |
+
💊 <b>Recommendation:</b> {r['recommendation']}
|
| 131 |
+
</div>
|
| 132 |
+
</div>"""
|
| 133 |
+
try:
|
| 134 |
+
ov, hm = generate_gradcam_overlay(image_model, pil, class_idx=1)
|
| 135 |
+
orig = np.array(pil.convert("RGB").resize((224, 224)))
|
| 136 |
+
heatmap = hm
|
| 137 |
+
overlay = ov
|
| 138 |
+
except Exception as e:
|
| 139 |
+
print(f"GradCAM error: {e}")
|
| 140 |
+
except Exception as e:
|
| 141 |
+
html += f"<p style='color:red;'>❌ Image error: {e}</p>"
|
| 142 |
+
|
| 143 |
+
# ── CLINICAL ──────────────────────────────────────────────────────────────
|
| 144 |
+
if use_clinical:
|
| 145 |
+
if tabular_arts is None:
|
| 146 |
+
html += "<p style='color:red;'>❌ Tabular model not loaded. Add pkl files to models/ folder.</p>"
|
| 147 |
+
else:
|
| 148 |
+
try:
|
| 149 |
+
from utils.tabular_predictor import predict_tabular
|
| 150 |
+
patient = {
|
| 151 |
+
"Age (yrs)": age, "BMI": bmi, "Weight (Kg)": weight,
|
| 152 |
+
"Waist(inch)": waist, "Hip(inch)": hip,
|
| 153 |
+
"Cycle(R/I)": 0 if cycle_type == "Regular" else 1,
|
| 154 |
+
"Cycle length(days)": cycle_len,
|
| 155 |
+
"FSH(mIU/mL)": fsh, "LH(mIU/mL)": lh,
|
| 156 |
+
"FSH/LH": round(fsh / (lh + 1e-6), 4),
|
| 157 |
+
"AMH(ng/mL)": amh, "PRG(ng/mL)": prg, "PRL(ng/mL)": prl,
|
| 158 |
+
"TSH (mIU/L)": tsh, "Vit D3 (ng/mL)": vitd,
|
| 159 |
+
"Follicle No. (L)": foll_l, "Follicle No. (R)": foll_r,
|
| 160 |
+
"Endometrium (mm)": endo, "RBS(mg/dl)": rbs,
|
| 161 |
+
"BP _Systolic (mmHg)": bp_sys, "BP _Diastolic (mmHg)": bp_dia,
|
| 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 |
+
"Weight gain(Y/N)": int(weight_gain),
|
| 167 |
+
"Fast food (Y/N)": int(fast_food),
|
| 168 |
+
"Reg.Exercise(Y/N)": int(exercise),
|
| 169 |
+
}
|
| 170 |
+
tab_res = predict_tabular(tabular_arts, patient)
|
| 171 |
+
r = tab_res
|
| 172 |
+
pc = TIER_COLOR[r["pcos_tier"]]
|
| 173 |
+
ic = TIER_COLOR[r["infertility_tier"]]
|
| 174 |
+
html += f"""
|
| 175 |
+
<div style='padding:1rem;border-radius:10px;border:1px solid #ddd;margin-bottom:1rem;'>
|
| 176 |
+
<h3>📋 Clinical Analysis</h3>
|
| 177 |
+
<div style='display:grid;grid-template-columns:1fr 1fr;gap:1rem;'>
|
| 178 |
+
<div style='padding:1rem;background:#f8f8f8;border-radius:8px;border-left:5px solid {pc};'>
|
| 179 |
+
<b>PCOS Risk</b><br>
|
| 180 |
+
<span style='font-size:2rem;font-weight:bold;color:{pc};'>{r['pcos_prob']:.1%}</span><br>
|
| 181 |
+
<span style='color:{pc};font-weight:600;'>{r['pcos_tier']} — {r['pcos_prediction']}</span>
|
| 182 |
+
</div>
|
| 183 |
+
<div style='padding:1rem;background:#f8f8f8;border-radius:8px;border-left:5px solid {ic};'>
|
| 184 |
+
<b>Infertility Risk</b><br>
|
| 185 |
+
<span style='font-size:2rem;font-weight:bold;color:{ic};'>{r['infertility_score']:.1%}</span><br>
|
| 186 |
+
<span style='color:{ic};font-weight:600;'>{r['infertility_tier']}</span>
|
| 187 |
+
</div>
|
| 188 |
+
</div>
|
| 189 |
+
<p style='margin-top:0.5rem;'>
|
| 190 |
+
<b>Overall PCOS Severity:</b> {r['overall_severity']:.3f} |
|
| 191 |
+
<b>Threshold:</b> {r['threshold']:.3f}
|
| 192 |
+
</p>
|
| 193 |
+
</div>"""
|
| 194 |
+
sev_fig = severity_plot(r["domain_scores"], r["overall_severity"])
|
| 195 |
+
prob_fig = base_model_plot(r["base_probs"])
|
| 196 |
+
except Exception as e:
|
| 197 |
+
html += f"<p style='color:red;'>❌ Clinical error: {e}</p>"
|
| 198 |
+
|
| 199 |
+
# ── COMBINED ──────────────────────────────────────────────────────────────
|
| 200 |
+
if use_image and use_clinical and img_res and tab_res:
|
| 201 |
+
combined = (img_res["prob_pcos"] + tab_res["pcos_prob"]) / 2
|
| 202 |
+
if combined < 0.33: ctier = "Low"; cc = "#27ae60"
|
| 203 |
+
elif combined < 0.66: ctier = "Moderate"; cc = "#f39c12"
|
| 204 |
+
else: ctier = "High"; cc = "#e74c3c"
|
| 205 |
+
|
| 206 |
+
recs = {
|
| 207 |
+
"Low": ["✅ Low PCOS probability from both imaging and clinical markers.",
|
| 208 |
+
"📅 Routine annual monitoring recommended.",
|
| 209 |
+
"🥗 Maintain healthy BMI and regular exercise."],
|
| 210 |
+
"Moderate": ["⚠️ Moderate PCOS probability — clinical evaluation recommended.",
|
| 211 |
+
"🔬 Hormonal workup: FSH, LH, AMH, Testosterone.",
|
| 212 |
+
f"🧬 Infertility risk: {tab_res['infertility_tier']} — discuss fertility planning.",
|
| 213 |
+
"👩⚕️ Gynaecologist referral within 4–6 weeks."],
|
| 214 |
+
"High": ["🚨 High PCOS probability — urgent clinical review.",
|
| 215 |
+
"👩⚕️ Gynaecologist referral recommended immediately.",
|
| 216 |
+
"🔬 Comprehensive hormonal + metabolic screening.",
|
| 217 |
+
f"🧬 Infertility risk: {tab_res['infertility_tier']} — fertility specialist advised."],
|
| 218 |
+
}
|
| 219 |
+
rec_li = "".join(f"<li>{x}</li>" for x in recs[ctier])
|
| 220 |
+
html += f"""
|
| 221 |
+
<div style='padding:1rem;border-radius:10px;border:2px solid {cc};margin-top:0.5rem;'>
|
| 222 |
+
<h3>🔬 Combined Dual-Modal Report</h3>
|
| 223 |
+
<div style='display:grid;grid-template-columns:1fr 1fr 1fr;gap:1rem;text-align:center;'>
|
| 224 |
+
<div style='padding:1rem;background:#f8f8f8;border-radius:8px;'>
|
| 225 |
+
<div style='font-size:0.8rem;color:#666;'>Image Model</div>
|
| 226 |
+
<div style='font-size:1.8rem;font-weight:bold;color:#667eea;'>{img_res['prob_pcos']:.1%}</div>
|
| 227 |
+
<div>{img_res['risk_category']}</div>
|
| 228 |
+
</div>
|
| 229 |
+
<div style='padding:1rem;background:#f8f8f8;border-radius:8px;'>
|
| 230 |
+
<div style='font-size:0.8rem;color:#666;'>Clinical Model</div>
|
| 231 |
+
<div style='font-size:1.8rem;font-weight:bold;color:#667eea;'>{tab_res['pcos_prob']:.1%}</div>
|
| 232 |
+
<div>{tab_res['pcos_tier']}</div>
|
| 233 |
+
</div>
|
| 234 |
+
<div style='padding:1rem;background:#f8f8f8;border-radius:8px;border:2px solid {cc};'>
|
| 235 |
+
<div style='font-size:0.8rem;color:#666;'>Combined</div>
|
| 236 |
+
<div style='font-size:1.8rem;font-weight:bold;color:{cc};'>{combined:.1%}</div>
|
| 237 |
+
<div style='color:{cc};font-weight:bold;'>{ctier} Risk</div>
|
| 238 |
+
</div>
|
| 239 |
+
</div>
|
| 240 |
+
<b>Clinical Recommendations:</b>
|
| 241 |
+
<ul>{rec_li}</ul>
|
| 242 |
+
</div>"""
|
| 243 |
+
|
| 244 |
+
if not html:
|
| 245 |
+
html = "<p style='color:orange;'>Please select a mode, upload image and/or fill clinical features, then click Run Analysis.</p>"
|
| 246 |
+
|
| 247 |
+
return html, orig, heatmap, overlay, sev_fig, prob_fig
|
| 248 |
+
|
| 249 |
+
# ── UI ────────────────────────────────────────────────────────────────────────
|
| 250 |
+
img_status = "✅ Ready" if image_model is not None else "❌ Not loaded"
|
| 251 |
+
tab_status = "✅ Ready" if tabular_arts is not None else "❌ Not loaded"
|
| 252 |
+
|
| 253 |
+
with gr.Blocks(title="PCOS Detection & Risk Assessment", theme=gr.themes.Soft()) as demo:
|
| 254 |
+
|
| 255 |
+
gr.HTML(f"""
|
| 256 |
+
<div style='background:linear-gradient(135deg,#667eea,#764ba2);
|
| 257 |
+
padding:1.5rem;border-radius:12px;color:white;text-align:center;margin-bottom:1rem;'>
|
| 258 |
+
<h1 style='color:white;margin:0;'>🩺 PCOS Detection & Risk Assessment</h1>
|
| 259 |
+
<p style='color:rgba(255,255,255,0.9);margin:0.4rem 0 0;'>
|
| 260 |
+
EfficientNetB0 (Image) + Stacked Ensemble (Clinical) | AUC 0.953 | Grad-CAM Explainability
|
| 261 |
+
</p>
|
| 262 |
+
</div>
|
| 263 |
+
<div style='background:#f0f0f0;padding:0.6rem 1rem;border-radius:8px;margin-bottom:1rem;
|
| 264 |
+
display:flex;gap:2rem;font-size:0.9rem;'>
|
| 265 |
+
<span>🖼️ Image model: <b>{img_status}</b></span>
|
| 266 |
+
<span>📋 Tabular model: <b>{tab_status}</b></span>
|
| 267 |
+
<span style='color:#888;font-size:0.8rem;'>⚠️ For research purposes only</span>
|
| 268 |
+
</div>""")
|
| 269 |
+
|
| 270 |
+
mode = gr.Radio(
|
| 271 |
+
choices=["🖼️ Ultrasound Image Only",
|
| 272 |
+
"📋 Clinical Features Only",
|
| 273 |
+
"🔬 Combined (Image + Clinical)"],
|
| 274 |
+
value="🔬 Combined (Image + Clinical)",
|
| 275 |
+
label="Analysis Mode")
|
| 276 |
+
|
| 277 |
+
with gr.Row():
|
| 278 |
+
|
| 279 |
+
# LEFT — inputs
|
| 280 |
+
with gr.Column(scale=1):
|
| 281 |
+
|
| 282 |
+
gr.Markdown("### 🖼️ Ultrasound Image")
|
| 283 |
+
image_in = gr.Image(label="Upload PCOS ultrasound (PNG/JPG)", type="numpy")
|
| 284 |
+
|
| 285 |
+
gr.Markdown("### 📋 Clinical Features")
|
| 286 |
+
|
| 287 |
+
with gr.Accordion("Anthropometric", open=True):
|
| 288 |
+
with gr.Row():
|
| 289 |
+
age = gr.Number(label="Age (yrs)", value=28, minimum=15, maximum=60)
|
| 290 |
+
bmi = gr.Number(label="BMI (kg/m²)", value=24.0)
|
| 291 |
+
weight = gr.Number(label="Weight (kg)", value=60.0)
|
| 292 |
+
with gr.Row():
|
| 293 |
+
waist = gr.Number(label="Waist (inch)", value=30.0)
|
| 294 |
+
hip = gr.Number(label="Hip (inch)", value=36.0)
|
| 295 |
+
|
| 296 |
+
with gr.Accordion("Cycle", open=True):
|
| 297 |
+
with gr.Row():
|
| 298 |
+
cycle_type = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle type")
|
| 299 |
+
cycle_len = gr.Number(label="Cycle length (days)", value=30)
|
| 300 |
+
|
| 301 |
+
with gr.Accordion("Hormonal Panel", open=True):
|
| 302 |
+
with gr.Row():
|
| 303 |
+
fsh = gr.Number(label="FSH (mIU/mL)", value=6.0)
|
| 304 |
+
lh = gr.Number(label="LH (mIU/mL)", value=8.0)
|
| 305 |
+
amh = gr.Number(label="AMH (ng/mL)", value=3.5)
|
| 306 |
+
with gr.Row():
|
| 307 |
+
prg = gr.Number(label="Progesterone (ng/mL)", value=1.0)
|
| 308 |
+
prl = gr.Number(label="Prolactin (ng/mL)", value=15.0)
|
| 309 |
+
tsh = gr.Number(label="TSH (mIU/L)", value=2.5)
|
| 310 |
+
vitd = gr.Number(label="Vit D3 (ng/mL)", value=25.0)
|
| 311 |
+
|
| 312 |
+
with gr.Accordion("Ultrasound / Metabolic", open=True):
|
| 313 |
+
with gr.Row():
|
| 314 |
+
foll_l = gr.Number(label="Follicle No. (L)", value=6, minimum=0)
|
| 315 |
+
foll_r = gr.Number(label="Follicle No. (R)", value=6, minimum=0)
|
| 316 |
+
endo = gr.Number(label="Endometrium (mm)", value=7.0)
|
| 317 |
+
with gr.Row():
|
| 318 |
+
rbs = gr.Number(label="RBS (mg/dl)", value=95.0)
|
| 319 |
+
bp_sys = gr.Number(label="BP Systolic (mmHg)", value=110)
|
| 320 |
+
bp_dia = gr.Number(label="BP Diastolic (mmHg)", value=70)
|
| 321 |
+
|
| 322 |
+
with gr.Accordion("Symptoms", open=False):
|
| 323 |
+
with gr.Row():
|
| 324 |
+
hair_growth = gr.Checkbox(label="Hair growth")
|
| 325 |
+
skin_dark = gr.Checkbox(label="Skin darkening")
|
| 326 |
+
hair_loss = gr.Checkbox(label="Hair loss")
|
| 327 |
+
with gr.Row():
|
| 328 |
+
pimples = gr.Checkbox(label="Pimples")
|
| 329 |
+
weight_gain = gr.Checkbox(label="Weight gain")
|
| 330 |
+
fast_food = gr.Checkbox(label="Fast food")
|
| 331 |
+
exercise = gr.Checkbox(label="Regular exercise")
|
| 332 |
+
|
| 333 |
+
run_btn = gr.Button("🔍 Run Analysis", variant="primary", size="lg")
|
| 334 |
+
|
| 335 |
+
# RIGHT — outputs
|
| 336 |
+
with gr.Column(scale=1):
|
| 337 |
+
|
| 338 |
+
results_html = gr.HTML()
|
| 339 |
+
|
| 340 |
+
gr.Markdown("### 🔬 Grad-CAM Explainability")
|
| 341 |
+
with gr.Row():
|
| 342 |
+
orig_out = gr.Image(label="Original", height=200)
|
| 343 |
+
hm_out = gr.Image(label="Heatmap", height=200)
|
| 344 |
+
ov_out = gr.Image(label="Overlay", height=200)
|
| 345 |
+
gr.HTML("<small style='color:#666;'>🔴 Warm regions = areas the model focuses on for PCOS detection</small>")
|
| 346 |
+
|
| 347 |
+
gr.Markdown("### 📊 Domain Severity Scores")
|
| 348 |
+
sev_out = gr.Plot()
|
| 349 |
+
|
| 350 |
+
gr.Markdown("### 🤖 Base Model Probabilities")
|
| 351 |
+
prob_out = gr.Plot()
|
| 352 |
+
|
| 353 |
+
run_btn.click(
|
| 354 |
+
fn=analyze,
|
| 355 |
+
inputs=[mode, image_in,
|
| 356 |
+
age, bmi, weight, waist, hip,
|
| 357 |
+
cycle_type, cycle_len,
|
| 358 |
+
fsh, lh, amh, prg, prl, tsh, vitd,
|
| 359 |
+
foll_l, foll_r, endo, rbs, bp_sys, bp_dia,
|
| 360 |
+
hair_growth, skin_dark, hair_loss, pimples,
|
| 361 |
+
weight_gain, fast_food, exercise],
|
| 362 |
+
outputs=[results_html, orig_out, hm_out, ov_out, sev_out, prob_out],
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
gr.HTML("""
|
| 366 |
+
<div style='text-align:center;color:#888;font-size:0.8rem;padding:1rem;border-top:1px solid #eee;margin-top:1rem;'>
|
| 367 |
+
PCOS Detection & Risk Assessment System | For Research & Educational Purposes Only
|
| 368 |
+
</div>""")
|
| 369 |
+
|
| 370 |
+
if __name__ == "__main__":
|
| 371 |
+
demo.launch()
|
models/base_models.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5eaca3bc272f79977630bce45c713b925213e2004e9e359706062b3c29ac82da
|
| 3 |
+
size 5442431
|
models/best_threshold.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d2bd4219181aa0bdab9b5fa2ebcdcf46c30b639cd6ef3baa09ce1c5683cb0f9
|
| 3 |
+
size 21
|
models/deployment_config.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_model": "Stacked Ensemble",
|
| 3 |
+
"meta_learner": "CalibratedClassifierCV(LogisticRegressionCV)",
|
| 4 |
+
"base_models": [
|
| 5 |
+
"Logistic",
|
| 6 |
+
"RandomForest",
|
| 7 |
+
"GradientBoost",
|
| 8 |
+
"CatBoost"
|
| 9 |
+
],
|
| 10 |
+
"optimal_threshold": 0.3173,
|
| 11 |
+
"risk_bins": {
|
| 12 |
+
"Low": "<33%",
|
| 13 |
+
"Moderate": "33\u201366%",
|
| 14 |
+
"High": ">66%"
|
| 15 |
+
},
|
| 16 |
+
"test_metrics": {
|
| 17 |
+
"Model": "Ensemble",
|
| 18 |
+
"Accuracy": 0.9541,
|
| 19 |
+
"Precision": 0.9697,
|
| 20 |
+
"Recall": 0.8889,
|
| 21 |
+
"Sensitivity": 0.8889,
|
| 22 |
+
"Specificity": 0.9863,
|
| 23 |
+
"F1": 0.9275,
|
| 24 |
+
"ROC_AUC": 0.9532,
|
| 25 |
+
"PR_AUC": 0.9413,
|
| 26 |
+
"MCC": 0.8959,
|
| 27 |
+
"Brier": 0.0637,
|
| 28 |
+
"TP": 32,
|
| 29 |
+
"TN": 72,
|
| 30 |
+
"FP": 1,
|
| 31 |
+
"FN": 4
|
| 32 |
+
},
|
| 33 |
+
"inference_steps": [
|
| 34 |
+
"1. clean_df_cols(patient_df)",
|
| 35 |
+
"2. mice.transform(X) \u2014 never refit",
|
| 36 |
+
"3. scaler.transform(X_imp) \u2014 never refit",
|
| 37 |
+
"4. apply_severity(domain_models, stats, X_raw, X_sc)",
|
| 38 |
+
"5. X_final = concat([X_sc, severity_df])",
|
| 39 |
+
"6. base probs: {name: model.predict_proba(X_final)[:,1]}",
|
| 40 |
+
"7. meta.predict_proba(base_probs_df)[:,1] \u2192 PCOS prob",
|
| 41 |
+
"8. prob >= best_threshold \u2192 prediction"
|
| 42 |
+
]
|
| 43 |
+
}
|
models/domain_models.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6e001c3d4d77e7f5c97e33d216f5fbc769ff4eda108606d4296b75732a77611a
|
| 3 |
+
size 789372
|
models/efficientnetb0.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5508e132dec61799ad47917bb148831c6798a81651fedcba56d941794b7458b4
|
| 3 |
+
size 48601848
|
models/ensemble_meta.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e534173821fb2fcbffb34d15e9310cd0dbb274296e3ca76da87d780bff7ab74
|
| 3 |
+
size 23548
|
models/feature_columns.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a29f8c420e31db21cd10a1e3c9cce32d53a9b50abdea9bb26906f0cfdef4680c
|
| 3 |
+
size 804
|
models/mice_imputer.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6119744f40d8d127542f581fc7fa505870996919c68b0cbe51abac39f9c47d88
|
| 3 |
+
size 1288465
|
models/scaler.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eeffc17c0b7de81122cfa8c8424b59450b493c9aa56fe075a292f2660ad6b418
|
| 3 |
+
size 2135
|
models/train_stats.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cea7d0d53b2c0a2b14c712891a688b1242ba77af9137902f7868b50b630bc6d9
|
| 3 |
+
size 349
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.0.0
|
| 2 |
+
torchvision>=0.15.0
|
| 3 |
+
numpy>=2.1.0
|
| 4 |
+
pandas>=2.0.0
|
| 5 |
+
scikit-learn>=1.5.0
|
| 6 |
+
catboost>=1.2.0
|
| 7 |
+
joblib>=1.3.0
|
| 8 |
+
Pillow>=10.0.0
|
| 9 |
+
opencv-python-headless>=4.8.0
|
| 10 |
+
matplotlib>=3.7.0
|
| 11 |
+
scipy>=1.11.0
|
utils/__init__.py
ADDED
|
File without changes
|
utils/image_predictor.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torchvision import models, transforms
|
| 7 |
+
|
| 8 |
+
IMG_SIZE = 224
|
| 9 |
+
DEVICE = torch.device("cpu")
|
| 10 |
+
|
| 11 |
+
PREPROCESS = transforms.Compose([
|
| 12 |
+
transforms.Resize((IMG_SIZE, IMG_SIZE)),
|
| 13 |
+
transforms.ToTensor(),
|
| 14 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 15 |
+
std =[0.229, 0.224, 0.225]),
|
| 16 |
+
])
|
| 17 |
+
|
| 18 |
+
RECOMMENDATIONS = {
|
| 19 |
+
"Low" : "Low PCOS probability. Routine monitoring recommended.",
|
| 20 |
+
"Moderate": "Moderate PCOS probability. Clinical evaluation and hormonal panel recommended.",
|
| 21 |
+
"High" : "High PCOS probability. Urgent clinical review and comprehensive workup advised.",
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
def load_image_model(model_path):
|
| 25 |
+
model = models.efficientnet_b0(weights=None)
|
| 26 |
+
in_features = model.classifier[1].in_features
|
| 27 |
+
model.classifier[1] = nn.Linear(in_features, 2)
|
| 28 |
+
checkpoint = torch.load(model_path, map_location=DEVICE, weights_only=False)
|
| 29 |
+
if isinstance(checkpoint, dict) and "model_state" in checkpoint:
|
| 30 |
+
model.load_state_dict(checkpoint["model_state"])
|
| 31 |
+
else:
|
| 32 |
+
model.load_state_dict(checkpoint)
|
| 33 |
+
model.eval()
|
| 34 |
+
return model.to(DEVICE)
|
| 35 |
+
|
| 36 |
+
def predict_image(model, pil_image):
|
| 37 |
+
tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE)
|
| 38 |
+
with torch.no_grad():
|
| 39 |
+
out = model(tensor)
|
| 40 |
+
probs = torch.softmax(out, dim=1)[0]
|
| 41 |
+
prob_pcos = round(probs[1].item(), 4)
|
| 42 |
+
prob_not = round(probs[0].item(), 4)
|
| 43 |
+
if prob_pcos < 0.33: cat = "Low"
|
| 44 |
+
elif prob_pcos < 0.66: cat = "Moderate"
|
| 45 |
+
else: cat = "High"
|
| 46 |
+
return {
|
| 47 |
+
"prob_pcos" : prob_pcos,
|
| 48 |
+
"prob_not_pcos" : prob_not,
|
| 49 |
+
"risk_score" : round(prob_pcos * 100, 1),
|
| 50 |
+
"risk_category" : cat,
|
| 51 |
+
"recommendation": RECOMMENDATIONS[cat],
|
| 52 |
+
"pred_label" : "PCOS" if prob_pcos >= 0.5 else "Not PCOS",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
class GradCAM:
|
| 56 |
+
def __init__(self, model, target_layer):
|
| 57 |
+
self.model = model
|
| 58 |
+
self.gradients = None
|
| 59 |
+
self.activations = None
|
| 60 |
+
self._fh = target_layer.register_forward_hook(self._save_act)
|
| 61 |
+
self._bh = target_layer.register_full_backward_hook(self._save_grad)
|
| 62 |
+
|
| 63 |
+
def _save_act(self, m, i, o): self.activations = o.detach()
|
| 64 |
+
def _save_grad(self, m, gi, go): self.gradients = go[0].detach()
|
| 65 |
+
|
| 66 |
+
def generate(self, tensor, class_idx=1):
|
| 67 |
+
self.model.zero_grad()
|
| 68 |
+
out = self.model(tensor)
|
| 69 |
+
out[0, class_idx].backward()
|
| 70 |
+
grads = self.gradients[0]
|
| 71 |
+
acts = self.activations[0]
|
| 72 |
+
weights = grads.mean(dim=(1, 2))
|
| 73 |
+
cam = torch.zeros(acts.shape[1:])
|
| 74 |
+
for i, w in enumerate(weights):
|
| 75 |
+
cam += w * acts[i]
|
| 76 |
+
cam = torch.relu(cam).numpy()
|
| 77 |
+
cam -= cam.min()
|
| 78 |
+
if cam.max() > 0: cam /= cam.max()
|
| 79 |
+
return cam
|
| 80 |
+
|
| 81 |
+
def remove(self):
|
| 82 |
+
self._fh.remove(); self._bh.remove()
|
| 83 |
+
|
| 84 |
+
def generate_gradcam_overlay(model, pil_image, class_idx=1):
|
| 85 |
+
img_rgb = np.array(pil_image.convert("RGB").resize((IMG_SIZE, IMG_SIZE)))
|
| 86 |
+
tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE)
|
| 87 |
+
tensor.requires_grad_(True)
|
| 88 |
+
gcam = GradCAM(model, model.features[-1])
|
| 89 |
+
cam = gcam.generate(tensor, class_idx=class_idx)
|
| 90 |
+
gcam.remove()
|
| 91 |
+
cam_r = cv2.resize(cam, (IMG_SIZE, IMG_SIZE))
|
| 92 |
+
heatmap = cv2.applyColorMap(np.uint8(255 * cam_r), cv2.COLORMAP_JET)
|
| 93 |
+
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
|
| 94 |
+
overlay = (0.5 * img_rgb + 0.5 * heatmap).astype(np.uint8)
|
| 95 |
+
return overlay, heatmap
|
utils/tabular_predictor.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import joblib
|
| 5 |
+
|
| 6 |
+
DEPLOY_DIR = os.path.join(os.path.dirname(__file__), "..", "models")
|
| 7 |
+
|
| 8 |
+
DOMAIN_WEIGHTS = {
|
| 9 |
+
"METABOLIC": 0.35, "REPRODUCTIVE": 0.40,
|
| 10 |
+
"HYPERANDROGENIC": 0.20, "GENERAL": 0.05,
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
BIOMARKER_DIRECTIONS = {
|
| 14 |
+
"FSH(mIU/mL)": 1, "LH(mIU/mL)": -1, "FSH/LH": 1,
|
| 15 |
+
"AMH(ng/mL)": -1, "Follicle No. (L)": -1, "Follicle No. (R)": -1,
|
| 16 |
+
"Endometrium (mm)": -1, "PRG(ng/mL)": -1, "Cycle(R/I)": 1,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
BIOMARKER_WEIGHTS = {
|
| 20 |
+
"FSH(mIU/mL)": 0.18, "LH(mIU/mL)": 0.08, "FSH/LH": 0.15,
|
| 21 |
+
"AMH(ng/mL)": 0.22, "Follicle No. (L)": 0.10, "Follicle No. (R)": 0.10,
|
| 22 |
+
"Endometrium (mm)": 0.08, "PRG(ng/mL)": 0.05, "Cycle(R/I)": 0.04,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
CLINICAL_RANGES = {
|
| 26 |
+
"FSH(mIU/mL)": (1.0, 30.0), "LH(mIU/mL)": (0.5, 40.0),
|
| 27 |
+
"FSH/LH": (0.1, 5.0), "AMH(ng/mL)": (0.1, 15.0),
|
| 28 |
+
"Follicle No. (L)": (0.0, 25.0), "Follicle No. (R)": (0.0, 25.0),
|
| 29 |
+
"Endometrium (mm)": (2.0, 16.0), "PRG(ng/mL)": (0.1, 25.0),
|
| 30 |
+
"Cycle(R/I)": (0.0, 1.0),
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
def clean_name(n):
|
| 34 |
+
return re.sub(r"[^0-9a-zA-Z_]", "_", n.strip())
|
| 35 |
+
|
| 36 |
+
def load_tabular_artifacts():
|
| 37 |
+
arts = {}
|
| 38 |
+
for key, fname in [
|
| 39 |
+
("meta", "ensemble_meta.pkl"), ("base_models", "base_models.pkl"),
|
| 40 |
+
("domain_models", "domain_models.pkl"), ("mice", "mice_imputer.pkl"),
|
| 41 |
+
("scaler", "scaler.pkl"), ("stats", "train_stats.pkl"),
|
| 42 |
+
("feat_cols", "feature_columns.pkl"), ("threshold", "best_threshold.pkl"),
|
| 43 |
+
]:
|
| 44 |
+
path = os.path.join(DEPLOY_DIR, fname)
|
| 45 |
+
arts[key] = joblib.load(path) if os.path.exists(path) else None
|
| 46 |
+
return arts
|
| 47 |
+
|
| 48 |
+
def _apply_severity(domain_models, stats, X_sc):
|
| 49 |
+
result = pd.DataFrame(index=X_sc.index)
|
| 50 |
+
for d, (model, fc) in domain_models.items():
|
| 51 |
+
avail = [c for c in fc if c in X_sc.columns]
|
| 52 |
+
if not avail:
|
| 53 |
+
result[f"{d}_SEV"] = 0.0
|
| 54 |
+
continue
|
| 55 |
+
p = model.predict_proba(X_sc[avail])[:, 1]
|
| 56 |
+
mn, mx = stats[d]["min"], stats[d]["max"]
|
| 57 |
+
result[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1)
|
| 58 |
+
result = result.fillna(0)
|
| 59 |
+
result["OVERALL_SEV"] = sum(
|
| 60 |
+
result[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
|
| 61 |
+
for d in DOMAIN_WEIGHTS if f"{d}_SEV" in result.columns
|
| 62 |
+
)
|
| 63 |
+
return result
|
| 64 |
+
|
| 65 |
+
def predict_tabular(arts, patient_dict):
|
| 66 |
+
feat_cols = arts["feat_cols"]
|
| 67 |
+
|
| 68 |
+
raw = pd.DataFrame([patient_dict])
|
| 69 |
+
if "FSH(mIU/mL)" in raw and "LH(mIU/mL)" in raw:
|
| 70 |
+
raw["FSH_LH_Ratio"] = raw["FSH(mIU/mL)"] / (raw["LH(mIU/mL)"] + 1e-6)
|
| 71 |
+
if "Follicle No. (L)" in raw and "Follicle No. (R)" in raw:
|
| 72 |
+
raw["Total_Follicles"] = raw["Follicle No. (L)"].fillna(0) + raw["Follicle No. (R)"].fillna(0)
|
| 73 |
+
if "AMH(ng/mL)" in raw and "FSH(mIU/mL)" in raw:
|
| 74 |
+
raw["AMH_FSH_Ratio"] = raw["AMH(ng/mL)"] / (raw["FSH(mIU/mL)"] + 1e-6)
|
| 75 |
+
if "BMI" in raw and "Waist(inch)" in raw:
|
| 76 |
+
raw["BMI_Waist_Ratio"] = raw["BMI"] / (raw["Waist(inch)"] + 1e-6)
|
| 77 |
+
andro = ["hair growth(Y/N)", "Skin darkening (Y/N)", "Hair loss(Y/N)", "Pimples(Y/N)", "PRL(ng/mL)"]
|
| 78 |
+
present = [f for f in andro if f in raw.columns]
|
| 79 |
+
if present:
|
| 80 |
+
raw["Androgenic_Score"] = raw[present].sum(axis=1)
|
| 81 |
+
|
| 82 |
+
raw_clean = raw.copy()
|
| 83 |
+
raw_clean.columns = [clean_name(c) for c in raw_clean.columns]
|
| 84 |
+
|
| 85 |
+
X = pd.DataFrame(columns=feat_cols)
|
| 86 |
+
X = pd.concat([X, raw_clean.reindex(columns=feat_cols)], ignore_index=True)
|
| 87 |
+
X = X.astype(float)
|
| 88 |
+
|
| 89 |
+
X_imp = pd.DataFrame(arts["mice"].transform(X), columns=X.columns, index=X.index)
|
| 90 |
+
X_sc = X_imp.copy()
|
| 91 |
+
num_c = X_sc.select_dtypes(include=np.number).columns
|
| 92 |
+
X_sc[num_c] = arts["scaler"].transform(X_imp[num_c])
|
| 93 |
+
|
| 94 |
+
sev = _apply_severity(arts["domain_models"], arts["stats"], X_sc)
|
| 95 |
+
X_final = pd.concat([X_sc, sev], axis=1)
|
| 96 |
+
|
| 97 |
+
base_probs = {}
|
| 98 |
+
for name, model in arts["base_models"].items():
|
| 99 |
+
try:
|
| 100 |
+
base_probs[name] = float(model.predict_proba(X_final)[:, 1][0])
|
| 101 |
+
except:
|
| 102 |
+
base_probs[name] = 0.5
|
| 103 |
+
|
| 104 |
+
meta_input = pd.DataFrame([base_probs])
|
| 105 |
+
pcos_prob = float(arts["meta"].predict_proba(meta_input)[:, 1][0])
|
| 106 |
+
threshold = float(arts["threshold"])
|
| 107 |
+
|
| 108 |
+
if pcos_prob < 0.33: pcos_tier = "Low"
|
| 109 |
+
elif pcos_prob < 0.66: pcos_tier = "Moderate"
|
| 110 |
+
else: pcos_tier = "High"
|
| 111 |
+
|
| 112 |
+
domain_scores = {
|
| 113 |
+
d: round(float(sev[f"{d}_SEV"].iloc[0]), 4)
|
| 114 |
+
for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev.columns
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
# Infertility risk
|
| 118 |
+
score = 0.0; total_w = 0.0
|
| 119 |
+
for feat, val in patient_dict.items():
|
| 120 |
+
if feat not in BIOMARKER_WEIGHTS or val is None: continue
|
| 121 |
+
lo, hi = CLINICAL_RANGES.get(feat, (0, 1))
|
| 122 |
+
norm = np.clip((float(val) - lo) / (hi - lo + 1e-6), 0, 1)
|
| 123 |
+
if BIOMARKER_DIRECTIONS.get(feat, 1) == -1: norm = 1 - norm
|
| 124 |
+
w = BIOMARKER_WEIGHTS[feat]
|
| 125 |
+
score += w * norm; total_w += w
|
| 126 |
+
inf_score = score / total_w if total_w > 0 else 0.5
|
| 127 |
+
if inf_score < 0.33: inf_tier = "Low"
|
| 128 |
+
elif inf_score < 0.66: inf_tier = "Moderate"
|
| 129 |
+
else: inf_tier = "High"
|
| 130 |
+
|
| 131 |
+
return {
|
| 132 |
+
"pcos_prob" : round(pcos_prob, 4),
|
| 133 |
+
"pcos_prediction" : "PCOS" if pcos_prob >= threshold else "Not PCOS",
|
| 134 |
+
"pcos_tier" : pcos_tier,
|
| 135 |
+
"threshold" : round(threshold, 4),
|
| 136 |
+
"base_probs" : {k: round(v, 4) for k, v in base_probs.items()},
|
| 137 |
+
"domain_scores" : domain_scores,
|
| 138 |
+
"overall_severity" : round(float(sev["OVERALL_SEV"].iloc[0]), 4),
|
| 139 |
+
"infertility_score": round(inf_score, 4),
|
| 140 |
+
"infertility_tier" : inf_tier,
|
| 141 |
+
}
|