shamssali commited on
Commit
2cda486
Β·
verified Β·
1 Parent(s): 53d91e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +246 -242
app.py CHANGED
@@ -1,29 +1,40 @@
1
  import os
2
  import io
3
- import cv2
4
- import torch
5
  import numpy as np
6
  import gradio as gr
 
7
  import torch.nn as nn
8
  import torch.nn.functional as F
9
  import timm
10
- import tempfile
11
  import matplotlib
12
  matplotlib.use("Agg")
13
  import matplotlib.pyplot as plt
14
- import matplotlib.patches as mpatches
15
 
16
  from PIL import Image, ImageFile
17
  from torchvision import transforms
18
  from collections import Counter
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  ImageFile.LOAD_TRUNCATED_IMAGES = True
21
 
22
  # ====================== CONFIG ======================
23
  BACKBONE = "convnext_tiny"
24
  MODEL_PATH = "best.pth"
25
  OOD_THRESHOLD = 0.55
26
- FRAME_GAP = 30 # extract 1 frame every N frames from video
27
 
28
  ZERO_SEVERITY_CLASSES = {
29
  "Non_Damage_Buildings_Street",
@@ -35,11 +46,7 @@ ZERO_SEVERITY_CLASSES = {
35
  "flyerposter",
36
  }
37
 
38
- # Severity thresholds on confidence %
39
- SEV_THRESHOLDS = {
40
- "High": 85,
41
- "Medium": 65,
42
- }
43
 
44
  # ====================== MODEL ======================
45
  class DisasterModel(nn.Module):
@@ -59,18 +66,17 @@ class DisasterModel(nn.Module):
59
  def load_model():
60
  if not os.path.exists(MODEL_PATH):
61
  raise FileNotFoundError(
62
- f"Model file '{MODEL_PATH}' not found. "
63
- "Please upload best.pth to the Space files."
64
  )
65
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
66
- ckpt = torch.load(MODEL_PATH, map_location=device)
67
- classes = ckpt["class_names"]
68
- zero_sev = set(ckpt.get("zero_severity_classes", list(ZERO_SEVERITY_CLASSES)))
69
- model = DisasterModel(len(classes), backbone=ckpt.get("backbone", BACKBONE))
70
- model.load_state_dict(ckpt["model_state"])
71
- model.to(device).eval()
72
  print(f"βœ… Model loaded on {device} | {len(classes)} classes")
73
- return model, classes, zero_sev, device
74
 
75
 
76
  model, CLASS_NAMES, ZERO_SEV, DEVICE = load_model()
@@ -85,18 +91,17 @@ val_tf = transforms.Compose([
85
 
86
  # ====================== HELPERS ======================
87
  def tensor_from_pil(img: Image.Image) -> torch.Tensor:
88
- return val_tf(img).unsqueeze(0).to(DEVICE)
89
 
90
 
91
- def infer(tensor: torch.Tensor):
92
  with torch.no_grad():
93
- logits = model(tensor)
94
- probs = F.softmax(logits, dim=1).squeeze().cpu().numpy()
95
  return probs
96
 
97
 
98
  def severity_info(pred_name: str, conf_pct: float, is_ood: bool):
99
- """Return (label, score 0-3, hex_color, pct_for_display)."""
100
  if is_ood:
101
  return "Unknown", 0, "#95a5a6", 0.0
102
  if pred_name in ZERO_SEV:
@@ -108,8 +113,87 @@ def severity_info(pred_name: str, conf_pct: float, is_ood: bool):
108
  return "Low", 1, "#3498db", conf_pct
109
 
110
 
111
- def make_result_figure(img_rgb, probs, title, sev_label, sev_color, is_ood, sev_pct):
112
- """Build and return a matplotlib Figure with 3 panels."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  top5_idx = probs.argsort()[::-1][:5]
114
  top5_prob = probs[top5_idx] * 100
115
  top5_name = [CLASS_NAMES[i] for i in top5_idx]
@@ -117,21 +201,21 @@ def make_result_figure(img_rgb, probs, title, sev_label, sev_color, is_ood, sev_
117
  fig, axes = plt.subplots(1, 3, figsize=(16, 5))
118
  fig.patch.set_facecolor("#f8f9fa")
119
 
120
- # ── Panel 1: image ────────────────────────────────────────────────────────
121
- axes[0].imshow(img_rgb)
122
  axes[0].axis("off")
123
  axes[0].set_title(title, fontsize=10, color=sev_color,
124
  fontweight="bold", wrap=True)
125
 
126
- # ── Panel 2: top-5 bar chart ──────────────────────────────────────────────
127
  bar_colors = (["#e74c3c"] * 5 if is_ood
128
  else ["#2980b9"] + ["#bdc3c7"] * 4)
129
  axes[1].barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1])
130
  for i, prob in enumerate(top5_prob[::-1]):
131
  axes[1].text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9)
132
  if is_ood:
133
- axes[1].axvline(OOD_THRESHOLD * 100, color="red",
134
- linestyle="--", linewidth=1.5,
135
  label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)")
136
  axes[1].legend(fontsize=8)
137
  axes[1].set_xlim(0, 110)
@@ -139,96 +223,44 @@ def make_result_figure(img_rgb, probs, title, sev_label, sev_color, is_ood, sev_
139
  axes[1].set_title("Top-5 Predictions" + (" ⚠️ OOD" if is_ood else ""))
140
  axes[1].spines[["top", "right"]].set_visible(False)
141
 
142
- # ── Panel 3: severity gauge ───────────────────────────────────────────────
143
  ax3 = axes[2]
144
  ax3.axis("off")
145
  gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"]
146
  gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"]
147
- sev_score = {"None (Safe)": 0, "Low": 1, "Medium": 2,
148
- "High": 3, "Unknown": -1}.get(sev_label, -1)
149
-
150
  for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)):
151
  alpha = 1.0 if gi == sev_score else 0.15
152
- rect = plt.Rectangle((gi * 0.24, 0.35), 0.22, 0.35,
153
- color=gc, alpha=alpha,
154
- transform=ax3.transAxes)
155
- ax3.add_patch(rect)
156
- ax3.text(gi * 0.24 + 0.11, 0.525, gl,
157
- ha="center", va="center", fontsize=9,
158
- color="black", transform=ax3.transAxes,
159
- fontweight="bold")
160
-
161
- # Severity % bar
 
 
 
162
  if sev_pct > 0:
163
- ax3.text(0.5, 0.88,
164
- f"Severity: {sev_label} ({sev_pct:.1f}%)",
165
- ha="center", va="center", fontsize=12,
166
- color=sev_color, transform=ax3.transAxes,
167
- fontweight="bold")
168
- # progress bar background
169
- ax3.add_patch(plt.Rectangle((0.05, 0.18), 0.9, 0.1,
170
- color="#ecf0f1",
171
- transform=ax3.transAxes))
172
- # filled portion
173
- ax3.add_patch(plt.Rectangle((0.05, 0.18),
174
- 0.9 * sev_pct / 100, 0.1,
175
- color=sev_color,
176
- transform=ax3.transAxes))
177
- ax3.text(0.5, 0.10, f"{sev_pct:.1f}%",
178
- ha="center", va="center", fontsize=10,
179
- color=sev_color, transform=ax3.transAxes,
180
- fontweight="bold")
181
- else:
182
- ax3.text(0.5, 0.88, f"Severity: {sev_label}",
183
- ha="center", va="center", fontsize=12,
184
- color=sev_color, transform=ax3.transAxes,
185
- fontweight="bold")
186
 
187
  ax3.set_title("Severity Level", fontsize=11)
188
  plt.tight_layout()
189
- return fig
190
-
191
-
192
- def fig_to_pil(fig) -> Image.Image:
193
- buf = io.BytesIO()
194
- fig.savefig(buf, format="png", bbox_inches="tight", dpi=120)
195
- plt.close(fig)
196
- buf.seek(0)
197
- return Image.open(buf).copy()
198
-
199
-
200
- # ====================== IMAGE PREDICTION ======================
201
- def predict_image(pil_img: Image.Image):
202
- img = pil_img.convert("RGB")
203
- tensor = tensor_from_pil(img)
204
- probs = infer(tensor)
205
-
206
- top_idx = int(probs.argmax())
207
- pred_name = CLASS_NAMES[top_idx]
208
- conf_pct = probs[top_idx] * 100
209
- is_ood = probs[top_idx] < OOD_THRESHOLD
210
-
211
- sev_label, _, sev_color, sev_pct = severity_info(pred_name, conf_pct, is_ood)
212
-
213
- if is_ood:
214
- title = f"⚠️ Unrecognised image ({conf_pct:.1f}% < threshold)"
215
- elif sev_label == "None (Safe)":
216
- title = f"βœ… {pred_name} | {conf_pct:.1f}% | Safe"
217
- else:
218
- icon_map = {"High": "πŸ”΄", "Medium": "🟑", "Low": "πŸ”΅"}
219
- icon = icon_map.get(sev_label, "πŸ”΅")
220
- title = f"{icon} {pred_name} | {conf_pct:.1f}% | Severity: {sev_label}"
221
 
222
- fig = make_result_figure(np.array(img), probs, title,
223
- sev_label, sev_color, is_ood, sev_pct)
224
  result_img = fig_to_pil(fig)
225
 
226
- # Text summary
227
  lines = [
228
  f"🌍 Class : {'UNKNOWN (OOD)' if is_ood else pred_name}",
229
  f"πŸ“Š Confidence : {conf_pct:.2f}%",
230
- f"⚠️ Severity : {sev_label}" +
231
- (f" ({sev_pct:.1f}%)" if sev_pct > 0 else ""),
232
  "",
233
  "All class probabilities:",
234
  ]
@@ -244,60 +276,45 @@ def predict_image(pil_img: Image.Image):
244
  def predict_video(video_path: str,
245
  frame_gap: int = FRAME_GAP,
246
  progress=gr.Progress()):
247
- cap = cv2.VideoCapture(video_path)
248
- if not cap.isOpened():
249
- return None, "❌ Could not open video file."
250
 
251
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
252
- fps = cap.get(cv2.CAP_PROP_FPS) or 30
253
- duration_s = total_frames / fps
254
-
255
- frame_indices, frame_bgrs = [], []
256
- count = 0
257
- while cap.isOpened():
258
- ret, frame = cap.read()
259
- if not ret:
260
- break
261
- if count % frame_gap == 0:
262
- frame_indices.append(count)
263
- frame_bgrs.append(frame.copy())
264
- count += 1
265
- cap.release()
266
 
267
- if not frame_bgrs:
268
- return None, "❌ No frames extracted from video."
269
 
270
- n_frames = len(frame_bgrs)
271
- all_probs = []
272
  frame_preds, frame_confs = [], []
273
 
274
- progress(0, desc="Analysing frames…")
275
- for fi, (idx, bgr) in enumerate(zip(frame_indices, frame_bgrs)):
276
- rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
277
- img = Image.fromarray(rgb)
278
- tensor = tensor_from_pil(img)
279
- probs = infer(tensor)
280
  all_probs.append(probs)
281
  frame_preds.append(int(probs.argmax()))
282
  frame_confs.append(float(probs.max()) * 100)
283
- progress((fi + 1) / n_frames, desc=f"Frame {fi+1}/{n_frames}")
 
284
 
285
- # ── Aggregate ─────────────────────────────────────────────────────────────
286
- mean_probs = np.mean(all_probs, axis=0) # confidence-weighted vote
287
- final_id = int(mean_probs.argmax())
288
- final_name = CLASS_NAMES[final_id]
289
- final_conf = mean_probs[final_id] * 100
290
- is_ood = mean_probs[final_id] < OOD_THRESHOLD
291
 
292
  sev_label, sev_score, sev_color, sev_pct = severity_info(
293
  final_name, final_conf, is_ood
294
  )
295
 
296
- # Danger frame % (frames NOT in zero-severity classes)
297
  danger_count = sum(CLASS_NAMES[p] not in ZERO_SEV for p in frame_preds)
298
  danger_pct = 100 * danger_count / n_frames
299
 
300
- # ── Build multi-panel figure ───────────────────────────────────────────────
301
  fig, axes = plt.subplots(2, 2, figsize=(16, 10))
302
  fig.patch.set_facecolor("#f8f9fa")
303
  fig.suptitle(
@@ -309,95 +326,100 @@ def predict_video(video_path: str,
309
  )
310
 
311
  # Panel A β€” per-frame class timeline
312
- ax = axes[0, 0]
313
- ax.plot(frame_indices, frame_preds, "o-", markersize=3,
314
- linewidth=1, color="#2980b9", label="Frame class")
315
- ax.axhline(final_id, color="#e74c3c", linestyle="--",
316
- linewidth=1.5, label=f"Final: {final_name}")
317
- ax.set_yticks(range(len(CLASS_NAMES)))
318
- ax.set_yticklabels(CLASS_NAMES, fontsize=7)
319
- ax.set_xlabel("Frame index")
320
- ax.set_title("Per-frame class prediction")
321
- ax.legend(fontsize=8)
322
- ax.spines[["top", "right"]].set_visible(False)
323
 
324
  # Panel B β€” per-frame confidence
325
- ax = axes[0, 1]
326
- ax.plot(frame_indices, frame_confs, "s-", markersize=3,
327
- linewidth=1, color=sev_color, label="Confidence %")
328
- ax.axhline(OOD_THRESHOLD * 100, color="gray", linestyle=":",
329
- linewidth=1, label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)")
330
- ax.set_ylim(0, 105)
331
- ax.set_xlabel("Frame index")
332
- ax.set_ylabel("Confidence (%)")
333
- ax.set_title("Per-frame confidence")
334
- ax.legend(fontsize=8)
335
- ax.spines[["top", "right"]].set_visible(False)
336
-
337
- # Panel C β€” top-5 aggregated confidence
338
- ax = axes[1, 0]
 
 
 
 
339
  top5_idx = mean_probs.argsort()[::-1][:5]
340
  top5_prob = mean_probs[top5_idx] * 100
341
  top5_name = [CLASS_NAMES[i] for i in top5_idx]
342
- bar_colors = ["#e74c3c" if is_ood else "#2980b9"] + ["#bdc3c7"] * 4
343
- ax.barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1])
 
344
  for i, prob in enumerate(top5_prob[::-1]):
345
- ax.text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9)
346
- ax.set_xlim(0, 110)
347
- ax.set_xlabel("Mean confidence (%)")
348
- ax.set_title("Top-5 (aggregated over all frames)")
349
- ax.spines[["top", "right"]].set_visible(False)
350
 
351
- # Panel D β€” severity summary card
352
- ax = axes[1, 1]
353
- ax.axis("off")
354
 
355
  gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"]
356
  gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"]
357
  for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)):
358
  alpha = 1.0 if gi == sev_score else 0.15
359
- rect = plt.Rectangle((gi * 0.24, 0.55), 0.22, 0.28,
360
- color=gc, alpha=alpha, transform=ax.transAxes)
361
- ax.add_patch(rect)
362
- ax.text(gi * 0.24 + 0.11, 0.695, gl,
363
- ha="center", va="center", fontsize=9,
364
- color="black", transform=ax.transAxes, fontweight="bold")
 
365
 
366
  stats = [
367
- ("Final class", final_name),
368
- ("Confidence", f"{final_conf:.1f}%"),
369
- ("Severity", f"{sev_label}" + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else "")),
370
- ("Danger frames", f"{danger_pct:.1f}% ({danger_count}/{n_frames})"),
371
- ("Frames analysed", f"{n_frames} (every {frame_gap} frames)"),
372
- ("Video duration", f"{duration_s:.1f}s"),
373
  ]
374
- y_pos = 0.48
375
  for label, value in stats:
376
- ax.text(0.02, y_pos, label + ":", fontsize=9,
377
- color="#7f8c8d", transform=ax.transAxes)
378
- ax.text(0.45, y_pos, value, fontsize=9,
379
- color="#2c3e50", transform=ax.transAxes, fontweight="bold")
380
  y_pos -= 0.08
381
 
382
  # Severity progress bar
383
  if sev_pct > 0:
384
- ax.add_patch(plt.Rectangle((0.02, 0.02), 0.96, 0.07,
385
- color="#ecf0f1", transform=ax.transAxes))
386
- ax.add_patch(plt.Rectangle((0.02, 0.02), 0.96 * sev_pct / 100, 0.07,
387
- color=sev_color, transform=ax.transAxes))
388
- ax.text(0.5, 0.055, f"Severity intensity: {sev_pct:.1f}%",
389
- ha="center", va="center", fontsize=9,
390
- color="white", transform=ax.transAxes, fontweight="bold")
 
391
 
392
- ax.set_title("Summary", fontsize=11)
393
 
394
  plt.tight_layout()
395
  result_img = fig_to_pil(fig)
396
 
397
- # Text summary
398
  lines = [
399
- f"πŸŽ₯ Video Analysis Complete",
400
- f"{'─'*45}",
401
  f"🌍 Final class : {'UNKNOWN (OOD)' if is_ood else final_name}",
402
  f"πŸ“Š Confidence : {final_conf:.2f}%",
403
  f"⚠️ Severity : {sev_label}" +
@@ -418,42 +440,37 @@ def predict_video(video_path: str,
418
  # ====================== GRADIO UI ======================
419
  DESCRIPTION = """
420
  # 🌍 Disaster Scene Classifier
421
-
422
  Upload an **image** or **video** to detect disaster types and estimate severity.
423
 
424
- **Disaster classes detected:** Earthquake Β· Infrastructure damage Β· Urban Fire Β· Wild Fire Β·
425
- Human Damage Β· Drought Β· Land Slide
426
 
427
- **Zero-severity classes** (safe scenes): Non-Damage Buildings/Street Β· Non-Damage Wildlife/Forest Β·
428
- Human (safe) Β· Sea Β· Water (safe) Β· Random Β· Flyer/Poster
429
  """
430
 
431
- SEVERITY_INFO = """
432
  ### Severity Scale
433
- | Level | Score | Meaning |
434
- |-------|-------|---------|
435
- | βœ… None (Safe) | 0% | Zero-severity class β€” no disaster |
436
- | πŸ”΅ Low | 1–64% | Possible damage, low confidence |
437
- | 🟑 Medium | 65–84% | Moderate disaster confidence |
438
- | πŸ”΄ High | 85–100% | High-confidence disaster detected |
439
-
440
- > ⚠️ If confidence < 55%, image is flagged as **out-of-distribution** (not a known scene type).
441
  """
442
 
443
  with gr.Blocks(
444
  title="Disaster Classifier",
445
  theme=gr.themes.Soft(primary_hue="blue"),
446
- css="""
447
- .result-text { font-family: monospace; font-size: 13px; }
448
- .header-md h1 { text-align: center; }
449
- """
450
  ) as demo:
451
 
452
  gr.Markdown(DESCRIPTION, elem_classes="header-md")
453
 
454
  with gr.Row():
455
  with gr.Column(scale=1):
456
- gr.Markdown(SEVERITY_INFO)
457
 
458
  with gr.Tabs():
459
 
@@ -468,26 +485,19 @@ with gr.Blocks(
468
  )
469
  img_btn = gr.Button("πŸ” Analyse Image",
470
  variant="primary", size="lg")
471
-
472
  with gr.Column(scale=2):
473
- img_output = gr.Image(label="Result", height=400)
474
  img_text = gr.Textbox(
475
  label="Detailed results",
476
  lines=20,
477
  elem_classes="result-text",
478
  )
479
-
480
  img_btn.click(
481
  fn=predict_image,
482
  inputs=img_input,
483
  outputs=[img_output, img_text],
484
  )
485
 
486
- gr.Examples(
487
- examples=[], # add example image paths here if needed
488
- inputs=img_input,
489
- )
490
-
491
  # ── VIDEO TAB ─────────────────────────────────────────────────────────
492
  with gr.Tab("πŸŽ₯ Video"):
493
  with gr.Row():
@@ -503,19 +513,14 @@ with gr.Blocks(
503
  )
504
  vid_btn = gr.Button("πŸ” Analyse Video",
505
  variant="primary", size="lg")
506
- gr.Markdown(
507
- "_Large videos may take a minute. "
508
- "Progress is shown below._"
509
- )
510
-
511
  with gr.Column(scale=2):
512
- vid_output = gr.Image(label="Result", height=500)
513
  vid_text = gr.Textbox(
514
  label="Detailed results",
515
  lines=20,
516
  elem_classes="result-text",
517
  )
518
-
519
  vid_btn.click(
520
  fn=predict_video,
521
  inputs=[vid_input, frame_slider],
@@ -523,8 +528,7 @@ with gr.Blocks(
523
  )
524
 
525
  gr.Markdown(
526
- "---\n"
527
- "Model: ConvNeXt-Tiny fine-tuned on Comprehensive Disaster Dataset (CDD) Β· "
528
  "Built with [Gradio](https://gradio.app)"
529
  )
530
 
 
1
  import os
2
  import io
 
 
3
  import numpy as np
4
  import gradio as gr
5
+ import torch
6
  import torch.nn as nn
7
  import torch.nn.functional as F
8
  import timm
 
9
  import matplotlib
10
  matplotlib.use("Agg")
11
  import matplotlib.pyplot as plt
 
12
 
13
  from PIL import Image, ImageFile
14
  from torchvision import transforms
15
  from collections import Counter
16
 
17
+ # Safe cv2 import β€” falls back to PIL-only video reading if cv2 unavailable
18
+ try:
19
+ import cv2
20
+ HAS_CV2 = True
21
+ except ImportError:
22
+ HAS_CV2 = False
23
+ print("⚠️ cv2 not available β€” video will be read frame-by-frame via imageio")
24
+
25
+ try:
26
+ import imageio
27
+ HAS_IMAGEIO = True
28
+ except ImportError:
29
+ HAS_IMAGEIO = False
30
+
31
  ImageFile.LOAD_TRUNCATED_IMAGES = True
32
 
33
  # ====================== CONFIG ======================
34
  BACKBONE = "convnext_tiny"
35
  MODEL_PATH = "best.pth"
36
  OOD_THRESHOLD = 0.55
37
+ FRAME_GAP = 30
38
 
39
  ZERO_SEVERITY_CLASSES = {
40
  "Non_Damage_Buildings_Street",
 
46
  "flyerposter",
47
  }
48
 
49
+ SEV_THRESHOLDS = {"High": 85, "Medium": 65}
 
 
 
 
50
 
51
  # ====================== MODEL ======================
52
  class DisasterModel(nn.Module):
 
66
  def load_model():
67
  if not os.path.exists(MODEL_PATH):
68
  raise FileNotFoundError(
69
+ f"'{MODEL_PATH}' not found. Upload best.pth to the Space root."
 
70
  )
71
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
72
+ ckpt = torch.load(MODEL_PATH, map_location=device)
73
+ classes = ckpt["class_names"]
74
+ zero_sev = set(ckpt.get("zero_severity_classes", list(ZERO_SEVERITY_CLASSES)))
75
+ m = DisasterModel(len(classes), backbone=ckpt.get("backbone", BACKBONE))
76
+ m.load_state_dict(ckpt["model_state"])
77
+ m.to(device).eval()
78
  print(f"βœ… Model loaded on {device} | {len(classes)} classes")
79
+ return m, classes, zero_sev, device
80
 
81
 
82
  model, CLASS_NAMES, ZERO_SEV, DEVICE = load_model()
 
91
 
92
  # ====================== HELPERS ======================
93
  def tensor_from_pil(img: Image.Image) -> torch.Tensor:
94
+ return val_tf(img.convert("RGB")).unsqueeze(0).to(DEVICE)
95
 
96
 
97
+ def infer(tensor: torch.Tensor) -> np.ndarray:
98
  with torch.no_grad():
99
+ probs = F.softmax(model(tensor), dim=1).squeeze().cpu().numpy()
 
100
  return probs
101
 
102
 
103
  def severity_info(pred_name: str, conf_pct: float, is_ood: bool):
104
+ """Return (label, score 0-3, hex_color, display_pct)."""
105
  if is_ood:
106
  return "Unknown", 0, "#95a5a6", 0.0
107
  if pred_name in ZERO_SEV:
 
113
  return "Low", 1, "#3498db", conf_pct
114
 
115
 
116
+ def fig_to_pil(fig) -> Image.Image:
117
+ buf = io.BytesIO()
118
+ fig.savefig(buf, format="png", bbox_inches="tight", dpi=120)
119
+ plt.close(fig)
120
+ buf.seek(0)
121
+ return Image.open(buf).copy()
122
+
123
+
124
+ # ====================== VIDEO FRAME EXTRACTION ======================
125
+ def extract_frames_cv2(video_path: str, frame_gap: int):
126
+ """Extract frames using cv2."""
127
+ cap = cv2.VideoCapture(video_path)
128
+ if not cap.isOpened():
129
+ return [], 0, 0.0
130
+
131
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
132
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30
133
+ frames, indices = [], []
134
+ count = 0
135
+
136
+ while cap.isOpened():
137
+ ret, frame = cap.read()
138
+ if not ret:
139
+ break
140
+ if count % frame_gap == 0:
141
+ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
142
+ frames.append(Image.fromarray(rgb))
143
+ indices.append(count)
144
+ count += 1
145
+ cap.release()
146
+ return frames, indices, total / fps
147
+
148
+
149
+ def extract_frames_imageio(video_path: str, frame_gap: int):
150
+ """Fallback frame extraction using imageio."""
151
+ reader = imageio.get_reader(video_path)
152
+ meta = reader.get_meta_data()
153
+ fps = meta.get("fps", 30)
154
+ frames, indices = [], []
155
+ for count, frame in enumerate(reader):
156
+ if count % frame_gap == 0:
157
+ frames.append(Image.fromarray(frame))
158
+ indices.append(count)
159
+ reader.close()
160
+ duration = indices[-1] / fps if indices else 0.0
161
+ return frames, indices, duration
162
+
163
+
164
+ def extract_frames(video_path: str, frame_gap: int):
165
+ if HAS_CV2:
166
+ return extract_frames_cv2(video_path, frame_gap)
167
+ if HAS_IMAGEIO:
168
+ return extract_frames_imageio(video_path, frame_gap)
169
+ raise RuntimeError("Neither cv2 nor imageio is available for video reading.")
170
+
171
+
172
+ # ====================== IMAGE PREDICTION ======================
173
+ def predict_image(pil_img: Image.Image):
174
+ if pil_img is None:
175
+ return None, "❌ Please upload an image."
176
+
177
+ img = pil_img.convert("RGB")
178
+ probs = infer(tensor_from_pil(img))
179
+
180
+ top_idx = int(probs.argmax())
181
+ pred_name = CLASS_NAMES[top_idx]
182
+ conf_pct = probs[top_idx] * 100
183
+ is_ood = probs[top_idx] < OOD_THRESHOLD
184
+
185
+ sev_label, sev_score, sev_color, sev_pct = severity_info(
186
+ pred_name, conf_pct, is_ood
187
+ )
188
+
189
+ if is_ood:
190
+ title = f"⚠️ Unrecognised image ({conf_pct:.1f}% β€” below OOD threshold)"
191
+ elif sev_label == "None (Safe)":
192
+ title = f"βœ… {pred_name} | {conf_pct:.1f}% | Safe"
193
+ else:
194
+ icon = {"High": "πŸ”΄", "Medium": "🟑", "Low": "πŸ”΅"}.get(sev_label, "πŸ”΅")
195
+ title = f"{icon} {pred_name} | {conf_pct:.1f}% | Severity: {sev_label}"
196
+
197
  top5_idx = probs.argsort()[::-1][:5]
198
  top5_prob = probs[top5_idx] * 100
199
  top5_name = [CLASS_NAMES[i] for i in top5_idx]
 
201
  fig, axes = plt.subplots(1, 3, figsize=(16, 5))
202
  fig.patch.set_facecolor("#f8f9fa")
203
 
204
+ # Panel 1 β€” image
205
+ axes[0].imshow(np.array(img))
206
  axes[0].axis("off")
207
  axes[0].set_title(title, fontsize=10, color=sev_color,
208
  fontweight="bold", wrap=True)
209
 
210
+ # Panel 2 β€” top-5 bar chart
211
  bar_colors = (["#e74c3c"] * 5 if is_ood
212
  else ["#2980b9"] + ["#bdc3c7"] * 4)
213
  axes[1].barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1])
214
  for i, prob in enumerate(top5_prob[::-1]):
215
  axes[1].text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9)
216
  if is_ood:
217
+ axes[1].axvline(OOD_THRESHOLD * 100, color="red", linestyle="--",
218
+ linewidth=1.5,
219
  label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)")
220
  axes[1].legend(fontsize=8)
221
  axes[1].set_xlim(0, 110)
 
223
  axes[1].set_title("Top-5 Predictions" + (" ⚠️ OOD" if is_ood else ""))
224
  axes[1].spines[["top", "right"]].set_visible(False)
225
 
226
+ # Panel 3 β€” severity gauge + progress bar
227
  ax3 = axes[2]
228
  ax3.axis("off")
229
  gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"]
230
  gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"]
 
 
 
231
  for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)):
232
  alpha = 1.0 if gi == sev_score else 0.15
233
+ ax3.add_patch(plt.Rectangle(
234
+ (gi * 0.24, 0.40), 0.22, 0.30,
235
+ color=gc, alpha=alpha, transform=ax3.transAxes
236
+ ))
237
+ ax3.text(gi * 0.24 + 0.11, 0.56, gl,
238
+ ha="center", va="center", fontsize=9, color="black",
239
+ transform=ax3.transAxes, fontweight="bold")
240
+
241
+ sev_display = f"{sev_label} ({sev_pct:.1f}%)" if sev_pct > 0 else sev_label
242
+ ax3.text(0.5, 0.88, f"Severity: {sev_display}",
243
+ ha="center", va="center", fontsize=12, color=sev_color,
244
+ transform=ax3.transAxes, fontweight="bold")
245
+
246
  if sev_pct > 0:
247
+ ax3.add_patch(plt.Rectangle((0.05, 0.18), 0.90, 0.10,
248
+ color="#ecf0f1", transform=ax3.transAxes))
249
+ ax3.add_patch(plt.Rectangle((0.05, 0.18), 0.90 * sev_pct / 100, 0.10,
250
+ color=sev_color, transform=ax3.transAxes))
251
+ ax3.text(0.5, 0.23, f"{sev_pct:.1f}%",
252
+ ha="center", va="center", fontsize=10, color="white",
253
+ transform=ax3.transAxes, fontweight="bold")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
  ax3.set_title("Severity Level", fontsize=11)
256
  plt.tight_layout()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
 
 
258
  result_img = fig_to_pil(fig)
259
 
 
260
  lines = [
261
  f"🌍 Class : {'UNKNOWN (OOD)' if is_ood else pred_name}",
262
  f"πŸ“Š Confidence : {conf_pct:.2f}%",
263
+ f"⚠️ Severity : {sev_label}" + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else ""),
 
264
  "",
265
  "All class probabilities:",
266
  ]
 
276
  def predict_video(video_path: str,
277
  frame_gap: int = FRAME_GAP,
278
  progress=gr.Progress()):
279
+ if video_path is None:
280
+ return None, "❌ Please upload a video."
 
281
 
282
+ progress(0, desc="Extracting frames…")
283
+ try:
284
+ frames, frame_indices, duration_s = extract_frames(video_path, int(frame_gap))
285
+ except Exception as e:
286
+ return None, f"❌ Frame extraction failed: {e}"
 
 
 
 
 
 
 
 
 
 
287
 
288
+ if not frames:
289
+ return None, "❌ No frames could be extracted from this video."
290
 
291
+ n_frames = len(frames)
292
+ all_probs = []
293
  frame_preds, frame_confs = [], []
294
 
295
+ for fi, img in enumerate(frames):
296
+ probs = infer(tensor_from_pil(img))
 
 
 
 
297
  all_probs.append(probs)
298
  frame_preds.append(int(probs.argmax()))
299
  frame_confs.append(float(probs.max()) * 100)
300
+ progress((fi + 1) / n_frames,
301
+ desc=f"Analysing frame {fi+1}/{n_frames}…")
302
 
303
+ # ── Aggregate: mean probability across all frames ─────────────────────────
304
+ mean_probs = np.mean(all_probs, axis=0)
305
+ final_id = int(mean_probs.argmax())
306
+ final_name = CLASS_NAMES[final_id]
307
+ final_conf = mean_probs[final_id] * 100
308
+ is_ood = mean_probs[final_id] < OOD_THRESHOLD
309
 
310
  sev_label, sev_score, sev_color, sev_pct = severity_info(
311
  final_name, final_conf, is_ood
312
  )
313
 
 
314
  danger_count = sum(CLASS_NAMES[p] not in ZERO_SEV for p in frame_preds)
315
  danger_pct = 100 * danger_count / n_frames
316
 
317
+ # ── Figure: 4 panels ──────────────────────────────────────────────────────
318
  fig, axes = plt.subplots(2, 2, figsize=(16, 10))
319
  fig.patch.set_facecolor("#f8f9fa")
320
  fig.suptitle(
 
326
  )
327
 
328
  # Panel A β€” per-frame class timeline
329
+ axes[0, 0].plot(frame_indices, frame_preds, "o-",
330
+ markersize=3, linewidth=1, color="#2980b9")
331
+ axes[0, 0].axhline(final_id, color="#e74c3c", linestyle="--",
332
+ linewidth=1.5, label=f"Final: {final_name}")
333
+ axes[0, 0].set_yticks(range(len(CLASS_NAMES)))
334
+ axes[0, 0].set_yticklabels(CLASS_NAMES, fontsize=7)
335
+ axes[0, 0].set_xlabel("Frame index")
336
+ axes[0, 0].set_title("Per-frame class prediction")
337
+ axes[0, 0].legend(fontsize=8)
338
+ axes[0, 0].spines[["top", "right"]].set_visible(False)
 
339
 
340
  # Panel B β€” per-frame confidence
341
+ axes[0, 1].plot(frame_indices, frame_confs, "s-",
342
+ markersize=3, linewidth=1, color=sev_color)
343
+ axes[0, 1].axhline(OOD_THRESHOLD * 100, color="gray", linestyle=":",
344
+ linewidth=1,
345
+ label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)")
346
+ axes[0, 1].fill_between(frame_indices, frame_confs,
347
+ OOD_THRESHOLD * 100,
348
+ where=[c > OOD_THRESHOLD * 100 for c in frame_confs],
349
+ alpha=0.15, color=sev_color,
350
+ label="Above threshold")
351
+ axes[0, 1].set_ylim(0, 105)
352
+ axes[0, 1].set_xlabel("Frame index")
353
+ axes[0, 1].set_ylabel("Confidence (%)")
354
+ axes[0, 1].set_title("Per-frame confidence")
355
+ axes[0, 1].legend(fontsize=8)
356
+ axes[0, 1].spines[["top", "right"]].set_visible(False)
357
+
358
+ # Panel C β€” top-5 aggregated
359
  top5_idx = mean_probs.argsort()[::-1][:5]
360
  top5_prob = mean_probs[top5_idx] * 100
361
  top5_name = [CLASS_NAMES[i] for i in top5_idx]
362
+ bar_colors = (["#e74c3c"] * 5 if is_ood
363
+ else ["#2980b9"] + ["#bdc3c7"] * 4)
364
+ axes[1, 0].barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1])
365
  for i, prob in enumerate(top5_prob[::-1]):
366
+ axes[1, 0].text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9)
367
+ axes[1, 0].set_xlim(0, 110)
368
+ axes[1, 0].set_xlabel("Mean confidence (%)")
369
+ axes[1, 0].set_title("Top-5 classes (aggregated)")
370
+ axes[1, 0].spines[["top", "right"]].set_visible(False)
371
 
372
+ # Panel D β€” summary card
373
+ ax4 = axes[1, 1]
374
+ ax4.axis("off")
375
 
376
  gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"]
377
  gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"]
378
  for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)):
379
  alpha = 1.0 if gi == sev_score else 0.15
380
+ ax4.add_patch(plt.Rectangle(
381
+ (gi * 0.24, 0.60), 0.22, 0.25,
382
+ color=gc, alpha=alpha, transform=ax4.transAxes
383
+ ))
384
+ ax4.text(gi * 0.24 + 0.11, 0.73, gl,
385
+ ha="center", va="center", fontsize=9, color="black",
386
+ transform=ax4.transAxes, fontweight="bold")
387
 
388
  stats = [
389
+ ("Final class", final_name),
390
+ ("Confidence", f"{final_conf:.1f}%"),
391
+ ("Severity", f"{sev_label}" + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else "")),
392
+ ("Danger frames", f"{danger_pct:.1f}% ({danger_count}/{n_frames})"),
393
+ ("Frames analysed", f"{n_frames} (every {int(frame_gap)} frames)"),
394
+ ("Video duration", f"{duration_s:.1f}s"),
395
  ]
396
+ y_pos = 0.54
397
  for label, value in stats:
398
+ ax4.text(0.02, y_pos, label + ":", fontsize=9,
399
+ color="#7f8c8d", transform=ax4.transAxes)
400
+ ax4.text(0.46, y_pos, value, fontsize=9,
401
+ color="#2c3e50", transform=ax4.transAxes, fontweight="bold")
402
  y_pos -= 0.08
403
 
404
  # Severity progress bar
405
  if sev_pct > 0:
406
+ ax4.add_patch(plt.Rectangle((0.02, 0.03), 0.96, 0.07,
407
+ color="#ecf0f1", transform=ax4.transAxes))
408
+ ax4.add_patch(plt.Rectangle((0.02, 0.03),
409
+ 0.96 * sev_pct / 100, 0.07,
410
+ color=sev_color, transform=ax4.transAxes))
411
+ ax4.text(0.5, 0.065, f"Severity intensity: {sev_pct:.1f}%",
412
+ ha="center", va="center", fontsize=9, color="white",
413
+ transform=ax4.transAxes, fontweight="bold")
414
 
415
+ ax4.set_title("Summary", fontsize=11)
416
 
417
  plt.tight_layout()
418
  result_img = fig_to_pil(fig)
419
 
 
420
  lines = [
421
+ "πŸŽ₯ Video Analysis Complete",
422
+ "─" * 45,
423
  f"🌍 Final class : {'UNKNOWN (OOD)' if is_ood else final_name}",
424
  f"πŸ“Š Confidence : {final_conf:.2f}%",
425
  f"⚠️ Severity : {sev_label}" +
 
440
  # ====================== GRADIO UI ======================
441
  DESCRIPTION = """
442
  # 🌍 Disaster Scene Classifier
 
443
  Upload an **image** or **video** to detect disaster types and estimate severity.
444
 
445
+ **Disaster classes:** Earthquake Β· Infrastructure Β· Urban Fire Β· Wild Fire Β· Human Damage Β· Drought Β· Land Slide
 
446
 
447
+ **Zero-severity (safe):** Non-Damage Buildings Β· Non-Damage Wildlife Β· Human Β· Sea Β· Water (safe) Β· Random Β· Flyer/Poster
 
448
  """
449
 
450
+ SEVERITY_MD = """
451
  ### Severity Scale
452
+ | Level | Trigger | Meaning |
453
+ |-------|---------|---------|
454
+ | βœ… None (Safe) | Zero-severity class | No disaster |
455
+ | πŸ”΅ Low | confidence < 65% | Weak signal |
456
+ | 🟑 Medium | 65 – 84% | Moderate confidence |
457
+ | πŸ”΄ High | β‰₯ 85% | High confidence disaster |
458
+
459
+ > If confidence < 55% β†’ flagged as **out-of-distribution** (OOD)
460
  """
461
 
462
  with gr.Blocks(
463
  title="Disaster Classifier",
464
  theme=gr.themes.Soft(primary_hue="blue"),
465
+ css=".result-text { font-family: monospace; font-size: 13px; }"
466
+ ".header-md h1 { text-align: center; }"
 
 
467
  ) as demo:
468
 
469
  gr.Markdown(DESCRIPTION, elem_classes="header-md")
470
 
471
  with gr.Row():
472
  with gr.Column(scale=1):
473
+ gr.Markdown(SEVERITY_MD)
474
 
475
  with gr.Tabs():
476
 
 
485
  )
486
  img_btn = gr.Button("πŸ” Analyse Image",
487
  variant="primary", size="lg")
 
488
  with gr.Column(scale=2):
489
+ img_output = gr.Image(label="Result", height=420)
490
  img_text = gr.Textbox(
491
  label="Detailed results",
492
  lines=20,
493
  elem_classes="result-text",
494
  )
 
495
  img_btn.click(
496
  fn=predict_image,
497
  inputs=img_input,
498
  outputs=[img_output, img_text],
499
  )
500
 
 
 
 
 
 
501
  # ── VIDEO TAB ─────────────────────────────────────────────────────────
502
  with gr.Tab("πŸŽ₯ Video"):
503
  with gr.Row():
 
513
  )
514
  vid_btn = gr.Button("πŸ” Analyse Video",
515
  variant="primary", size="lg")
516
+ gr.Markdown("_Progress bar shown below during processing._")
 
 
 
 
517
  with gr.Column(scale=2):
518
+ vid_output = gr.Image(label="Result", height=520)
519
  vid_text = gr.Textbox(
520
  label="Detailed results",
521
  lines=20,
522
  elem_classes="result-text",
523
  )
 
524
  vid_btn.click(
525
  fn=predict_video,
526
  inputs=[vid_input, frame_slider],
 
528
  )
529
 
530
  gr.Markdown(
531
+ "---\nModel: ConvNeXt-Tiny fine-tuned on CDD Β· "
 
532
  "Built with [Gradio](https://gradio.app)"
533
  )
534