File size: 26,514 Bytes
071b854
6f44c3b
071b854
eecd8b4
071b854
 
 
 
7094b3e
 
eecd8b4
071b854
7094b3e
071b854
a51dc80
eecd8b4
6f44c3b
 
 
 
 
 
 
bd6e528
071b854
bd6e528
 
 
 
 
 
9c4e54a
6f44c3b
bd6e528
6f44c3b
bd6e528
9c4e54a
bd6e528
 
 
9c4e54a
bd6e528
 
6f44c3b
 
9c4e54a
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
6f44c3b
 
bd6e528
a51dc80
bd6e528
 
 
7094b3e
bd6e528
6f44c3b
bd6e528
6f44c3b
bd6e528
 
6f44c3b
 
 
bd6e528
 
 
6f44c3b
 
bd6e528
6f44c3b
bd6e528
6f44c3b
 
 
 
 
 
 
 
 
 
 
bd6e528
6f44c3b
 
bd6e528
6f44c3b
 
bd6e528
6f44c3b
 
 
 
bd6e528
071b854
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
071b854
6f44c3b
 
 
 
bd6e528
6f44c3b
071b854
6f44c3b
071b854
6f44c3b
 
071b854
6f44c3b
 
 
 
7094b3e
6f44c3b
7094b3e
6f44c3b
 
 
 
 
 
071b854
6f44c3b
 
071b854
6f44c3b
 
 
071b854
6f44c3b
 
 
bd6e528
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
6f44c3b
 
 
 
 
 
 
bd6e528
6f44c3b
 
 
 
 
 
 
 
 
 
 
071b854
 
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
071b854
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
071b854
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
6f44c3b
 
 
 
 
7094b3e
6f44c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd6e528
9c4e54a
071b854
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
import os
import io
import warnings
import numpy as np
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import gradio as gr

warnings.filterwarnings("ignore")

# ═══════════════════════════════════════════════════════════════
# CONFIG
# ═══════════════════════════════════════════════════════════════
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]),
])

# ═══════════════════════════════════════════════════════════════
# MODEL LOADING
# ═══════════════════════════════════════════════════════════════
def load_model():
    candidates = [
        os.path.join(MODELS_DIR, "best_model.pth"),
        os.path.join(MODELS_DIR, "efficientnetb0.pth"),
        os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
    ]
    pth = next((p for p in candidates if os.path.exists(p)), None)
    if pth is None:
        print(f"❌ No model found. models/ = {os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else 'missing'}")
        return None

    net = models.efficientnet_b0(weights=None)
    net.classifier[1] = nn.Linear(net.classifier[1].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"βœ… Model loaded: {pth}")
    return net

MODEL = load_model()

# ═══════════════════════════════════════════════════════════════
# CORE INFERENCE
# ═══════════════════════════════════════════════════════════════
def run_inference(img_rgb: Image.Image):
    """Returns (pcos_prob, notpcos_prob, pred_idx)."""
    tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
    with torch.no_grad():
        probs = torch.softmax(MODEL(tensor), dim=1)[0]
    pcos_p = float(probs[PCOS_IDX])
    notp   = float(probs[1 - PCOS_IDX])
    pred   = int(probs.argmax())
    return pcos_p, notp, pred, tensor

# ═══════════════════════════════════════════════════════════════
# GRAD-CAM
# ═══════════════════════════════════════════════════════════════
def compute_gradcam(img_rgb: Image.Image, target_class: int) -> plt.Figure:
    grads, acts = [], []

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

    handle = MODEL.features[-1].register_forward_hook(fwd_hook)
    tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
    MODEL.zero_grad()
    MODEL(tensor)[0, target_class].backward()
    handle.remove()

    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.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})
    panels = [
        (orig_r,       None,  "Original Image"),
        (cam_up,       "jet", "Grad-CAM Heatmap"),
        (overlay,      None,  "Activation Overlay"),
    ]
    for ax, (img, cmap, title) in zip(axes, panels):
        ax.set_facecolor("#0f172a")
        ax.imshow(img, cmap=cmap)
        ax.set_title(title, color="white", fontsize=11,
                     fontweight="bold", pad=6)
        ax.axis("off")
        for sp in ax.spines.values():
            sp.set_linewidth(0)

    fig.text(0.5, -0.02,
             f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
             ha="center", color="#94a3b8", fontsize=10)
    plt.tight_layout(pad=0.4)
    return fig

# ═══════════════════════════════════════════════════════════════
# PROBABILITY GAUGE CHART
# ═══════════════════════════════════════════════════════════════
def make_gauge(pcos_prob: float) -> plt.Figure:
    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")

    # Background bar
    ax.barh([0.5], [1.0], height=0.32, color="#1e293b",
            left=0, align="center", zorder=1)
    # Colored fill
    color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
    ax.barh([0.5], [pcos_prob], height=0.32, color=color,
            left=0, align="center", zorder=2)
    # Threshold line
    ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
    # Percentage label
    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")
    # Zone labels
    ax.text(0.16, 0.12, "Low", color="#22c55e", fontsize=8, ha="center", alpha=0.8)
    ax.text(0.50, 0.12, "Moderate", color="#f59e0b", fontsize=8, ha="center", alpha=0.8)
    ax.text(0.83, 0.12, "High", color="#ef4444", 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

# ═══════════════════════════════════════════════════════════════
# SINGLE IMAGE PREDICTION
# ═══════════════════════════════════════════════════════════════
def predict_single(image):
    if MODEL is None:
        return "❌ Model not loaded β€” upload `best_model.pth` to `models/`.", 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_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}** |

*EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
> ⚠️ Research use only β€” not a clinical tool."""

        gauge       = make_gauge(pcos_p)
        gradcam_fig = compute_gradcam(img_rgb, pred)
        return result, gauge, gradcam_fig

    except Exception as e:
        import traceback
        return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None

# ═══════════════════════════════════════════════════════════════
# BATCH PREDICTION
# ═══════════════════════════════════════════════════════════════
def predict_batch(files):
    if MODEL is None:
        return "❌ Model not loaded.", None
    if not files:
        return "⚠️ Please 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_inference(img)
            label = CLASS_NAMES[pred]
            risk  = "Low" if pcos_p < 0.33 else "Moderate" if pcos_p < 0.66 else "High"
            icon  = "πŸ”΄" if pred == PCOS_IDX else "🟒"
            fname = os.path.basename(f.name)
            rows.append({
                "File"            : fname,
                "Prediction"      : f"{icon} {label}",
                "PCOS Prob (%)"   : f"{pcos_p*100:.1f}",
                "Not PCOS Prob (%)": f"{notp*100:.1f}",
                "Risk"            : risk,
            })
            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"❌ Error: {e}",
                "PCOS Prob (%)"   : "β€”",
                "Not PCOS Prob (%)": "β€”",
                "Risk"            : "β€”",
            })

    total = len(rows)

    # ── Summary markdown ─────────────────────────────────────────
    summary = f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total > 1 else ''}

| | Count | Percentage |
|---|---|---|
| πŸ”΄ PCOS Detected | **{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 |
|---|---|---|---|---|
""" + "\n".join(
        f"| `{r['File']}` | {r['Prediction']} | {r['PCOS Prob (%)']}% | {r['Not PCOS Prob (%)']}% | {r['Risk']} |"
        for r in rows
    ) + "\n\n> ⚠️ Research use only β€” not a clinical tool."

    # ── Summary pie chart ─────────────────────────────────────────
    summary_fig = make_batch_chart(pcos_c, notp_c, total)

    return summary, summary_fig


def make_batch_chart(pcos_c: int, notp_c: int, total: int) -> plt.Figure:
    fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")

    # ── Pie ──────────────────────────────────────────────────────
    ax1 = fig.add_subplot(1, 2, 1)
    ax1.set_facecolor("#0f172a")
    if total > 0:
        sizes  = [pcos_c, notp_c]
        labels = [f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"]
        colors = ["#ef4444", "#22c55e"]
        wedges, texts, autotexts = ax1.pie(
            sizes, labels=labels, colors=colors,
            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)

    # ── Bar β€” counts ──────────────────────────────────────────────
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.set_facecolor("#0f172a")
    cats   = ["Not PCOS", "PCOS"]
    counts = [notp_c, pcos_c]
    colors = ["#22c55e", "#ef4444"]
    bars   = ax2.bar(cats, counts, color=colors, width=0.45,
                     edgecolor="#0f172a", linewidth=2)
    ax2.set_ylim(0, max(counts) * 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, counts):
        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 ''}  Β·  EfficientNetB0",
             ha="center", color="#64748b", fontsize=9)
    plt.tight_layout(pad=1.5)
    return fig

# ═══════════════════════════════════════════════════════════════
# CSS
# ═══════════════════════════════════════════════════════════════
CSS = """
/* ── Global ── */
body, .gradio-container {
    background: #0f172a !important;
    font-family: 'Inter', 'Segoe UI', sans-serif !important;
}
/* ── Header banner ── */
.app-header {
    background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #1e1b4b 100%);
    border: 1px solid #4338ca;
    border-radius: 16px;
    padding: 28px 36px;
    margin-bottom: 20px;
    text-align: center;
}
.app-header h1 {
    color: #e0e7ff !important;
    font-size: 2rem !important;
    font-weight: 700 !important;
    margin: 0 0 6px 0 !important;
    letter-spacing: -0.5px;
}
.app-header p {
    color: #a5b4fc !important;
    font-size: 0.95rem !important;
    margin: 0 !important;
}
/* ── Disclaimer ── */
.disclaimer {
    background: #1c1917;
    border-left: 4px solid #f59e0b;
    border-radius: 8px;
    padding: 10px 16px;
    color: #fbbf24 !important;
    font-size: 0.85rem;
    margin-bottom: 16px;
}
/* ── Cards ── */
.card {
    background: #1e293b;
    border: 1px solid #334155;
    border-radius: 14px;
    padding: 20px;
}
/* ── Section headings ── */
.section-title {
    color: #c7d2fe !important;
    font-size: 0.8rem !important;
    font-weight: 600 !important;
    letter-spacing: 1.2px !important;
    text-transform: uppercase !important;
    margin: 0 0 12px 0 !important;
    padding-bottom: 8px !important;
    border-bottom: 1px solid #334155 !important;
}
/* ── Stat pills ── */
.stat-row {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin: 10px 0;
}
.stat-pill {
    background: #0f172a;
    border: 1px solid #475569;
    border-radius: 8px;
    padding: 8px 14px;
    font-size: 0.85rem;
    color: #e2e8f0;
    min-width: 120px;
}
.stat-pill strong { color: #818cf8; display: block; font-size: 1.1rem; }
/* ── Tab nav ── */
.tab-nav button {
    color: #94a3b8 !important;
    font-size: 0.9rem !important;
    font-weight: 600 !important;
    border-radius: 8px 8px 0 0 !important;
    padding: 10px 20px !important;
}
.tab-nav button.selected {
    color: #818cf8 !important;
    border-bottom: 2px solid #818cf8 !important;
    background: #1e293b !important;
}
/* ── Buttons ── */
button.primary {
    background: linear-gradient(135deg, #4f46e5, #7c3aed) !important;
    border: none !important;
    border-radius: 10px !important;
    font-weight: 700 !important;
    font-size: 1rem !important;
    color: white !important;
    letter-spacing: 0.3px;
    padding: 12px 0 !important;
    transition: opacity 0.2s;
}
button.primary:hover { opacity: 0.88 !important; }
/* ── Input panels ── */
.input-panel {
    background: #1e293b;
    border: 1px solid #334155;
    border-radius: 14px;
    padding: 16px;
}
/* ── Result panel ── */
.result-panel {
    background: #1e293b;
    border: 1px solid #334155;
    border-radius: 14px;
    padding: 16px;
    min-height: 200px;
}
/* ── Markdown tables ── */
table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
th {
    background: #1e3a5f;
    color: #93c5fd;
    padding: 8px 12px;
    text-align: left;
    font-weight: 600;
}
td { padding: 8px 12px; border-bottom: 1px solid #1e293b; color: #e2e8f0; }
tr:nth-child(even) td { background: #1a2540; }
/* ── Plots ── */
.gradio-plot { border-radius: 12px !important; overflow: hidden; }
/* ── File upload ── */
.upload-zone {
    border: 2px dashed #4338ca !important;
    border-radius: 14px !important;
    background: #1e293b !important;
}
/* ── Info box ── */
.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; }
"""

# ═══════════════════════════════════════════════════════════════
# GRADIO UI
# ═══════════════════════════════════════════════════════════════
with gr.Blocks(css=CSS, title="PCOS Ultrasound Detection") as demo:

    # ── Header ──────────────────────────────────────────────────
    gr.HTML("""
    <div class="app-header">
        <h1>🩺 PCOS Ultrasound Detection</h1>
        <p>EfficientNetB0 &nbsp;Β·&nbsp; Fine-tuned on ovarian ultrasound dataset &nbsp;Β·&nbsp; Grad-CAM XAI</p>
    </div>
    <div class="disclaimer">
        ⚠️ <strong>Medical Disclaimer:</strong> This tool is intended for
        <strong>research and educational purposes only</strong>. It is not a certified
        medical device and must not be used as a substitute for professional clinical diagnosis.
    </div>
    """)

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

        # ══════════════════════════════════════════════════════════
        # TAB 1 β€” SINGLE IMAGE
        # ══════════════════════════════════════════════════════════
        with gr.TabItem("πŸ”¬ Single Image Analysis"):

            with gr.Row(equal_height=False):

                # ── Upload column ──────────────────────────────────
                with gr.Column(scale=4):
                    gr.HTML('<p class="section-title">πŸ“ Upload Image</p>')
                    img_input = gr.Image(
                        label="",
                        type="pil",
                        height=290,
                        elem_classes="upload-zone",
                    )
                    analyze_btn = gr.Button(
                        "πŸ”  Analyze Image",
                        variant="primary",
                        size="lg",
                        elem_classes="primary",
                    )
                    gr.HTML("""
                    <div class="info-box" style="margin-top:14px">
                        <strong>How to use</strong><br>
                        1. Upload a clear ovarian ultrasound (PNG / JPG)<br>
                        2. Click <strong>Analyze Image</strong><br>
                        3. Review the diagnosis, probability gauge, and Grad-CAM heatmap<br><br>
                        <strong>Model info</strong><br>
                        Architecture: EfficientNetB0 &nbsp;|&nbsp; Input: 224Γ—224 RGB<br>
                        Classes: <code>not_pcos</code> (0) &nbsp;Β·&nbsp; <code>pcos</code> (1)
                    </div>
                    """)

                # ── Result column ──────────────────────────────────
                with gr.Column(scale=6):
                    gr.HTML('<p class="section-title">πŸ“‹ Diagnosis Result</p>')
                    result_md = gr.Markdown(
                        value="*Upload an image and click **Analyze Image** to see the result.*",
                    )
                    gr.HTML('<p class="section-title" style="margin-top:16px">πŸ“Š PCOS Probability Gauge</p>')
                    gauge_plot = gr.Plot(label="", show_label=False)

            # ── Grad-CAM ─────────────────────────────────────────────
            gr.HTML('<p class="section-title" style="margin-top:8px">πŸ”₯ Grad-CAM Explainability</p>')
            gradcam_plot = gr.Plot(label="", show_label=False)

            analyze_btn.click(
                fn=predict_single,
                inputs=[img_input],
                outputs=[result_md, gauge_plot, gradcam_plot],
            )

        # ══════════════════════════════════════════════════════════
        # TAB 2 β€” BATCH
        # ══════════════════════════════════════════════════════════
        with gr.TabItem("πŸ“‚ Batch Analysis"):

            with gr.Row():
                with gr.Column(scale=4):
                    gr.HTML('<p class="section-title">πŸ“ Upload Multiple Images</p>')
                    batch_input = gr.File(
                        label="",
                        file_count="multiple",
                        file_types=["image"],
                        elem_classes="upload-zone",
                    )
                    batch_btn = gr.Button(
                        "⚑  Run Batch Analysis",
                        variant="primary",
                        size="lg",
                        elem_classes="primary",
                    )
                    gr.HTML("""
                    <div class="info-box" style="margin-top:14px">
                        <strong>Batch mode</strong><br>
                        Upload multiple ultrasound images at once.<br>
                        Each image is analysed independently and results
                        are shown in a summary table with per-image
                        PCOS probability and risk tier.<br><br>
                        <strong>Supported formats:</strong> PNG, JPG, JPEG, BMP, TIFF
                    </div>
                    """)

                with gr.Column(scale=6):
                    gr.HTML('<p class="section-title">πŸ“Š Batch Summary &amp; Per-Image Results</p>')
                    batch_result_md = gr.Markdown(
                        value="*Upload images and click **Run Batch Analysis**.*"
                    )

            gr.HTML('<p class="section-title" style="margin-top:8px">πŸ“ˆ Distribution Chart</p>')
            batch_chart = gr.Plot(label="", show_label=False)

            batch_btn.click(
                fn=predict_batch,
                inputs=[batch_input],
                outputs=[batch_result_md, batch_chart],
            )

        # ══════════════════════════════════════════════════════════
        # TAB 3 β€” ABOUT
        # ══════════════════════════════════════════════════════════
        with gr.TabItem("ℹ️ About"):
            gr.Markdown("""
## About This Application

### 🧠 Model Architecture

| Parameter | Detail |
|---|---|
| Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
| Input size | 224 Γ— 224 RGB |
| Normalisation | Mean [0.485, 0.456, 0.406] Β· Std [0.229, 0.224, 0.225] |
| Output classes | `not_pcos` (0), `pcos` (1) β€” alphabetical order |
| Decision threshold | 0.50 (softmax argmax) |
| Checkpoint key | `model_state` |
| Saved criterion | Best validation AUC |

### πŸ‹οΈ Training Details

| Setting | Value |
|---|---|
| Optimiser | Adam (lr=1e-4, weight_decay=1e-5) |
| Loss | CrossEntropyLoss with class weights (balanced) |
| Sampler | WeightedRandomSampler for batch balance |
| Scheduler | ReduceLROnPlateau (factor=0.3, patience=3) |
| Early stopping | Patience = 7 epochs |
| Max epochs | 30 |
| Batch size | 32 |
| Augmentation | RandomHorizontalFlip, RandomRotation(15Β°), ColorJitter |

### πŸ”₯ Grad-CAM Explainability

Gradient-weighted Class Activation Mapping (Grad-CAM) highlights image
regions that most influenced the model's decision.
- **Target layer:** `features[-1]` (last convolutional block)
- **Target class:** Predicted class
- Heatmap is upsampled to 224Γ—224 and overlaid on the original image

### ⚠️ Disclaimer

This application is for **research and educational purposes only**.
It is not certified for clinical use and must not replace the judgement
of a qualified medical professional.
            """)

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