File size: 49,018 Bytes
686a400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
"""
PCOS Integrated Detection System
- Tab 1: Clinical Analysis  (stacked ensemble, trains on Excel at startup)
- Tab 2: Ultrasound Single  (DenseNet121 β€” best model by MCC/ValAUC/LogLoss)
- Tab 3: Ultrasound Batch   (multi-image, summary table + chart)
- Tab 4: About
"""

import os, re, copy, warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.gridspec import GridSpec
import matplotlib.cm as cm_mod
import gradio as gr

# ── image deps ────────────────────────────────────────────────
import torch
import torch.nn as nn
from torchvision import models as tv_models, transforms
from PIL import Image

# ── clinical deps ─────────────────────────────────────────────
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.preprocessing import RobustScaler
from sklearn.experimental import enable_iterative_imputer   # noqa
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import roc_auc_score, roc_curve
from catboost import CatBoostClassifier

# ══════════════════════════════════════════════════════════════
# SECTION 1 β€” IMAGE PIPELINE  (DenseNet121)
# ══════════════════════════════════════════════════════════════
MODELS_DIR  = "models"
IMG_SIZE    = 224
DEVICE      = torch.device("cpu")
CLASS_NAMES = ["Not PCOS", "PCOS"]   # alphabetical: not_pcos=0, pcos=1
PCOS_IDX    = 1

VAL_TRANSFORM = transforms.Compose([
    transforms.Resize((IMG_SIZE, IMG_SIZE)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std =[0.229, 0.224, 0.225]),
])

def load_image_model():
    candidates = [
        os.path.join(MODELS_DIR, "best_model.pth"),
        os.path.join(MODELS_DIR, "densenet121.pth"),
        os.path.join(MODELS_DIR, "DenseNet121.pth"),
    ]
    pth = next((p for p in candidates if os.path.exists(p)), None)
    if pth is None:
        existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else []
        print(f"⚠️ Image model not found. models/ contains: {existing}")
        return None
    try:
        # ── DenseNet121: classifier is a single Linear, not classifier[1] ──
        net = tv_models.densenet121(weights=None)
        in_features = net.classifier.in_features
        net.classifier = nn.Linear(in_features, 2)

        ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
        if isinstance(ckpt, dict):
            state = (ckpt.get("model_state") or ckpt.get("model_state_dict")
                     or ckpt.get("state_dict") or ckpt)
        else:
            state = ckpt
        net.load_state_dict(state, strict=True)
        net.to(DEVICE).eval()
        print(f"βœ… DenseNet121 loaded: {pth}")
        return net
    except Exception as e:
        print(f"⚠️ Image model failed to load: {e}")
        return None

IMAGE_MODEL = load_image_model()

def run_image_inference(img_rgb: Image.Image):
    tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
    with torch.no_grad():
        probs = torch.softmax(IMAGE_MODEL(tensor), dim=1)[0]
    return float(probs[PCOS_IDX]), float(probs[1 - PCOS_IDX]), int(probs.argmax())

def compute_gradcam(img_rgb: Image.Image, target_class: int):
    grads, acts = [], []

    def fwd_hook(m, inp, out):
        acts.append(out.detach())
        out.register_hook(lambda g: grads.append(g.detach()))

    # ── DenseNet121: target layer is features.denseblock4 (not features[-1]) ──
    handle = IMAGE_MODEL.features.denseblock4.register_forward_hook(fwd_hook)
    tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
    IMAGE_MODEL.zero_grad()

    # Enable gradients for Grad-CAM
    for param in IMAGE_MODEL.parameters():
        param.requires_grad_(True)

    output = IMAGE_MODEL(tensor)
    output[0, target_class].backward()
    handle.remove()

    if not grads or not acts:
        return None

    w   = grads[0].squeeze(0).mean(dim=(1, 2)).cpu().numpy()
    act = acts[0].squeeze(0).cpu().numpy()
    cam = np.maximum(sum(w[i] * act[i] for i in range(len(w))), 0)
    if cam.max() > 1e-8:
        cam /= cam.max()

    cam_up = np.array(
        Image.fromarray((cam * 255).astype(np.uint8)).resize(
            (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
    ) / 255.0
    orig_r  = np.array(img_rgb.resize((IMG_SIZE, IMG_SIZE)))
    heat    = cm_mod.jet(cam_up)[:, :, :3]
    overlay = np.clip(0.55 * orig_r / 255.0 + 0.45 * heat, 0, 1)

    fig, axes = plt.subplots(1, 3, figsize=(14, 4), facecolor="#0f172a",
                             gridspec_kw={"wspace": 0.05})
    for ax, (img, cmap, title) in zip(axes, [
        (orig_r,  None,  "Original Image"),
        (cam_up,  "jet", "Grad-CAM Heatmap"),
        (overlay, None,  "Activation Overlay"),
    ]):
        ax.set_facecolor("#0f172a")
        ax.imshow(img, cmap=cmap)
        ax.set_title(title, color="white", fontsize=11, fontweight="bold", pad=6)
        ax.axis("off")
    fig.text(0.5, -0.01,
             f"Grad-CAM Β· DenseNet121 Β· features.denseblock4 Β· Predicted: {CLASS_NAMES[target_class]}",
             ha="center", color="#94a3b8", fontsize=9)
    plt.tight_layout(pad=0.3)
    return fig

def make_image_gauge(pcos_prob: float):
    fig, ax = plt.subplots(figsize=(5, 2.6), facecolor="#0f172a")
    ax.set_facecolor("#0f172a")
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
    ax.barh([0.5], [1.0], height=0.30, color="#1e293b", left=0, align="center", zorder=1)
    color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
    ax.barh([0.5], [pcos_prob], height=0.30, color=color, left=0, align="center", zorder=2)
    ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
    ax.text(pcos_prob, 0.5, f" {pcos_prob*100:.1f}%", va="center", color="white",
            fontsize=16, fontweight="bold", zorder=4,
            ha="left" if pcos_prob < 0.85 else "right")
    for x, lbl, c in [(0.16, "Low", "#22c55e"), (0.50, "Moderate", "#f59e0b"), (0.83, "High", "#ef4444")]:
        ax.text(x, 0.12, lbl, color=c, fontsize=8, ha="center", alpha=0.8)
    ax.text(0.5, 0.92, "PCOS Probability", color="#94a3b8", fontsize=9, ha="center", va="top")
    plt.tight_layout(pad=0.2)
    return fig

def make_batch_chart(pcos_c: int, notp_c: int, total: int):
    fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")
    ax1 = fig.add_subplot(1, 2, 1); ax1.set_facecolor("#0f172a")
    if total > 0:
        _, _, autotexts = ax1.pie(
            [pcos_c, notp_c],
            labels=[f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"],
            colors=["#ef4444", "#22c55e"], autopct="%1.1f%%", startangle=90,
            textprops={"color": "white", "fontsize": 10},
            wedgeprops={"linewidth": 2, "edgecolor": "#0f172a"}, pctdistance=0.75)
        for at in autotexts:
            at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold")
    ax1.set_title("Class Distribution", color="white", fontsize=12, fontweight="bold", pad=12)
    ax2 = fig.add_subplot(1, 2, 2); ax2.set_facecolor("#0f172a")
    bars = ax2.bar(["Not PCOS", "PCOS"], [notp_c, pcos_c],
                   color=["#22c55e", "#ef4444"], width=0.45, edgecolor="#0f172a", linewidth=2)
    ax2.set_ylim(0, max(pcos_c, notp_c) * 1.35 + 0.5)
    ax2.set_title("Count per Class", color="white", fontsize=12, fontweight="bold", pad=12)
    ax2.tick_params(colors="white", labelsize=11)
    for sp in ax2.spines.values(): sp.set_visible(False)
    ax2.yaxis.set_visible(False)
    for bar, cnt in zip(bars, [notp_c, pcos_c]):
        ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.15,
                 str(cnt), ha="center", color="white", fontsize=14, fontweight="bold")
    fig.text(0.5, 0.01, f"Total: {total} image{'s' if total > 1 else ''} Β· DenseNet121",
             ha="center", color="#64748b", fontsize=9)
    plt.tight_layout(pad=1.5)
    return fig

# ══════════════════════════════════════════════════════════════
# SECTION 2 β€” CLINICAL PIPELINE  (unchanged)
# ══════════════════════════════════════════════════════════════
RANDOM_STATE = 42
TEST_SIZE    = 0.2
CV_FOLDS     = 5
BG  = "#0D0D1A"
TC  = "#E8E8F0"
ACC = "#A855F7"

DOMAIN_WEIGHTS = {
    "METABOLIC": 0.35, "REPRODUCTIVE": 0.40,
    "HYPERANDROGENIC": 0.20, "GENERAL": 0.05,
}
FEATURE_GROUPS_BASE = {
    "METABOLIC": ["BMI","Weight (Kg)","Waist(inch)","Hip(inch)",
                  "Waist:Hip Ratio","RBS(mg/dl)","Weight gain(Y/N)",
                  "BP _Systolic (mmHg)","BP _Diastolic (mmHg)",
                  "Fast food (Y/N)","Reg.Exercise(Y/N)"],
    "REPRODUCTIVE": ["Cycle(R/I)","Cycle length(days)","FSH(mIU/mL)","LH(mIU/mL)","FSH/LH",
                     "AMH(ng/mL)","PRG(ng/mL)","Follicle No. (L)","Follicle No. (R)",
                     "Avg. F size (L) (mm)","Avg. F size (R) (mm)","Endometrium (mm)"],
    "HYPERANDROGENIC": ["hair growth(Y/N)","Skin darkening (Y/N)",
                        "Hair loss(Y/N)","Pimples(Y/N)","PRL(ng/mL)"],
    "GENERAL": ["Age (yrs)","Hb(g/dl)","Pulse rate(bpm)",
                "RR (breaths/min)","TSH (mIU/L)","Vit D3 (ng/mL)"],
}
DROP_COLS = ["Sl. No","Patient File No.","Blood Group","Marraige Status (Yrs)",
             "Pregnant(Y/N)","No. of aborptions","Unnamed: 44"]
DOMAIN_COLORS = {"Metabolic":"#E74C3C","Reproductive":"#9B59B6",
                 "Hyperandrogenic":"#E67E22","General":"#27AE60"}
BIOMARKER_DIRECTIONS = {
    "FSH(mIU/mL)":1,"LH(mIU/mL)":-1,"FSH/LH":1,"AMH(ng/mL)":-1,
    "Follicle No. (L)":-1,"Follicle No. (R)":-1,"Endometrium (mm)":-1,
    "PRG(ng/mL)":-1,"Cycle(R/I)":1,
}
BIOMARKER_WEIGHTS = {
    "FSH(mIU/mL)":0.18,"LH(mIU/mL)":0.08,"FSH/LH":0.15,"AMH(ng/mL)":0.22,
    "Follicle No. (L)":0.10,"Follicle No. (R)":0.10,"Endometrium (mm)":0.08,
    "PRG(ng/mL)":0.05,"Cycle(R/I)":0.04,
}
BIOMARKER_RANGES = {
    "FSH(mIU/mL)":(0.5,22.0),"LH(mIU/mL)":(0.2,49.0),"FSH/LH":(0.1,20.0),
    "AMH(ng/mL)":(0.01,18.0),"Follicle No. (L)":(0.0,22.0),"Follicle No. (R)":(0.0,22.0),
    "Endometrium (mm)":(1.0,15.0),"PRG(ng/mL)":(0.1,25.0),"Cycle(R/I)":(2.0,4.0),
}
EXAMPLE_PCOS = dict(age=28,weight=72,height=158,bmi=28.8,pulse_rate=82,rr=19,hb=11.5,
    cycle=4,cycle_length=35,fsh=4.8,lh=12.5,fsh_lh_ratio=0.38,hip=40,waist=36,
    waist_hip=0.90,tsh=2.8,amh=8.5,prl=22,vit_d3=18,prg=0.6,rbs=105,
    weight_gain=1,hair_growth=1,skin_darkening=1,hair_loss=0,pimples=1,
    fast_food=1,reg_exercise=0,follicle_l=14,follicle_r=13,avg_f_size_l=8,avg_f_size_r=8,endometrium=6)
EXAMPLE_NORMAL = dict(age=26,weight=58,height=162,bmi=22.1,pulse_rate=70,rr=16,hb=13.2,
    cycle=2,cycle_length=28,fsh=7.2,lh=4.8,fsh_lh_ratio=1.5,hip=37,waist=28,
    waist_hip=0.76,tsh=2.1,amh=3.2,prl=14,vit_d3=30,prg=1.8,rbs=85,
    weight_gain=0,hair_growth=0,skin_darkening=0,hair_loss=0,pimples=0,
    fast_food=0,reg_exercise=1,follicle_l=6,follicle_r=6,avg_f_size_l=16,avg_f_size_r=16,endometrium=9)
INPUT_KEYS = ["age","weight","height","bmi","pulse_rate","rr","hb","cycle","cycle_length",
              "fsh","lh","fsh_lh_ratio","hip","waist","waist_hip","tsh","amh","prl",
              "vit_d3","prg","rbs","weight_gain","hair_growth","skin_darkening","hair_loss",
              "pimples","fast_food","reg_exercise","follicle_l","follicle_r",
              "avg_f_size_l","avg_f_size_r","endometrium"]

def clean_name(n): return re.sub(r"[^0-9a-zA-Z_]","_",n.strip())
def clean_df_cols(df):
    df=df.copy(); df.columns=[clean_name(c) for c in df.columns]; return df
def get_clean_feats(fl,av): return [clean_name(f) for f in fl if clean_name(f) in av]

def get_base_models():
    return {
        "Logistic"    : LogisticRegression(max_iter=2000,class_weight="balanced"),
        "RandomForest": RandomForestClassifier(n_estimators=300,max_depth=10,
                            class_weight="balanced",random_state=RANDOM_STATE),
        "GradientBoost": GradientBoostingClassifier(n_estimators=200,learning_rate=0.05,
                            max_depth=3,subsample=0.85,random_state=RANDOM_STATE),
        "CatBoost"    : CatBoostClassifier(iterations=300,learning_rate=0.05,depth=6,
                            random_seed=RANDOM_STATE,eval_metric="AUC",verbose=0),
    }

def load_and_engineer(dp):
    df=pd.read_excel(dp); df=df.drop(columns=DROP_COLS,errors="ignore")
    df.columns=df.columns.str.strip()
    y=pd.to_numeric(df["PCOS (Y/N)"],errors="coerce"); mask=y.notna()
    df=df.loc[mask].copy().reset_index(drop=True); y=y.loc[mask].astype(int).reset_index(drop=True)
    for c in df.columns:
        if df[c].dtype=="object" and c!="PCOS (Y/N)":
            df[c]=pd.to_numeric(df[c].astype(str).str.strip(),errors="coerce")
    df["FSH_LH_Ratio"]=df["FSH(mIU/mL)"]/(df["LH(mIU/mL)"]+1e-6)
    df["Total_Follicles"]=df["Follicle No. (L)"].fillna(0)+df["Follicle No. (R)"].fillna(0)
    df["AMH_FSH_Ratio"]=df["AMH(ng/mL)"]/(df["FSH(mIU/mL)"]+1e-6)
    df["BMI_Waist_Ratio"]=df["BMI"]/(df["Waist(inch)"]+1e-6)
    andro=[c for c in FEATURE_GROUPS_BASE["HYPERANDROGENIC"] if c in df.columns]
    if andro: df["Androgenic_Score"]=df[andro].sum(axis=1)
    FG=copy.deepcopy(FEATURE_GROUPS_BASE)
    FG["REPRODUCTIVE"]+=["FSH_LH_Ratio","Total_Follicles","AMH_FSH_Ratio"]
    FG["METABOLIC"]+=["BMI_Waist_Ratio"]; FG["HYPERANDROGENIC"]+=["Androgenic_Score"]
    return clean_df_cols(df.drop(columns=["PCOS (Y/N)"])),y,FG

def preprocess(Xtr,Xte):
    mice=IterativeImputer(max_iter=10,random_state=RANDOM_STATE)
    Xti=pd.DataFrame(mice.fit_transform(Xtr),columns=Xtr.columns,index=Xtr.index)
    Xei=pd.DataFrame(mice.transform(Xte),columns=Xte.columns,index=Xte.index)
    nc=Xti.select_dtypes(include=np.number).columns.tolist(); sc=RobustScaler()
    Xts=Xti.copy(); Xes=Xei.copy()
    Xts[nc]=sc.fit_transform(Xti[nc]); Xes[nc]=sc.transform(Xei[nc])
    return Xts,Xes,mice,sc,nc

def compute_oof_severity(Xtr,ytr,Xts,FG):
    skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
    sev=pd.DataFrame(index=Xtr.index); mods,stats={},{}
    for domain,feats in FG.items():
        fc=get_clean_feats(feats,Xts.columns)
        if len(fc)<3: continue
        oof=np.zeros(len(Xts))
        for tr,val in skf.split(Xts,ytr):
            m=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
                                         max_depth=3,random_state=RANDOM_STATE)
            m.fit(Xts.iloc[tr][fc],ytr.iloc[tr]); oof[val]=m.predict_proba(Xts.iloc[val][fc])[:,1]
        stats[domain]={"min":oof.min(),"max":oof.max()}
        sev[f"{domain}_SEV"]=(oof-oof.min())/(oof.max()-oof.min()+1e-6)
        fm=GradientBoostingClassifier(n_estimators=100,learning_rate=0.05,
                                      max_depth=3,random_state=RANDOM_STATE)
        fm.fit(Xts[fc],ytr); mods[domain]=(fm,fc)
    sev["OVERALL_SEV"]=sum(sev[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
                           for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev)
    return sev.fillna(0),mods,stats

def apply_severity(mods,stats,Xsc):
    out=pd.DataFrame(index=Xsc.index)
    for d,(m,fc) in mods.items():
        fca=[f for f in fc if f in Xsc.columns]
        p=m.predict_proba(Xsc[fca])[:,1]
        out[f"{d}_SEV"]=np.clip((p-stats[d]["min"])/(stats[d]["max"]-stats[d]["min"]+1e-6),0,1)
    out=out.fillna(0)
    out["OVERALL_SEV"]=sum(out[f"{d}_SEV"]*DOMAIN_WEIGHTS[d]
                           for d in DOMAIN_WEIGHTS if f"{d}_SEV" in out)
    return out

def build_pipeline(dp):
    print("πŸ”„ Training clinical pipeline...")
    X,y,FG=load_and_engineer(dp)
    Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=TEST_SIZE,stratify=y,random_state=RANDOM_STATE)
    Xts,Xes,mice,sc,nc=preprocess(Xtr,Xte)
    sev_tr,dm,stats=compute_oof_severity(Xtr,ytr,Xts,FG)
    sev_te=apply_severity(dm,stats,Xes)
    Xf=pd.concat([Xts,sev_tr],axis=1); Xef=pd.concat([Xes,sev_te],axis=1)
    skf=StratifiedKFold(CV_FOLDS,shuffle=True,random_state=RANDOM_STATE)
    om=pd.DataFrame(index=Xf.index); tm=pd.DataFrame(index=Xef.index); tb={}
    for name,model in get_base_models().items():
        oof=np.zeros(len(Xf))
        for tri,vi in skf.split(Xf,ytr):
            model.fit(Xf.iloc[tri],ytr.iloc[tri]); oof[vi]=model.predict_proba(Xf.iloc[vi])[:,1]
        model.fit(Xf,ytr); om[name]=oof; tm[name]=model.predict_proba(Xef)[:,1]; tb[name]=model
        print(f"  βœ… {name} AUC:{roc_auc_score(ytr,oof):.4f}")
    meta=CalibratedClassifierCV(LogisticRegressionCV(cv=5,class_weight={0:1,1:3}),method="isotonic")
    meta.fit(om,ytr); ep=meta.predict_proba(tm)[:,1]
    fpr,tpr,ths=roc_curve(yte,ep); bt=float(ths[np.argmax(tpr-fpr)]); auc=roc_auc_score(yte,ep)
    print(f"  βœ… Ensemble AUC:{auc:.4f} threshold:{bt:.4f}\nβœ… Clinical pipeline ready")
    return dict(meta=meta,base=tb,dm=dm,stats=stats,mice=mice,sc=sc,nc=nc,
                sc_cols=list(Xts.columns),fc=list(Xf.columns),thr=bt,auc=round(auc,4))

def compute_infertility_risk(pr):
    def _v(v):
        try: return not np.isnan(float(v)) if v is not None else False
        except: return False
    av={f:w for f,w in BIOMARKER_WEIGHTS.items() if f in pr and _v(pr[f])}
    if not av: return {"score":0.5,"tier":"Unknown","breakdown":{}}
    tw=sum(av.values()); score=0.0; bd={}
    for feat,w in av.items():
        val=float(pr[feat]); lo,hi=BIOMARKER_RANGES.get(feat,(0,1))
        norm=np.clip((val-lo)/(hi-lo+1e-8),0,1)
        ori=(1-norm) if BIOMARKER_DIRECTIONS.get(feat,1)==-1 else norm
        c=(w/tw)*ori; score+=c
        bd[feat]={"raw":round(val,3),"oriented":round(ori,3),"contribution":round(c,4),
                  "direction":"↑ risk" if BIOMARKER_DIRECTIONS.get(feat,1)==1 else "↓ protective"}
    tier="High" if score>=0.66 else("Moderate" if score>=0.33 else "Low")
    return {"score":round(score,4),"tier":tier,"breakdown":bd}

def predict_clinical_single(pl,pr):
    row={k:np.nan for k in pl["sc_cols"]}
    for rk,val in pr.items():
        ck=clean_name(rk)
        if ck in row and val is not None:
            try: row[ck]=float(val)
            except: pass
    Xr=pd.DataFrame([row])
    for c in Xr.columns: Xr[c]=pd.to_numeric(Xr[c],errors="coerce")
    Xi=pd.DataFrame(pl["mice"].transform(Xr),columns=Xr.columns)
    Xs=Xi.copy(); ncc=[c for c in pl["nc"] if c in Xs.columns]
    Xs[ncc]=pl["sc"].transform(Xi[ncc])
    sev=apply_severity(pl["dm"],pl["stats"],Xs)
    Xf=pd.concat([Xs.reset_index(drop=True),sev.reset_index(drop=True)],axis=1)
    for c in pl["fc"]:
        if c not in Xf.columns: Xf[c]=0.0
    Xf=Xf[pl["fc"]].clip(-10,10)
    bp={n:m.predict_proba(Xf)[:,1][0] for n,m in pl["base"].items()}
    pp=pl["meta"].predict_proba(pd.DataFrame([bp]))[:,1][0]
    pred=int(pp>=pl["thr"])
    def _s(c): return float(sev[c].iloc[0]) if c in sev.columns else 0.0
    sv={"Metabolic":_s("METABOLIC_SEV"),"Reproductive":_s("REPRODUCTIVE_SEV"),
        "Hyperandrogenic":_s("HYPERANDROGENIC_SEV"),"General":_s("GENERAL_SEV"),"Overall":_s("OVERALL_SEV")}
    return pp,pred,sv,bp

# ── Startup ───────────────────────────────────────────────────
DATA_PATH = os.path.join(os.path.dirname(__file__), "PCOS_data_without_infertility.xlsx")
if os.path.exists(DATA_PATH):
    try:
        PIPELINE=build_pipeline(DATA_PATH); PIPELINE_READY=True
    except Exception as _e:
        print(f"⚠️ Pipeline error: {_e}"); PIPELINE=None; PIPELINE_READY=False
else:
    print(f"⚠️ Dataset not found: {DATA_PATH}"); PIPELINE=None; PIPELINE_READY=False

# ══════════════════════════════════════════════════════════════
# SECTION 3 β€” CLINICAL CHARTS
# ══════════════════════════════════════════════════════════════
def draw_gauge(ax,value,title,val_label,sub_label,val_col):
    ax.set_facecolor(BG)
    theta=np.linspace(np.pi,0,300)
    for i in range(len(theta)-1):
        ax.fill_between([np.cos(theta[i]),np.cos(theta[i+1])],
                        [np.sin(theta[i]),np.sin(theta[i+1])],
                        alpha=0.9,color=plt.cm.RdYlGn_r(i/(len(theta)-1)))
    angle=np.pi*(1-value)
    ax.annotate("",xy=(0.65*np.cos(angle),0.65*np.sin(angle)),xytext=(0,0),
                arrowprops=dict(arrowstyle="-|>",color="white",lw=3))
    ax.plot(0,0,"o",color="white",markersize=6,zorder=5)
    ax.text(0,-0.15,val_label,ha="center",fontsize=22,fontweight="bold",color=val_col,va="center")
    ax.text(0,-0.58,sub_label,ha="center",fontsize=10,fontweight="bold",color=val_col)
    for pct,lbl in [(0,"0%"),(0.5,"50%"),(1.0,"100%")]:
        a=np.pi*(1-pct)
        ax.text(0.88*np.cos(a),0.88*np.sin(a),lbl,ha="center",va="center",fontsize=6,color="#888")
    ax.set_xlim(-1.05,1.05); ax.set_ylim(-0.72,1.05); ax.axis("off")
    ax.set_title(title,color=TC,fontsize=12,fontweight="bold",pad=4)

def make_clinical_figure(pp,pred,sv,bp,inf,thr):
    fig=plt.figure(figsize=(18,13),facecolor=BG)
    gs=GridSpec(3,4,figure=fig,hspace=0.58,wspace=0.45,top=0.93,bottom=0.05,left=0.05,right=0.97)
    ax_pg=fig.add_subplot(gs[0,0]); ax_ig=fig.add_subplot(gs[0,1])
    ax_rd=fig.add_subplot(gs[0,2:],polar=True)
    ax_br=fig.add_subplot(gs[1,:2]); ax_bi=fig.add_subplot(gs[1,2:])
    ax_sv=fig.add_subplot(gs[2,:])
    rc="#E74C3C" if pp>0.65 else("#F39C12" if pp>0.35 else "#2ECC71")
    it=inf["tier"]; ic="#E74C3C" if it=="High" else("#F39C12" if it=="Moderate" else "#2ECC71")
    draw_gauge(ax_pg,pp,"PCOS Risk",f"{pp*100:.1f}%","⚠️ PCOS Detected" if pred else "βœ… No PCOS",rc)
    draw_gauge(ax_ig,inf["score"],"Infertility Risk",f"{inf['score']*100:.1f}%",
               f"{'πŸ”΄' if it=='High' else('🟑' if it=='Moderate' else '🟒')} {it}",ic)
    doms=["Metabolic","Reproductive","Hyperandrogenic","General"]
    vals=[sv[d] for d in doms]
    ang=np.linspace(0,2*np.pi,len(doms),endpoint=False).tolist()
    vc=vals+[vals[0]]; ac=ang+[ang[0]]
    ax_rd.set_facecolor(BG)
    for lv,al,co in [(1.0,0.05,"#E74C3C"),(0.65,0.08,"#F39C12"),(0.35,0.08,"#2ECC71")]:
        ax_rd.fill(ac,[lv]*len(ac),alpha=al,color=co)
    ax_rd.plot(ac,vc,"o-",lw=2.5,color=ACC,markersize=7); ax_rd.fill(ac,vc,alpha=0.30,color=ACC)
    ax_rd.set_xticks(ang)
    ax_rd.set_xticklabels([f"{d}\n{vals[i]*100:.0f}%" for i,d in enumerate(doms)],
                           color=TC,fontsize=10,fontweight="bold")
    ax_rd.set_ylim(0,1); ax_rd.set_yticks([0.35,0.65,1.0])
    ax_rd.set_yticklabels(["Low→Mod","Mod→High","Max"],color="#666",fontsize=7)
    ax_rd.grid(color="#333355",alpha=0.6,lw=0.8); ax_rd.spines["polar"].set_color("#333355")
    ax_rd.set_title("Domain Severity Radar",color=TC,fontsize=13,fontweight="bold",pad=22)
    ax_br.set_facecolor(BG)
    names=list(bp.keys()); probs_=[bp[n] for n in names]
    cols=["#3B82F6","#10B981","#F59E0B","#EF4444"]
    bars=ax_br.barh(names,probs_,color=cols[:len(names)],height=0.52,alpha=0.88)
    for bar,p in zip(bars,probs_):
        ax_br.text(min(p+0.018,0.97),bar.get_y()+bar.get_height()/2,
                   f"{p:.3f}",va="center",color=TC,fontsize=11,fontweight="bold")
    ax_br.axvline(0.5,color="white",ls="--",alpha=0.3,lw=1.5)
    ax_br.axvline(thr,color=ACC,ls=":",alpha=0.6,lw=1.5,label=f"Youden threshold ({thr:.2f})")
    ax_br.set_xlim(0,1.12); ax_br.tick_params(colors=TC,labelsize=11)
    for sp in ax_br.spines.values(): sp.set_color("#2A2A4A")
    ax_br.set_title("Base Model Probabilities",color=TC,fontsize=12,fontweight="bold")
    ax_br.set_xlabel("PCOS Probability",color=TC,fontsize=10)
    ax_br.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8,loc="lower right")
    ax_bi.set_facecolor(BG); ax_bi.tick_params(colors=TC,labelsize=8)
    for sp in ax_bi.spines.values(): sp.set_color("#2A2A4A")
    ax_bi.set_title("Infertility Biomarker Contributions",color=TC,fontsize=12,fontweight="bold")
    ax_bi.set_xlabel("Weighted contribution",color=TC,fontsize=9)
    bd=inf.get("breakdown",{})
    if bd:
        fn=list(bd.keys()); fv=[bd[f]["contribution"] for f in fn]
        fc_=[("#10B981" if bd[f]["oriented"]>0.5 else "#EF4444") for f in fn]
        sn=[f.split("(")[0].strip()[:14] for f in fn]
        sp2=sorted(zip(sn,fv,fc_),key=lambda x:x[1],reverse=True)
        sn,fv,fc_=zip(*sp2)
        b2=ax_bi.barh(sn,fv,color=fc_,height=0.52,alpha=0.88)
        for bar,val in zip(b2,fv):
            ax_bi.text(val+0.001,bar.get_y()+bar.get_height()/2,f"{val:.3f}",va="center",color=TC,fontsize=9)
        ax_bi.legend(handles=[mpatches.Patch(color="#EF4444",label="↑ Increases risk"),
                               mpatches.Patch(color="#10B981",label="↓ Protective")],
                     facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=8)
    else:
        ax_bi.text(0.5,0.5,"Enter FSH, LH, AMH,\nfollicle values",ha="center",va="center",
                   color="#666",fontsize=10,transform=ax_bi.transAxes)
    ax_sv.set_facecolor(BG)
    sv_v=[sv[d] for d in doms]; sv_c=[DOMAIN_COLORS[d] for d in doms]
    xp=np.arange(len(doms)); b3=ax_sv.bar(xp,sv_v,color=sv_c,alpha=0.88,width=0.5)
    for bar,val,d in zip(b3,sv_v,doms):
        lv="High" if val>0.65 else("Moderate" if val>0.35 else "Low")
        lc="#E74C3C" if lv=="High" else("#F39C12" if lv=="Moderate" else "#2ECC71")
        ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.02,f"{val*100:.1f}%",
                   ha="center",va="bottom",color=TC,fontsize=14,fontweight="bold")
        ax_sv.text(bar.get_x()+bar.get_width()/2,val+0.09,f"({lv})",
                   ha="center",va="bottom",color=lc,fontsize=11)
    ax_sv.axhline(0.65,color="#E74C3C",ls="--",alpha=0.45,lw=1.5,label="High (65%)")
    ax_sv.axhline(0.35,color="#F39C12",ls="--",alpha=0.45,lw=1.5,label="Moderate (35%)")
    ax_sv.set_ylim(0,1.3); ax_sv.set_xticks(xp)
    ax_sv.set_xticklabels(doms,color=TC,fontsize=13,fontweight="bold")
    ax_sv.tick_params(axis="y",colors=TC,labelsize=10)
    for sp in ax_sv.spines.values(): sp.set_color("#2A2A4A")
    ax_sv.set_title("PCOS Domain Severity Breakdown",color=TC,fontsize=13,fontweight="bold")
    ax_sv.set_ylabel("Severity Score",color=TC,fontsize=11)
    ax_sv.legend(facecolor="#1A1A2E",edgecolor="#333355",labelcolor=TC,fontsize=9,loc="upper right")
    fig.patch.set_facecolor(BG)
    fig.suptitle("🩺 PCOS Clinical Assessment Report",color=TC,fontsize=16,fontweight="bold",y=0.97)
    return fig

# ══════════════════════════════════════════════════════════════
# SECTION 4 β€” GRADIO HANDLER FUNCTIONS
# ══════════════════════════════════════════════════════════════
def predict_clinical(*args):
    vals=dict(zip(INPUT_KEYS,args))
    if not PIPELINE_READY:
        return ("❌ Clinical pipeline not ready.\nUpload `PCOS_data_without_infertility.xlsx` "
                "to the Space root folder."), None, ""
    bmi=vals["bmi"]; fsh=vals["fsh"]; lh=vals["lh"]
    if (not bmi or bmi==0) and vals["weight"] and vals["height"] and vals["height"]>0:
        bmi=vals["weight"]/((vals["height"]/100)**2)
    if (not vals["fsh_lh_ratio"] or vals["fsh_lh_ratio"]==0) and fsh and lh:
        vals["fsh_lh_ratio"]=fsh/(lh+1e-6)
    vals["bmi"]=bmi
    pr={
        "Age (yrs)":vals["age"],"Weight (Kg)":vals["weight"],"BMI":vals["bmi"],
        "Pulse rate(bpm)":vals["pulse_rate"],"RR (breaths/min)":vals["rr"],
        "Hb(g/dl)":vals["hb"],"Cycle(R/I)":vals["cycle"],
        "Cycle length(days)":vals["cycle_length"],
        "FSH(mIU/mL)":vals["fsh"],"LH(mIU/mL)":vals["lh"],"FSH/LH":vals["fsh_lh_ratio"],
        "Hip(inch)":vals["hip"],"Waist(inch)":vals["waist"],"Waist:Hip Ratio":vals["waist_hip"],
        "TSH (mIU/L)":vals["tsh"],"AMH(ng/mL)":vals["amh"],"PRL(ng/mL)":vals["prl"],
        "Vit D3 (ng/mL)":vals["vit_d3"],"PRG(ng/mL)":vals["prg"],"RBS(mg/dl)":vals["rbs"],
        "Weight gain(Y/N)":vals["weight_gain"],"hair growth(Y/N)":vals["hair_growth"],
        "Skin darkening (Y/N)":vals["skin_darkening"],"Hair loss(Y/N)":vals["hair_loss"],
        "Pimples(Y/N)":vals["pimples"],"Fast food (Y/N)":vals["fast_food"],
        "Reg.Exercise(Y/N)":vals["reg_exercise"],
        "Follicle No. (L)":vals["follicle_l"],"Follicle No. (R)":vals["follicle_r"],
        "Avg. F size (L) (mm)":vals["avg_f_size_l"],"Avg. F size (R) (mm)":vals["avg_f_size_r"],
        "Endometrium (mm)":vals["endometrium"],
        "BP _Systolic (mmHg)":120,"BP _Diastolic (mmHg)":80,
    }
    try:
        pp,pred,sv,bp=predict_clinical_single(PIPELINE,pr)
    except Exception as e:
        return f"❌ Prediction error: {e}", None, ""
    inf=compute_infertility_risk(pr)
    it=inf["tier"]; ii="πŸ”΄" if it=="High" else("🟑" if it=="Moderate" else "🟒")
    pt="HIGH RISK πŸ”΄" if pp>0.65 else("MODERATE RISK 🟑" if pp>0.35 else "LOW RISK 🟒")
    recs=[]
    if pred: recs.append("πŸ₯ **Consult an endocrinologist / gynaecologist immediately.**")
    if it=="High": recs.append("🧬 **High infertility risk β€” fertility specialist evaluation recommended.**")
    elif it=="Moderate": recs.append("πŸ”¬ Hormonal panel follow-up (FSH, LH, AMH) recommended.")
    if sv["Metabolic"]>0.5: recs.append("βš–οΈ Weight management and regular exercise advised.")
    if sv["Hyperandrogenic"]>0.5: recs.append("πŸ’Š Discuss anti-androgen therapy with your doctor.")
    if not recs: recs.append("βœ… Continue routine annual screening and a healthy lifestyle.")
    sev_rows="\n".join(
        f"| {d} | {sv[d]*100:.1f}% | {'πŸ”΄ High' if sv[d]>0.65 else('🟑 Moderate' if sv[d]>0.35 else '🟒 Low')} |"
        for d in ["Metabolic","Reproductive","Hyperandrogenic","General"])
    bio_rows="\n".join(
        f"| {f.split('(')[0].strip()} | {v['raw']} | {v['direction']} | {v['contribution']:.3f} |"
        for f,v in inf.get("breakdown",{}).items()
    ) or "| β€” | Enter hormonal values | β€” | β€” |"
    rec_text="\n".join(f"- {r}" for r in recs)
    summary=f"""## Clinical Assessment β€” {pt}
| Metric | Value |
|---|---|
| **PCOS Probability** | **{pp*100:.1f}%** |
| **Diagnosis** | {"⚠️ PCOS Detected" if pred else "βœ… No PCOS Detected"} |
| **Overall Severity** | {sv['Overall']*100:.1f}% |
| **Infertility Risk** | {ii} {it} ({inf['score']*100:.1f}%) |
---
### PCOS Domain Severity
| Domain | Score | Level |
|---|---|---|
{sev_rows}
### Infertility Biomarker Breakdown
| Biomarker | Value | Direction | Contribution |
|---|---|---|---|
{bio_rows}
### Clinical Recommendations
{rec_text}
---
*βš•οΈ For research/educational purposes only. Not medical advice.*"""
    fig=make_clinical_figure(pp,pred,sv,bp,inf,PIPELINE["thr"])
    info=f"Ensemble AUC: {PIPELINE['auc']} | Threshold: {PIPELINE['thr']:.4f} | LR+RF+GBM+CatBoost β†’ CalibratedLRCV"
    return summary, fig, info


def predict_image_single(image):
    if IMAGE_MODEL is None:
        return ("## ❌ Image model not loaded\n\n"
                "Upload `best_model.pth` to the `models/` folder on HuggingFace.\n\n"
                "The **Clinical tab works normally**."), None, None
    if image is None:
        return "⚠️ Please upload an ultrasound image.", None, None
    try:
        img_rgb=(image if isinstance(image,Image.Image) else Image.fromarray(image)).convert("RGB")
        pcos_p,notp,pred=run_image_inference(img_rgb)
        icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
        label=CLASS_NAMES[pred]
        conf=pcos_p if pred==PCOS_IDX else notp
        risk="🟒 Low" if pcos_p<0.33 else "🟑 Moderate" if pcos_p<0.66 else "πŸ”΄ High"
        result=f"""### {icon} {label}
| Metric | Value |
|---|---|
| PCOS Probability | **{pcos_p*100:.1f}%** |
| Not PCOS Probability | **{notp*100:.1f}%** |
| Confidence | **{conf*100:.1f}%** |
| Risk Level | **{risk}** |
*DenseNet121 Β· 224Γ—224 Β· ImageNet normalisation Β· Val AUC: 0.9998 Β· MCC: 0.9648*
> ⚠️ Research use only β€” not a clinical tool."""
        return result, make_image_gauge(pcos_p), compute_gradcam(img_rgb, pred)
    except Exception as e:
        import traceback
        return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None


def predict_image_batch(files):
    if IMAGE_MODEL is None:
        return ("## ❌ Image model not loaded\n\nUpload `best_model.pth` to `models/`.\n\n"
                "The **Clinical tab works normally**."), None
    if not files:
        return "⚠️ Upload at least one image.", None
    rows=[]; pcos_c=0; notp_c=0
    for f in files:
        try:
            img=Image.open(f.name).convert("RGB")
            pcos_p,notp,pred=run_image_inference(img)
            icon="πŸ”΄" if pred==PCOS_IDX else "🟒"
            rows.append({"File":os.path.basename(f.name),
                         "Prediction":f"{icon} {CLASS_NAMES[pred]}",
                         "PCOS%":f"{pcos_p*100:.1f}","Not PCOS%":f"{notp*100:.1f}",
                         "Risk":"Low" if pcos_p<0.33 else "Moderate" if pcos_p<0.66 else "High"})
            if pred==PCOS_IDX: pcos_c+=1
            else: notp_c+=1
        except Exception as e:
            rows.append({"File":os.path.basename(f.name),"Prediction":f"❌ {e}",
                         "PCOS%":"β€”","Not PCOS%":"β€”","Risk":"β€”"})
    total=len(rows)
    table="\n".join(
        f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |"
        for r in rows)
    summary=f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total>1 else ''}
| | Count | % |
|---|---|---|
| πŸ”΄ PCOS | **{pcos_c}** | **{pcos_c/total*100:.1f}%** |
| 🟒 Not PCOS | **{notp_c}** | **{notp_c/total*100:.1f}%** |
| Total | **{total}** | 100% |
---
### Per-Image Results
| File | Prediction | PCOS% | Not PCOS% | Risk |
|---|---|---|---|---|
{table}
> ⚠️ Research use only."""
    return summary, make_batch_chart(pcos_c, notp_c, total)

# ══════════════════════════════════════════════════════════════
# SECTION 5 β€” CSS + UI
# ══════════════════════════════════════════════════════════════
CSS = """
body,.gradio-container{background:#0D0D1A !important;font-family:'Inter','Segoe UI',sans-serif !important;}
.app-header{background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%);
  border:1px solid #4338ca;border-radius:16px;padding:28px 36px;margin-bottom:16px;text-align:center;}
.app-header h1{color:#e0e7ff !important;font-size:2rem !important;font-weight:700 !important;margin:0 0 4px 0 !important;}
.app-header p{color:#a5b4fc !important;font-size:0.95rem !important;margin:0 !important;}
.disclaimer{background:#1c1917;border-left:4px solid #f59e0b;border-radius:8px;
  padding:10px 16px;color:#fbbf24 !important;font-size:0.85rem;margin-bottom:16px;}
.sec{color:#c7d2fe !important;font-size:0.75rem !important;font-weight:700 !important;
  letter-spacing:1.4px !important;text-transform:uppercase !important;
  margin:0 0 8px 0 !important;padding-bottom:6px !important;border-bottom:1px solid #334155 !important;}
.info-box{background:#1e293b;border:1px solid #334155;border-radius:10px;
  padding:14px 18px;font-size:0.85rem;color:#94a3b8;line-height:1.7;}
.info-box strong{color:#c7d2fe;}
.tab-nav button{color:#94a3b8 !important;font-size:0.9rem !important;font-weight:600 !important;}
.tab-nav button.selected{color:#818cf8 !important;border-bottom:2px solid #818cf8 !important;background:#1e293b !important;}
button.primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important;
  border:none !important;border-radius:10px !important;font-weight:700 !important;
  color:white !important;padding:12px 0 !important;}
table{width:100%;border-collapse:collapse;font-size:0.88rem;}
th{background:#1e3a5f;color:#93c5fd;padding:8px 12px;text-align:left;font-weight:600;}
td{padding:7px 12px;border-bottom:1px solid #1e293b;color:#e2e8f0;}
tr:nth-child(even) td{background:#1a2540;}
footer{display:none !important;}
"""

with gr.Blocks(
    theme=gr.themes.Base(primary_hue="purple",secondary_hue="violet",neutral_hue="slate",
                         font=[gr.themes.GoogleFont("Inter"),"sans-serif"]),
    css=CSS, title="PCOS Integrated Detection System"
) as demo:

    gr.HTML("""
    <div class="app-header">
        <h1>🩺 PCOS Integrated Detection System</h1>
        <p>Clinical Stacked Ensemble &nbsp;Β·&nbsp; DenseNet121 Ultrasound &nbsp;Β·&nbsp;
           Infertility Risk &nbsp;Β·&nbsp; Grad-CAM XAI &nbsp;Β·&nbsp; Batch Analysis</p>
    </div>
    <div class="disclaimer">
        ⚠️ <strong>Medical Disclaimer:</strong> For <strong>research &amp; educational purposes only</strong>.
        Not a certified medical device. Consult a qualified clinician for any health decisions.
    </div>""")

    with gr.Tabs(elem_classes="tab-nav"):

        # ── TAB 1: CLINICAL ──────────────────────────────────────
        with gr.TabItem("πŸ”¬ Clinical Analysis"):
            with gr.Row():
                btn_pcos  =gr.Button("πŸ“‹ Load PCOS Example",  variant="secondary",size="sm")
                btn_norm  =gr.Button("πŸ“‹ Load Normal Example", variant="secondary",size="sm")
                btn_clear =gr.Button("πŸ—‘οΈ Clear All",           variant="secondary",size="sm")

            with gr.Row(equal_height=False):
                with gr.Column(scale=1):
                    with gr.Accordion("πŸ“‹ General & Vitals",open=True):
                        age=gr.Number(label="Age (yrs)",value=25)
                        weight=gr.Number(label="Weight (Kg)",value=60)
                        height=gr.Number(label="Height (cm)",value=160)
                        bmi=gr.Number(label="BMI (auto-computed)",value=0)
                        pulse_rate=gr.Number(label="Pulse rate (bpm)",value=72)
                        rr=gr.Number(label="RR (breaths/min)",value=18)
                        hb=gr.Number(label="Hb (g/dl)",value=12)
                        tsh=gr.Number(label="TSH (mIU/L)",value=2.5)
                        vit_d3=gr.Number(label="Vit D3 (ng/mL)",value=25)
                with gr.Column(scale=1):
                    with gr.Accordion("πŸ”΄ Metabolic",open=True):
                        rbs=gr.Number(label="RBS (mg/dl)",value=90)
                        waist=gr.Number(label="Waist (inch)",value=30)
                        hip=gr.Number(label="Hip (inch)",value=37)
                        waist_hip=gr.Number(label="Waist:Hip Ratio",value=0.81)
                        weight_gain=gr.Radio([0,1],label="Weight Gain (Y=1)",value=0)
                        fast_food=gr.Radio([0,1],label="Fast Food (Y=1)",value=0)
                        reg_exercise=gr.Radio([0,1],label="Exercise (Y=1)",value=1)
                with gr.Column(scale=1):
                    with gr.Accordion("🟣 Reproductive & Hormonal β˜…",open=True):
                        cycle=gr.Radio([2,4],label="Cycle  Regular=2 / Irregular=4",value=2)
                        cycle_length=gr.Number(label="Cycle length (days)",value=28)
                        fsh=gr.Number(label="FSH (mIU/mL) β˜…",value=6.5)
                        lh=gr.Number(label="LH (mIU/mL) β˜…",value=5.0)
                        fsh_lh_ratio=gr.Number(label="FSH/LH (auto if 0) β˜…",value=0)
                        amh=gr.Number(label="AMH (ng/mL) β˜…",value=2.5)
                        prg=gr.Number(label="PRG (ng/mL) β˜…",value=1.0)
                        endometrium=gr.Number(label="Endometrium (mm) β˜…",value=8.0)
                        follicle_l=gr.Number(label="Follicle No. (L) β˜…",value=6)
                        follicle_r=gr.Number(label="Follicle No. (R) β˜…",value=6)
                        avg_f_size_l=gr.Number(label="Avg F size L (mm)",value=15)
                        avg_f_size_r=gr.Number(label="Avg F size R (mm)",value=15)
                        gr.HTML("<p style='color:#94a3b8;font-size:0.8rem'>β˜… Used for PCOS + Infertility Risk</p>")
                with gr.Column(scale=1):
                    with gr.Accordion("🟠 Hyperandrogenic",open=True):
                        hair_growth=gr.Radio([0,1],label="Hair Growth (Y=1)",value=0)
                        skin_darkening=gr.Radio([0,1],label="Skin Darkening (Y=1)",value=0)
                        hair_loss=gr.Radio([0,1],label="Hair Loss (Y=1)",value=0)
                        pimples=gr.Radio([0,1],label="Pimples (Y=1)",value=0)
                        prl=gr.Number(label="PRL (ng/mL)",value=15)
                    gr.HTML("<br>")
                    predict_btn=gr.Button("πŸ”¬ Run Full Analysis",variant="primary",size="lg")

            ALL_INPUTS=[age,weight,height,bmi,pulse_rate,rr,hb,cycle,cycle_length,
                        fsh,lh,fsh_lh_ratio,hip,waist,waist_hip,tsh,amh,prl,vit_d3,prg,rbs,
                        weight_gain,hair_growth,skin_darkening,hair_loss,pimples,fast_food,
                        reg_exercise,follicle_l,follicle_r,avg_f_size_l,avg_f_size_r,endometrium]

            with gr.Row():
                with gr.Column(scale=1):
                    gr.HTML('<p class="sec">πŸ“‹ Assessment Summary</p>')
                    summary_out=gr.Markdown(value="*Fill the form and click Run Full Analysis.*")
                    model_info=gr.Textbox(label="Pipeline info",interactive=False,lines=2)
                with gr.Column(scale=2):
                    gr.HTML('<p class="sec">πŸ“Š Assessment Charts</p>')
                    chart_out=gr.Plot(label="",show_label=False)

            def load_ex(ex): return [ex[k] for k in INPUT_KEYS]
            def clear_all():
                d=dict(age=25,weight=60,height=160,bmi=0,pulse_rate=72,rr=18,hb=12,
                       cycle=2,cycle_length=28,fsh=6.5,lh=5.0,fsh_lh_ratio=0,
                       hip=37,waist=30,waist_hip=0.81,tsh=2.5,amh=2.5,prl=15,
                       vit_d3=25,prg=1.0,rbs=90,weight_gain=0,hair_growth=0,
                       skin_darkening=0,hair_loss=0,pimples=0,fast_food=0,reg_exercise=1,
                       follicle_l=6,follicle_r=6,avg_f_size_l=15,avg_f_size_r=15,endometrium=8)
                return [d[k] for k in INPUT_KEYS]

            btn_pcos.click(fn=lambda: load_ex(EXAMPLE_PCOS),   outputs=ALL_INPUTS)
            btn_norm.click(fn=lambda: load_ex(EXAMPLE_NORMAL), outputs=ALL_INPUTS)
            btn_clear.click(fn=clear_all, outputs=ALL_INPUTS)
            predict_btn.click(fn=predict_clinical,inputs=ALL_INPUTS,
                              outputs=[summary_out,chart_out,model_info])

        # ── TAB 2: SINGLE IMAGE ───────────────────────────────────
        with gr.TabItem("πŸ–ΌοΈ Ultrasound β€” Single"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=4):
                    gr.HTML('<p class="sec">πŸ“ Upload Image</p>')
                    img_input=gr.Image(label="",type="pil",height=280)
                    img_btn=gr.Button("πŸ” Analyze Image",variant="primary",size="lg")
                    gr.HTML("""<div class="info-box" style="margin-top:12px">
                        <strong>Model:</strong> DenseNet121 (fine-tuned Β· best model)<br>
                        <strong>Selection:</strong> Highest MCC (0.9648) Β· Val AUC (0.9998) Β· Lowest Log Loss (0.0357)<br>
                        <strong>Input:</strong> 224Γ—224 RGB Β· ImageNet normalisation<br>
                        <strong>Classes:</strong> <code>not_pcos</code> (0) Β· <code>pcos</code> (1)<br>
                        <strong>Checkpoint:</strong> <code>models/best_model.pth</code><br>
                        <strong>XAI:</strong> Grad-CAM on <code>features.denseblock4</code>
                    </div>""")
                with gr.Column(scale=6):
                    gr.HTML('<p class="sec">πŸ“‹ Diagnosis Result</p>')
                    img_result=gr.Markdown(value="*Upload an image and click Analyze.*")
                    gr.HTML('<p class="sec" style="margin-top:14px">πŸ“Š Probability Gauge</p>')
                    img_gauge=gr.Plot(label="",show_label=False)
            gr.HTML('<p class="sec" style="margin-top:6px">πŸ”₯ Grad-CAM Explainability</p>')
            img_gradcam=gr.Plot(label="",show_label=False)
            img_btn.click(fn=predict_image_single,inputs=[img_input],
                          outputs=[img_result,img_gauge,img_gradcam])

        # ── TAB 3: BATCH IMAGE ────────────────────────────────────
        with gr.TabItem("πŸ“‚ Ultrasound β€” Batch"):
            with gr.Row(equal_height=False):
                with gr.Column(scale=4):
                    gr.HTML('<p class="sec">πŸ“ Upload Multiple Images</p>')
                    batch_input=gr.File(label="",file_count="multiple",file_types=["image"])
                    batch_btn=gr.Button("⚑ Run Batch Analysis",variant="primary",size="lg")
                    gr.HTML("""<div class="info-box" style="margin-top:12px">
                        Upload any number of ultrasound images.<br>
                        Each is analysed independently using DenseNet121.<br>
                        Results shown as a summary table + distribution chart.<br><br>
                        <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF
                    </div>""")
                with gr.Column(scale=6):
                    gr.HTML('<p class="sec">πŸ“Š Batch Summary</p>')
                    batch_result=gr.Markdown(value="*Upload images and click Run Batch Analysis.*")
            gr.HTML('<p class="sec" style="margin-top:6px">πŸ“ˆ Distribution Chart</p>')
            batch_chart=gr.Plot(label="",show_label=False)
            batch_btn.click(fn=predict_image_batch,inputs=[batch_input],
                            outputs=[batch_result,batch_chart])

        # ── TAB 4: ABOUT ──────────────────────────────────────────
        with gr.TabItem("ℹ️ About"):
            gr.Markdown("""
## About This System
### πŸ–ΌοΈ Image Pipeline β€” DenseNet121
| Component | Detail |
|---|---|
| Architecture | DenseNet121 (ImageNet pretrained, fine-tuned) |
| Why selected | Best MCC (0.9648) Β· Val AUC (0.9998) Β· Lowest Log Loss (0.0357) Β· Best Specificity (0.9918) |
| Input | 224Γ—224 RGB Β· ImageNet normalisation |
| Classes | `not_pcos` (0) Β· `pcos` (1) β€” alphabetical |
| Checkpoint key | `model_state` |
| XAI | Grad-CAM on `features.denseblock4` |
| File | `models/best_model.pth` |
| Test ROC-AUC | 0.9994 Β· F1: 0.9926 Β· Accuracy: 0.9883 |
### πŸ”¬ Clinical Pipeline
| Component | Detail |
|---|---|
| Base models | Logistic Regression Β· Random Forest Β· Gradient Boosting Β· CatBoost |
| Meta-learner | CalibratedClassifierCV (LogisticRegressionCV, isotonic) |
| Imputation | MICE (IterativeImputer, max_iter=10) |
| Scaling | RobustScaler |
| Severity scoring | OOF GBM per domain β†’ normalised 0–1 |
| Threshold | Youden-J optimal on test ROC |
| Dataset | PCOS_data_without_infertility.xlsx (Space root) |
**Domain weights:** Reproductive 40% Β· Metabolic 35% Β· Hyperandrogenic 20% Β· General 5%
### 🧬 Infertility Risk
Weighted biomarker formula (no training): AMH 0.22 Β· FSH 0.18 Β· FSH/LH 0.15 Β· Follicles 0.10Γ—2 Β· Endometrium 0.08 Β· LH 0.08 Β· PRG 0.05 Β· Cycle 0.04
### ⚠️ Disclaimer
For **research and educational purposes only**. Not a certified medical device.
Always consult a qualified healthcare professional for clinical decisions.
            """)

demo.launch(server_name="0.0.0.0", server_port=7860)