DheivaCodes commited on
Commit
a51dc80
·
verified ·
1 Parent(s): 68fe087

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +332 -364
app.py CHANGED
@@ -1,371 +1,339 @@
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} &nbsp;|&nbsp;
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(ssr_mode=False, server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, re, warnings
2
+ import streamlit as st
 
3
  import numpy as np
4
+ import pandas as pd
 
5
  import matplotlib.pyplot as plt
6
+ warnings.filterwarnings("ignore")
 
 
 
 
 
 
 
7
 
8
+ st.set_page_config(page_title="PCOS Detection & Risk Assessment",
9
+ page_icon="🩺", layout="wide", initial_sidebar_state="expanded")
10
+
11
+ st.markdown("""
12
+ <style>
13
+ @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');
14
+ html,body,[class*="css"]{font-family:'Plus Jakarta Sans',sans-serif;}
15
+ .stApp{background:#f0f4ff;}
16
+ div[data-testid="stSidebar"]{background:#fff;box-shadow:2px 0 12px rgba(0,0,0,.07);}
17
+ .hero{background:linear-gradient(135deg,#4f46e5,#7c3aed);border-radius:18px;padding:30px 34px;color:#fff;margin-bottom:22px;}
18
+ .hero h1{font-size:1.85rem;font-weight:700;margin:0 0 5px;}
19
+ .hero p{font-size:.92rem;opacity:.88;margin:0;}
20
+ .card{background:#fff;border-radius:14px;padding:20px 22px;box-shadow:0 2px 10px rgba(0,0,0,.06);margin-bottom:12px;}
21
+ .cl{border-left:4px solid #4f46e5;}.cg{border-left:4px solid #10b981;}
22
+ .cr{border-left:4px solid #ef4444;}.cy{border-left:4px solid #f59e0b;}
23
+ .mlabel{font-size:.7rem;color:#6b7280;font-weight:600;text-transform:uppercase;letter-spacing:.06em;}
24
+ .mval{font-size:1.6rem;font-weight:700;color:#111827;line-height:1.2;}
25
+ .msub{font-size:.78rem;color:#6b7280;margin-top:2px;}
26
+ .risk-lo{background:#ecfdf5;border:1.5px solid #10b981;border-radius:12px;padding:18px;}
27
+ .risk-md{background:#fffbeb;border:1.5px solid #f59e0b;border-radius:12px;padding:18px;}
28
+ .risk-hi{background:#fef2f2;border:1.5px solid #ef4444;border-radius:12px;padding:18px;}
29
+ .pill{display:inline-block;border-radius:999px;padding:3px 11px;font-size:.73rem;font-weight:600;}
30
+ .pg{background:#d1fae5;color:#065f46;}.pr{background:#fee2e2;color:#991b1b;}
31
+ .stButton>button{background:linear-gradient(135deg,#4f46e5,#7c3aed);color:#fff;
32
+ border:none;border-radius:10px;padding:11px 24px;font-weight:600;font-size:.93rem;width:100%;}
33
+ .shdr{font-size:.98rem;font-weight:700;color:#374151;border-bottom:2px solid #e5e7eb;padding-bottom:7px;margin:18px 0 12px;}
34
+ .info{background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:13px 17px;font-size:.84rem;color:#1e40af;margin-bottom:14px;}
35
+ </style>""", unsafe_allow_html=True)
36
+
37
+ DOMAIN_WEIGHTS = {"METABOLIC":0.35,"REPRODUCTIVE":0.40,"HYPERANDROGENIC":0.20,"GENERAL":0.05}
38
+
39
+ @st.cache_resource(show_spinner=False)
40
  def load_models():
41
+ import joblib
42
+ needed=["ensemble_meta","base_models","domain_models","train_stats","mice_imputer","scaler","feature_columns","best_threshold"]
43
+ missing=[f for f in needed if not os.path.exists(f"models/{f}.pkl")]
44
+ if missing: return None, f"Missing pkl files: {missing}"
 
 
 
 
 
 
 
 
 
45
  try:
46
+ return {
47
+ "meta": joblib.load("models/ensemble_meta.pkl"),
48
+ "base": joblib.load("models/base_models.pkl"),
49
+ "domain": joblib.load("models/domain_models.pkl"),
50
+ "stats": joblib.load("models/train_stats.pkl"),
51
+ "mice": joblib.load("models/mice_imputer.pkl"),
52
+ "scaler": joblib.load("models/scaler.pkl"),
53
+ "features": joblib.load("models/feature_columns.pkl"),
54
+ "threshold":joblib.load("models/best_threshold.pkl"),
55
+ }, None
56
+ except Exception as e: return None, str(e)
57
+
58
+
59
+ def apply_severity(domain_models, stats, X_raw, X_sc):
60
+ """Exact copy of pipeline apply_severity(models, stats, X_raw, X_sc)."""
61
+ df = pd.DataFrame(index=X_sc.index)
62
+ for d, (model, fc) in domain_models.items():
63
+ avail = [f for f in fc if f in X_sc.columns]
64
+ if not avail:
65
+ df[f"{d}_SEV"] = 0.0
66
+ continue
67
+ p = model.predict_proba(X_sc[avail])[:, 1]
68
+ lo, hi = stats[d]["min"], stats[d]["max"]
69
+ df[f"{d}_SEV"] = np.clip((p - lo) / (hi - lo + 1e-6), 0, 1)
70
+ df = df.fillna(0)
71
+ df["OVERALL_SEV"] = sum(
72
+ df[f"{d}_SEV"] * DOMAIN_WEIGHTS[d]
73
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  )
75
+ return df
76
+
77
+
78
+ def predict(inp, mdl):
79
+ """
80
+ Exact pipeline inference steps (deployment_config.json):
81
+ 1. Build raw row
82
+ 2. mice.transform (never refit)
83
+ 3. scaler.transform (never refit)
84
+ 4. apply_severity(domain_models, stats, X_raw, X_sc)
85
+ 5. X_final = concat([X_sc, severity_df])
86
+ 6. base probs
87
+ 7. meta.predict_proba
88
+ 8. prob >= threshold
89
+ """
90
+ # feature_columns = list(Xtr_f.columns) = scaled_cols + SEV_cols
91
+ all_fc = mdl["features"]
92
+
93
+ # Separate scaled feature cols from SEV cols
94
+ sev_col_names = [c for c in all_fc if c.endswith("_SEV")]
95
+ base_fc = [c for c in all_fc if not c.endswith("_SEV")]
96
+
97
+ # Step 1: build raw row with only base features
98
+ row_raw = pd.DataFrame([{c: inp.get(c, np.nan) for c in base_fc}])
99
+
100
+ # Step 2: MICE impute
101
+ row_imp = pd.DataFrame(
102
+ mdl["mice"].transform(row_raw), columns=base_fc, index=row_raw.index)
103
+
104
+ # Step 3: Scale
105
+ row_sc = pd.DataFrame(
106
+ mdl["scaler"].transform(row_imp), columns=base_fc, index=row_raw.index)
107
+
108
+ # Step 4: Domain severity — pass X_raw and X_sc (matching pipeline signature)
109
+ sev_df = apply_severity(mdl["domain"], mdl["stats"], row_raw, row_sc)
110
+
111
+ # Step 5: Concatenate to get full feature matrix matching feature_columns order
112
+ X_final = pd.concat([row_sc, sev_df], axis=1)
113
+
114
+ # Ensure column order exactly matches what models were trained on
115
+ X_final = X_final.reindex(columns=all_fc, fill_value=0)
116
+
117
+ # Step 6+7: Base probs → meta
118
+ base_probs = pd.DataFrame(
119
+ {name: m.predict_proba(X_final)[:, 1] for name, m in mdl["base"].items()})
120
+ prob = mdl["meta"].predict_proba(base_probs)[:, 1][0]
121
+
122
+ # Step 8: Threshold
123
+ pred = int(prob >= mdl["threshold"])
124
+
125
+ # Collect severity scores for display
126
+ sev_scores = {d: float(sev_df[f"{d}_SEV"].iloc[0]) for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev_df}
127
+ sev_scores["OVERALL"] = float(sev_df["OVERALL_SEV"].iloc[0])
128
+
129
+ return pred, float(prob), sev_scores, X_final, base_probs
130
+
131
+
132
+ def infertility_risk(inp):
133
+ parts=[]
134
+ amh=inp.get("AMH_ng_mL_",np.nan); fsh=inp.get("FSH_mIU_mL_",np.nan)
135
+ foll=(inp.get("Follicle_No___L_",0) or 0)+(inp.get("Follicle_No___R_",0) or 0)
136
+ cyc=inp.get("Cycle_R_I_",4); bmi=inp.get("BMI",np.nan)
137
+ if not np.isnan(amh): parts.append(("AMH Reserve",max(0,1-amh/5),0.35))
138
+ if not np.isnan(fsh): parts.append(("FSH Level",min(1,fsh/20),0.25))
139
+ if foll>0: parts.append(("Follicle Count",max(0,1-foll/20),0.20))
140
+ parts.append(("Cycle",0.70 if cyc==2 else 0.20,0.15))
141
+ if not np.isnan(bmi): parts.append(("BMI",0.6 if bmi<18.5 or bmi>30 else 0.3 if bmi>25 else 0.0,0.05))
142
+ if not parts: return 0.5,"Moderate",parts
143
+ tw=sum(w for _,_,w in parts); sc=sum(r*w for _,r,w in parts)/tw
144
+ return sc,("Low" if sc<0.35 else "High" if sc>=0.60 else "Moderate"),parts
145
+
146
+ def radar_chart(sev):
147
+ doms=["METABOLIC","REPRODUCTIVE","HYPERANDROGENIC","GENERAL"]
148
+ vals=[sev.get(d,0) for d in doms]+[sev.get(doms[0],0)]
149
+ ang=[n/len(doms)*2*np.pi for n in range(len(doms))]+[0]
150
+ fig,ax=plt.subplots(figsize=(4,4),subplot_kw=dict(polar=True))
151
+ fig.patch.set_facecolor("#f0f4ff"); ax.set_facecolor("#f0f4ff")
152
+ ax.plot(ang,vals,"o-",lw=2,color="#4f46e5"); ax.fill(ang,vals,alpha=0.22,color="#4f46e5")
153
+ ax.set_xticks(ang[:-1]); ax.set_xticklabels([d.capitalize() for d in doms],fontsize=8)
154
+ ax.set_ylim(0,1); ax.set_yticks([.25,.5,.75,1]); ax.set_yticklabels(["25%","50%","75%","100%"],fontsize=6)
155
+ ax.set_title("Domain Severity",fontsize=10,fontweight="bold",pad=14)
156
+ plt.tight_layout(); return fig
157
+
158
+ def prob_gauge(prob,title):
159
+ col="#ef4444" if prob>0.6 else "#f59e0b" if prob>0.4 else "#10b981"
160
+ fig,ax=plt.subplots(figsize=(4,2)); fig.patch.set_facecolor("#f0f4ff"); ax.set_facecolor("#f0f4ff")
161
+ ax.barh([0],[1],color="#e5e7eb",height=0.4); ax.barh([0],[prob],color=col,height=0.4)
162
+ ax.set_xlim(0,1); ax.set_ylim(-.5,.5); ax.set_yticks([])
163
+ ax.set_xticks([0,.25,.5,.75,1]); ax.set_xticklabels(["0%","25%","50%","75%","100%"],fontsize=8)
164
+ ax.set_title(f"{title}\n{prob:.1%}",fontsize=10,fontweight="bold",color=col)
165
+ ax.spines[["top","right","left"]].set_visible(False); plt.tight_layout(); return fig
166
+
167
+ def inf_bar(parts,score):
168
+ if not parts: return None
169
+ labels=[c[0] for c in parts]; vals=[c[1] for c in parts]
170
+ cols=["#ef4444" if v>0.6 else "#f59e0b" if v>0.35 else "#10b981" for v in vals]
171
+ fig,ax=plt.subplots(figsize=(5,2.8)); fig.patch.set_facecolor("#f0f4ff"); ax.set_facecolor("#f0f4ff")
172
+ bars=ax.barh(labels,vals,color=cols,height=0.5,edgecolor="white")
173
+ for b,v in zip(bars,vals): ax.text(v+.02,b.get_y()+b.get_height()/2,f"{v:.0%}",va="center",fontsize=8)
174
+ ax.axvline(score,color="#4f46e5",lw=1.5,ls="--",label=f"Score:{score:.0%}")
175
+ ax.set_xlim(0,1.15); ax.legend(fontsize=8); ax.spines[["top","right"]].set_visible(False)
176
+ ax.tick_params(labelsize=8); ax.set_title("Infertility Risk Factors",fontsize=10,fontweight="bold")
177
+ plt.tight_layout(); return fig
178
+
179
+ def sidebar_inputs():
180
+ st.sidebar.markdown("## 📋 Clinical Inputs")
181
+ inp={}
182
+ with st.sidebar.expander("👤 General",expanded=True):
183
+ inp["Age__yrs_"]=st.number_input("Age (yrs)",15,60,28)
184
+ inp["BMI"]=st.number_input("BMI",10.0,60.0,22.0,step=0.1)
185
+ inp["Weight__Kg_"]=st.number_input("Weight (kg)",30.0,150.0,60.0,step=0.5)
186
+ inp["Hb__g_dl_"]=st.number_input("Hb (g/dL)",5.0,18.0,13.0,step=0.1)
187
+ inp["Pulse_rate_bpm_"]=st.number_input("Pulse (bpm)",40,120,72)
188
+ inp["RR__breaths_min_"]=st.number_input("Resp Rate",10,30,16)
189
+ with st.sidebar.expander("🩸 Hormones & Labs"):
190
+ inp["FSH_mIU_mL_"]=st.number_input("FSH (mIU/mL)",0.0,50.0,7.0,step=0.1)
191
+ inp["LH_mIU_mL_"]=st.number_input("LH (mIU/mL)",0.0,50.0,5.0,step=0.1)
192
+ inp["FSH_LH"]=round(inp["FSH_mIU_mL_"]/max(inp["LH_mIU_mL_"],0.01),3)
193
+ st.caption(f"FSH/LH = {inp['FSH_LH']:.3f} (auto)")
194
+ inp["AMH_ng_mL_"]=st.number_input("AMH (ng/mL)",0.0,20.0,3.5,step=0.1)
195
+ inp["PRG_ng_mL_"]=st.number_input("Progesterone (ng/mL)",0.0,30.0,1.0,step=0.1)
196
+ inp["PRL_ng_mL_"]=st.number_input("Prolactin (ng/mL)",0.0,100.0,15.0,step=0.5)
197
+ inp["TSH__mIU_L_"]=st.number_input("TSH (mIU/L)",0.0,10.0,2.0,step=0.1)
198
+ inp["Vit_D3__ng_mL_"]=st.number_input("Vit D3 (ng/mL)",0.0,100.0,25.0,step=0.5)
199
+ inp["RBS_mg_dl_"]=st.number_input("RBS (mg/dL)",50.0,400.0,90.0,step=1.0)
200
+ with st.sidebar.expander("📐 Measurements"):
201
+ inp["Waist_inch_"]=st.number_input("Waist (inch)",20.0,60.0,32.0,step=0.5)
202
+ inp["Hip_inch_"]=st.number_input("Hip (inch)",25.0,70.0,38.0,step=0.5)
203
+ whr=round(inp["Waist_inch_"]/max(inp["Hip_inch_"],1),3)
204
+ inp["Waist_Hip_Ratio"]=whr; st.caption(f"Waist:Hip = {whr:.3f} (auto)")
205
+ inp["BP__Systolic__mmHg_"]=st.number_input("BP Systolic (mmHg)",80,200,120)
206
+ inp["BP__Diastolic__mmHg_"]=st.number_input("BP Diastolic (mmHg)",50,130,80)
207
+ with st.sidebar.expander("🫘 Follicles & Cycle"):
208
+ inp["Follicle_No___L_"]=st.number_input("Follicles Left",0,30,6)
209
+ inp["Follicle_No___R_"]=st.number_input("Follicles Right",0,30,6)
210
+ inp["Avg_F_size__L__mm_"]=st.number_input("Avg Size L (mm)",0.0,30.0,8.0,step=0.5)
211
+ inp["Avg_F_size__R__mm_"]=st.number_input("Avg Size R (mm)",0.0,30.0,8.0,step=0.5)
212
+ inp["Endometrium__mm_"]=st.number_input("Endometrium (mm)",0.0,20.0,8.0,step=0.5)
213
+ inp["Cycle_R_I_"]=st.selectbox("Cycle Type",[2,4],format_func=lambda x:"Irregular" if x==2 else "Regular")
214
+ inp["Cycle_length_days_"]=st.number_input("Cycle Length (days)",20,60,28)
215
+ with st.sidebar.expander("⚕️ Symptoms & Lifestyle"):
216
+ inp["Weight_gain_Y_N_"]=int(st.checkbox("Weight Gain"))
217
+ inp["hair_growth_Y_N_"]=int(st.checkbox("Excess Hair Growth"))
218
+ inp["Skin_darkening__Y_N_"]=int(st.checkbox("Skin Darkening"))
219
+ inp["Hair_loss_Y_N_"]=int(st.checkbox("Hair Loss"))
220
+ inp["Pimples_Y_N_"]=int(st.checkbox("Pimples"))
221
+ inp["Fast_food__Y_N_"]=int(st.checkbox("Fast Food Regularly"))
222
+ inp["Reg_Exercise_Y_N_"]=int(st.checkbox("Regular Exercise"))
223
+ # Engineered features — exact names from pipeline clean_name()
224
+ fsh=inp["FSH_mIU_mL_"]; lh=inp["LH_mIU_mL_"]; amh=inp["AMH_ng_mL_"]
225
+ inp["FSH_LH_Ratio"]=round(fsh/max(lh,0.01),4)
226
+ inp["Total_Follicles"]=inp["Follicle_No___L_"]+inp["Follicle_No___R_"]
227
+ inp["AMH_FSH_Ratio"]=round(amh/max(fsh,0.01),4)
228
+ inp["BMI_Waist_Ratio"]=round(inp["BMI"]/max(inp["Waist_inch_"],1),4)
229
+ inp["Androgenic_Score"]=(inp["hair_growth_Y_N_"]+inp["Skin_darkening__Y_N_"]+inp["Hair_loss_Y_N_"]+inp["Pimples_Y_N_"])
230
+ return inp
231
+
232
+ def main():
233
+ st.markdown("""<div class="hero">
234
+ <h1>🩺 PCOS Detection & Risk Assessment</h1>
235
+ <p>Stacked Ensemble (LR · RF · GradientBoost · CatBoost) &nbsp;|&nbsp; Domain Severity &nbsp;|&nbsp; Infertility Risk</p>
236
+ </div>""", unsafe_allow_html=True)
237
+
238
+ with st.spinner("Loading models…"):
239
+ mdl, err = load_models()
240
+ if err:
241
+ st.error(f"❌ {err}")
242
+ st.info("Upload all pkl files to the models/ folder.")
243
+ st.stop()
244
+
245
+ st.markdown('<div class="info">ℹ️ Fill clinical inputs in the sidebar then click <b>▶ Run Analysis</b></div>',unsafe_allow_html=True)
246
+ inp = sidebar_inputs()
247
+ run = st.button("▶ Run Analysis", use_container_width=True)
248
+
249
+ if not run:
250
+ c1,c2,c3,c4=st.columns(4)
251
+ for col,icon,t,d in [(c1,"🧬","Stacked Ensemble","AUC 0.953 · MCC 0.896"),
252
+ (c2,"📊","Domain Severity","4-domain PCOS profiling"),
253
+ (c3,"🔴","Infertility Risk","AMH · FSH · Follicles · Cycle"),
254
+ (c4,"📋","Clinical Recs","Personalised guidance")]:
255
+ with col:
256
+ st.markdown(f'<div class="card cl"><div style="font-size:1.5rem">{icon}</div><div class="mlabel">{t}</div><div class="msub">{d}</div></div>',unsafe_allow_html=True)
257
+ return
258
 
259
+ try:
260
+ pred,prob,sev,X_final,base_probs=predict(inp,mdl)
261
+ except Exception as e:
262
+ st.error(f"Prediction failed: {e}")
263
+ st.exception(e)
264
+ return
265
+
266
+ st.markdown("---"); st.markdown("## 📊 Results")
267
+
268
+ diag="PCOS Detected" if pred else "No PCOS Detected"
269
+ vcol="#ef4444" if pred else "#10b981"
270
+ ppill="pr" if pred else "pg"
271
+ picon="⚠️ Positive" if pred else "✅ Negative"
272
+ ov=sev.get("OVERALL",0)
273
+ svlbl="Severe" if ov>0.7 else "Moderate" if ov>0.4 else "Mild"
274
+ iscore,itier,_=infertility_risk(inp)
275
+ tc={"Low":"cg","Moderate":"cy","High":"cr"}[itier]
276
+
277
+ c1,c2,c3,c4=st.columns(4)
278
+ with c1: st.markdown(f'<div class="card {"cr" if pred else "cg"}"><div class="mlabel">Diagnosis</div><div class="mval" style="color:{vcol};font-size:1.2rem">{diag}</div><div class="msub"><span class="pill {ppill}">{picon}</span></div></div>',unsafe_allow_html=True)
279
+ with c2: st.markdown(f'<div class="card cl"><div class="mlabel">PCOS Probability</div><div class="mval">{prob:.1%}</div><div class="msub">Threshold: {mdl["threshold"]:.3f}</div></div>',unsafe_allow_html=True)
280
+ with c3: st.markdown(f'<div class="card cy"><div class="mlabel">Overall Severity</div><div class="mval">{ov:.1%}</div><div class="msub">{svlbl}</div></div>',unsafe_allow_html=True)
281
+ with c4: st.markdown(f'<div class="card {tc}"><div class="mlabel">Infertility Risk</div><div class="mval">{iscore:.0%}</div><div class="msub">{itier} tier</div></div>',unsafe_allow_html=True)
282
+
283
+ st.markdown('<div class="shdr">📊 Domain Severity Analysis</div>',unsafe_allow_html=True)
284
+ d1,d2=st.columns(2)
285
+ with d1: st.pyplot(radar_chart(sev),use_container_width=True)
286
+ with d2:
287
+ st.pyplot(prob_gauge(prob,"PCOS Probability"),use_container_width=True)
288
+ st.markdown("<br>",unsafe_allow_html=True)
289
+ for dom in ["METABOLIC","REPRODUCTIVE","HYPERANDROGENIC","GENERAL"]:
290
+ v=sev.get(dom,0); bc="#ef4444" if v>0.7 else "#f59e0b" if v>0.4 else "#10b981"
291
+ st.markdown(f'<div style="display:flex;align-items:center;gap:10px;margin:5px 0"><span style="width:120px;font-size:.78rem;color:#374151">{dom.capitalize()}</span><div style="flex:1;background:#e5e7eb;border-radius:4px;height:9px"><div style="width:{v*100:.0f}%;background:{bc};height:9px;border-radius:4px"></div></div><span style="width:36px;text-align:right;font-size:.78rem;font-weight:600;color:{bc}">{v:.0%}</span></div>',unsafe_allow_html=True)
292
+
293
+ st.markdown('<div class="shdr">🔴 Infertility Risk Assessment</div>',unsafe_allow_html=True)
294
+ iscore,itier,iparts=infertility_risk(inp)
295
+ rcls={"Low":"risk-lo","Moderate":"risk-md","High":"risk-hi"}[itier]
296
+ ricon={"Low":"🟢","Moderate":"🟡","High":"🔴"}[itier]
297
+ ir1,ir2=st.columns(2)
298
+ with ir1:
299
+ st.markdown(f'<div class="{rcls}"><div style="font-size:1.05rem;font-weight:700">{ricon} {itier} Infertility Risk</div><div style="font-size:1.8rem;font-weight:700;margin:8px 0">{iscore:.0%}</div><div style="font-size:.8rem;color:#374151">Based on AMH · FSH · Follicles · Cycle · BMI</div></div>',unsafe_allow_html=True)
300
+ notes=[]
301
+ amh=inp.get("AMH_ng_mL_"); fsh=inp.get("FSH_mIU_mL_"); tf=inp.get("Total_Follicles",0)
302
+ if amh and amh<1.0: notes.append("⚠️ Very low AMH — reduced ovarian reserve")
303
+ if amh and amh>6.0: notes.append("ℹ️ High AMH — polycystic morphology likely")
304
+ if fsh and fsh>10: notes.append("⚠️ Elevated FSH — diminished ovarian reserve")
305
+ if tf>=20: notes.append("ℹ️ High follicle count — consistent with PCOS")
306
+ if inp.get("Cycle_R_I_")==2: notes.append("⚠️ Irregular cycle — affects conception")
307
+ if notes:
308
+ st.markdown("<br>**Clinical Notes:**",unsafe_allow_html=True)
309
+ for n in notes: st.markdown(f"- {n}")
310
+ with ir2:
311
+ fig=inf_bar(iparts,iscore)
312
+ if fig: st.pyplot(fig,use_container_width=True)
313
+
314
+ st.markdown("---"); st.markdown('<div class="shdr">📋 Clinical Recommendations</div>',unsafe_allow_html=True)
315
+ recs=[]
316
+ if pred:
317
+ recs+=["**Confirm PCOS** with transvaginal ultrasound if not done",
318
+ "Full hormonal panel: FSH, LH, AMH, testosterone, DHEAS",
319
+ "Metabolic screen: fasting glucose, insulin, HbA1c, lipid profile"]
320
+ if inp.get("Cycle_R_I_")==2: recs.append("Discuss cycle regulation — OCP or progesterone cycling")
321
+ if inp.get("BMI",22)>25: recs.append("Lifestyle: 5–10% weight loss can restore ovulation")
322
+ if inp.get("BMI",22)>30: recs.append("Consider metformin for insulin sensitisation")
323
+ else:
324
+ recs+=["PCOS unlikely — routine annual review recommended","Maintain healthy BMI and regular exercise"]
325
+ if itier=="High": recs.append("**Fertility specialist referral recommended** — high infertility risk (>60%)")
326
+ elif itier=="Moderate": recs.append("Consider fertility evaluation if conception not achieved in 6–12 months")
327
+ for r in recs: st.markdown(f"• {r}")
328
+
329
+ with st.expander("🔍 Base Model Probabilities"):
330
+ bm_cols=st.columns(len(mdl["base"]))
331
+ for col,(name,_) in zip(bm_cols,mdl["base"].items()):
332
+ p=float(base_probs[name].iloc[0]); pill="pr" if p>=0.5 else "pg"
333
+ with col:
334
+ st.markdown(f'<div class="card cl" style="text-align:center"><div class="mlabel">{name}</div><div class="mval">{p:.1%}</div><div class="msub"><span class="pill {pill}">{"PCOS" if p>=0.5 else "No PCOS"}</span></div></div>',unsafe_allow_html=True)
335
+
336
+ st.markdown('<div style="font-size:.73rem;color:#9ca3af;text-align:center;padding:6px 0">⚕️ For clinical decision support only.</div>',unsafe_allow_html=True)
337
+
338
+ if __name__=="__main__":
339
+ main()