DheivaCodes commited on
Commit
7094b3e
Β·
verified Β·
1 Parent(s): a51dc80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +394 -286
app.py CHANGED
@@ -1,63 +1,51 @@
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]
@@ -75,265 +63,385 @@ def apply_severity(domain_models, stats, X_raw, X_sc):
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os, re, warnings
 
2
  import numpy as np
3
  import pandas as pd
4
+ import matplotlib
5
+ matplotlib.use("Agg")
6
  import matplotlib.pyplot as plt
7
+ import gradio as gr
8
  warnings.filterwarnings("ignore")
9
 
10
+ # ── Domain weights (must match pipeline exactly) ───────────────────────────────
11
+ DOMAIN_WEIGHTS = {
12
+ "METABOLIC": 0.35,
13
+ "REPRODUCTIVE": 0.40,
14
+ "HYPERANDROGENIC": 0.20,
15
+ "GENERAL": 0.05,
16
+ }
17
+
18
+ # ── Model loading ──────────────────────────────────────────────────────────────
19
+ _mdl = None
20
+
21
+ def get_models():
22
+ global _mdl
23
+ if _mdl is not None:
24
+ return _mdl, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  import joblib
26
+ needed = ["ensemble_meta", "base_models", "domain_models", "train_stats",
27
+ "mice_imputer", "scaler", "feature_columns", "best_threshold"]
28
+ missing = [f for f in needed if not os.path.exists(f"models/{f}.pkl")]
29
+ if missing:
30
+ return None, f"Missing pkl files: {missing}"
31
  try:
32
+ _mdl = {
33
+ "meta": joblib.load("models/ensemble_meta.pkl"),
34
+ "base": joblib.load("models/base_models.pkl"),
35
+ "domain": joblib.load("models/domain_models.pkl"),
36
+ "stats": joblib.load("models/train_stats.pkl"),
37
+ "mice": joblib.load("models/mice_imputer.pkl"),
38
+ "scaler": joblib.load("models/scaler.pkl"),
39
+ "features": joblib.load("models/feature_columns.pkl"),
40
+ "threshold": joblib.load("models/best_threshold.pkl"),
41
+ }
42
+ return _mdl, None
43
+ except Exception as e:
44
+ return None, str(e)
45
 
46
 
47
+ # ── Exact pipeline apply_severity(models, stats, X_raw, X_sc) ─────────────────
48
  def apply_severity(domain_models, stats, X_raw, X_sc):
 
49
  df = pd.DataFrame(index=X_sc.index)
50
  for d, (model, fc) in domain_models.items():
51
  avail = [f for f in fc if f in X_sc.columns]
 
63
  return df
64
 
65
 
66
+ # ── Full inference matching pipeline deployment_config.json steps ─────────────
67
  def predict(inp, mdl):
 
 
 
 
 
 
 
 
 
 
 
 
68
  all_fc = mdl["features"]
69
+ # Split feature_columns into base features and SEV columns
70
+ base_fc = [c for c in all_fc if not c.endswith("_SEV")]
71
 
72
+ # Step 1: raw row (base features only β€” SEV cols added later)
 
 
 
 
73
  row_raw = pd.DataFrame([{c: inp.get(c, np.nan) for c in base_fc}])
74
 
75
+ # Step 2: MICE impute (never refit)
76
  row_imp = pd.DataFrame(
77
+ mdl["mice"].transform(row_raw),
78
+ columns=base_fc, index=row_raw.index)
79
 
80
+ # Step 3: Scale (never refit)
81
  row_sc = pd.DataFrame(
82
+ mdl["scaler"].transform(row_imp),
83
+ columns=base_fc, index=row_raw.index)
84
 
85
+ # Step 4: Domain severity
86
  sev_df = apply_severity(mdl["domain"], mdl["stats"], row_raw, row_sc)
87
 
88
+ # Step 5: Concat + reindex to exact feature_columns order
89
+ X_final = pd.concat([row_sc, sev_df], axis=1).reindex(columns=all_fc, fill_value=0)
 
 
 
90
 
91
+ # Step 6+7: Base probs β†’ meta-learner
92
  base_probs = pd.DataFrame(
93
+ {name: m.predict_proba(X_final)[:, 1]
94
+ for name, m in mdl["base"].items()})
95
  prob = mdl["meta"].predict_proba(base_probs)[:, 1][0]
96
 
97
  # Step 8: Threshold
98
  pred = int(prob >= mdl["threshold"])
99
 
100
+ sev_scores = {
101
+ d: float(sev_df[f"{d}_SEV"].iloc[0])
102
+ for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev_df
103
+ }
104
  sev_scores["OVERALL"] = float(sev_df["OVERALL_SEV"].iloc[0])
105
+ return pred, float(prob), sev_scores, base_probs
106
+
107
+
108
+ # ── Infertility risk score ─────────────────────────────────────────────────────
109
+ def infertility_risk(amh, fsh, foll_l, foll_r, cycle, bmi):
110
+ parts = []
111
+ foll = (foll_l or 0) + (foll_r or 0)
112
+ if amh: parts.append(("AMH Reserve", max(0, 1 - amh / 5), 0.35))
113
+ if fsh: parts.append(("FSH Level", min(1, fsh / 20), 0.25))
114
+ if foll: parts.append(("Follicle Count", max(0, 1 - foll / 20), 0.20))
115
+ parts.append(("Cycle", 0.70 if cycle == "Irregular" else 0.20, 0.15))
116
+ if bmi: parts.append(("BMI", 0.6 if bmi < 18.5 or bmi > 30 else 0.3 if bmi > 25 else 0.0, 0.05))
117
+ if not parts:
118
+ return 0.5, "Moderate"
119
+ tw = sum(w for _, _, w in parts)
120
+ sc = sum(r * w for _, r, w in parts) / tw
121
+ return sc, ("Low" if sc < 0.35 else "High" if sc >= 0.60 else "Moderate")
122
+
123
+
124
+ # ── Plots ──────────────────────────────────────────────────────────────────────
125
+ def make_radar(sev):
126
+ doms = ["METABOLIC", "REPRODUCTIVE", "HYPERANDROGENIC", "GENERAL"]
127
+ vals = [sev.get(d, 0) for d in doms] + [sev.get(doms[0], 0)]
128
+ ang = [n / len(doms) * 2 * np.pi for n in range(len(doms))] + [0]
129
+ fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
130
+ fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
131
+ ax.plot(ang, vals, "o-", lw=2.5, color="#4f46e5")
132
+ ax.fill(ang, vals, alpha=0.25, color="#4f46e5")
133
+ ax.set_xticks(ang[:-1])
134
+ ax.set_xticklabels([d.capitalize() for d in doms], fontsize=10)
135
+ ax.set_ylim(0, 1); ax.set_yticks([.25, .5, .75, 1])
136
+ ax.set_yticklabels(["25%", "50%", "75%", "100%"], fontsize=7)
137
+ ax.set_title("Domain Severity Profile", fontsize=12, fontweight="bold", pad=16)
138
+ plt.tight_layout()
139
+ return fig
140
+
141
+
142
+ def make_base_bar(base_probs, threshold):
143
+ names = list(base_probs.columns)
144
+ probs = [float(base_probs[n].iloc[0]) for n in names]
145
+ cols = ["#ef4444" if p >= threshold else "#10b981" for p in probs]
146
+ fig, ax = plt.subplots(figsize=(6, 3))
147
+ fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
148
+ bars = ax.bar(names, probs, color=cols, edgecolor="white", width=0.5)
149
+ for b, p in zip(bars, probs):
150
+ ax.text(b.get_x() + b.get_width() / 2, p + 0.02,
151
+ f"{p:.1%}", ha="center", fontsize=10, fontweight="600")
152
+ ax.axhline(threshold, color="#f59e0b", lw=2, ls="--",
153
+ label=f"Threshold {threshold:.3f}")
154
+ ax.set_ylim(0, 1.15); ax.legend(fontsize=9)
155
+ ax.set_title("Base Model Probabilities", fontsize=11, fontweight="bold")
156
+ ax.spines[["top", "right"]].set_visible(False)
157
+ ax.tick_params(labelsize=10)
158
+ plt.tight_layout()
159
+ return fig
160
+
161
+
162
+ def make_inf_bar(amh, fsh, foll_l, foll_r, cycle, bmi):
163
+ foll = (foll_l or 0) + (foll_r or 0)
164
+ parts = []
165
+ if amh: parts.append(("AMH Reserve", max(0, 1 - amh / 5)))
166
+ if fsh: parts.append(("FSH Level", min(1, fsh / 20)))
167
+ if foll: parts.append(("Follicle Count", max(0, 1 - foll / 20)))
168
+ parts.append(("Cycle", 0.70 if cycle == "Irregular" else 0.20))
169
+ if bmi: parts.append(("BMI", 0.6 if bmi < 18.5 or bmi > 30 else 0.3 if bmi > 25 else 0.0))
170
+ if not parts:
171
+ return None
172
+ labels = [p[0] for p in parts]
173
+ vals = [p[1] for p in parts]
174
+ colors = ["#ef4444" if v > 0.6 else "#f59e0b" if v > 0.35 else "#10b981" for v in vals]
175
+ fig, ax = plt.subplots(figsize=(6, 3))
176
+ fig.patch.set_facecolor("#f8f9ff"); ax.set_facecolor("#f8f9ff")
177
+ bars = ax.barh(labels, vals, color=colors, height=0.5, edgecolor="white")
178
+ for b, v in zip(bars, vals):
179
+ ax.text(v + 0.02, b.get_y() + b.get_height() / 2,
180
+ f"{v:.0%}", va="center", fontsize=9)
181
+ ax.set_xlim(0, 1.15)
182
+ ax.spines[["top", "right"]].set_visible(False)
183
+ ax.set_title("Infertility Risk Factors", fontsize=11, fontweight="bold")
184
+ plt.tight_layout()
185
+ return fig
186
+
187
+
188
+ # ── Main prediction function ───────────────────────────────────────────────────
189
+ def run_analysis(age, bmi, weight, hb, pulse, rr,
190
+ fsh, lh, amh, prg, prl, tsh, vitd3, rbs,
191
+ waist, hip, bp_sys, bp_dia,
192
+ foll_l, foll_r, avg_fl, avg_fr, endo,
193
+ cycle, cycle_len,
194
+ wt_gain, hair_growth, skin_dark,
195
+ hair_loss, pimples, fast_food, exercise):
196
+
197
+ mdl, err = get_models()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  if err:
199
+ err_html = f'<div style="color:red;padding:20px;font-family:sans-serif">❌ {err}<br>Make sure all 8 pkl files are in the models/ folder.</div>'
200
+ return err_html, None, None, "", ""
201
+
202
+ cycle_code = 2 if cycle == "Irregular" else 4
203
+ whr = round(waist / max(hip, 1), 3)
204
+
205
+ inp = {
206
+ "Age__yrs_": age, "BMI": bmi, "Weight__Kg_": weight,
207
+ "Hb__g_dl_": hb, "Pulse_rate_bpm_": pulse, "RR__breaths_min_": rr,
208
+ "FSH_mIU_mL_": fsh, "LH_mIU_mL_": lh,
209
+ "FSH_LH": round(fsh / max(lh, 0.01), 3),
210
+ "AMH_ng_mL_": amh, "PRG_ng_mL_": prg, "PRL_ng_mL_": prl,
211
+ "TSH__mIU_L_": tsh, "Vit_D3__ng_mL_": vitd3, "RBS_mg_dl_": rbs,
212
+ "Waist_inch_": waist, "Hip_inch_": hip, "Waist_Hip_Ratio": whr,
213
+ "BP__Systolic__mmHg_": bp_sys, "BP__Diastolic__mmHg_": bp_dia,
214
+ "Follicle_No___L_": foll_l, "Follicle_No___R_": foll_r,
215
+ "Avg_F_size__L__mm_": avg_fl, "Avg_F_size__R__mm_": avg_fr,
216
+ "Endometrium__mm_": endo, "Cycle_R_I_": cycle_code,
217
+ "Cycle_length_days_": cycle_len,
218
+ "Weight_gain_Y_N_": int(wt_gain), "hair_growth_Y_N_": int(hair_growth),
219
+ "Skin_darkening__Y_N_": int(skin_dark), "Hair_loss_Y_N_": int(hair_loss),
220
+ "Pimples_Y_N_": int(pimples), "Fast_food__Y_N_": int(fast_food),
221
+ "Reg_Exercise_Y_N_": int(exercise),
222
+ # Engineered features
223
+ "FSH_LH_Ratio": round(fsh / max(lh, 0.01), 4),
224
+ "Total_Follicles": foll_l + foll_r,
225
+ "AMH_FSH_Ratio": round(amh / max(fsh, 0.01), 4),
226
+ "BMI_Waist_Ratio": round(bmi / max(waist, 1), 4),
227
+ "Androgenic_Score": int(hair_growth) + int(skin_dark) + int(hair_loss) + int(pimples),
228
+ }
229
 
230
  try:
231
+ pred, prob, sev, base_probs = predict(inp, mdl)
232
  except Exception as e:
233
+ err_html = f'<div style="color:red;padding:20px;font-family:sans-serif">❌ Prediction error: {e}</div>'
234
+ return err_html, None, None, "", ""
235
+
236
+ # ── Diagnosis HTML ─────────────────────────────────────────────────────────
237
+ diag = "πŸ”΄ PCOS DETECTED" if pred else "🟒 NO PCOS DETECTED"
238
+ dcol = "#ef4444" if pred else "#10b981"
239
+ conf = prob if pred else 1 - prob
240
+ ov = sev.get("OVERALL", 0)
241
+ svlbl = "Severe" if ov > 0.7 else "Moderate" if ov > 0.4 else "Mild"
242
+
243
+ dom_bars = ""
244
+ for d in ["METABOLIC", "REPRODUCTIVE", "HYPERANDROGENIC", "GENERAL"]:
245
+ v = sev.get(d, 0)
246
+ bc = "#ef4444" if v > 0.7 else "#f59e0b" if v > 0.4 else "#10b981"
247
+ dom_bars += f"""
248
+ <div style="display:flex;align-items:center;gap:10px;margin:6px 0">
249
+ <span style="width:130px;font-size:.82rem;color:#374151">{d.capitalize()}</span>
250
+ <div style="flex:1;background:#e5e7eb;border-radius:4px;height:10px">
251
+ <div style="width:{v*100:.0f}%;background:{bc};height:10px;border-radius:4px"></div>
252
+ </div>
253
+ <span style="width:38px;text-align:right;font-size:.82rem;font-weight:600;color:{bc}">{v:.0%}</span>
254
+ </div>"""
255
+
256
+ result_html = f"""
257
+ <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
258
+ <div style="font-size:1.7rem;font-weight:700;color:{dcol};margin-bottom:16px">{diag}</div>
259
+ <div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:20px">
260
+ <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
261
+ box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid #4f46e5">
262
+ <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">PCOS Probability</div>
263
+ <div style="font-size:1.7rem;font-weight:700;color:#4f46e5">{prob:.1%}</div>
264
+ <div style="font-size:.75rem;color:#6b7280">Threshold: {mdl['threshold']:.3f}</div>
265
+ </div>
266
+ <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
267
+ box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid {dcol}">
268
+ <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">Confidence</div>
269
+ <div style="font-size:1.7rem;font-weight:700;color:{dcol}">{conf:.1%}</div>
270
+ <div style="font-size:.75rem;color:#6b7280">{'Positive' if pred else 'Negative'}</div>
271
+ </div>
272
+ <div style="background:white;border-radius:10px;padding:14px 18px;min-width:140px;
273
+ box-shadow:0 2px 8px rgba(0,0,0,.07);border-left:4px solid #f59e0b">
274
+ <div style="font-size:.68rem;color:#6b7280;font-weight:600;text-transform:uppercase">Overall Severity</div>
275
+ <div style="font-size:1.7rem;font-weight:700;color:#f59e0b">{ov:.1%}</div>
276
+ <div style="font-size:.75rem;color:#6b7280">{svlbl}</div>
277
+ </div>
278
+ </div>
279
+ <div style="background:white;border-radius:10px;padding:16px 20px;box-shadow:0 2px 8px rgba(0,0,0,.07)">
280
+ <div style="font-weight:700;margin-bottom:10px;color:#374151">Domain Severity Breakdown</div>
281
+ {dom_bars}
282
+ </div>
283
+ </div>"""
284
+
285
+ # ── Infertility risk HTML ──────────────────────────────────────────────────
286
+ iscore, itier = infertility_risk(amh, fsh, foll_l, foll_r, cycle, bmi)
287
+ tcol = {"Low": "#10b981", "Moderate": "#f59e0b", "High": "#ef4444"}[itier]
288
+ ticon = {"Low": "🟒", "Moderate": "🟑", "High": "πŸ”΄"}[itier]
289
+
290
+ notes = []
291
+ if amh and amh < 1.0: notes.append("⚠️ Very low AMH β€” reduced ovarian reserve")
292
+ if amh and amh > 6.0: notes.append("ℹ️ High AMH β€” polycystic morphology likely")
293
+ if fsh and fsh > 10: notes.append("⚠️ Elevated FSH β€” diminished ovarian reserve")
294
+ if (foll_l + foll_r) >= 20: notes.append("ℹ️ High follicle count β€” consistent with PCOS")
295
+ if cycle == "Irregular": notes.append("⚠️ Irregular cycle β€” impacts conception")
296
+
297
+ inf_html = f"""
298
+ <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
299
+ <div style="font-size:1.1rem;font-weight:700;color:{tcol}">{ticon} {itier} Infertility Risk</div>
300
+ <div style="font-size:2.2rem;font-weight:700;color:{tcol};margin:8px 0">{iscore:.0%}</div>
301
+ <div style="font-size:.85rem;color:#6b7280;margin-bottom:14px">Based on AMH Β· FSH Β· Follicles Β· Cycle Β· BMI</div>
302
+ {''.join(f'<div style="font-size:.85rem;margin:5px 0;color:#374151">{n}</div>' for n in notes)}
303
+ </div>"""
304
+
305
+ # ── Clinical recommendations ───────────────────────────────────────────────
306
+ recs = []
307
  if pred:
308
+ recs += [
309
+ "βœ… Confirm PCOS with transvaginal ultrasound",
310
+ "βœ… Full hormonal panel: FSH, LH, AMH, testosterone, DHEAS",
311
+ "βœ… Metabolic screen: fasting glucose, insulin, HbA1c, lipid profile",
312
+ ]
313
+ if cycle == "Irregular":
314
+ recs.append("βœ… Discuss cycle regulation β€” OCP or progesterone cycling")
315
+ if bmi > 25:
316
+ recs.append("βœ… Lifestyle: 5–10% weight loss can restore ovulation")
317
+ if bmi > 30:
318
+ recs.append("βœ… Consider metformin for insulin sensitisation")
319
  else:
320
+ recs += [
321
+ "βœ… PCOS unlikely β€” routine annual review recommended",
322
+ "βœ… Maintain healthy BMI and regular exercise",
323
+ ]
324
+ if itier == "High":
325
+ recs.append("πŸ”΄ Fertility specialist referral recommended β€” high infertility risk (>60%)")
326
+ elif itier == "Moderate":
327
+ recs.append("🟑 Consider fertility evaluation if conception not achieved in 6–12 months")
328
+
329
+ rec_html = f"""
330
+ <div style="font-family:sans-serif;padding:22px;background:#f8f9ff;border-radius:14px">
331
+ <div style="font-size:1rem;font-weight:700;color:#374151;margin-bottom:12px">πŸ“‹ Clinical Recommendations</div>
332
+ {''.join(f'<div style="font-size:.88rem;margin:7px 0;color:#374151">{r}</div>' for r in recs)}
333
+ <div style="margin-top:16px;font-size:.72rem;color:#9ca3af;border-top:1px solid #e5e7eb;padding-top:10px">
334
+ βš•οΈ For clinical decision support only. Results must be interpreted by a qualified healthcare provider.
335
+ </div>
336
+ </div>"""
337
+
338
+ radar_fig = make_radar(sev)
339
+ base_fig = make_base_bar(base_probs, mdl["threshold"])
340
+
341
+ return result_html, radar_fig, base_fig, inf_html, rec_html
342
+
343
+
344
+ # ── Gradio UI ──────────────────────────────────────────────────────────────────
345
+ css = """
346
+ .gradio-container{background:#f0f4ff !important;}
347
+ .gr-button-primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;border:none !important;}
348
+ """
349
+
350
+ with gr.Blocks(title="PCOS Detection & Risk Assessment", css=css) as demo:
351
+
352
+ gr.HTML("""
353
+ <div style="background:linear-gradient(135deg,#4f46e5,#7c3aed);border-radius:16px;
354
+ padding:28px 32px;color:white;margin-bottom:20px">
355
+ <h1 style="margin:0 0 6px;font-size:1.8rem">🩺 PCOS Detection & Risk Assessment</h1>
356
+ <p style="margin:0;opacity:.88;font-size:.92rem">
357
+ Stacked Ensemble (LR Β· RF Β· GradientBoost Β· CatBoost) &nbsp;|&nbsp;
358
+ Domain Severity Scoring &nbsp;|&nbsp; Infertility Risk Stratification
359
+ </p>
360
+ </div>""")
361
+
362
+ with gr.Row():
363
+ # ── Column 1: General + Measurements ──────────────────────────────────
364
+ with gr.Column():
365
+ gr.Markdown("### πŸ‘€ General")
366
+ age = gr.Slider(15, 60, value=28, step=1, label="Age (yrs)")
367
+ bmi = gr.Slider(10, 60, value=22.0, step=0.1, label="BMI (kg/mΒ²)")
368
+ weight = gr.Slider(30, 150, value=60.0, step=0.5, label="Weight (kg)")
369
+ hb = gr.Slider(5, 18, value=13.0, step=0.1, label="Hb (g/dL)")
370
+ pulse = gr.Slider(40, 120, value=72, step=1, label="Pulse (bpm)")
371
+ rr = gr.Slider(10, 30, value=16, step=1, label="Resp Rate (breaths/min)")
372
+
373
+ gr.Markdown("### πŸ“ Measurements")
374
+ waist = gr.Slider(20, 60, value=32.0, step=0.5, label="Waist (inch)")
375
+ hip = gr.Slider(25, 70, value=38.0, step=0.5, label="Hip (inch)")
376
+ bp_sys = gr.Slider(80, 200, value=120, step=1, label="BP Systolic (mmHg)")
377
+ bp_dia = gr.Slider(50, 130, value=80, step=1, label="BP Diastolic (mmHg)")
378
+
379
+ # ── Column 2: Hormones + Follicles ────────────────────────────────────
380
+ with gr.Column():
381
+ gr.Markdown("### 🩸 Hormones & Labs")
382
+ fsh = gr.Slider(0, 50, value=7.0, step=0.1, label="FSH (mIU/mL)")
383
+ lh = gr.Slider(0, 50, value=5.0, step=0.1, label="LH (mIU/mL)")
384
+ amh = gr.Slider(0, 20, value=3.5, step=0.1, label="AMH (ng/mL)")
385
+ prg = gr.Slider(0, 30, value=1.0, step=0.1, label="Progesterone (ng/mL)")
386
+ prl = gr.Slider(0, 100, value=15.0, step=0.5, label="Prolactin (ng/mL)")
387
+ tsh = gr.Slider(0, 10, value=2.0, step=0.1, label="TSH (mIU/L)")
388
+ vitd3 = gr.Slider(0, 100, value=25.0, step=0.5, label="Vit D3 (ng/mL)")
389
+ rbs = gr.Slider(50, 400, value=90.0, step=1.0, label="RBS (mg/dL)")
390
+
391
+ gr.Markdown("### 🫘 Follicles & Cycle")
392
+ foll_l = gr.Slider(0, 30, value=6, step=1, label="Follicles Left")
393
+ foll_r = gr.Slider(0, 30, value=6, step=1, label="Follicles Right")
394
+ avg_fl = gr.Slider(0, 30, value=8.0, step=0.5, label="Avg Follicle Size L (mm)")
395
+ avg_fr = gr.Slider(0, 30, value=8.0, step=0.5, label="Avg Follicle Size R (mm)")
396
+ endo = gr.Slider(0, 20, value=8.0, step=0.5, label="Endometrium (mm)")
397
+ cycle = gr.Radio(["Regular", "Irregular"], value="Regular", label="Cycle Type")
398
+ cycle_len = gr.Slider(20, 60, value=28, step=1, label="Cycle Length (days)")
399
+
400
+ # ── Column 3: Symptoms + Run button ───────────────────────────────────
401
+ with gr.Column():
402
+ gr.Markdown("### βš•οΈ Symptoms & Lifestyle")
403
+ wt_gain = gr.Checkbox(label="Weight Gain")
404
+ hair_growth = gr.Checkbox(label="Excess Hair Growth")
405
+ skin_dark = gr.Checkbox(label="Skin Darkening")
406
+ hair_loss = gr.Checkbox(label="Hair Loss")
407
+ pimples = gr.Checkbox(label="Pimples")
408
+ fast_food = gr.Checkbox(label="Fast Food Regularly")
409
+ exercise = gr.Checkbox(label="Regular Exercise")
410
+
411
+ gr.Markdown("---")
412
+ run_btn = gr.Button("β–Ά Run Analysis", variant="primary", size="lg")
413
+ gr.Markdown("""
414
+ <div style="font-size:.8rem;color:#6b7280;margin-top:8px">
415
+ Fill all inputs then click <b>Run Analysis</b>.
416
+ Models load automatically from the <code>models/</code> folder.
417
+ </div>""")
418
+
419
+ gr.Markdown("---")
420
+ gr.Markdown("## πŸ“Š Results")
421
+
422
+ result_out = gr.HTML(label="Diagnosis & Severity")
423
+
424
+ with gr.Row():
425
+ radar_out = gr.Plot(label="Domain Severity Radar")
426
+ base_out = gr.Plot(label="Base Model Probabilities")
427
+
428
+ with gr.Row():
429
+ inf_out = gr.HTML(label="Infertility Risk")
430
+ rec_out = gr.HTML(label="Clinical Recommendations")
431
+
432
+ all_inputs = [
433
+ age, bmi, weight, hb, pulse, rr,
434
+ fsh, lh, amh, prg, prl, tsh, vitd3, rbs,
435
+ waist, hip, bp_sys, bp_dia,
436
+ foll_l, foll_r, avg_fl, avg_fr, endo, cycle, cycle_len,
437
+ wt_gain, hair_growth, skin_dark, hair_loss, pimples, fast_food, exercise,
438
+ ]
439
+
440
+ run_btn.click(
441
+ fn=run_analysis,
442
+ inputs=all_inputs,
443
+ outputs=[result_out, radar_out, base_out, inf_out, rec_out],
444
+ )
445
+
446
+ if __name__ == "__main__":
447
+ demo.launch(server_name="0.0.0.0", server_port=7860)