Update app.py
Browse files
app.py
CHANGED
|
@@ -1,94 +1,106 @@
|
|
| 1 |
-
#!/usr/bin/env python
|
| 2 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 3 |
-
# BubbleAI Image-Safety Detector β
|
| 4 |
-
# -------------------------------------------------------------
|
| 5 |
-
#
|
| 6 |
-
#
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
from
|
| 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 |
-
self.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 3 |
+
# BubbleAI Image-Safety Detector β fixed version
|
| 4 |
+
# -------------------------------------------------------------
|
| 5 |
+
# Loads checkpoint `resnet_safety_classifier.pth` whose keys are
|
| 6 |
+
# saved under feature_extractor.* and classifier.*; serves a
|
| 7 |
+
# Gradio UI that predicts βSafeβ vs βUnsafeβ.
|
| 8 |
+
#
|
| 9 |
+
# Coder: Amir Mehdi Memari (2025-08-06)
|
| 10 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import pathlib
|
| 14 |
+
import typing as t
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torchvision
|
| 18 |
+
from torchvision import transforms
|
| 19 |
+
from PIL import Image
|
| 20 |
+
import gradio as gr
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ββ 1. Paths & device βββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
REPO_DIR = pathlib.Path(__file__).parent
|
| 25 |
+
CKPT_PATH = REPO_DIR / "resnet_safety_classifier.pth"
|
| 26 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ββ 2. Architecture that matches checkpoint keys ββββββββββββββ
|
| 30 |
+
class SafetyResNet(torch.nn.Module):
|
| 31 |
+
"""
|
| 32 |
+
ResNet-50 backbone (conv1 βΈ layer4) β global avg-pool
|
| 33 |
+
β MLP (2048β512β2). Keys align with:
|
| 34 |
+
β’ feature_extractor.*
|
| 35 |
+
β’ classifier.*
|
| 36 |
+
"""
|
| 37 |
+
def __init__(self) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
base = torchvision.models.resnet50(weights=None)
|
| 41 |
+
|
| 42 |
+
# keep stem + 4 stages (0-7) [conv1, bn1, relu, maxpool, layer1-4]
|
| 43 |
+
self.feature_extractor = torch.nn.Sequential(*list(base.children())[:8])
|
| 44 |
+
|
| 45 |
+
self.pool = torch.nn.AdaptiveAvgPool2d((1, 1))
|
| 46 |
+
self.classifier = torch.nn.Sequential(
|
| 47 |
+
torch.nn.Flatten(), # (B, 2048, 1, 1) β (B, 2048)
|
| 48 |
+
torch.nn.Linear(2048, 512, bias=True),
|
| 49 |
+
torch.nn.ReLU(inplace=True),
|
| 50 |
+
torch.nn.Dropout(p=0.30),
|
| 51 |
+
torch.nn.Linear(512, 2, bias=True)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 55 |
+
x = self.feature_extractor(x) # (B, 2048, H/32, W/32)
|
| 56 |
+
x = self.pool(x) # (B, 2048, 1, 1)
|
| 57 |
+
x = self.classifier(x) # (B, 2)
|
| 58 |
+
return x
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ββ 3. Instantiate & load weights βββββββββββββββββββββββββββββ
|
| 62 |
+
model = SafetyResNet().to(DEVICE)
|
| 63 |
+
state = torch.load(CKPT_PATH, map_location=DEVICE)
|
| 64 |
+
model.load_state_dict(state, strict=True)
|
| 65 |
+
model.eval()
|
| 66 |
+
|
| 67 |
+
CLASSES = ["Safe", "Unsafe"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ββ 4. Pre-processing pipeline (ImageNet stats) βββββββββββββββ
|
| 71 |
+
preprocess = transforms.Compose([
|
| 72 |
+
transforms.Resize(256),
|
| 73 |
+
transforms.CenterCrop(224),
|
| 74 |
+
transforms.ToTensor(),
|
| 75 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 76 |
+
std =[0.229, 0.224, 0.225]),
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ββ 5. Inference helper βββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
@torch.inference_mode()
|
| 82 |
+
def predict(img: Image.Image) -> t.Dict[str, float]:
|
| 83 |
+
"""
|
| 84 |
+
Returns {class_name: probability} for a single PIL image.
|
| 85 |
+
"""
|
| 86 |
+
tensor = preprocess(img).unsqueeze(0).to(DEVICE)
|
| 87 |
+
probs = torch.softmax(model(tensor)[0], dim=0).cpu().tolist()
|
| 88 |
+
return {CLASSES[i]: float(probs[i]) for i in range(2)}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ββ 6. Gradio interface βββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
demo = gr.Interface(
|
| 93 |
+
fn=predict,
|
| 94 |
+
inputs=gr.Image(type="pil", label="Upload an image"),
|
| 95 |
+
outputs=gr.Label(num_top_classes=2, label="Prediction"),
|
| 96 |
+
title="BubbleAI Image-Safety Detector",
|
| 97 |
+
description=(
|
| 98 |
+
"Drop an image to check whether it's **Safe** or **Unsafe** "
|
| 99 |
+
"using BubbleAIβs ResNet-50 classifier."
|
| 100 |
+
),
|
| 101 |
+
cache_examples=False,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# ββ 7. Launch ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
demo.launch()
|