# 📷 Object Detection Demo | CPU-only HF Space import gradio as gr from transformers import pipeline from PIL import Image, ImageDraw # Load DETR object‐detection pipeline (requires timm in requirements) detector = pipeline("object-detection", model="facebook/detr-resnet-50", device=-1) def detect_objects(image: Image.Image): outputs = detector(image) annotated = image.convert("RGB") draw = ImageDraw.Draw(annotated) table = [] for obj in outputs: box = obj["box"] # DETR pipeline may return box as dict or list if isinstance(box, dict): xmin = int(box.get("xmin", box.get("x", 0))) ymin = int(box.get("ymin", box.get("y", 0))) xmax = int(box.get("xmax", xmin)) ymax = int(box.get("ymax", ymin)) else: # assume [x, y, w, h] x, y, w, h = box xmin, ymin = int(x), int(y) xmax, ymax = int(x + w), int(y + h) label = obj["label"] score = round(obj["score"], 3) # draw box & label draw.rectangle([xmin, ymin, xmax, ymax], outline="red", width=2) draw.text((xmin, max(ymin - 10, 0)), f"{label} ({score})", fill="red") table.append([label, score]) return annotated, table with gr.Blocks(title="📷✨ Object Detection Demo") as demo: gr.Markdown( """ # 📷✨ Object Detection Upload an image and let DETR identify objects on CPU. """ ) with gr.Row(): img_in = gr.Image(type="pil", label="Upload Image") btn = gr.Button("Detect Objects 🔍", variant="primary") img_out = gr.Image(label="Annotated Image") table_out = gr.Dataframe( headers=["Label", "Score"], datatype=["str", "number"], wrap=True, interactive=False, label="Detections" ) btn.click(detect_objects, inputs=img_in, outputs=[img_out, table_out]) if __name__ == "__main__": demo.launch(server_name="0.0.0.0")