DheivaCodes commited on
Commit
6f44c3b
Β·
verified Β·
1 Parent(s): 6245fe9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +548 -247
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import warnings
3
  import numpy as np
4
  import torch
@@ -13,19 +14,15 @@ import gradio as gr
13
 
14
  warnings.filterwarnings("ignore")
15
 
16
- # ─────────────────────────────────────────────────────────────
17
- # CONFIG β€” mirrors pipeline exactly
18
- # ─────────────────────────────────────────────────────────────
19
- MODELS_DIR = "models"
20
- IMG_SIZE = 224
21
- DEVICE = torch.device("cpu")
22
-
23
- # ImageFolder sorts alphabetically: ['not_pcos', 'pcos']
24
- # β†’ index 0 = not_pcos, index 1 = pcos
25
- CLASS_NAMES = ["Not PCOS", "PCOS"] # index 0, 1
26
  PCOS_IDX = 1
27
 
28
- # Val/test transform β€” no augmentation, same as pipeline
29
  VAL_TRANSFORM = transforms.Compose([
30
  transforms.Resize((IMG_SIZE, IMG_SIZE)),
31
  transforms.ToTensor(),
@@ -33,10 +30,9 @@ VAL_TRANSFORM = transforms.Compose([
33
  std =[0.229, 0.224, 0.225]),
34
  ])
35
 
36
- # ─────────────────────────────────────────────────────────────
37
  # MODEL LOADING
38
- # checkpoint format: {"model_state": ..., "epoch": ..., ...}
39
- # ─────────────────────────────────────────────────────────────
40
  def load_model():
41
  candidates = [
42
  os.path.join(MODELS_DIR, "best_model.pth"),
@@ -44,51 +40,42 @@ def load_model():
44
  os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
45
  ]
46
  pth = next((p for p in candidates if os.path.exists(p)), None)
47
-
48
  if pth is None:
49
- existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else []
50
- print(f"❌ No model file found. models/ contains: {existing}")
51
- return None, None
52
-
53
- try:
54
- net = models.efficientnet_b0(weights=None)
55
- net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
56
-
57
- ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
58
-
59
- # Handle all checkpoint formats from pipeline
60
- if isinstance(ckpt, dict):
61
- if "model_state" in ckpt: # pipeline format
62
- state = ckpt["model_state"]
63
- elif "model_state_dict" in ckpt:
64
- state = ckpt["model_state_dict"]
65
- elif "state_dict" in ckpt:
66
- state = ckpt["state_dict"]
67
- else:
68
- state = ckpt # raw state dict
69
- else:
70
- state = ckpt
71
-
72
- net.load_state_dict(state, strict=True)
73
- net.to(DEVICE).eval()
74
- print(f"βœ… Model loaded from {pth}")
75
- return net, pth
76
- except Exception as e:
77
- print(f"❌ Model load error: {e}")
78
- return None, None
79
-
80
-
81
- MODEL, MODEL_PATH = load_model()
82
-
83
 
84
- # ─────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  # GRAD-CAM
86
- # ─────────────────────────────────────────────────────────────
87
- def compute_gradcam(image_rgb: Image.Image, tensor: torch.Tensor, target_class: int):
88
- """
89
- Grad-CAM on EfficientNetB0 features[-1] (last conv block).
90
- Returns overlaid figure.
91
- """
92
  grads, acts = [], []
93
 
94
  def fwd_hook(m, inp, out):
@@ -96,231 +83,545 @@ def compute_gradcam(image_rgb: Image.Image, tensor: torch.Tensor, target_class:
96
  out.register_hook(lambda g: grads.append(g.detach()))
97
 
98
  handle = MODEL.features[-1].register_forward_hook(fwd_hook)
99
-
100
  MODEL.zero_grad()
101
- output = MODEL(tensor)
102
- output[0, target_class].backward()
103
  handle.remove()
104
 
105
- if not grads or not acts:
106
- return None
107
-
108
- # weights = global average pooled gradients
109
- w = grads[0].squeeze(0).mean(dim=(1, 2)) # (C,)
110
- act = acts[0].squeeze(0).cpu().numpy() # (C, H, W)
111
- cam = np.zeros(act.shape[1:], dtype=np.float32)
112
- for i, wi in enumerate(w.cpu().numpy()):
113
- cam += wi * act[i]
114
-
115
- cam = np.maximum(cam, 0)
116
  if cam.max() > 1e-8:
117
  cam /= cam.max()
118
 
119
- cam_up = np.array(
120
- Image.fromarray((cam * 255).astype(np.uint8)).resize(
121
- (IMG_SIZE, IMG_SIZE), Image.BILINEAR)
122
  ) / 255.0
123
-
124
- orig_r = image_rgb.resize((IMG_SIZE, IMG_SIZE))
125
  heat = cm.jet(cam_up)[:, :, :3]
126
- overlay = np.clip(0.55 * np.array(orig_r) / 255.0 + 0.45 * heat, 0, 1)
127
-
128
- fig, axes = plt.subplots(1, 3, figsize=(15, 5), facecolor="#111827")
129
- titles = ["Original Image", "Grad-CAM Heatmap", "Overlay"]
130
- imgs = [orig_r, cam_up, overlay]
131
- cmaps = [None, "jet", None]
132
-
133
- for ax, title, img, cmap in zip(axes, titles, imgs, cmaps):
134
- ax.set_facecolor("#111827")
 
 
135
  ax.imshow(img, cmap=cmap)
136
- ax.set_title(title, color="white", fontsize=12, fontweight="bold", pad=8)
 
137
  ax.axis("off")
 
 
138
 
139
- label = CLASS_NAMES[target_class]
140
- plt.suptitle(
141
- f"Grad-CAM β€” Model attention for: {label}",
142
- color="white", fontsize=13, fontweight="bold", y=1.02
143
- )
144
- plt.tight_layout()
145
  return fig
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- # ─────────────────────────────────────────────────────────────
149
- # MAIN PREDICTION FUNCTION
150
- # ─────────────────────────────────────────────────────────────
151
- def predict(image):
152
  if MODEL is None:
153
- existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else "folder missing"
154
- msg = (
155
- "## ❌ Model not loaded\n\n"
156
- f"Files found in `models/`: `{existing}`\n\n"
157
- "**Fix:** Upload `best_model.pth` to the `models/` folder on HuggingFace."
158
- )
159
- return msg, None, None
160
-
161
  if image is None:
162
- return "## ⚠️ Please upload an ultrasound image.", None, None
163
-
164
  try:
165
- # ── Preprocess ───────────────────────────────────────────
166
- if not isinstance(image, Image.Image):
167
- image = Image.fromarray(image)
168
- img_rgb = image.convert("RGB")
169
- tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
170
-
171
- # ── Forward pass ─────────────────────────────────────────
172
- MODEL.eval()
173
- with torch.no_grad():
174
- logits = MODEL(tensor)
175
- probs = torch.softmax(logits, dim=1)[0]
176
-
177
- pcos_prob = float(probs[PCOS_IDX])
178
- notpcos_prob = float(probs[1 - PCOS_IDX])
179
- pred_idx = int(probs.argmax())
180
- pred_label = CLASS_NAMES[pred_idx]
181
- confidence = float(probs[pred_idx])
182
-
183
- # ── Risk tier ─────────────────────────────────────────────
184
- if pcos_prob < 0.33:
185
- risk, risk_color = "🟒 Low Risk", "green"
186
- elif pcos_prob < 0.66:
187
- risk, risk_color = "🟑 Moderate Risk", "orange"
188
- else:
189
- risk, risk_color = "πŸ”΄ High Risk", "red"
190
-
191
- diagnosis_icon = "πŸ”΄" if pred_idx == PCOS_IDX else "🟒"
192
-
193
- # ── Result markdown ───────────────────────────────────────
194
- result = (
195
- f"## {diagnosis_icon} Diagnosis: **{pred_label}**\n\n"
196
- f"| Metric | Value |\n"
197
- f"|--------|-------|\n"
198
- f"| PCOS Probability | **{pcos_prob*100:.1f}%** |\n"
199
- f"| Not PCOS Probability | **{notpcos_prob*100:.1f}%** |\n"
200
- f"| Model Confidence | **{confidence*100:.1f}%** |\n"
201
- f"| Risk Level | **{risk}** |\n\n"
202
- f"*Model: EfficientNetB0 Β· Input: 224Γ—224 RGB Β· Threshold: 0.50*\n\n"
203
- f"> ⚠️ For research purposes only. Consult a qualified clinician."
204
- )
205
 
206
- # ── Probability bar chart ─────────────────────────��───────
207
- bar_fig = make_prob_chart(pcos_prob, notpcos_prob)
 
 
208
 
209
- # ── Grad-CAM (use predicted class) ───────────────────────
210
- # Re-run with grad enabled
211
- tensor_grad = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
212
- tensor_grad.requires_grad_(False)
213
- gradcam_fig = compute_gradcam(img_rgb, tensor_grad, pred_idx)
214
 
215
- return result, bar_fig, gradcam_fig
 
 
 
 
 
216
 
217
- except Exception as e:
218
- import traceback
219
- return f"## ❌ Prediction error\n\n```\n{traceback.format_exc()}\n```", None, None
220
 
 
 
 
221
 
222
- # ─────────────────────────────────────────────────────────────
223
- # PROBABILITY BAR CHART
224
- # ─────────────────────────────────────────────────────────────
225
- def make_prob_chart(pcos_prob: float, notpcos_prob: float):
226
- fig, ax = plt.subplots(figsize=(6, 2.8), facecolor="#111827")
227
- ax.set_facecolor("#111827")
228
 
229
- labels = ["Not PCOS", "PCOS"]
230
- vals = [notpcos_prob, pcos_prob]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  colors = ["#22c55e", "#ef4444"]
232
-
233
- bars = ax.barh(labels, vals, color=colors, height=0.45, edgecolor="none")
234
- ax.axvline(0.5, color="white", lw=1, ls="--", alpha=0.5)
235
- ax.set_xlim(0, 1.08)
236
- ax.set_xlabel("Probability", color="#9ca3af", fontsize=10)
237
- ax.set_title("Class Probabilities", color="white", fontsize=12, fontweight="bold", pad=10)
238
- ax.tick_params(colors="white", labelsize=11)
239
- for sp in ax.spines.values():
240
  sp.set_visible(False)
241
-
242
- for bar, val in zip(bars, vals):
243
- ax.text(
244
- min(val + 0.025, 1.0), bar.get_y() + bar.get_height() / 2,
245
- f"{val*100:.1f}%", va="center", color="white",
246
- fontsize=11, fontweight="bold"
247
- )
248
-
249
- plt.tight_layout()
 
 
250
  return fig
251
 
252
-
253
- # ─────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  # GRADIO UI
255
- # ─────────────────────────────────────────────────────────────
256
- with gr.Blocks(
257
- theme=gr.themes.Soft(primary_hue="purple", neutral_hue="slate"),
258
- title="PCOS Ultrasound Detection"
259
- ) as demo:
260
-
261
- gr.Markdown("""
262
- # 🩺 PCOS Ultrasound Image Detection
263
- **EfficientNetB0 Β· Fine-tuned on PCOS ovarian ultrasound dataset Β· Grad-CAM visualization**
264
-
265
- Upload an ovarian ultrasound image to detect PCOS. The model will highlight which regions
266
- influenced its decision using Grad-CAM.
267
-
268
- > ⚠️ **Disclaimer:** For research/educational purposes only. Not a substitute for professional medical diagnosis.
269
  """)
270
 
271
- with gr.Row():
272
- # ── Left: upload + button ──────────────────────────────────
273
- with gr.Column(scale=1, min_width=280):
274
- img_input = gr.Image(
275
- label="Upload Ovarian Ultrasound (PNG / JPG)",
276
- type="pil",
277
- height=300,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  )
279
- analyze_btn = gr.Button(
280
- "πŸ” Analyze Image",
281
- variant="primary",
282
- size="lg",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  )
 
 
 
 
 
284
  gr.Markdown("""
285
- **How to use:**
286
- 1. Upload a clear ovarian ultrasound image
287
- 2. Click **Analyze Image**
288
- 3. View diagnosis, confidence, and Grad-CAM heatmap
289
-
290
- **Class mapping (alphabetical):**
291
- - `not_pcos` β†’ index 0
292
- - `pcos` β†’ index 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  """)
294
 
295
- # ── Right: result + probability chart ─────────────────────
296
- with gr.Column(scale=1, min_width=300):
297
- result_md = gr.Markdown(
298
- value="*Upload an image and click Analyze.*"
299
- )
300
- prob_plot = gr.Plot(label="Class Probabilities")
301
-
302
- # ── Grad-CAM full width ────────────────────────────────────────
303
- with gr.Row():
304
- gradcam_plot = gr.Plot(label="Grad-CAM Visualization β€” Model Attention Map")
305
-
306
- analyze_btn.click(
307
- fn=predict,
308
- inputs=[img_input],
309
- outputs=[result_md, prob_plot, gradcam_plot],
310
- )
311
-
312
- gr.Markdown("""
313
- ---
314
- ### About the Model
315
- | Parameter | Value |
316
- |-----------|-------|
317
- | Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
318
- | Input size | 224 Γ— 224 RGB |
319
- | Normalization | ImageNet stats (mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]) |
320
- | Checkpoint key | `model_state` |
321
- | Classes | `not_pcos` (0), `pcos` (1) β€” alphabetical |
322
- | Visualization | Grad-CAM on `features[-1]` |
323
- | Saved by | Best val AUC during training |
324
- """)
325
-
326
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
+ import io
3
  import warnings
4
  import numpy as np
5
  import torch
 
14
 
15
  warnings.filterwarnings("ignore")
16
 
17
+ # ═══════════════════════════════════════════════════════════════
18
+ # CONFIG
19
+ # ═══════════════════════════════════════════════════════════════
20
+ MODELS_DIR = "models"
21
+ IMG_SIZE = 224
22
+ DEVICE = torch.device("cpu")
23
+ CLASS_NAMES = ["Not PCOS", "PCOS"] # alphabetical: not_pcos=0, pcos=1
 
 
 
24
  PCOS_IDX = 1
25
 
 
26
  VAL_TRANSFORM = transforms.Compose([
27
  transforms.Resize((IMG_SIZE, IMG_SIZE)),
28
  transforms.ToTensor(),
 
30
  std =[0.229, 0.224, 0.225]),
31
  ])
32
 
33
+ # ═══════════════════════════════════════════════════════════════
34
  # MODEL LOADING
35
+ # ═══════════════════════════════════════════════════════════════
 
36
  def load_model():
37
  candidates = [
38
  os.path.join(MODELS_DIR, "best_model.pth"),
 
40
  os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
41
  ]
42
  pth = next((p for p in candidates if os.path.exists(p)), None)
 
43
  if pth is None:
44
+ print(f"❌ No model found. models/ = {os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else 'missing'}")
45
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ net = models.efficientnet_b0(weights=None)
48
+ net.classifier[1] = nn.Linear(net.classifier[1].in_features, 2)
49
+ ckpt = torch.load(pth, map_location=DEVICE, weights_only=False)
50
+ if isinstance(ckpt, dict):
51
+ state = (ckpt.get("model_state") or ckpt.get("model_state_dict")
52
+ or ckpt.get("state_dict") or ckpt)
53
+ else:
54
+ state = ckpt
55
+ net.load_state_dict(state, strict=True)
56
+ net.to(DEVICE).eval()
57
+ print(f"βœ… Model loaded: {pth}")
58
+ return net
59
+
60
+ MODEL = load_model()
61
+
62
+ # ═══════════════════════════════════════════════════════════════
63
+ # CORE INFERENCE
64
+ # ════════════════════���══════════════════════════════════════════
65
+ def run_inference(img_rgb: Image.Image):
66
+ """Returns (pcos_prob, notpcos_prob, pred_idx)."""
67
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
68
+ with torch.no_grad():
69
+ probs = torch.softmax(MODEL(tensor), dim=1)[0]
70
+ pcos_p = float(probs[PCOS_IDX])
71
+ notp = float(probs[1 - PCOS_IDX])
72
+ pred = int(probs.argmax())
73
+ return pcos_p, notp, pred, tensor
74
+
75
+ # ═══════════════════════════════════════════════════════════════
76
  # GRAD-CAM
77
+ # ═══════════════════════════════════════════════════════════════
78
+ def compute_gradcam(img_rgb: Image.Image, target_class: int) -> plt.Figure:
 
 
 
 
79
  grads, acts = [], []
80
 
81
  def fwd_hook(m, inp, out):
 
83
  out.register_hook(lambda g: grads.append(g.detach()))
84
 
85
  handle = MODEL.features[-1].register_forward_hook(fwd_hook)
86
+ tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
87
  MODEL.zero_grad()
88
+ MODEL(tensor)[0, target_class].backward()
 
89
  handle.remove()
90
 
91
+ w = grads[0].squeeze(0).mean(dim=(1, 2)).cpu().numpy()
92
+ act = acts[0].squeeze(0).cpu().numpy()
93
+ cam = np.maximum(sum(w[i] * act[i] for i in range(len(w))), 0)
 
 
 
 
 
 
 
 
94
  if cam.max() > 1e-8:
95
  cam /= cam.max()
96
 
97
+ cam_up = np.array(
98
+ Image.fromarray((cam * 255).astype(np.uint8)).resize((IMG_SIZE, IMG_SIZE), Image.BILINEAR)
 
99
  ) / 255.0
100
+ orig_r = np.array(img_rgb.resize((IMG_SIZE, IMG_SIZE)))
 
101
  heat = cm.jet(cam_up)[:, :, :3]
102
+ overlay = np.clip(0.55 * orig_r / 255.0 + 0.45 * heat, 0, 1)
103
+
104
+ fig, axes = plt.subplots(1, 3, figsize=(14, 4), facecolor="#0f172a",
105
+ gridspec_kw={"wspace": 0.05})
106
+ panels = [
107
+ (orig_r, None, "Original Image"),
108
+ (cam_up, "jet", "Grad-CAM Heatmap"),
109
+ (overlay, None, "Activation Overlay"),
110
+ ]
111
+ for ax, (img, cmap, title) in zip(axes, panels):
112
+ ax.set_facecolor("#0f172a")
113
  ax.imshow(img, cmap=cmap)
114
+ ax.set_title(title, color="white", fontsize=11,
115
+ fontweight="bold", pad=6)
116
  ax.axis("off")
117
+ for sp in ax.spines.values():
118
+ sp.set_linewidth(0)
119
 
120
+ fig.text(0.5, -0.02,
121
+ f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
122
+ ha="center", color="#94a3b8", fontsize=10)
123
+ plt.tight_layout(pad=0.4)
 
 
124
  return fig
125
 
126
+ # ═══════════════════════════════════════════════════════════════
127
+ # PROBABILITY GAUGE CHART
128
+ # ═══════════════════════════════════════════════════════════════
129
+ def make_gauge(pcos_prob: float) -> plt.Figure:
130
+ fig, ax = plt.subplots(figsize=(5, 2.6), facecolor="#0f172a")
131
+ ax.set_facecolor("#0f172a")
132
+ ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off")
133
+
134
+ # Background bar
135
+ ax.barh([0.5], [1.0], height=0.32, color="#1e293b",
136
+ left=0, align="center", zorder=1)
137
+ # Colored fill
138
+ color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
139
+ ax.barh([0.5], [pcos_prob], height=0.32, color=color,
140
+ left=0, align="center", zorder=2)
141
+ # Threshold line
142
+ ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
143
+ # Percentage label
144
+ ax.text(pcos_prob, 0.5, f" {pcos_prob*100:.1f}%",
145
+ va="center", color="white", fontsize=16,
146
+ fontweight="bold", zorder=4,
147
+ ha="left" if pcos_prob < 0.85 else "right")
148
+ # Zone labels
149
+ ax.text(0.16, 0.12, "Low", color="#22c55e", fontsize=8, ha="center", alpha=0.8)
150
+ ax.text(0.50, 0.12, "Moderate", color="#f59e0b", fontsize=8, ha="center", alpha=0.8)
151
+ ax.text(0.83, 0.12, "High", color="#ef4444", fontsize=8, ha="center", alpha=0.8)
152
+ ax.text(0.5, 0.92, "PCOS Probability", color="#94a3b8",
153
+ fontsize=9, ha="center", va="top")
154
+ plt.tight_layout(pad=0.2)
155
+ return fig
156
 
157
+ # ═══════════════════════════════════════════════════════════════
158
+ # SINGLE IMAGE PREDICTION
159
+ # ═══════════════════════════════════════════════════════════════
160
+ def predict_single(image):
161
  if MODEL is None:
162
+ return "❌ Model not loaded β€” upload `best_model.pth` to `models/`.", None, None
 
 
 
 
 
 
 
163
  if image is None:
164
+ return "⚠️ Please upload an ultrasound image.", None, None
 
165
  try:
166
+ img_rgb = (image if isinstance(image, Image.Image) else Image.fromarray(image)).convert("RGB")
167
+ pcos_p, notp, pred, _ = run_inference(img_rgb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
+ icon = "πŸ”΄" if pred == PCOS_IDX else "🟒"
170
+ label = CLASS_NAMES[pred]
171
+ conf = pcos_p if pred == PCOS_IDX else notp
172
+ risk = "🟒 Low" if pcos_p < 0.33 else "🟑 Moderate" if pcos_p < 0.66 else "πŸ”΄ High"
173
 
174
+ result = f"""### {icon} {label}
 
 
 
 
175
 
176
+ | Metric | Value |
177
+ |---|---|
178
+ | PCOS Probability | **{pcos_p*100:.1f}%** |
179
+ | Not PCOS Probability | **{notp*100:.1f}%** |
180
+ | Confidence | **{conf*100:.1f}%** |
181
+ | Risk Level | **{risk}** |
182
 
183
+ *EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
184
+ > ⚠️ Research use only β€” not a clinical tool."""
 
185
 
186
+ gauge = make_gauge(pcos_p)
187
+ gradcam_fig = compute_gradcam(img_rgb, pred)
188
+ return result, gauge, gradcam_fig
189
 
190
+ except Exception as e:
191
+ import traceback
192
+ return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None
 
 
 
193
 
194
+ # ═══════════════════════════════════════════════════════════════
195
+ # BATCH PREDICTION
196
+ # ═══════════════════════════════════════════════════════════════
197
+ def predict_batch(files):
198
+ if MODEL is None:
199
+ return "❌ Model not loaded.", None
200
+ if not files:
201
+ return "⚠️ Please upload at least one image.", None
202
+
203
+ rows = []
204
+ pcos_c = 0
205
+ notp_c = 0
206
+
207
+ for f in files:
208
+ try:
209
+ img = Image.open(f.name).convert("RGB")
210
+ pcos_p, notp, pred, _ = run_inference(img)
211
+ label = CLASS_NAMES[pred]
212
+ risk = "Low" if pcos_p < 0.33 else "Moderate" if pcos_p < 0.66 else "High"
213
+ icon = "πŸ”΄" if pred == PCOS_IDX else "🟒"
214
+ fname = os.path.basename(f.name)
215
+ rows.append({
216
+ "File" : fname,
217
+ "Prediction" : f"{icon} {label}",
218
+ "PCOS Prob (%)" : f"{pcos_p*100:.1f}",
219
+ "Not PCOS Prob (%)": f"{notp*100:.1f}",
220
+ "Risk" : risk,
221
+ })
222
+ if pred == PCOS_IDX:
223
+ pcos_c += 1
224
+ else:
225
+ notp_c += 1
226
+ except Exception as e:
227
+ rows.append({
228
+ "File" : os.path.basename(f.name),
229
+ "Prediction" : f"❌ Error: {e}",
230
+ "PCOS Prob (%)" : "β€”",
231
+ "Not PCOS Prob (%)": "β€”",
232
+ "Risk" : "β€”",
233
+ })
234
+
235
+ total = len(rows)
236
+
237
+ # ── Summary markdown ─────────────────────────────────────────
238
+ summary = f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total > 1 else ''}
239
+
240
+ | | Count | Percentage |
241
+ |---|---|---|
242
+ | πŸ”΄ PCOS Detected | **{pcos_c}** | **{pcos_c/total*100:.1f}%** |
243
+ | 🟒 Not PCOS | **{notp_c}** | **{notp_c/total*100:.1f}%** |
244
+ | πŸ“ Total | **{total}** | 100% |
245
+
246
+ ---
247
+ ### πŸ—‚οΈ Per-Image Results
248
+
249
+ | File | Prediction | PCOS% | Not PCOS% | Risk |
250
+ |---|---|---|---|---|
251
+ """ + "\n".join(
252
+ f"| `{r['File']}` | {r['Prediction']} | {r['PCOS Prob (%)']}% | {r['Not PCOS Prob (%)']}% | {r['Risk']} |"
253
+ for r in rows
254
+ ) + "\n\n> ⚠️ Research use only β€” not a clinical tool."
255
+
256
+ # ── Summary pie chart ─────────────────────────────────────────
257
+ summary_fig = make_batch_chart(pcos_c, notp_c, total)
258
+
259
+ return summary, summary_fig
260
+
261
+
262
+ def make_batch_chart(pcos_c: int, notp_c: int, total: int) -> plt.Figure:
263
+ fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")
264
+
265
+ # ── Pie ──────────────────────────────────────────────────────
266
+ ax1 = fig.add_subplot(1, 2, 1)
267
+ ax1.set_facecolor("#0f172a")
268
+ if total > 0:
269
+ sizes = [pcos_c, notp_c]
270
+ labels = [f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"]
271
+ colors = ["#ef4444", "#22c55e"]
272
+ wedges, texts, autotexts = ax1.pie(
273
+ sizes, labels=labels, colors=colors,
274
+ autopct="%1.1f%%", startangle=90,
275
+ textprops={"color": "white", "fontsize": 10},
276
+ wedgeprops={"linewidth": 2, "edgecolor": "#0f172a"},
277
+ pctdistance=0.75,
278
+ )
279
+ for at in autotexts:
280
+ at.set_color("white")
281
+ at.set_fontsize(10)
282
+ at.set_fontweight("bold")
283
+ ax1.set_title("Class Distribution", color="white",
284
+ fontsize=12, fontweight="bold", pad=12)
285
+
286
+ # ── Bar β€” counts ──────────────────────────────────────────────
287
+ ax2 = fig.add_subplot(1, 2, 2)
288
+ ax2.set_facecolor("#0f172a")
289
+ cats = ["Not PCOS", "PCOS"]
290
+ counts = [notp_c, pcos_c]
291
  colors = ["#22c55e", "#ef4444"]
292
+ bars = ax2.bar(cats, counts, color=colors, width=0.45,
293
+ edgecolor="#0f172a", linewidth=2)
294
+ ax2.set_ylim(0, max(counts) * 1.35 + 0.5)
295
+ ax2.set_title("Count per Class", color="white",
296
+ fontsize=12, fontweight="bold", pad=12)
297
+ ax2.tick_params(colors="white", labelsize=11)
298
+ for sp in ax2.spines.values():
 
299
  sp.set_visible(False)
300
+ ax2.yaxis.set_visible(False)
301
+ for bar, cnt in zip(bars, counts):
302
+ ax2.text(bar.get_x() + bar.get_width() / 2,
303
+ bar.get_height() + 0.15,
304
+ str(cnt), ha="center", color="white",
305
+ fontsize=14, fontweight="bold")
306
+
307
+ fig.text(0.5, 0.01,
308
+ f"Total: {total} image{'s' if total > 1 else ''} Β· EfficientNetB0",
309
+ ha="center", color="#64748b", fontsize=9)
310
+ plt.tight_layout(pad=1.5)
311
  return fig
312
 
313
+ # ═══════════════════════════════════════════════════════════════
314
+ # CSS
315
+ # ═══════════════════════════════════════════════════════════════
316
+ CSS = """
317
+ /* ── Global ── */
318
+ body, .gradio-container {
319
+ background: #0f172a !important;
320
+ font-family: 'Inter', 'Segoe UI', sans-serif !important;
321
+ }
322
+ /* ── Header banner ── */
323
+ .app-header {
324
+ background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #1e1b4b 100%);
325
+ border: 1px solid #4338ca;
326
+ border-radius: 16px;
327
+ padding: 28px 36px;
328
+ margin-bottom: 20px;
329
+ text-align: center;
330
+ }
331
+ .app-header h1 {
332
+ color: #e0e7ff !important;
333
+ font-size: 2rem !important;
334
+ font-weight: 700 !important;
335
+ margin: 0 0 6px 0 !important;
336
+ letter-spacing: -0.5px;
337
+ }
338
+ .app-header p {
339
+ color: #a5b4fc !important;
340
+ font-size: 0.95rem !important;
341
+ margin: 0 !important;
342
+ }
343
+ /* ── Disclaimer ── */
344
+ .disclaimer {
345
+ background: #1c1917;
346
+ border-left: 4px solid #f59e0b;
347
+ border-radius: 8px;
348
+ padding: 10px 16px;
349
+ color: #fbbf24 !important;
350
+ font-size: 0.85rem;
351
+ margin-bottom: 16px;
352
+ }
353
+ /* ── Cards ── */
354
+ .card {
355
+ background: #1e293b;
356
+ border: 1px solid #334155;
357
+ border-radius: 14px;
358
+ padding: 20px;
359
+ }
360
+ /* ── Section headings ── */
361
+ .section-title {
362
+ color: #c7d2fe !important;
363
+ font-size: 0.8rem !important;
364
+ font-weight: 600 !important;
365
+ letter-spacing: 1.2px !important;
366
+ text-transform: uppercase !important;
367
+ margin: 0 0 12px 0 !important;
368
+ padding-bottom: 8px !important;
369
+ border-bottom: 1px solid #334155 !important;
370
+ }
371
+ /* ── Stat pills ── */
372
+ .stat-row {
373
+ display: flex;
374
+ gap: 10px;
375
+ flex-wrap: wrap;
376
+ margin: 10px 0;
377
+ }
378
+ .stat-pill {
379
+ background: #0f172a;
380
+ border: 1px solid #475569;
381
+ border-radius: 8px;
382
+ padding: 8px 14px;
383
+ font-size: 0.85rem;
384
+ color: #e2e8f0;
385
+ min-width: 120px;
386
+ }
387
+ .stat-pill strong { color: #818cf8; display: block; font-size: 1.1rem; }
388
+ /* ── Tab nav ── */
389
+ .tab-nav button {
390
+ color: #94a3b8 !important;
391
+ font-size: 0.9rem !important;
392
+ font-weight: 600 !important;
393
+ border-radius: 8px 8px 0 0 !important;
394
+ padding: 10px 20px !important;
395
+ }
396
+ .tab-nav button.selected {
397
+ color: #818cf8 !important;
398
+ border-bottom: 2px solid #818cf8 !important;
399
+ background: #1e293b !important;
400
+ }
401
+ /* ── Buttons ── */
402
+ button.primary {
403
+ background: linear-gradient(135deg, #4f46e5, #7c3aed) !important;
404
+ border: none !important;
405
+ border-radius: 10px !important;
406
+ font-weight: 700 !important;
407
+ font-size: 1rem !important;
408
+ color: white !important;
409
+ letter-spacing: 0.3px;
410
+ padding: 12px 0 !important;
411
+ transition: opacity 0.2s;
412
+ }
413
+ button.primary:hover { opacity: 0.88 !important; }
414
+ /* ── Input panels ── */
415
+ .input-panel {
416
+ background: #1e293b;
417
+ border: 1px solid #334155;
418
+ border-radius: 14px;
419
+ padding: 16px;
420
+ }
421
+ /* ── Result panel ── */
422
+ .result-panel {
423
+ background: #1e293b;
424
+ border: 1px solid #334155;
425
+ border-radius: 14px;
426
+ padding: 16px;
427
+ min-height: 200px;
428
+ }
429
+ /* ── Markdown tables ── */
430
+ table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
431
+ th {
432
+ background: #1e3a5f;
433
+ color: #93c5fd;
434
+ padding: 8px 12px;
435
+ text-align: left;
436
+ font-weight: 600;
437
+ }
438
+ td { padding: 8px 12px; border-bottom: 1px solid #1e293b; color: #e2e8f0; }
439
+ tr:nth-child(even) td { background: #1a2540; }
440
+ /* ── Plots ── */
441
+ .gradio-plot { border-radius: 12px !important; overflow: hidden; }
442
+ /* ── File upload ── */
443
+ .upload-zone {
444
+ border: 2px dashed #4338ca !important;
445
+ border-radius: 14px !important;
446
+ background: #1e293b !important;
447
+ }
448
+ /* ── Info box ── */
449
+ .info-box {
450
+ background: #1e293b;
451
+ border: 1px solid #334155;
452
+ border-radius: 10px;
453
+ padding: 14px 18px;
454
+ font-size: 0.85rem;
455
+ color: #94a3b8;
456
+ line-height: 1.7;
457
+ }
458
+ .info-box strong { color: #c7d2fe; }
459
+ """
460
+
461
+ # ═══════════════════════════════════════════════════════════════
462
  # GRADIO UI
463
+ # ═══════════════════════════════════════════════════════════════
464
+ with gr.Blocks(css=CSS, title="PCOS Ultrasound Detection") as demo:
465
+
466
+ # ── Header ──────────────────────────────────────────────────
467
+ gr.HTML("""
468
+ <div class="app-header">
469
+ <h1>🩺 PCOS Ultrasound Detection</h1>
470
+ <p>EfficientNetB0 &nbsp;Β·&nbsp; Fine-tuned on ovarian ultrasound dataset &nbsp;Β·&nbsp; Grad-CAM XAI</p>
471
+ </div>
472
+ <div class="disclaimer">
473
+ ⚠️ <strong>Medical Disclaimer:</strong> This tool is intended for
474
+ <strong>research and educational purposes only</strong>. It is not a certified
475
+ medical device and must not be used as a substitute for professional clinical diagnosis.
476
+ </div>
477
  """)
478
 
479
+ with gr.Tabs(elem_classes="tab-nav"):
480
+
481
+ # ══════════════════════════════════════════════════════════
482
+ # TAB 1 β€” SINGLE IMAGE
483
+ # ══════════════════════════════════════════════════════════
484
+ with gr.TabItem("πŸ”¬ Single Image Analysis"):
485
+
486
+ with gr.Row(equal_height=False):
487
+
488
+ # ── Upload column ──────────────────────────────────
489
+ with gr.Column(scale=4):
490
+ gr.HTML('<p class="section-title">πŸ“ Upload Image</p>')
491
+ img_input = gr.Image(
492
+ label="",
493
+ type="pil",
494
+ height=290,
495
+ elem_classes="upload-zone",
496
+ )
497
+ analyze_btn = gr.Button(
498
+ "πŸ” Analyze Image",
499
+ variant="primary",
500
+ size="lg",
501
+ elem_classes="primary",
502
+ )
503
+ gr.HTML("""
504
+ <div class="info-box" style="margin-top:14px">
505
+ <strong>How to use</strong><br>
506
+ 1. Upload a clear ovarian ultrasound (PNG / JPG)<br>
507
+ 2. Click <strong>Analyze Image</strong><br>
508
+ 3. Review the diagnosis, probability gauge, and Grad-CAM heatmap<br><br>
509
+ <strong>Model info</strong><br>
510
+ Architecture: EfficientNetB0 &nbsp;|&nbsp; Input: 224Γ—224 RGB<br>
511
+ Classes: <code>not_pcos</code> (0) &nbsp;Β·&nbsp; <code>pcos</code> (1)
512
+ </div>
513
+ """)
514
+
515
+ # ── Result column ──────────────────────────────────
516
+ with gr.Column(scale=6):
517
+ gr.HTML('<p class="section-title">πŸ“‹ Diagnosis Result</p>')
518
+ result_md = gr.Markdown(
519
+ value="*Upload an image and click **Analyze Image** to see the result.*",
520
+ )
521
+ gr.HTML('<p class="section-title" style="margin-top:16px">πŸ“Š PCOS Probability Gauge</p>')
522
+ gauge_plot = gr.Plot(label="", show_label=False)
523
+
524
+ # ── Grad-CAM ─────────────────────────────────────────────
525
+ gr.HTML('<p class="section-title" style="margin-top:8px">πŸ”₯ Grad-CAM Explainability</p>')
526
+ gradcam_plot = gr.Plot(label="", show_label=False)
527
+
528
+ analyze_btn.click(
529
+ fn=predict_single,
530
+ inputs=[img_input],
531
+ outputs=[result_md, gauge_plot, gradcam_plot],
532
  )
533
+
534
+ # ══════════════════════════════════════════════════════════
535
+ # TAB 2 β€” BATCH
536
+ # ══════════════════════════════════════════════════════════
537
+ with gr.TabItem("πŸ“‚ Batch Analysis"):
538
+
539
+ with gr.Row():
540
+ with gr.Column(scale=4):
541
+ gr.HTML('<p class="section-title">πŸ“ Upload Multiple Images</p>')
542
+ batch_input = gr.File(
543
+ label="",
544
+ file_count="multiple",
545
+ file_types=["image"],
546
+ elem_classes="upload-zone",
547
+ )
548
+ batch_btn = gr.Button(
549
+ "⚑ Run Batch Analysis",
550
+ variant="primary",
551
+ size="lg",
552
+ elem_classes="primary",
553
+ )
554
+ gr.HTML("""
555
+ <div class="info-box" style="margin-top:14px">
556
+ <strong>Batch mode</strong><br>
557
+ Upload multiple ultrasound images at once.<br>
558
+ Each image is analysed independently and results
559
+ are shown in a summary table with per-image
560
+ PCOS probability and risk tier.<br><br>
561
+ <strong>Supported formats:</strong> PNG, JPG, JPEG, BMP, TIFF
562
+ </div>
563
+ """)
564
+
565
+ with gr.Column(scale=6):
566
+ gr.HTML('<p class="section-title">πŸ“Š Batch Summary &amp; Per-Image Results</p>')
567
+ batch_result_md = gr.Markdown(
568
+ value="*Upload images and click **Run Batch Analysis**.*"
569
+ )
570
+
571
+ gr.HTML('<p class="section-title" style="margin-top:8px">πŸ“ˆ Distribution Chart</p>')
572
+ batch_chart = gr.Plot(label="", show_label=False)
573
+
574
+ batch_btn.click(
575
+ fn=predict_batch,
576
+ inputs=[batch_input],
577
+ outputs=[batch_result_md, batch_chart],
578
  )
579
+
580
+ # ══════════════════════════════════════════════════════════
581
+ # TAB 3 β€” ABOUT
582
+ # ══════════════════════════════════════════════════════════
583
+ with gr.TabItem("ℹ️ About"):
584
  gr.Markdown("""
585
+ ## About This Application
586
+
587
+ ### 🧠 Model Architecture
588
+
589
+ | Parameter | Detail |
590
+ |---|---|
591
+ | Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
592
+ | Input size | 224 Γ— 224 RGB |
593
+ | Normalisation | Mean [0.485, 0.456, 0.406] Β· Std [0.229, 0.224, 0.225] |
594
+ | Output classes | `not_pcos` (0), `pcos` (1) β€” alphabetical order |
595
+ | Decision threshold | 0.50 (softmax argmax) |
596
+ | Checkpoint key | `model_state` |
597
+ | Saved criterion | Best validation AUC |
598
+
599
+ ### πŸ‹οΈ Training Details
600
+
601
+ | Setting | Value |
602
+ |---|---|
603
+ | Optimiser | Adam (lr=1e-4, weight_decay=1e-5) |
604
+ | Loss | CrossEntropyLoss with class weights (balanced) |
605
+ | Sampler | WeightedRandomSampler for batch balance |
606
+ | Scheduler | ReduceLROnPlateau (factor=0.3, patience=3) |
607
+ | Early stopping | Patience = 7 epochs |
608
+ | Max epochs | 30 |
609
+ | Batch size | 32 |
610
+ | Augmentation | RandomHorizontalFlip, RandomRotation(15Β°), ColorJitter |
611
+
612
+ ### πŸ”₯ Grad-CAM Explainability
613
+
614
+ Gradient-weighted Class Activation Mapping (Grad-CAM) highlights image
615
+ regions that most influenced the model's decision.
616
+ - **Target layer:** `features[-1]` (last convolutional block)
617
+ - **Target class:** Predicted class
618
+ - Heatmap is upsampled to 224Γ—224 and overlaid on the original image
619
+
620
+ ### ⚠️ Disclaimer
621
+
622
+ This application is for **research and educational purposes only**.
623
+ It is not certified for clinical use and must not replace the judgement
624
+ of a qualified medical professional.
625
  """)
626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  demo.launch(server_name="0.0.0.0", server_port=7860)