Spaces:
Sleeping
Sleeping
Download app.py from shamssali/MyDisasterChecker: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/shamssali/MyDisasterChecker/resolve/main/app.py
- Command line
-
hf download hf://spaces/shamssali/MyDisasterChecker/app.py
-
curl -L -o app.py https://huggingface.co/spaces/shamssali/MyDisasterChecker/resolve/main/app.py
20.4 kB
| import os | |
| import io | |
| import numpy as np | |
| import gradio as gr | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import timm | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from PIL import Image, ImageFile | |
| from torchvision import transforms | |
| from collections import Counter | |
| # Safe cv2 import β falls back to PIL-only video reading if cv2 unavailable | |
| try: | |
| import cv2 | |
| HAS_CV2 = True | |
| except ImportError: | |
| HAS_CV2 = False | |
| print("β οΈ cv2 not available β video will be read frame-by-frame via imageio") | |
| try: | |
| import imageio | |
| HAS_IMAGEIO = True | |
| except ImportError: | |
| HAS_IMAGEIO = False | |
| ImageFile.LOAD_TRUNCATED_IMAGES = True | |
| # ====================== CONFIG ====================== | |
| BACKBONE = "convnext_tiny" | |
| MODEL_PATH = "best.pth" | |
| OOD_THRESHOLD = 0.55 | |
| FRAME_GAP = 30 | |
| ZERO_SEVERITY_CLASSES = { | |
| "Non_Damage_Buildings_Street", | |
| "Non_Damage_Wildlife_Forest", | |
| "human", | |
| "sea", | |
| "Water_Disaster", | |
| "Random_Non_Disaster", | |
| "flyerposter", | |
| } | |
| SEV_THRESHOLDS = {"High": 85, "Medium": 65} | |
| # ====================== MODEL ====================== | |
| class DisasterModel(nn.Module): | |
| def __init__(self, n, backbone=BACKBONE): | |
| super().__init__() | |
| self.backbone = timm.create_model(backbone, pretrained=False) | |
| in_f = self.backbone.head.fc.in_features | |
| self.backbone.head.fc = nn.Sequential( | |
| nn.Dropout(0.3), | |
| nn.Linear(in_f, n) | |
| ) | |
| def forward(self, x): | |
| return self.backbone(x) | |
| def load_model(): | |
| if not os.path.exists(MODEL_PATH): | |
| raise FileNotFoundError( | |
| f"'{MODEL_PATH}' not found. Upload best.pth to the Space root." | |
| ) | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| ckpt = torch.load(MODEL_PATH, map_location=device) | |
| classes = ckpt["class_names"] | |
| zero_sev = set(ckpt.get("zero_severity_classes", list(ZERO_SEVERITY_CLASSES))) | |
| m = DisasterModel(len(classes), backbone=ckpt.get("backbone", BACKBONE)) | |
| m.load_state_dict(ckpt["model_state"]) | |
| m.to(device).eval() | |
| print(f"β Model loaded on {device} | {len(classes)} classes") | |
| return m, classes, zero_sev, device | |
| model, CLASS_NAMES, ZERO_SEV, DEVICE = load_model() | |
| # ====================== TRANSFORM ====================== | |
| val_tf = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], | |
| [0.229, 0.224, 0.225]), | |
| ]) | |
| # ====================== HELPERS ====================== | |
| def tensor_from_pil(img: Image.Image) -> torch.Tensor: | |
| return val_tf(img.convert("RGB")).unsqueeze(0).to(DEVICE) | |
| def infer(tensor: torch.Tensor) -> np.ndarray: | |
| with torch.no_grad(): | |
| probs = F.softmax(model(tensor), dim=1).squeeze().cpu().numpy() | |
| return probs | |
| def severity_info(pred_name: str, conf_pct: float, is_ood: bool): | |
| """Return (label, score 0-3, hex_color, display_pct).""" | |
| if is_ood: | |
| return "Unknown", 0, "#95a5a6", 0.0 | |
| if pred_name in ZERO_SEV: | |
| return "None (Safe)", 0, "#2ecc71", 0.0 | |
| if conf_pct >= SEV_THRESHOLDS["High"]: | |
| return "High", 3, "#e74c3c", conf_pct | |
| if conf_pct >= SEV_THRESHOLDS["Medium"]: | |
| return "Medium", 2, "#f39c12", conf_pct | |
| return "Low", 1, "#3498db", conf_pct | |
| def fig_to_pil(fig) -> Image.Image: | |
| buf = io.BytesIO() | |
| fig.savefig(buf, format="png", bbox_inches="tight", dpi=120) | |
| plt.close(fig) | |
| buf.seek(0) | |
| return Image.open(buf).copy() | |
| # ====================== VIDEO FRAME EXTRACTION ====================== | |
| def extract_frames_cv2(video_path: str, frame_gap: int): | |
| """Extract frames using cv2.""" | |
| cap = cv2.VideoCapture(video_path) | |
| if not cap.isOpened(): | |
| return [], 0, 0.0 | |
| total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| fps = cap.get(cv2.CAP_PROP_FPS) or 30 | |
| frames, indices = [], [] | |
| count = 0 | |
| while cap.isOpened(): | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| if count % frame_gap == 0: | |
| rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| frames.append(Image.fromarray(rgb)) | |
| indices.append(count) | |
| count += 1 | |
| cap.release() | |
| return frames, indices, total / fps | |
| def extract_frames_imageio(video_path: str, frame_gap: int): | |
| """Fallback frame extraction using imageio.""" | |
| reader = imageio.get_reader(video_path) | |
| meta = reader.get_meta_data() | |
| fps = meta.get("fps", 30) | |
| frames, indices = [], [] | |
| for count, frame in enumerate(reader): | |
| if count % frame_gap == 0: | |
| frames.append(Image.fromarray(frame)) | |
| indices.append(count) | |
| reader.close() | |
| duration = indices[-1] / fps if indices else 0.0 | |
| return frames, indices, duration | |
| def extract_frames(video_path: str, frame_gap: int): | |
| if HAS_CV2: | |
| return extract_frames_cv2(video_path, frame_gap) | |
| if HAS_IMAGEIO: | |
| return extract_frames_imageio(video_path, frame_gap) | |
| raise RuntimeError("Neither cv2 nor imageio is available for video reading.") | |
| # ====================== IMAGE PREDICTION ====================== | |
| def predict_image(pil_img: Image.Image): | |
| if pil_img is None: | |
| return None, "β Please upload an image." | |
| img = pil_img.convert("RGB") | |
| probs = infer(tensor_from_pil(img)) | |
| top_idx = int(probs.argmax()) | |
| pred_name = CLASS_NAMES[top_idx] | |
| conf_pct = probs[top_idx] * 100 | |
| is_ood = probs[top_idx] < OOD_THRESHOLD | |
| sev_label, sev_score, sev_color, sev_pct = severity_info( | |
| pred_name, conf_pct, is_ood | |
| ) | |
| if is_ood: | |
| title = f"β οΈ Unrecognised image ({conf_pct:.1f}% β below OOD threshold)" | |
| elif sev_label == "None (Safe)": | |
| title = f"β {pred_name} | {conf_pct:.1f}% | Safe" | |
| else: | |
| icon = {"High": "π΄", "Medium": "π‘", "Low": "π΅"}.get(sev_label, "π΅") | |
| title = f"{icon} {pred_name} | {conf_pct:.1f}% | Severity: {sev_label}" | |
| top5_idx = probs.argsort()[::-1][:5] | |
| top5_prob = probs[top5_idx] * 100 | |
| top5_name = [CLASS_NAMES[i] for i in top5_idx] | |
| fig, axes = plt.subplots(1, 3, figsize=(16, 5)) | |
| fig.patch.set_facecolor("#f8f9fa") | |
| # Panel 1 β image | |
| axes[0].imshow(np.array(img)) | |
| axes[0].axis("off") | |
| axes[0].set_title(title, fontsize=10, color=sev_color, | |
| fontweight="bold", wrap=True) | |
| # Panel 2 β top-5 bar chart | |
| bar_colors = (["#e74c3c"] * 5 if is_ood | |
| else ["#2980b9"] + ["#bdc3c7"] * 4) | |
| axes[1].barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1]) | |
| for i, prob in enumerate(top5_prob[::-1]): | |
| axes[1].text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9) | |
| if is_ood: | |
| axes[1].axvline(OOD_THRESHOLD * 100, color="red", linestyle="--", | |
| linewidth=1.5, | |
| label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)") | |
| axes[1].legend(fontsize=8) | |
| axes[1].set_xlim(0, 110) | |
| axes[1].set_xlabel("Confidence (%)") | |
| axes[1].set_title("Top-5 Predictions" + (" β οΈ OOD" if is_ood else "")) | |
| axes[1].spines[["top", "right"]].set_visible(False) | |
| # Panel 3 β severity gauge + progress bar | |
| ax3 = axes[2] | |
| ax3.axis("off") | |
| gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"] | |
| gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"] | |
| for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)): | |
| alpha = 1.0 if gi == sev_score else 0.15 | |
| ax3.add_patch(plt.Rectangle( | |
| (gi * 0.24, 0.40), 0.22, 0.30, | |
| color=gc, alpha=alpha, transform=ax3.transAxes | |
| )) | |
| ax3.text(gi * 0.24 + 0.11, 0.56, gl, | |
| ha="center", va="center", fontsize=9, color="black", | |
| transform=ax3.transAxes, fontweight="bold") | |
| sev_display = f"{sev_label} ({sev_pct:.1f}%)" if sev_pct > 0 else sev_label | |
| ax3.text(0.5, 0.88, f"Severity: {sev_display}", | |
| ha="center", va="center", fontsize=12, color=sev_color, | |
| transform=ax3.transAxes, fontweight="bold") | |
| if sev_pct > 0: | |
| ax3.add_patch(plt.Rectangle((0.05, 0.18), 0.90, 0.10, | |
| color="#ecf0f1", transform=ax3.transAxes)) | |
| ax3.add_patch(plt.Rectangle((0.05, 0.18), 0.90 * sev_pct / 100, 0.10, | |
| color=sev_color, transform=ax3.transAxes)) | |
| ax3.text(0.5, 0.23, f"{sev_pct:.1f}%", | |
| ha="center", va="center", fontsize=10, color="white", | |
| transform=ax3.transAxes, fontweight="bold") | |
| ax3.set_title("Severity Level", fontsize=11) | |
| plt.tight_layout() | |
| result_img = fig_to_pil(fig) | |
| lines = [ | |
| f"π Class : {'UNKNOWN (OOD)' if is_ood else pred_name}", | |
| f"π Confidence : {conf_pct:.2f}%", | |
| f"β οΈ Severity : {sev_label}" + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else ""), | |
| "", | |
| "All class probabilities:", | |
| ] | |
| for i, name in enumerate(CLASS_NAMES): | |
| bar = "β" * int(probs[i] * 30) | |
| marker = " β predicted" if i == top_idx else "" | |
| lines.append(f" {name:<35} {probs[i]*100:5.1f}% {bar}{marker}") | |
| return result_img, "\n".join(lines) | |
| # ====================== VIDEO PREDICTION ====================== | |
| def predict_video(video_path: str, | |
| frame_gap: int = FRAME_GAP, | |
| progress=gr.Progress()): | |
| if video_path is None: | |
| return None, "β Please upload a video." | |
| progress(0, desc="Extracting framesβ¦") | |
| try: | |
| frames, frame_indices, duration_s = extract_frames(video_path, int(frame_gap)) | |
| except Exception as e: | |
| return None, f"β Frame extraction failed: {e}" | |
| if not frames: | |
| return None, "β No frames could be extracted from this video." | |
| n_frames = len(frames) | |
| all_probs = [] | |
| frame_preds, frame_confs = [], [] | |
| for fi, img in enumerate(frames): | |
| probs = infer(tensor_from_pil(img)) | |
| all_probs.append(probs) | |
| frame_preds.append(int(probs.argmax())) | |
| frame_confs.append(float(probs.max()) * 100) | |
| progress((fi + 1) / n_frames, | |
| desc=f"Analysing frame {fi+1}/{n_frames}β¦") | |
| # ββ Aggregate: mean probability across all frames βββββββββββββββββββββββββ | |
| mean_probs = np.mean(all_probs, axis=0) | |
| final_id = int(mean_probs.argmax()) | |
| final_name = CLASS_NAMES[final_id] | |
| final_conf = mean_probs[final_id] * 100 | |
| is_ood = mean_probs[final_id] < OOD_THRESHOLD | |
| sev_label, sev_score, sev_color, sev_pct = severity_info( | |
| final_name, final_conf, is_ood | |
| ) | |
| danger_count = sum(CLASS_NAMES[p] not in ZERO_SEV for p in frame_preds) | |
| danger_pct = 100 * danger_count / n_frames | |
| # ββ Figure: 4 panels ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| fig, axes = plt.subplots(2, 2, figsize=(16, 10)) | |
| fig.patch.set_facecolor("#f8f9fa") | |
| fig.suptitle( | |
| f"{'β οΈ UNKNOWN (OOD)' if is_ood else final_name} | " | |
| f"Confidence: {final_conf:.1f}% | Severity: {sev_label}" | |
| + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else "") | |
| + f" | Danger frames: {danger_pct:.1f}%", | |
| fontsize=13, fontweight="bold", color=sev_color, y=1.01 | |
| ) | |
| # Panel A β per-frame class timeline | |
| axes[0, 0].plot(frame_indices, frame_preds, "o-", | |
| markersize=3, linewidth=1, color="#2980b9") | |
| axes[0, 0].axhline(final_id, color="#e74c3c", linestyle="--", | |
| linewidth=1.5, label=f"Final: {final_name}") | |
| axes[0, 0].set_yticks(range(len(CLASS_NAMES))) | |
| axes[0, 0].set_yticklabels(CLASS_NAMES, fontsize=7) | |
| axes[0, 0].set_xlabel("Frame index") | |
| axes[0, 0].set_title("Per-frame class prediction") | |
| axes[0, 0].legend(fontsize=8) | |
| axes[0, 0].spines[["top", "right"]].set_visible(False) | |
| # Panel B β per-frame confidence | |
| axes[0, 1].plot(frame_indices, frame_confs, "s-", | |
| markersize=3, linewidth=1, color=sev_color) | |
| axes[0, 1].axhline(OOD_THRESHOLD * 100, color="gray", linestyle=":", | |
| linewidth=1, | |
| label=f"OOD threshold ({OOD_THRESHOLD*100:.0f}%)") | |
| axes[0, 1].fill_between(frame_indices, frame_confs, | |
| OOD_THRESHOLD * 100, | |
| where=[c > OOD_THRESHOLD * 100 for c in frame_confs], | |
| alpha=0.15, color=sev_color, | |
| label="Above threshold") | |
| axes[0, 1].set_ylim(0, 105) | |
| axes[0, 1].set_xlabel("Frame index") | |
| axes[0, 1].set_ylabel("Confidence (%)") | |
| axes[0, 1].set_title("Per-frame confidence") | |
| axes[0, 1].legend(fontsize=8) | |
| axes[0, 1].spines[["top", "right"]].set_visible(False) | |
| # Panel C β top-5 aggregated | |
| top5_idx = mean_probs.argsort()[::-1][:5] | |
| top5_prob = mean_probs[top5_idx] * 100 | |
| top5_name = [CLASS_NAMES[i] for i in top5_idx] | |
| bar_colors = (["#e74c3c"] * 5 if is_ood | |
| else ["#2980b9"] + ["#bdc3c7"] * 4) | |
| axes[1, 0].barh(top5_name[::-1], top5_prob[::-1], color=bar_colors[::-1]) | |
| for i, prob in enumerate(top5_prob[::-1]): | |
| axes[1, 0].text(prob + 0.5, i, f"{prob:.1f}%", va="center", fontsize=9) | |
| axes[1, 0].set_xlim(0, 110) | |
| axes[1, 0].set_xlabel("Mean confidence (%)") | |
| axes[1, 0].set_title("Top-5 classes (aggregated)") | |
| axes[1, 0].spines[["top", "right"]].set_visible(False) | |
| # Panel D β summary card | |
| ax4 = axes[1, 1] | |
| ax4.axis("off") | |
| gauge_labels = ["None\n(Safe)", "Low", "Medium", "High"] | |
| gauge_colors = ["#2ecc71", "#3498db", "#f39c12", "#e74c3c"] | |
| for gi, (gl, gc) in enumerate(zip(gauge_labels, gauge_colors)): | |
| alpha = 1.0 if gi == sev_score else 0.15 | |
| ax4.add_patch(plt.Rectangle( | |
| (gi * 0.24, 0.60), 0.22, 0.25, | |
| color=gc, alpha=alpha, transform=ax4.transAxes | |
| )) | |
| ax4.text(gi * 0.24 + 0.11, 0.73, gl, | |
| ha="center", va="center", fontsize=9, color="black", | |
| transform=ax4.transAxes, fontweight="bold") | |
| stats = [ | |
| ("Final class", final_name), | |
| ("Confidence", f"{final_conf:.1f}%"), | |
| ("Severity", f"{sev_label}" + (f" ({sev_pct:.1f}%)" if sev_pct > 0 else "")), | |
| ("Danger frames", f"{danger_pct:.1f}% ({danger_count}/{n_frames})"), | |
| ("Frames analysed", f"{n_frames} (every {int(frame_gap)} frames)"), | |
| ("Video duration", f"{duration_s:.1f}s"), | |
| ] | |
| y_pos = 0.54 | |
| for label, value in stats: | |
| ax4.text(0.02, y_pos, label + ":", fontsize=9, | |
| color="#7f8c8d", transform=ax4.transAxes) | |
| ax4.text(0.46, y_pos, value, fontsize=9, | |
| color="#2c3e50", transform=ax4.transAxes, fontweight="bold") | |
| y_pos -= 0.08 | |
| # Severity progress bar | |
| if sev_pct > 0: | |
| ax4.add_patch(plt.Rectangle((0.02, 0.03), 0.96, 0.07, | |
| color="#ecf0f1", transform=ax4.transAxes)) | |
| ax4.add_patch(plt.Rectangle((0.02, 0.03), | |
| 0.96 * sev_pct / 100, 0.07, | |
| color=sev_color, transform=ax4.transAxes)) | |
| ax4.text(0.5, 0.065, f"Severity intensity: {sev_pct:.1f}%", | |
| ha="center", va="center", fontsize=9, color="white", | |
| transform=ax4.transAxes, fontweight="bold") | |
| ax4.set_title("Summary", fontsize=11) | |
| plt.tight_layout() | |
| result_img = fig_to_pil(fig) | |
| lines = [ | |
| "π₯ Video Analysis Complete", | |
| "β" * 45, | |
| f"π Final class : {'UNKNOWN (OOD)' if is_ood else final_name}", | |
| f"π Confidence : {final_conf:.2f}%", | |
| f"β οΈ Severity : {sev_label}" + | |
| (f" ({sev_pct:.1f}%)" if sev_pct > 0 else ""), | |
| f"π₯ Danger frames : {danger_pct:.1f}% ({danger_count}/{n_frames})", | |
| f"ποΈ Frames analysed: {n_frames}", | |
| f"β±οΈ Duration : {duration_s:.1f}s", | |
| "", | |
| "Top-5 aggregated probabilities:", | |
| ] | |
| for name, prob in zip(top5_name, top5_prob): | |
| bar = "β" * int(prob / 100 * 30) | |
| lines.append(f" {name:<35} {prob:5.1f}% {bar}") | |
| return result_img, "\n".join(lines) | |
| # ====================== GRADIO UI ====================== | |
| DESCRIPTION = """ | |
| # π Disaster Scene Classifier | |
| Upload an **image** or **video** to detect disaster types and estimate severity. | |
| **Disaster classes:** Earthquake Β· Infrastructure Β· Urban Fire Β· Wild Fire Β· Human Damage Β· Drought Β· Land Slide | |
| **Zero-severity (safe):** Non-Damage Buildings Β· Non-Damage Wildlife Β· Human Β· Sea Β· Water (safe) Β· Random Β· Flyer/Poster | |
| """ | |
| SEVERITY_MD = """ | |
| ### Severity Scale | |
| | Level | Trigger | Meaning | | |
| |-------|---------|---------| | |
| | β None (Safe) | Zero-severity class | No disaster | | |
| | π΅ Low | confidence < 65% | Weak signal | | |
| | π‘ Medium | 65 β 84% | Moderate confidence | | |
| | π΄ High | β₯ 85% | High confidence disaster | | |
| > If confidence < 55% β flagged as **out-of-distribution** (OOD) | |
| """ | |
| with gr.Blocks( | |
| title="Disaster Classifier", | |
| theme=gr.themes.Soft(primary_hue="blue"), | |
| css=".result-text { font-family: monospace; font-size: 13px; }" | |
| ".header-md h1 { text-align: center; }" | |
| ) as demo: | |
| gr.Markdown(DESCRIPTION, elem_classes="header-md") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown(SEVERITY_MD) | |
| with gr.Tabs(): | |
| # ββ IMAGE TAB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Tab("π· Image"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| img_input = gr.Image( | |
| type="pil", | |
| label="Upload image (JPG / PNG / BMP)", | |
| height=300, | |
| ) | |
| img_btn = gr.Button("π Analyse Image", | |
| variant="primary", size="lg") | |
| with gr.Column(scale=2): | |
| img_output = gr.Image(label="Result", height=420) | |
| img_text = gr.Textbox( | |
| label="Detailed results", | |
| lines=20, | |
| elem_classes="result-text", | |
| ) | |
| img_btn.click( | |
| fn=predict_image, | |
| inputs=img_input, | |
| outputs=[img_output, img_text], | |
| ) | |
| # ββ VIDEO TAB βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Tab("π₯ Video"): | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| vid_input = gr.Video( | |
| label="Upload video (MP4 / AVI / MOV)", | |
| height=300, | |
| ) | |
| frame_slider = gr.Slider( | |
| minimum=5, maximum=60, value=30, step=5, | |
| label="Frame gap (analyse every Nth frame)", | |
| info="Lower = more accurate but slower" | |
| ) | |
| vid_btn = gr.Button("π Analyse Video", | |
| variant="primary", size="lg") | |
| gr.Markdown("_Progress bar shown below during processing._") | |
| with gr.Column(scale=2): | |
| vid_output = gr.Image(label="Result", height=520) | |
| vid_text = gr.Textbox( | |
| label="Detailed results", | |
| lines=20, | |
| elem_classes="result-text", | |
| ) | |
| vid_btn.click( | |
| fn=predict_video, | |
| inputs=[vid_input, frame_slider], | |
| outputs=[vid_output, vid_text], | |
| ) | |
| gr.Markdown( | |
| "---\nModel: ConvNeXt-Tiny fine-tuned on CDD Β· " | |
| "Built with [Gradio](https://gradio.app)" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |