import gradio as gr import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import cv2 import timm from PIL import Image import matplotlib.pyplot as plt import matplotlib.patches as patches import io device = "cpu" # Hugging Face free tier is CPU only model = timm.create_model("vit_base_patch16_224", pretrained=False, num_classes=80) checkpoint = torch.load("vit_coco_final_slim.pth", map_location=device) model.load_state_dict(checkpoint["model_state_dict"]) model.eval() class_names = checkpoint["class_names"] BOX_COLORS = ["red", "blue", "green", "orange", "purple", "brown", "magenta", "cyan"] def get_class_specific_map(m, input_tensor, class_idx, layer_candidates=(9, 6, 3, 0)): for layer_idx in layer_candidates: input_t = input_tensor.to(device).clone().detach() input_t.requires_grad_(True) activations = {} def fwd_hook(module, inp, output): output.retain_grad() activations["value"] = output target_layer = m.blocks[layer_idx] h1 = target_layer.register_forward_hook(fwd_hook) m.zero_grad() logits = m(input_t) score = logits[0, class_idx] score.backward(retain_graph=True) h1.remove() acts = activations["value"][0].detach() grads = activations["value"].grad[0].detach() relevance = (grads * acts).sum(dim=1) relevance = relevance[1:197] relevance = F.relu(relevance) cam = relevance.reshape(14, 14).cpu().numpy() if cam.max() - cam.min() > 1e-10: cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-10) return cam return np.zeros((14, 14)) def mask_to_bbox(mask, original_shape, threshold=0.5): h, w = original_shape[:2] mask_resized = cv2.resize(mask, (w, h)) binary = (mask_resized > threshold).astype(np.uint8) contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours) == 0: return None largest = max(contours, key=cv2.contourArea) return cv2.boundingRect(largest) def run_detection_per_class(pil_image, threshold=0.3): if pil_image is None: return None, "Please upload an image." image = pil_image.convert("RGB") original = np.array(image) img = torch.ByteTensor(torch.ByteStorage.from_buffer(image.tobytes())) img = img.view(image.size[1], image.size[0], 3) img = img.permute(2, 0, 1).contiguous().float() / 255.0 img = F.interpolate(img.unsqueeze(0), size=(224, 224), mode="bilinear", align_corners=False) mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) input_tensor = (img - mean) / std with torch.no_grad(): logits = model(input_tensor.to(device)) probs = torch.sigmoid(logits[0]).cpu().numpy() detected = sorted( [(i, class_names[i], float(probs[i])) for i in range(len(class_names)) if probs[i] > threshold], key=lambda x: x[2], reverse=True )[:5] if len(detected) == 0: return None, "No objects detected. Try lowering the threshold." per_class_boxes = [] for class_idx, name, score in detected: cam = get_class_specific_map(model, input_tensor, class_idx) bbox = mask_to_bbox(cam, original.shape, threshold=0.5) if bbox is not None: per_class_boxes.append((name, score, bbox)) fig, ax = plt.subplots(1, 1, figsize=(8, 8)) ax.imshow(original) for idx, (name, score, bbox) in enumerate(per_class_boxes): x, y, bw, bh = bbox color = BOX_COLORS[idx % len(BOX_COLORS)] rect = patches.Rectangle((x, y), bw, bh, linewidth=2.5, edgecolor=color, facecolor="none") ax.add_patch(rect) ax.text(x, max(y - 6, 10), f"{name} {score:.2f}", color=color, fontsize=11, bbox=dict(facecolor="white", alpha=0.8, pad=1)) ax.set_title(f"Detected {len(per_class_boxes)} objects") ax.axis("off") plt.tight_layout() buf = io.BytesIO() plt.savefig(buf, format="png", dpi=120) buf.seek(0) result_img = Image.open(buf) plt.close() text_output = f"Total objects detected: {len(per_class_boxes)}\n\n" + "\n".join( f" {name:25s} {score:.2f}" for name, score, _ in per_class_boxes ) return result_img, text_output with gr.Blocks(title="ViT Object Detection") as app: gr.Markdown("# ViT Object Detection (trained on full COCO)") gr.Markdown("Upload any image. Model detects from 80 COCO classes.") with gr.Row(): with gr.Column(): input_image = gr.Image(type="pil", label="Upload Image") threshold_slider = gr.Slider(0.1, 0.9, value=0.3, step=0.05, label="Threshold") detect_btn = gr.Button("Detect Objects", variant="primary") with gr.Column(): output_image = gr.Image(type="pil", label="Detection Result") output_text = gr.Textbox(label="Detected Objects", lines=10) detect_btn.click(fn=run_detection_per_class, inputs=[input_image, threshold_slider], outputs=[output_image, output_text]) gr.Markdown("### Supported 80 classes") gr.Markdown(", ".join(class_names)) app.launch()