Spaces:
Running
Running
Commit
·
d0ba1f1
1
Parent(s):
d3b24af
Sync from GitHub
Browse files- .huggingface.yaml +7 -0
- hf_space/.github/workflows/docker-build-push.yml +26 -0
- hf_space/.github/workflows/hf-space-sync.yml +36 -0
- hf_space/.gitignore +5 -0
- hf_space/Dockerfile +13 -0
- hf_space/LICENSE +21 -0
- hf_space/app.py +384 -0
- hf_space/hf_space/.gitattributes +35 -0
- hf_space/hf_space/README.md +12 -0
- hf_space/requirements.txt +8 -0
.huggingface.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sdk: gradio
|
| 2 |
+
python_version: 3.10
|
| 3 |
+
app_file: app.py
|
| 4 |
+
title: Object Detection App
|
| 5 |
+
subtitle: Real-time object detection in images using Gradio
|
| 6 |
+
hardware: cpu-basic
|
| 7 |
+
license: apache-2.0
|
hf_space/.github/workflows/docker-build-push.yml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build and Push Docker Image to Docker Hub
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
build-and-push:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
steps:
|
| 12 |
+
- name: Checkout code
|
| 13 |
+
uses: actions/checkout@v4
|
| 14 |
+
|
| 15 |
+
- name: Log in to Docker Hub
|
| 16 |
+
uses: docker/login-action@v3
|
| 17 |
+
with:
|
| 18 |
+
username: ${{ secrets.DOCKER_USERNAME }}
|
| 19 |
+
password: ${{ secrets.DOCKER_PAT }}
|
| 20 |
+
|
| 21 |
+
- name: Build and push Docker image
|
| 22 |
+
uses: docker/build-push-action@v6
|
| 23 |
+
with:
|
| 24 |
+
context: .
|
| 25 |
+
push: true
|
| 26 |
+
tags: ${{ secrets.DOCKER_USERNAME }}/objectdetection:latest
|
hf_space/.github/workflows/hf-space-sync.yml
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Sync to Hugging Face Space
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ main ]
|
| 6 |
+
|
| 7 |
+
jobs:
|
| 8 |
+
deploy-to-hf-space:
|
| 9 |
+
runs-on: ubuntu-latest
|
| 10 |
+
|
| 11 |
+
steps:
|
| 12 |
+
- name: Checkout Repository
|
| 13 |
+
uses: actions/checkout@v3
|
| 14 |
+
|
| 15 |
+
- name: Install Git
|
| 16 |
+
run: sudo apt-get install git
|
| 17 |
+
|
| 18 |
+
- name: Push to Hugging Face Space
|
| 19 |
+
env:
|
| 20 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 21 |
+
HF_USERNAME: ${{ secrets.HF_USERNAME }}
|
| 22 |
+
EMAIL: ${{ secrets.EMAIL }}
|
| 23 |
+
run: |
|
| 24 |
+
git config --global user.email $EMAIL
|
| 25 |
+
git config --global user.name $HF_USERNAME
|
| 26 |
+
|
| 27 |
+
git clone https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/ObjectDetection hf_space
|
| 28 |
+
rsync -av --exclude='.git' ./ hf_space/
|
| 29 |
+
cd hf_space
|
| 30 |
+
git add .
|
| 31 |
+
if git diff --cached --quiet; then
|
| 32 |
+
echo "✅ No changes to commit."
|
| 33 |
+
else
|
| 34 |
+
git commit -m "Sync from GitHub"
|
| 35 |
+
git push
|
| 36 |
+
fi
|
hf_space/.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
venv/
|
| 3 |
+
*.pyc
|
| 4 |
+
.DS_Store
|
| 5 |
+
.env
|
hf_space/Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
COPY app.py .
|
| 10 |
+
|
| 11 |
+
EXPOSE 5000
|
| 12 |
+
|
| 13 |
+
CMD ["python", "app.py"]
|
hf_space/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Neeraj Sathish Kumar
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
hf_space/app.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import DetrImageProcessor, DetrForObjectDetection
|
| 4 |
+
from transformers import YolosImageProcessor, YolosForObjectDetection
|
| 5 |
+
from transformers import DetrForSegmentation
|
| 6 |
+
from PIL import Image, ImageDraw, ImageStat
|
| 7 |
+
import requests
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
import base64
|
| 10 |
+
from collections import Counter
|
| 11 |
+
import logging
|
| 12 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
|
| 13 |
+
from fastapi.responses import JSONResponse
|
| 14 |
+
import uvicorn
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import traceback
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
# Set up logging
|
| 20 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# Constants
|
| 24 |
+
CONFIDENCE_THRESHOLD = 0.5
|
| 25 |
+
VALID_MODELS = [
|
| 26 |
+
"facebook/detr-resnet-50",
|
| 27 |
+
"facebook/detr-resnet-101",
|
| 28 |
+
"facebook/detr-resnet-50-panoptic",
|
| 29 |
+
"facebook/detr-resnet-101-panoptic",
|
| 30 |
+
"hustvl/yolos-tiny",
|
| 31 |
+
"hustvl/yolos-base"
|
| 32 |
+
]
|
| 33 |
+
MODEL_DESCRIPTIONS = {
|
| 34 |
+
"facebook/detr-resnet-50": "DETR with ResNet-50 backbone for object detection. Fast and accurate for general use.",
|
| 35 |
+
"facebook/detr-resnet-101": "DETR with ResNet-101 backbone for object detection. More accurate but slower than ResNet-50.",
|
| 36 |
+
"facebook/detr-resnet-50-panoptic": "DETR with ResNet-50 for panoptic segmentation. Detects objects and segments scenes.",
|
| 37 |
+
"facebook/detr-resnet-101-panoptic": "DETR with ResNet-101 for panoptic segmentation. High accuracy for complex scenes.",
|
| 38 |
+
"hustvl/yolos-tiny": "YOLOS Tiny model. Lightweight and fast, ideal for resource-constrained environments.",
|
| 39 |
+
"hustvl/yolos-base": "YOLOS Base model. Balances speed and accuracy for object detection."
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
# Lazy model loading
|
| 43 |
+
models = {}
|
| 44 |
+
processors = {}
|
| 45 |
+
|
| 46 |
+
def process(image, model_name):
|
| 47 |
+
"""Process an image and return detected image, objects, confidences, unique objects, unique confidences, and properties."""
|
| 48 |
+
try:
|
| 49 |
+
if model_name not in VALID_MODELS:
|
| 50 |
+
raise ValueError(f"Invalid model: {model_name}. Choose from: {VALID_MODELS}")
|
| 51 |
+
|
| 52 |
+
# Load model and processor
|
| 53 |
+
if model_name not in models:
|
| 54 |
+
logger.info(f"Loading model: {model_name}")
|
| 55 |
+
if "yolos" in model_name:
|
| 56 |
+
models[model_name] = YolosForObjectDetection.from_pretrained(model_name)
|
| 57 |
+
processors[model_name] = YolosImageProcessor.from_pretrained(model_name)
|
| 58 |
+
elif "panoptic" in model_name:
|
| 59 |
+
models[model_name] = DetrForSegmentation.from_pretrained(model_name)
|
| 60 |
+
processors[model_name] = DetrImageProcessor.from_pretrained(model_name)
|
| 61 |
+
else:
|
| 62 |
+
models[model_name] = DetrForObjectDetection.from_pretrained(model_name)
|
| 63 |
+
processors[model_name] = DetrImageProcessor.from_pretrained(model_name)
|
| 64 |
+
|
| 65 |
+
model, processor = models[model_name], processors[model_name]
|
| 66 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 67 |
+
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
outputs = model(**inputs)
|
| 70 |
+
|
| 71 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
| 72 |
+
draw = ImageDraw.Draw(image)
|
| 73 |
+
object_names = []
|
| 74 |
+
confidence_scores = []
|
| 75 |
+
object_counter = Counter()
|
| 76 |
+
|
| 77 |
+
if "panoptic" in model_name:
|
| 78 |
+
processed_sizes = torch.tensor([[inputs["pixel_values"].shape[2], inputs["pixel_values"].shape[3]]])
|
| 79 |
+
results = processor.post_process_panoptic(outputs, target_sizes=target_sizes, processed_sizes=processed_sizes)[0]
|
| 80 |
+
|
| 81 |
+
for segment in results["segments_info"]:
|
| 82 |
+
label = segment["label_id"]
|
| 83 |
+
label_name = model.config.id2label.get(label, "Unknown")
|
| 84 |
+
score = segment.get("score", 1.0)
|
| 85 |
+
|
| 86 |
+
if "masks" in results and segment["id"] < len(results["masks"]):
|
| 87 |
+
mask = results["masks"][segment["id"]].cpu().numpy()
|
| 88 |
+
if mask.shape[0] > 0 and mask.shape[1] > 0:
|
| 89 |
+
mask_image = Image.fromarray((mask * 255).astype("uint8"))
|
| 90 |
+
colored_mask = Image.new("RGBA", image.size, (0, 0, 0, 0))
|
| 91 |
+
mask_draw = ImageDraw.Draw(colored_mask)
|
| 92 |
+
r, g, b = (segment["id"] * 50) % 255, (segment["id"] * 100) % 255, (segment["id"] * 150) % 255
|
| 93 |
+
mask_draw.bitmap((0, 0), mask_image, fill=(r, g, b, 128))
|
| 94 |
+
image = Image.alpha_composite(image.convert("RGBA"), colored_mask).convert("RGB")
|
| 95 |
+
draw = ImageDraw.Draw(image)
|
| 96 |
+
|
| 97 |
+
if score > CONFIDENCE_THRESHOLD:
|
| 98 |
+
object_names.append(label_name)
|
| 99 |
+
confidence_scores.append(float(score))
|
| 100 |
+
object_counter[label_name] = float(score)
|
| 101 |
+
else:
|
| 102 |
+
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)[0]
|
| 103 |
+
|
| 104 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 105 |
+
if score > CONFIDENCE_THRESHOLD:
|
| 106 |
+
x, y, x2, y2 = box.tolist()
|
| 107 |
+
draw.rectangle([x, y, x2, y2], outline="#32CD32", width=2)
|
| 108 |
+
label_name = model.config.id2label.get(label.item(), "Unknown")
|
| 109 |
+
# Place text at top-right corner, outside the box, with smaller size
|
| 110 |
+
text = f"{label_name}: {score:.2f}"
|
| 111 |
+
text_bbox = draw.textbbox((0, 0), text)
|
| 112 |
+
text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
|
| 113 |
+
draw.text((x2 - text_width - 2, y - text_height - 2), text, fill="#32CD32")
|
| 114 |
+
object_names.append(label_name)
|
| 115 |
+
confidence_scores.append(float(score))
|
| 116 |
+
object_counter[label_name] = float(score)
|
| 117 |
+
|
| 118 |
+
unique_objects = list(object_counter.keys())
|
| 119 |
+
unique_confidences = [object_counter[obj] for obj in unique_objects]
|
| 120 |
+
|
| 121 |
+
# Image properties
|
| 122 |
+
file_size = "Unknown"
|
| 123 |
+
if hasattr(image, "fp") and image.fp is not None:
|
| 124 |
+
buffered = BytesIO()
|
| 125 |
+
image.save(buffered, format="PNG")
|
| 126 |
+
file_size = f"{len(buffered.getvalue()) / 1024:.2f} KB"
|
| 127 |
+
|
| 128 |
+
# Color statistics
|
| 129 |
+
try:
|
| 130 |
+
stat = ImageStat.Stat(image)
|
| 131 |
+
color_stats = {
|
| 132 |
+
"mean": [f"{m:.2f}" for m in stat.mean],
|
| 133 |
+
"stddev": [f"{s:.2f}" for s in stat.stddev]
|
| 134 |
+
}
|
| 135 |
+
except Exception as e:
|
| 136 |
+
logger.error(f"Error calculating color statistics: {str(e)}")
|
| 137 |
+
color_stats = {"mean": "Error", "stddev": "Error"}
|
| 138 |
+
|
| 139 |
+
properties = {
|
| 140 |
+
"Format": image.format if hasattr(image, "format") and image.format else "Unknown",
|
| 141 |
+
"Size": f"{image.width}x{image.height}",
|
| 142 |
+
"Width": f"{image.width} px",
|
| 143 |
+
"Height": f"{image.height} px",
|
| 144 |
+
"Mode": image.mode,
|
| 145 |
+
"Aspect Ratio": f"{round(image.width / image.height, 2) if image.height != 0 else 'Undefined'}",
|
| 146 |
+
"File Size": file_size,
|
| 147 |
+
"Mean (R,G,B)": ", ".join(color_stats["mean"]) if isinstance(color_stats["mean"], list) else color_stats["mean"],
|
| 148 |
+
"StdDev (R,G,B)": ", ".join(color_stats["stddev"]) if isinstance(color_stats["stddev"], list) else color_stats["stddev"]
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
return image, object_names, confidence_scores, unique_objects, unique_confidences, properties
|
| 152 |
+
except Exception as e:
|
| 153 |
+
logger.error(f"Error in process: {str(e)}\n{traceback.format_exc()}")
|
| 154 |
+
raise
|
| 155 |
+
|
| 156 |
+
# FastAPI Setup
|
| 157 |
+
app = FastAPI(title="Object Detection API")
|
| 158 |
+
|
| 159 |
+
@app.post("/detect")
|
| 160 |
+
async def detect_objects_endpoint(
|
| 161 |
+
file: UploadFile = File(None),
|
| 162 |
+
image_url: str = Form(None),
|
| 163 |
+
model_name: str = Form(VALID_MODELS[0])
|
| 164 |
+
):
|
| 165 |
+
"""FastAPI endpoint to detect objects in an image from file or URL."""
|
| 166 |
+
try:
|
| 167 |
+
if (file is None and not image_url) or (file is not None and image_url):
|
| 168 |
+
raise HTTPException(status_code=400, detail="Provide either an image file or an image URL, but not both.")
|
| 169 |
+
|
| 170 |
+
if file:
|
| 171 |
+
if not file.content_type.startswith("image/"):
|
| 172 |
+
raise HTTPException(status_code=400, detail="File must be an image")
|
| 173 |
+
contents = await file.read()
|
| 174 |
+
image = Image.open(BytesIO(contents)).convert("RGB")
|
| 175 |
+
else:
|
| 176 |
+
response = requests.get(image_url, timeout=10)
|
| 177 |
+
response.raise_for_status()
|
| 178 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 179 |
+
|
| 180 |
+
if model_name not in VALID_MODELS:
|
| 181 |
+
raise HTTPException(status_code=400, detail=f"Invalid model. Choose from: {VALID_MODELS}")
|
| 182 |
+
|
| 183 |
+
detected_image, detected_objects, detected_confidences, unique_objects, unique_confidences, _ = process(image, model_name)
|
| 184 |
+
|
| 185 |
+
buffered = BytesIO()
|
| 186 |
+
detected_image.save(buffered, format="PNG")
|
| 187 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 188 |
+
img_url = f"data:image/png;base64,{img_base64}"
|
| 189 |
+
|
| 190 |
+
return JSONResponse(content={
|
| 191 |
+
"image_url": img_url,
|
| 192 |
+
"detected_objects": detected_objects,
|
| 193 |
+
"confidence_scores": detected_confidences,
|
| 194 |
+
"unique_objects": unique_objects,
|
| 195 |
+
"unique_confidence_scores": unique_confidences
|
| 196 |
+
})
|
| 197 |
+
except Exception as e:
|
| 198 |
+
logger.error(f"Error in FastAPI endpoint: {str(e)}\n{traceback.format_exc()}")
|
| 199 |
+
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
|
| 200 |
+
|
| 201 |
+
# Gradio UI
|
| 202 |
+
def create_gradio_ui():
|
| 203 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="gray")) as demo:
|
| 204 |
+
gr.Markdown(
|
| 205 |
+
"""
|
| 206 |
+
# 🚀 Object Detection App
|
| 207 |
+
Upload an image or provide a URL to detect objects using state-of-the-art transformer models (DETR, YOLOS).
|
| 208 |
+
"""
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
with gr.Tabs():
|
| 212 |
+
with gr.Tab("📷 Image Upload"):
|
| 213 |
+
with gr.Row():
|
| 214 |
+
with gr.Column(scale=1):
|
| 215 |
+
gr.Markdown("### Input")
|
| 216 |
+
model_choice = gr.Dropdown(
|
| 217 |
+
choices=VALID_MODELS,
|
| 218 |
+
value=VALID_MODELS[0],
|
| 219 |
+
label="🔎 Select Model",
|
| 220 |
+
info="Choose a model for object detection or panoptic segmentation."
|
| 221 |
+
)
|
| 222 |
+
model_info = gr.Markdown(
|
| 223 |
+
f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",
|
| 224 |
+
visible=True
|
| 225 |
+
)
|
| 226 |
+
image_input = gr.Image(type="pil", label="📷 Upload Image")
|
| 227 |
+
image_url_input = gr.Textbox(
|
| 228 |
+
label="🔗 Image URL",
|
| 229 |
+
placeholder="https://example.com/image.jpg"
|
| 230 |
+
)
|
| 231 |
+
with gr.Row():
|
| 232 |
+
submit_btn = gr.Button("✨ Detect", variant="primary")
|
| 233 |
+
clear_btn = gr.Button("🗑️ Clear", variant="secondary")
|
| 234 |
+
|
| 235 |
+
model_choice.change(
|
| 236 |
+
fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}",
|
| 237 |
+
inputs=model_choice,
|
| 238 |
+
outputs=model_info
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
with gr.Column(scale=2):
|
| 242 |
+
gr.Markdown("### Results")
|
| 243 |
+
error_output = gr.Textbox(
|
| 244 |
+
label="⚠️ Errors",
|
| 245 |
+
visible=False,
|
| 246 |
+
lines=3,
|
| 247 |
+
max_lines=5
|
| 248 |
+
)
|
| 249 |
+
output_image = gr.Image(
|
| 250 |
+
type="pil",
|
| 251 |
+
label="🎯 Detected Image",
|
| 252 |
+
interactive=False
|
| 253 |
+
)
|
| 254 |
+
with gr.Row():
|
| 255 |
+
objects_output = gr.DataFrame(
|
| 256 |
+
label="📋 Detected Objects",
|
| 257 |
+
interactive=False,
|
| 258 |
+
value=None
|
| 259 |
+
)
|
| 260 |
+
unique_objects_output = gr.DataFrame(
|
| 261 |
+
label="🔍 Unique Objects",
|
| 262 |
+
interactive=False,
|
| 263 |
+
value=None
|
| 264 |
+
)
|
| 265 |
+
properties_output = gr.DataFrame(
|
| 266 |
+
label="📄 Image Properties",
|
| 267 |
+
interactive=False,
|
| 268 |
+
value=None
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
def process_for_gradio(image, url, model_name):
|
| 272 |
+
try:
|
| 273 |
+
if image is None and not url:
|
| 274 |
+
return None, None, None, None, "Please provide an image or URL"
|
| 275 |
+
if image and url:
|
| 276 |
+
return None, None, None, None, "Please provide either an image or URL, not both"
|
| 277 |
+
|
| 278 |
+
if url:
|
| 279 |
+
response = requests.get(url, timeout=10)
|
| 280 |
+
response.raise_for_status()
|
| 281 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 282 |
+
|
| 283 |
+
detected_image, objects, scores, unique_objects, unique_scores, properties = process(image, model_name)
|
| 284 |
+
objects_df = pd.DataFrame({
|
| 285 |
+
"Object": objects,
|
| 286 |
+
"Confidence Score": [f"{score:.2f}" for score in scores]
|
| 287 |
+
}) if objects else pd.DataFrame(columns=["Object", "Confidence Score"])
|
| 288 |
+
unique_objects_df = pd.DataFrame({
|
| 289 |
+
"Unique Object": unique_objects,
|
| 290 |
+
"Confidence Score": [f"{score:.2f}" for score in unique_scores]
|
| 291 |
+
}) if unique_objects else pd.DataFrame(columns=["Unique Object", "Confidence Score"])
|
| 292 |
+
properties_df = pd.DataFrame([properties]) if properties else pd.DataFrame(columns=properties.keys())
|
| 293 |
+
return detected_image, objects_df, unique_objects_df, properties_df, ""
|
| 294 |
+
except Exception as e:
|
| 295 |
+
error_msg = f"Error processing image: {str(e)}"
|
| 296 |
+
logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
| 297 |
+
return None, None, None, None, error_msg
|
| 298 |
+
|
| 299 |
+
submit_btn.click(
|
| 300 |
+
fn=process_for_gradio,
|
| 301 |
+
inputs=[image_input, image_url_input, model_choice],
|
| 302 |
+
outputs=[output_image, objects_output, unique_objects_output, properties_output, error_output]
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
clear_btn.click(
|
| 306 |
+
fn=lambda: [None, "", None, None, None, None],
|
| 307 |
+
inputs=None,
|
| 308 |
+
outputs=[image_input, image_url_input, output_image, objects_output, unique_objects_output, properties_output, error_output]
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
with gr.Tab("🔗 URL Input"):
|
| 312 |
+
gr.Markdown("### Process Image from URL")
|
| 313 |
+
image_url_input = gr.Textbox(
|
| 314 |
+
label="🔗 Image URL",
|
| 315 |
+
placeholder="https://example.com/image.jpg"
|
| 316 |
+
)
|
| 317 |
+
url_model_choice = gr.Dropdown(
|
| 318 |
+
choices=VALID_MODELS,
|
| 319 |
+
value=VALID_MODELS[0],
|
| 320 |
+
label="🔎 Select Model"
|
| 321 |
+
)
|
| 322 |
+
url_model_info = gr.Markdown(
|
| 323 |
+
f"**Model Info**: {MODEL_DESCRIPTIONS[VALID_MODELS[0]]}",
|
| 324 |
+
visible=True
|
| 325 |
+
)
|
| 326 |
+
url_submit_btn = gr.Button("🔄 Process URL", variant="primary")
|
| 327 |
+
url_output = gr.JSON(label="API Response")
|
| 328 |
+
|
| 329 |
+
url_model_choice.change(
|
| 330 |
+
fn=lambda model_name: f"**Model Info**: {MODEL_DESCRIPTIONS.get(model_name, 'No description available.')}",
|
| 331 |
+
inputs=url_model_choice,
|
| 332 |
+
outputs=url_model_info
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
def process_url_for_gradio(url, model_name):
|
| 336 |
+
try:
|
| 337 |
+
response = requests.get(url, timeout=10)
|
| 338 |
+
response.raise_for_status()
|
| 339 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 340 |
+
detected_image, objects, scores, unique_objects, unique_scores, _ = process(image, model_name)
|
| 341 |
+
buffered = BytesIO()
|
| 342 |
+
detected_image.save(buffered, format="PNG")
|
| 343 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 344 |
+
return {
|
| 345 |
+
"image_url": f"data:image/png;base64,{img_base64}",
|
| 346 |
+
"detected_objects": objects,
|
| 347 |
+
"confidence_scores": scores,
|
| 348 |
+
"unique_objects": unique_objects,
|
| 349 |
+
"unique_confidence_scores": unique_scores
|
| 350 |
+
}
|
| 351 |
+
except Exception as e:
|
| 352 |
+
error_msg = f"Error processing URL: {str(e)}"
|
| 353 |
+
logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
| 354 |
+
return {"error": error_msg}
|
| 355 |
+
|
| 356 |
+
url_submit_btn.click(
|
| 357 |
+
fn=process_url_for_gradio,
|
| 358 |
+
inputs=[image_url_input, url_model_choice],
|
| 359 |
+
outputs=[url_output]
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
with gr.Tab("ℹ️ Help"):
|
| 363 |
+
gr.Markdown(
|
| 364 |
+
"""
|
| 365 |
+
## How to Use
|
| 366 |
+
- **Image Upload**: Select a model, upload an image or provide a URL, and click "Detect" to see detected objects and image properties.
|
| 367 |
+
- **URL Input**: Enter an image URL, select a model, and click "Process URL" to get results in JSON format.
|
| 368 |
+
- **Models**: Choose from DETR (object detection or panoptic segmentation) or YOLOS (lightweight detection).
|
| 369 |
+
- **Clear**: Reset all inputs and outputs using the "Clear" button.
|
| 370 |
+
- **Errors**: Check the error box for any processing issues.
|
| 371 |
+
|
| 372 |
+
## Tips
|
| 373 |
+
- Use high-quality images for better detection results.
|
| 374 |
+
- Panoptic models (e.g., DETR-ResNet-50-panoptic) provide segmentation masks for complex scenes.
|
| 375 |
+
- For faster processing, try YOLOS-Tiny on resource-constrained devices.
|
| 376 |
+
"""
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
return demo
|
| 380 |
+
|
| 381 |
+
if __name__ == "__main__":
|
| 382 |
+
demo = create_gradio_ui()
|
| 383 |
+
demo.launch()
|
| 384 |
+
# To run FastAPI, use: uvicorn object_detection:app --host 0.0.0.0 --port 8000
|
hf_space/hf_space/.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
hf_space/hf_space/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: ObjectDetection
|
| 3 |
+
emoji: 🦀
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.29.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
hf_space/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
torch
|
| 3 |
+
tensorflow
|
| 4 |
+
gradio
|
| 5 |
+
pillow
|
| 6 |
+
timm
|
| 7 |
+
fastapi
|
| 8 |
+
requests
|