DheivaCodes commited on
Commit
57c2253
Β·
verified Β·
1 Parent(s): 4a36e1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -128
app.py CHANGED
@@ -37,12 +37,12 @@ from sklearn.metrics import roc_auc_score, roc_curve
37
  from catboost import CatBoostClassifier
38
 
39
  # ══════════════════════════════════════════════════════════════
40
- # SECTION 1 β€” IMAGE PIPELINE
41
  # ══════════════════════════════════════════════════════════════
42
  MODELS_DIR = "models"
43
  IMG_SIZE = 224
44
  DEVICE = torch.device("cpu")
45
- CLASS_NAMES = ["Not PCOS", "PCOS"]
46
  PCOS_IDX = 1
47
 
48
  VAL_TRANSFORM = transforms.Compose([
@@ -68,10 +68,8 @@ def load_image_model():
68
  net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
69
  ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
70
  if isinstance(ckpt, dict):
71
- state = (ckpt.get("model_state")
72
- or ckpt.get("model_state_dict")
73
- or ckpt.get("state_dict")
74
- or ckpt)
75
  else:
76
  state = ckpt
77
  net.load_state_dict(state, strict=True)
@@ -179,7 +177,7 @@ def make_batch_chart(pcos_c: int, notp_c: int, total: int):
179
  return fig
180
 
181
  # ══════════════════════════════════════════════════════════════
182
- # SECTION 2 β€” CLINICAL PIPELINE
183
  # ══════════════════════════════════════════════════════════════
184
  RANDOM_STATE = 42
185
  TEST_SIZE = 0.2
@@ -286,7 +284,7 @@ def preprocess(Xtr,Xte):
286
 
287
  def compute_oof_severity(Xtr,ytr,Xts,FG):
288
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
289
- sev=pd.DataFrame(index=Xts.index); mods,stats={},{}
290
  for domain,feats in FG.items():
291
  fc=get_clean_feats(feats,Xts.columns)
292
  if len(fc)<3: continue
@@ -391,7 +389,7 @@ else:
391
  print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False
392
 
393
  # ══════════════════════════════════════════════════════════════
394
- # SECTION 3 β€” CLINICAL CHARTS
395
  # ══════════════════════════════════════════════════════════════
396
  def draw_gauge(ax,value,title,val_label,sub_label,val_col):
397
  ax.set_facecolor(BG)
@@ -424,6 +422,7 @@ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
424
  draw_gauge(ax_pg,pp,"PCOS Risk",f"{pp*100:.1f}%","⚠️ PCOS Detected" if pred else "βœ… No PCOS",rc)
425
  draw_gauge(ax_ig,inf["score"],"Infertility Risk",f"{inf['score']*100:.1f}%",
426
  f"{'πŸ”΄' if it=='High' else('🟑' if it=='Moderate' else '🟒')} {it}",ic)
 
427
  doms=["Metabolic","Reproductive","Hyperandrogenic","General"]
428
  vals=[sv[d] for d in doms]
429
  ang=np.linspace(0,2*np.pi,len(doms),endpoint=False).tolist()
@@ -439,6 +438,7 @@ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
439
  ax_rd.set_yticklabels(["Lowβ†’Mod","Modβ†’High","Max"],color="#666",fontsize=7)
440
  ax_rd.grid(color="#333355",alpha=0.6,lw=0.8); ax_rd.spines["polar"].set_color("#333355")
441
  ax_rd.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
 
442
  ax_br.set_facecolor(BG)
443
  names=list(bp.keys()); probs_=[bp[n] for n in names]
444
  cols=["#3B82F6","#10B981","#F59E0B","#EF4444"]
@@ -453,6 +453,7 @@ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
453
  ax_br.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
454
  ax_br.set_xlabel("PCOS Probability",color=TC,fontsize=10)
455
  ax_br.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
 
456
  ax_bi.set_facecolor(BG); ax_bi.tick_params(colors=TC,labelsize=8)
457
  for sp in ax_bi.spines.values(): sp.set_color("#2A2A4A")
458
  ax_bi.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
@@ -473,6 +474,7 @@ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
473
  else:
474
  ax_bi.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values",ha="center",va="center",
475
  color="#666",fontsize=10,transform=ax_bi.transAxes)
 
476
  ax_sv.set_facecolor(BG)
477
  sv_v=[sv[d] for d in doms]; sv_c=[DOMAIN_COLORS[d] for d in doms]
478
  xp=np.arange(len(doms)); b3=ax_sv.bar(xp,sv_v,color=sv_c,alpha=0.88,width=0.5)
@@ -497,7 +499,7 @@ def make_clinical_figure(pp,pred,sv,bp,inf,thr):
497
  return fig
498
 
499
  # ══════════════════════════════════════════════════════════════
500
- # SECTION 4 β€” GRADIO HANDLERS
501
  # ══════════════════════════════════════════════════════════════
502
  def predict_clinical(*args):
503
  vals=dict(zip(INPUT_KEYS,args))
@@ -658,123 +660,29 @@ def predict_image_batch(files):
658
  # SECTION 5 β€” CSS + UI
659
  # ══════════════════════════════════════════════════════════════
660
  CSS = """
661
- /* ══ FORCE DARK THEME β€” overrides system light/dark preference ══ */
662
- :root { color-scheme: dark !important; }
663
-
664
- html, body {
665
- background:#0D0D1A !important;
666
- color:#E8E8F0 !important;
667
- font-family:'Inter','Segoe UI',sans-serif !important;
668
- }
669
-
670
- /* Gradio container and all wrappers */
671
- .gradio-container, .gradio-container > *,
672
- .main, .contain, .wrap, .form,
673
- .block, .panel, .gap, .padded,
674
- [class*="svelte-"] {
675
- background:#0D0D1A !important;
676
- color:#E8E8F0 !important;
677
- }
678
-
679
- /* Every text-bearing element β€” catches Gradio's generated svelte classes */
680
- *, *::before, *::after {
681
- color: inherit;
682
- box-sizing: border-box;
683
- }
684
- p, span, label, div, h1, h2, h3, h4, h5, h6,
685
- li, a, td, th, code, pre, summary, small, strong, em {
686
- color:#E8E8F0 !important;
687
- }
688
-
689
- /* Inputs */
690
- input, textarea, select {
691
- background:#1e293b !important;
692
- color:#E8E8F0 !important;
693
- border:1px solid #334155 !important;
694
- }
695
- input::placeholder, textarea::placeholder { color:#64748b !important; }
696
-
697
- /* Accordion / details */
698
- details, summary,
699
- .gradio-accordion, .accordion-content {
700
- background:#111827 !important;
701
- color:#E8E8F0 !important;
702
- border-color:#334155 !important;
703
- }
704
-
705
- /* Radio & checkbox labels */
706
- .gradio-radio label, .gradio-checkboxgroup label,
707
- fieldset label, .wrap label {
708
- color:#E8E8F0 !important;
709
- }
710
-
711
- /* Number inputs */
712
- .gradio-number input { background:#1e293b !important; color:#E8E8F0 !important; }
713
-
714
- /* Markdown / prose output */
715
- .prose, .prose *, .output-markdown, .output-markdown *,
716
- .gradio-markdown, .gradio-markdown * { color:#E8E8F0 !important; }
717
-
718
- /* Textbox */
719
- .gradio-textbox textarea, .gradio-textbox input {
720
- background:#1e293b !important; color:#E8E8F0 !important;
721
- }
722
-
723
- /* Tabs */
724
- .tabs, .tabitem, .tab-nav { background:#0D0D1A !important; }
725
-
726
- /* Plot / image containers */
727
- .gradio-plot, .gradio-image { background:#0D0D1A !important; }
728
-
729
- /* ══ Custom component classes ══ */
730
- .app-header {
731
- background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
732
- border:1px solid #4338ca; border-radius:16px;
733
- padding:28px 36px; margin-bottom:16px; text-align:center;
734
- }
735
- .app-header h1 { color:#e0e7ff !important; font-size:2rem !important; font-weight:700 !important; margin:0 0 4px 0 !important; }
736
- .app-header p { color:#a5b4fc !important; font-size:0.95rem !important; margin:0 !important; }
737
-
738
- .disclaimer {
739
- background:#1c1917; border-left:4px solid #f59e0b; border-radius:8px;
740
- padding:10px 16px; color:#fbbf24 !important; font-size:0.85rem; margin-bottom:16px;
741
- }
742
- .disclaimer * { color:#fbbf24 !important; }
743
-
744
- .sec {
745
- color:#c7d2fe !important; font-size:0.75rem !important; font-weight:700 !important;
746
- letter-spacing:1.4px !important; text-transform:uppercase !important;
747
- margin:0 0 8px 0 !important; padding-bottom:6px !important;
748
- border-bottom:1px solid #334155 !important;
749
- }
750
-
751
- .info-box {
752
- background:#1e293b; border:1px solid #334155; border-radius:10px;
753
- padding:14px 18px; font-size:0.85rem; color:#94a3b8 !important; line-height:1.7;
754
- }
755
- .info-box * { color:#94a3b8 !important; }
756
- .info-box strong { color:#c7d2fe !important; }
757
- .info-box code {
758
- color:#a5b4fc !important; background:#0f172a;
759
- padding:1px 5px; border-radius:4px;
760
- }
761
-
762
- .tab-nav button { color:#94a3b8 !important; font-size:0.9rem !important; font-weight:600 !important; }
763
- .tab-nav button.selected { color:#818cf8 !important; border-bottom:2px solid #818cf8 !important; background:#1e293b !important; }
764
-
765
- button.primary {
766
- background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
767
- border:none !important; border-radius:10px !important;
768
- font-weight:700 !important; color:white !important; padding:12px 0 !important;
769
- }
770
-
771
- /* Markdown tables */
772
- table { width:100%; border-collapse:collapse; font-size:0.88rem; }
773
- th { background:#1e3a5f !important; color:#93c5fd !important; padding:8px 12px; text-align:left; font-weight:600; }
774
- td { padding:7px 12px; border-bottom:1px solid #1e293b; color:#e2e8f0 !important; }
775
- tr:nth-child(even) td { background:#1a2540 !important; }
776
-
777
- footer { display:none !important; }
778
  """
779
 
780
  with gr.Blocks(
@@ -960,4 +868,4 @@ For **research and educational purposes only**. Not a certified medical device.
960
  Always consult a qualified healthcare professional for clinical decisions.
961
  """)
962
 
963
- demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
 
37
  from catboost import CatBoostClassifier
38
 
39
  # ══════════════════════════════════════════════════════════════
40
+ # SECTION 1 β€” IMAGE PIPELINE (exact standalone code that worked)
41
  # ══════════════════════════════════════════════════════════════
42
  MODELS_DIR = "models"
43
  IMG_SIZE = 224
44
  DEVICE = torch.device("cpu")
45
+ CLASS_NAMES = ["Not PCOS", "PCOS"] # alphabetical: not_pcos=0, pcos=1
46
  PCOS_IDX = 1
47
 
48
  VAL_TRANSFORM = transforms.Compose([
 
68
  net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
69
  ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
70
  if isinstance(ckpt, dict):
71
+ state = (ckpt.get("model_state") or ckpt.get("model_state_dict")
72
+ or ckpt.get("state_dict") or ckpt)
 
 
73
  else:
74
  state = ckpt
75
  net.load_state_dict(state, strict=True)
 
177
  return fig
178
 
179
  # ══════════════════════════════════════════════════════════════
180
+ # SECTION 2 β€” CLINICAL PIPELINE (your exact code)
181
  # ══════════════════════════════════════════════════════════════
182
  RANDOM_STATE = 42
183
  TEST_SIZE = 0.2
 
284
 
285
  def compute_oof_severity(Xtr,ytr,Xts,FG):
286
  skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
287
+ sev=pd.DataFrame(index=Xtr.index); mods,stats={},{}
288
  for domain,feats in FG.items():
289
  fc=get_clean_feats(feats,Xts.columns)
290
  if len(fc)<3: continue
 
389
  print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False
390
 
391
  # ══════════════════════════════════════════════════════════════
392
+ # SECTION 3 β€” CLINICAL CHARTS (your exact draw_gauge code)
393
  # ══════════════════════════════════════════════════════════════
394
  def draw_gauge(ax,value,title,val_label,sub_label,val_col):
395
  ax.set_facecolor(BG)
 
422
  draw_gauge(ax_pg,pp,"PCOS Risk",f"{pp*100:.1f}%","⚠️ PCOS Detected" if pred else "βœ… No PCOS",rc)
423
  draw_gauge(ax_ig,inf["score"],"Infertility Risk",f"{inf['score']*100:.1f}%",
424
  f"{'πŸ”΄' if it=='High' else('🟑' if it=='Moderate' else '🟒')} {it}",ic)
425
+ # Radar
426
  doms=["Metabolic","Reproductive","Hyperandrogenic","General"]
427
  vals=[sv[d] for d in doms]
428
  ang=np.linspace(0,2*np.pi,len(doms),endpoint=False).tolist()
 
438
  ax_rd.set_yticklabels(["Lowβ†’Mod","Modβ†’High","Max"],color="#666",fontsize=7)
439
  ax_rd.grid(color="#333355",alpha=0.6,lw=0.8); ax_rd.spines["polar"].set_color("#333355")
440
  ax_rd.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
441
+ # Base model bars
442
  ax_br.set_facecolor(BG)
443
  names=list(bp.keys()); probs_=[bp[n] for n in names]
444
  cols=["#3B82F6","#10B981","#F59E0B","#EF4444"]
 
453
  ax_br.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
454
  ax_br.set_xlabel("PCOS Probability",color=TC,fontsize=10)
455
  ax_br.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
456
+ # Biomarker bars
457
  ax_bi.set_facecolor(BG); ax_bi.tick_params(colors=TC,labelsize=8)
458
  for sp in ax_bi.spines.values(): sp.set_color("#2A2A4A")
459
  ax_bi.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
 
474
  else:
475
  ax_bi.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values",ha="center",va="center",
476
  color="#666",fontsize=10,transform=ax_bi.transAxes)
477
+ # Domain severity bars
478
  ax_sv.set_facecolor(BG)
479
  sv_v=[sv[d] for d in doms]; sv_c=[DOMAIN_COLORS[d] for d in doms]
480
  xp=np.arange(len(doms)); b3=ax_sv.bar(xp,sv_v,color=sv_c,alpha=0.88,width=0.5)
 
499
  return fig
500
 
501
  # ══════════════════════════════════════════════════════════════
502
+ # SECTION 4 β€” GRADIO HANDLER FUNCTIONS
503
  # ══════════════════════════════════════════════════════════════
504
  def predict_clinical(*args):
505
  vals=dict(zip(INPUT_KEYS,args))
 
660
  # SECTION 5 β€” CSS + UI
661
  # ══════════════════════════════════════════════════════════════
662
  CSS = """
663
+ body,.gradio-container{background:#0D0D1A !important;font-family:'Inter','Segoe UI',sans-serif !important;}
664
+ .app-header{background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
665
+ border:1px solid #4338ca;border-radius:16px;padding:28px 36px;margin-bottom:16px;text-align:center;}
666
+ .app-header h1{color:#e0e7ff !important;font-size:2rem !important;font-weight:700 !important;margin:0 0 4px 0 !important;}
667
+ .app-header p{color:#a5b4fc !important;font-size:0.95rem !important;margin:0 !important;}
668
+ .disclaimer{background:#1c1917;border-left:4px solid #f59e0b;border-radius:8px;
669
+ padding:10px 16px;color:#fbbf24 !important;font-size:0.85rem;margin-bottom:16px;}
670
+ .sec{color:#c7d2fe !important;font-size:0.75rem !important;font-weight:700 !important;
671
+ letter-spacing:1.4px !important;text-transform:uppercase !important;
672
+ margin:0 0 8px 0 !important;padding-bottom:6px !important;border-bottom:1px solid #334155 !important;}
673
+ .info-box{background:#1e293b;border:1px solid #334155;border-radius:10px;
674
+ padding:14px 18px;font-size:0.85rem;color:#94a3b8;line-height:1.7;}
675
+ .info-box strong{color:#c7d2fe;}
676
+ .tab-nav button{color:#94a3b8 !important;font-size:0.9rem !important;font-weight:600 !important;}
677
+ .tab-nav button.selected{color:#818cf8 !important;border-bottom:2px solid #818cf8 !important;background:#1e293b !important;}
678
+ button.primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
679
+ border:none !important;border-radius:10px !important;font-weight:700 !important;
680
+ color:white !important;padding:12px 0 !important;}
681
+ table{width:100%;border-collapse:collapse;font-size:0.88rem;}
682
+ th{background:#1e3a5f;color:#93c5fd;padding:8px 12px;text-align:left;font-weight:600;}
683
+ td{padding:7px 12px;border-bottom:1px solid #1e293b;color:#e2e8f0;}
684
+ tr:nth-child(even) td{background:#1a2540;}
685
+ footer{display:none !important;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
  """
687
 
688
  with gr.Blocks(
 
868
  Always consult a qualified healthcare professional for clinical decisions.
869
  """)
870
 
871
+ demo.launch(server_name="0.0.0.0", server_port=7860)