Spaces:
Build error
Build error
Batched vidoe processing + supervision
Browse files- app.py +180 -203
- image.jpg → examples/images/crossroad.jpg +0 -0
- video.mp4 → examples/videos/break_dance.mp4 +0 -0
- examples/videos/fast_and_furious.mp4 +3 -0
- examples/videos/traffic.mp4 +3 -0
- packages.txt +1 -0
- requirements.txt +5 -2
app.py
CHANGED
|
@@ -1,19 +1,27 @@
|
|
| 1 |
-
import logging
|
| 2 |
import os
|
| 3 |
-
|
| 4 |
-
|
| 5 |
import shutil
|
| 6 |
import tempfile
|
| 7 |
-
import
|
| 8 |
-
import
|
|
|
|
|
|
|
|
|
|
| 9 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from PIL import Image
|
| 11 |
-
from transformers import
|
| 12 |
from transformers.image_utils import load_image
|
| 13 |
-
|
| 14 |
|
| 15 |
# Configuration constants
|
| 16 |
CHECKPOINTS = [
|
|
|
|
| 17 |
"ustc-community/dfine_m_obj365",
|
| 18 |
"ustc-community/dfine_n_coco",
|
| 19 |
"ustc-community/dfine_s_coco",
|
|
@@ -24,15 +32,17 @@ CHECKPOINTS = [
|
|
| 24 |
"ustc-community/dfine_l_obj365",
|
| 25 |
"ustc-community/dfine_x_obj365",
|
| 26 |
"ustc-community/dfine_s_obj2coco",
|
| 27 |
-
"ustc-community/dfine_m_obj2coco",
|
| 28 |
"ustc-community/dfine_l_obj2coco_e25",
|
| 29 |
"ustc-community/dfine_x_obj2coco",
|
| 30 |
]
|
| 31 |
-
MAX_NUM_FRAMES = 300
|
| 32 |
DEFAULT_CHECKPOINT = CHECKPOINTS[0]
|
| 33 |
DEFAULT_CONFIDENCE_THRESHOLD = 0.3
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
IMAGE_EXAMPLES = [
|
| 35 |
-
{"path": "./
|
| 36 |
{
|
| 37 |
"path": None,
|
| 38 |
"use_url": True,
|
|
@@ -40,216 +50,195 @@ IMAGE_EXAMPLES = [
|
|
| 40 |
"label": "Flickr Image",
|
| 41 |
},
|
| 42 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
VIDEO_EXAMPLES = [
|
| 44 |
-
{"path": "./
|
|
|
|
|
|
|
| 45 |
]
|
| 46 |
-
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov"}
|
| 47 |
|
| 48 |
logging.basicConfig(
|
| 49 |
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 50 |
)
|
| 51 |
logger = logging.getLogger(__name__)
|
| 52 |
|
| 53 |
-
VIDEO_OUTPUT_DIR = Path("static/videos")
|
| 54 |
-
VIDEO_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
|
|
|
| 57 |
def detect_objects(
|
| 58 |
-
image: Optional[Image.Image],
|
| 59 |
checkpoint: str,
|
|
|
|
| 60 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
) -> Tuple[
|
| 64 |
-
Optional[Tuple[Image.Image, List[Tuple[Tuple[int, int, int, int], str]]]],
|
| 65 |
-
gr.Markdown,
|
| 66 |
-
]:
|
| 67 |
-
if use_url and url:
|
| 68 |
-
try:
|
| 69 |
-
input_image = load_image(url)
|
| 70 |
-
except Exception as e:
|
| 71 |
-
logger.error(f"Failed to load image from URL {url}: {str(e)}")
|
| 72 |
-
return None, gr.Markdown(
|
| 73 |
-
f"**Error**: Failed to load image from URL: {str(e)}", visible=True
|
| 74 |
-
)
|
| 75 |
-
elif image is not None:
|
| 76 |
-
if not isinstance(image, Image.Image):
|
| 77 |
-
logger.error("Input image is not a PIL Image")
|
| 78 |
-
return None, gr.Markdown("**Error**: Invalid image format.", visible=True)
|
| 79 |
-
input_image = image
|
| 80 |
-
else:
|
| 81 |
-
return None, gr.Markdown(
|
| 82 |
-
"**Error**: Please provide an image or URL.", visible=True
|
| 83 |
-
)
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
"object-detection",
|
| 88 |
-
model=checkpoint,
|
| 89 |
-
image_processor=checkpoint,
|
| 90 |
-
device="cpu",
|
| 91 |
-
)
|
| 92 |
-
except Exception as e:
|
| 93 |
-
logger.error(f"Failed to initialize model pipeline for {checkpoint}: {str(e)}")
|
| 94 |
-
return None, gr.Markdown(
|
| 95 |
-
f"**Error**: Failed to load model: {str(e)}", visible=True
|
| 96 |
-
)
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
if score < confidence_threshold:
|
| 105 |
-
continue
|
| 106 |
-
label = f"{result['label']} ({score:.2f})"
|
| 107 |
-
box = result["box"]
|
| 108 |
-
# Validate and convert box to (xmin, ymin, xmax, ymax)
|
| 109 |
-
bbox_xmin = max(0, int(box["xmin"]))
|
| 110 |
-
bbox_ymin = max(0, int(box["ymin"]))
|
| 111 |
-
bbox_xmax = min(img_width, int(box["xmax"]))
|
| 112 |
-
bbox_ymax = min(img_height, int(box["ymax"]))
|
| 113 |
-
if bbox_xmax <= bbox_xmin or bbox_ymax <= bbox_ymin:
|
| 114 |
-
continue
|
| 115 |
-
bounding_box = (bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax)
|
| 116 |
-
annotations.append((bounding_box, label))
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
visible=True,
|
| 122 |
-
)
|
| 123 |
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
|
| 127 |
-
def
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
(xmin, ymin - text_size[1] - 4),
|
| 139 |
-
(xmin + text_size[0], ymin),
|
| 140 |
-
(255, 255, 255),
|
| 141 |
-
-1,
|
| 142 |
-
)
|
| 143 |
-
cv2.putText(
|
| 144 |
-
image_bgr,
|
| 145 |
-
label,
|
| 146 |
-
(xmin, ymin - 4),
|
| 147 |
-
cv2.FONT_HERSHEY_SIMPLEX,
|
| 148 |
-
0.5,
|
| 149 |
-
(0, 0, 0),
|
| 150 |
-
1,
|
| 151 |
-
)
|
| 152 |
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
def process_video(
|
| 157 |
video_path: str,
|
| 158 |
checkpoint: str,
|
| 159 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
| 160 |
progress: gr.Progress = gr.Progress(track_tqdm=True),
|
| 161 |
-
) ->
|
|
|
|
| 162 |
if not video_path or not os.path.isfile(video_path):
|
| 163 |
-
|
| 164 |
-
return None, gr.Markdown(
|
| 165 |
-
"**Error**: Please provide a valid video file.", visible=True
|
| 166 |
-
)
|
| 167 |
|
| 168 |
ext = os.path.splitext(video_path)[1].lower()
|
| 169 |
if ext not in ALLOWED_VIDEO_EXTENSIONS:
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 186 |
-
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 187 |
-
|
| 188 |
-
# Use H.264 codec for browser compatibility
|
| 189 |
-
# fourcc = cv2.VideoWriter_fourcc(*"H264")
|
| 190 |
-
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 191 |
-
temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
|
| 192 |
-
writer = cv2.VideoWriter(temp_file.name, fourcc, fps, (width, height))
|
| 193 |
-
if not writer.isOpened():
|
| 194 |
-
logger.error("Failed to initialize video writer")
|
| 195 |
-
cap.release()
|
| 196 |
-
temp_file.close()
|
| 197 |
-
os.unlink(temp_file.name)
|
| 198 |
-
return None, gr.Markdown(
|
| 199 |
-
"**Error**: Failed to initialize video writer.", visible=True
|
| 200 |
-
)
|
| 201 |
|
| 202 |
-
|
| 203 |
-
for _ in tqdm.tqdm(
|
| 204 |
-
range(min(MAX_NUM_FRAMES, num_frames)), desc="Processing video"
|
| 205 |
-
):
|
| 206 |
-
ok, frame = cap.read()
|
| 207 |
-
if not ok:
|
| 208 |
-
break
|
| 209 |
-
rgb_frame = frame[:, :, ::-1] # BGR to RGB
|
| 210 |
-
pil_image = Image.fromarray(rgb_frame)
|
| 211 |
-
(annotated_image, annotations), _ = detect_objects(
|
| 212 |
-
pil_image, checkpoint, confidence_threshold, use_url=False, url=""
|
| 213 |
-
)
|
| 214 |
-
if annotated_image is None:
|
| 215 |
-
continue
|
| 216 |
-
annotated_frame = annotate_frame(annotated_image, annotations)
|
| 217 |
-
writer.write(annotated_frame)
|
| 218 |
-
frame_count += 1
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
|
|
|
| 222 |
|
| 223 |
-
if
|
| 224 |
-
|
| 225 |
-
temp_file.close()
|
| 226 |
-
os.unlink(temp_file.name)
|
| 227 |
-
return None, gr.Markdown(
|
| 228 |
-
"**Warning**: No valid frames processed. Try a different video or threshold.",
|
| 229 |
-
visible=True,
|
| 230 |
-
)
|
| 231 |
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
logger.info(f"Video saved to {output_path}")
|
| 240 |
-
|
| 241 |
-
return str(output_path), gr.Markdown(visible=False)
|
| 242 |
-
|
| 243 |
-
except Exception as e:
|
| 244 |
-
logger.error(f"Video processing failed: {str(e)}")
|
| 245 |
-
if "temp_file" in locals():
|
| 246 |
-
temp_file.close()
|
| 247 |
-
if os.path.exists(temp_file.name):
|
| 248 |
-
os.unlink(temp_file.name)
|
| 249 |
-
return None, gr.Markdown(
|
| 250 |
-
f"**Error**: Video processing failed: {str(e)}", visible=True
|
| 251 |
)
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
def create_image_inputs() -> List[gr.components.Component]:
|
| 255 |
return [
|
|
@@ -340,7 +329,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 340 |
image_input,
|
| 341 |
use_url,
|
| 342 |
url_input,
|
| 343 |
-
|
| 344 |
image_confidence_threshold,
|
| 345 |
) = create_image_inputs()
|
| 346 |
image_detect_button, image_clear_button = create_button_row(
|
|
@@ -353,10 +342,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 353 |
color_map=None,
|
| 354 |
elem_classes="output-component",
|
| 355 |
)
|
| 356 |
-
image_error_message = gr.Markdown(
|
| 357 |
-
visible=False, elem_classes="error-text"
|
| 358 |
-
)
|
| 359 |
-
|
| 360 |
gr.Examples(
|
| 361 |
examples=[
|
| 362 |
[
|
|
@@ -372,18 +357,18 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 372 |
image_input,
|
| 373 |
use_url,
|
| 374 |
url_input,
|
| 375 |
-
|
| 376 |
image_confidence_threshold,
|
| 377 |
],
|
| 378 |
-
outputs=[image_output
|
| 379 |
-
fn=
|
| 380 |
cache_examples=False,
|
| 381 |
label="Select an image example to populate inputs",
|
| 382 |
)
|
| 383 |
|
| 384 |
with gr.Tab("Video"):
|
| 385 |
gr.Markdown(
|
| 386 |
-
f"The input video will be
|
| 387 |
)
|
| 388 |
with gr.Row():
|
| 389 |
with gr.Column(scale=1, min_width=300):
|
|
@@ -400,9 +385,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 400 |
format="mp4", # Explicit MP4 format
|
| 401 |
elem_classes="output-component",
|
| 402 |
)
|
| 403 |
-
video_error_message = gr.Markdown(
|
| 404 |
-
visible=False, elem_classes="error-text"
|
| 405 |
-
)
|
| 406 |
|
| 407 |
gr.Examples(
|
| 408 |
examples=[
|
|
@@ -410,7 +392,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 410 |
for example in VIDEO_EXAMPLES
|
| 411 |
],
|
| 412 |
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
| 413 |
-
outputs=[video_output
|
| 414 |
fn=process_video,
|
| 415 |
cache_examples=False,
|
| 416 |
label="Select a video example to populate inputs",
|
|
@@ -432,16 +414,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 432 |
DEFAULT_CHECKPOINT,
|
| 433 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
| 434 |
None,
|
| 435 |
-
gr.Markdown(visible=False),
|
| 436 |
),
|
| 437 |
outputs=[
|
| 438 |
image_input,
|
| 439 |
use_url,
|
| 440 |
url_input,
|
| 441 |
-
|
| 442 |
image_confidence_threshold,
|
| 443 |
image_output,
|
| 444 |
-
image_error_message,
|
| 445 |
],
|
| 446 |
)
|
| 447 |
|
|
@@ -452,35 +432,32 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 452 |
DEFAULT_CHECKPOINT,
|
| 453 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
| 454 |
None,
|
| 455 |
-
gr.Markdown(visible=False),
|
| 456 |
),
|
| 457 |
outputs=[
|
| 458 |
video_input,
|
| 459 |
video_checkpoint,
|
| 460 |
video_confidence_threshold,
|
| 461 |
video_output,
|
| 462 |
-
video_error_message,
|
| 463 |
],
|
| 464 |
)
|
| 465 |
|
| 466 |
# Image detect button
|
| 467 |
image_detect_button.click(
|
| 468 |
-
fn=
|
| 469 |
inputs=[
|
|
|
|
| 470 |
image_input,
|
| 471 |
-
image_checkpoint,
|
| 472 |
-
image_confidence_threshold,
|
| 473 |
-
use_url,
|
| 474 |
url_input,
|
|
|
|
| 475 |
],
|
| 476 |
-
outputs=[image_output
|
| 477 |
)
|
| 478 |
|
| 479 |
# Video detect button
|
| 480 |
video_detect_button.click(
|
| 481 |
fn=process_video,
|
| 482 |
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
| 483 |
-
outputs=[video_output
|
| 484 |
)
|
| 485 |
|
| 486 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import tqdm
|
| 4 |
import shutil
|
| 5 |
import tempfile
|
| 6 |
+
import logging
|
| 7 |
+
import supervision as sv
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
import spaces
|
| 11 |
import gradio as gr
|
| 12 |
+
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from typing import List, Optional, Tuple
|
| 16 |
+
|
| 17 |
from PIL import Image
|
| 18 |
+
from transformers import AutoModelForObjectDetection, AutoImageProcessor
|
| 19 |
from transformers.image_utils import load_image
|
| 20 |
+
|
| 21 |
|
| 22 |
# Configuration constants
|
| 23 |
CHECKPOINTS = [
|
| 24 |
+
"ustc-community/dfine_m_obj2coco",
|
| 25 |
"ustc-community/dfine_m_obj365",
|
| 26 |
"ustc-community/dfine_n_coco",
|
| 27 |
"ustc-community/dfine_s_coco",
|
|
|
|
| 32 |
"ustc-community/dfine_l_obj365",
|
| 33 |
"ustc-community/dfine_x_obj365",
|
| 34 |
"ustc-community/dfine_s_obj2coco",
|
|
|
|
| 35 |
"ustc-community/dfine_l_obj2coco_e25",
|
| 36 |
"ustc-community/dfine_x_obj2coco",
|
| 37 |
]
|
|
|
|
| 38 |
DEFAULT_CHECKPOINT = CHECKPOINTS[0]
|
| 39 |
DEFAULT_CONFIDENCE_THRESHOLD = 0.3
|
| 40 |
+
|
| 41 |
+
TORCH_DTYPE = torch.float32
|
| 42 |
+
|
| 43 |
+
# Image
|
| 44 |
IMAGE_EXAMPLES = [
|
| 45 |
+
{"path": "./examples/images/crossroad.jpg", "use_url": False, "url": "", "label": "Local Image"},
|
| 46 |
{
|
| 47 |
"path": None,
|
| 48 |
"use_url": True,
|
|
|
|
| 50 |
"label": "Flickr Image",
|
| 51 |
},
|
| 52 |
]
|
| 53 |
+
|
| 54 |
+
# Video
|
| 55 |
+
MAX_NUM_FRAMES = 500
|
| 56 |
+
BATCH_SIZE = 4
|
| 57 |
+
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov"}
|
| 58 |
+
VIDEO_OUTPUT_DIR = Path("static/videos")
|
| 59 |
+
VIDEO_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 60 |
VIDEO_EXAMPLES = [
|
| 61 |
+
{"path": "./examples/videos/traffic.mp4", "label": "Local Video"},
|
| 62 |
+
{"path": "./examples/videos/fast_and_furious.mp4", "label": "Local Video"},
|
| 63 |
+
{"path": "./examples/videos/break_dance.mp4", "label": "Local Video"},
|
| 64 |
]
|
|
|
|
| 65 |
|
| 66 |
logging.basicConfig(
|
| 67 |
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 68 |
)
|
| 69 |
logger = logging.getLogger(__name__)
|
| 70 |
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
@lru_cache(maxsize=3)
|
| 73 |
+
def get_model_and_image_processor(checkpoint: str, device: str = "cpu"):
|
| 74 |
+
model = AutoModelForObjectDetection.from_pretrained(checkpoint, torch_dtype=TORCH_DTYPE).to(device)
|
| 75 |
+
image_processor = AutoImageProcessor.from_pretrained(checkpoint)
|
| 76 |
+
return model, image_processor
|
| 77 |
|
| 78 |
+
@spaces.GPU(duration=20)
|
| 79 |
def detect_objects(
|
|
|
|
| 80 |
checkpoint: str,
|
| 81 |
+
images: Optional[List[Image.Image]] = None,
|
| 82 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
| 83 |
+
target_sizes: Optional[List[Tuple[int, int]]] = None,
|
| 84 |
+
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 87 |
+
model, image_processor = get_model_and_image_processor(checkpoint, device=device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# preprocess images
|
| 90 |
+
inputs = image_processor(images=images, return_tensors="pt")
|
| 91 |
+
inputs = inputs.to(device).to(TORCH_DTYPE)
|
| 92 |
|
| 93 |
+
# forward pass
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
outputs = model(**inputs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# postprocess outputs
|
| 98 |
+
if not target_sizes:
|
| 99 |
+
target_sizes = [(image.height, image.width) for image in images]
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
results = image_processor.post_process_object_detection(
|
| 102 |
+
outputs, target_sizes=target_sizes, threshold=confidence_threshold
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
return results, model.config.id2label
|
| 106 |
|
| 107 |
|
| 108 |
+
def process_image(
|
| 109 |
+
checkpoint: str = DEFAULT_CHECKPOINT,
|
| 110 |
+
image: Optional[Image.Image] = None,
|
| 111 |
+
url: Optional[str] = None,
|
| 112 |
+
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
| 113 |
+
):
|
| 114 |
|
| 115 |
+
if (image is None) ^ bool(url):
|
| 116 |
+
raise ValueError(f"Either image or url must be provided, but not both.")
|
| 117 |
+
|
| 118 |
+
if url:
|
| 119 |
+
image = load_image(url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
results, id2label = detect_objects(
|
| 122 |
+
checkpoint=checkpoint,
|
| 123 |
+
images=[image],
|
| 124 |
+
confidence_threshold=confidence_threshold,
|
| 125 |
+
)
|
| 126 |
+
result = results[0] # first image in batch (we have batch size 1)
|
| 127 |
|
| 128 |
+
annotations = []
|
| 129 |
+
for label, score, box in zip(result["labels"], result["scores"], result["boxes"]):
|
| 130 |
+
text_label = id2label[label.item()]
|
| 131 |
+
formatted_label = f"{text_label} ({score:.2f})"
|
| 132 |
+
x_min, y_min, x_max, y_max = box.cpu().numpy().round().astype(int)
|
| 133 |
+
x_min = max(0, x_min)
|
| 134 |
+
y_min = max(0, y_min)
|
| 135 |
+
x_max = min(image.width - 1, x_max)
|
| 136 |
+
y_max = min(image.height - 1, y_max)
|
| 137 |
+
annotations.append(((x_min, y_min, x_max, y_max), formatted_label))
|
| 138 |
+
|
| 139 |
+
return (image, annotations)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_target_size(image_height, image_width, max_size: int):
|
| 143 |
+
if image_height < max_size and image_width < max_size:
|
| 144 |
+
return image_width, image_height
|
| 145 |
+
if image_height > image_width:
|
| 146 |
+
new_height = max_size
|
| 147 |
+
new_width = int(image_width * max_size / image_height)
|
| 148 |
+
else:
|
| 149 |
+
new_width = max_size
|
| 150 |
+
new_height = int(image_height * max_size / image_width)
|
| 151 |
+
return new_width, new_height
|
| 152 |
|
| 153 |
def process_video(
|
| 154 |
video_path: str,
|
| 155 |
checkpoint: str,
|
| 156 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
| 157 |
progress: gr.Progress = gr.Progress(track_tqdm=True),
|
| 158 |
+
) -> str:
|
| 159 |
+
|
| 160 |
if not video_path or not os.path.isfile(video_path):
|
| 161 |
+
raise ValueError(f"Invalid video path: {video_path}")
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
ext = os.path.splitext(video_path)[1].lower()
|
| 164 |
if ext not in ALLOWED_VIDEO_EXTENSIONS:
|
| 165 |
+
raise ValueError(f"Unsupported video format: {ext}, supported formats: {ALLOWED_VIDEO_EXTENSIONS}")
|
| 166 |
+
|
| 167 |
+
cap = cv2.VideoCapture(video_path)
|
| 168 |
+
if not cap.isOpened():
|
| 169 |
+
raise ValueError(f"Failed to open video: {video_path}")
|
| 170 |
+
|
| 171 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 172 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 173 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 174 |
+
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 175 |
+
|
| 176 |
+
process_each_frame = fps // 25
|
| 177 |
+
target_fps = fps / process_each_frame
|
| 178 |
+
target_width, target_height = get_target_size(height, width, 1080)
|
| 179 |
+
|
| 180 |
+
# Use H.264 codec for browser compatibility
|
| 181 |
+
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
|
| 182 |
+
temp_file = tempfile.NamedTemporaryFile(suffix=".avi", delete=False)
|
| 183 |
+
writer = cv2.VideoWriter(temp_file.name, fourcc, target_fps, (target_width, target_height))
|
| 184 |
+
|
| 185 |
+
box_annotator = sv.BoxAnnotator(thickness=1)
|
| 186 |
+
label_annotator = sv.LabelAnnotator(text_scale=0.5)
|
| 187 |
+
|
| 188 |
+
if not writer.isOpened():
|
| 189 |
+
cap.release()
|
| 190 |
+
temp_file.close()
|
| 191 |
+
os.unlink(temp_file.name)
|
| 192 |
+
raise ValueError("Failed to initialize video writer")
|
| 193 |
|
| 194 |
+
frames_to_process = int(min(MAX_NUM_FRAMES * process_each_frame, num_frames))
|
| 195 |
+
batch = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
for i in tqdm.tqdm(range(frames_to_process), desc="Processing video"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
ok, frame = cap.read()
|
| 200 |
+
if not ok:
|
| 201 |
+
break
|
| 202 |
|
| 203 |
+
if not i % process_each_frame == 0:
|
| 204 |
+
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
if len(batch) < BATCH_SIZE:
|
| 207 |
+
frame = frame[:, :, ::-1].copy() # BGR to RGB
|
| 208 |
+
batch.append(frame)
|
| 209 |
+
continue
|
| 210 |
|
| 211 |
+
results, id2label = detect_objects(
|
| 212 |
+
images=[Image.fromarray(frame) for frame in batch],
|
| 213 |
+
checkpoint=checkpoint,
|
| 214 |
+
confidence_threshold=confidence_threshold,
|
| 215 |
+
target_sizes=[(target_height, target_width)] * len(batch),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
)
|
| 217 |
|
| 218 |
+
for frame, result in zip(batch, results):
|
| 219 |
+
frame = cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_AREA)
|
| 220 |
+
detections = sv.Detections.from_transformers(result, id2label=id2label)
|
| 221 |
+
detections = detections.with_nms(threshold=0.95, class_agnostic=True)
|
| 222 |
+
annotated_frame = box_annotator.annotate(scene=frame, detections=detections)
|
| 223 |
+
annotated_frame = label_annotator.annotate(scene=annotated_frame, detections=detections)
|
| 224 |
+
writer.write(cv2.cvtColor(annotated_frame, cv2.COLOR_RGB2BGR))
|
| 225 |
+
|
| 226 |
+
batch = []
|
| 227 |
+
|
| 228 |
+
writer.release()
|
| 229 |
+
cap.release()
|
| 230 |
+
temp_file.close()
|
| 231 |
+
|
| 232 |
+
# Copy to persistent directory for Gradio access
|
| 233 |
+
output_filename = f"output_{os.path.basename(temp_file.name)}"
|
| 234 |
+
output_path = VIDEO_OUTPUT_DIR / output_filename
|
| 235 |
+
shutil.copy(temp_file.name, output_path)
|
| 236 |
+
os.unlink(temp_file.name) # Remove temporary file
|
| 237 |
+
logger.info(f"Video saved to {output_path}")
|
| 238 |
+
|
| 239 |
+
return str(output_path)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
|
| 243 |
def create_image_inputs() -> List[gr.components.Component]:
|
| 244 |
return [
|
|
|
|
| 329 |
image_input,
|
| 330 |
use_url,
|
| 331 |
url_input,
|
| 332 |
+
image_model_checkpoint,
|
| 333 |
image_confidence_threshold,
|
| 334 |
) = create_image_inputs()
|
| 335 |
image_detect_button, image_clear_button = create_button_row(
|
|
|
|
| 342 |
color_map=None,
|
| 343 |
elem_classes="output-component",
|
| 344 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
gr.Examples(
|
| 346 |
examples=[
|
| 347 |
[
|
|
|
|
| 357 |
image_input,
|
| 358 |
use_url,
|
| 359 |
url_input,
|
| 360 |
+
image_model_checkpoint,
|
| 361 |
image_confidence_threshold,
|
| 362 |
],
|
| 363 |
+
outputs=[image_output],
|
| 364 |
+
fn=process_image,
|
| 365 |
cache_examples=False,
|
| 366 |
label="Select an image example to populate inputs",
|
| 367 |
)
|
| 368 |
|
| 369 |
with gr.Tab("Video"):
|
| 370 |
gr.Markdown(
|
| 371 |
+
f"The input video will be processed in ~25 FPS (up to {MAX_NUM_FRAMES} frames in result)."
|
| 372 |
)
|
| 373 |
with gr.Row():
|
| 374 |
with gr.Column(scale=1, min_width=300):
|
|
|
|
| 385 |
format="mp4", # Explicit MP4 format
|
| 386 |
elem_classes="output-component",
|
| 387 |
)
|
|
|
|
|
|
|
|
|
|
| 388 |
|
| 389 |
gr.Examples(
|
| 390 |
examples=[
|
|
|
|
| 392 |
for example in VIDEO_EXAMPLES
|
| 393 |
],
|
| 394 |
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
| 395 |
+
outputs=[video_output],
|
| 396 |
fn=process_video,
|
| 397 |
cache_examples=False,
|
| 398 |
label="Select a video example to populate inputs",
|
|
|
|
| 414 |
DEFAULT_CHECKPOINT,
|
| 415 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
| 416 |
None,
|
|
|
|
| 417 |
),
|
| 418 |
outputs=[
|
| 419 |
image_input,
|
| 420 |
use_url,
|
| 421 |
url_input,
|
| 422 |
+
image_model_checkpoint,
|
| 423 |
image_confidence_threshold,
|
| 424 |
image_output,
|
|
|
|
| 425 |
],
|
| 426 |
)
|
| 427 |
|
|
|
|
| 432 |
DEFAULT_CHECKPOINT,
|
| 433 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
| 434 |
None,
|
|
|
|
| 435 |
),
|
| 436 |
outputs=[
|
| 437 |
video_input,
|
| 438 |
video_checkpoint,
|
| 439 |
video_confidence_threshold,
|
| 440 |
video_output,
|
|
|
|
| 441 |
],
|
| 442 |
)
|
| 443 |
|
| 444 |
# Image detect button
|
| 445 |
image_detect_button.click(
|
| 446 |
+
fn=process_image,
|
| 447 |
inputs=[
|
| 448 |
+
image_model_checkpoint,
|
| 449 |
image_input,
|
|
|
|
|
|
|
|
|
|
| 450 |
url_input,
|
| 451 |
+
image_confidence_threshold,
|
| 452 |
],
|
| 453 |
+
outputs=[image_output],
|
| 454 |
)
|
| 455 |
|
| 456 |
# Video detect button
|
| 457 |
video_detect_button.click(
|
| 458 |
fn=process_video,
|
| 459 |
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
| 460 |
+
outputs=[video_output],
|
| 461 |
)
|
| 462 |
|
| 463 |
if __name__ == "__main__":
|
image.jpg → examples/images/crossroad.jpg
RENAMED
|
File without changes
|
video.mp4 → examples/videos/break_dance.mp4
RENAMED
|
File without changes
|
examples/videos/fast_and_furious.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5980eada9d80c65b4da5b536427ccf8ff8ea2707ee3e4aa52fb2c4e1b1979dae
|
| 3 |
+
size 16872922
|
examples/videos/traffic.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71908c136bba6b50b9071fb2015553f651c91a7ee857924f33616c046011aaed
|
| 3 |
+
size 8591523
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
requirements.txt
CHANGED
|
@@ -2,6 +2,9 @@ gradio
|
|
| 2 |
transformers @ git+https://github.com/huggingface/transformers
|
| 3 |
torch
|
| 4 |
torchvision
|
| 5 |
-
opencv-python
|
|
|
|
| 6 |
tqdm
|
| 7 |
-
pillow
|
|
|
|
|
|
|
|
|
| 2 |
transformers @ git+https://github.com/huggingface/transformers
|
| 3 |
torch
|
| 4 |
torchvision
|
| 5 |
+
opencv-python-headless
|
| 6 |
+
ffmpeg-python
|
| 7 |
tqdm
|
| 8 |
+
pillow
|
| 9 |
+
supervision
|
| 10 |
+
spaces
|