Spaces:
Sleeping
Sleeping
File size: 14,406 Bytes
d725335 114ea19 d725335 114ea19 d725335 8536e24 f005306 d725335 20905e1 114ea19 d725335 20905e1 d725335 114ea19 d725335 20905e1 d725335 114ea19 d725335 20905e1 d725335 20905e1 d725335 f005306 d725335 20905e1 114ea19 d725335 20905e1 114ea19 8536e24 114ea19 20905e1 8536e24 114ea19 20905e1 114ea19 20905e1 d725335 114ea19 d725335 114ea19 d725335 f005306 d725335 20905e1 d725335 20905e1 d725335 20905e1 d725335 20905e1 d725335 20905e1 d725335 20905e1 114ea19 d725335 20905e1 d725335 114ea19 d725335 114ea19 d725335 20905e1 d725335 20905e1 d725335 20905e1 d725335 20905e1 d725335 8536e24 d725335 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 | from __future__ import annotations
import hashlib
import logging
import shutil
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Callable
from uuid import uuid4
from .detector import Detector, UltralyticsYOLOEDetector, parse_class_prompt, suppress_duplicate_detections
from .models import ActionEvent, Detection, FrameSample, VideoProcessResult
ProgressCallback = Callable[[int, int | None], None]
MP4_CODEC = "mp4v"
LOGGER = logging.getLogger(__name__)
def process_video(
*,
video_path: str,
class_prompt: str | list[str],
confidence: float = 0.25,
frame_stride: int = 5,
sample_interval_sec: float | None = None,
max_frames: int = 120,
model_name: str = "yoloe-26s-seg.pt",
image_size: int | None = None,
device: str | None = None,
max_detections: int | None = None,
tracking_enabled: bool = False,
detector: Detector | None = None,
output_dir: str | None = None,
progress: ProgressCallback | None = None,
) -> VideoProcessResult:
"""Sample a video, run open-vocabulary detection, and write an annotated clip."""
try:
import cv2
except ImportError as exc: # pragma: no cover - optional heavy dependency
raise RuntimeError("Install opencv-python-headless to process videos.") from exc
classes = parse_class_prompt(class_prompt)
if not classes:
raise ValueError("At least one class prompt is required.")
if frame_stride < 1:
raise ValueError("frame_stride must be at least 1.")
if sample_interval_sec is not None and sample_interval_sec <= 0:
raise ValueError("sample_interval_sec must be greater than 0.")
if max_frames < 1:
raise ValueError("max_frames must be at least 1.")
if image_size is not None and image_size < 32:
raise ValueError("image_size must be at least 32.")
if max_detections is not None and max_detections < 1:
raise ValueError("max_detections must be at least 1.")
if detector is None:
LOGGER.info(
"Loading detector model=%s classes=%s device=%s tracking=%s",
model_name,
", ".join(classes),
device or "auto",
tracking_enabled,
)
detector_started = time.perf_counter()
detector = UltralyticsYOLOEDetector(
class_names=classes,
model_name=model_name,
device=device or None,
tracking_enabled=tracking_enabled,
)
LOGGER.info("Detector loaded in %.2fs", time.perf_counter() - detector_started)
capture = cv2.VideoCapture(video_path)
if not capture.isOpened():
raise ValueError(f"Could not open video: {video_path}")
source_fps = float(capture.get(cv2.CAP_PROP_FPS) or 30.0)
effective_frame_stride = _sampling_frame_stride(
source_fps=source_fps,
frame_stride=frame_stride,
sample_interval_sec=sample_interval_sec,
)
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
output_fps = source_fps
output_size = _browser_frame_size(width, height)
output_path = _output_path(video_path, output_dir)
writer = _create_browser_mp4_writer(output_path, output_fps, output_size)
if writer is None:
capture.release()
raise ValueError(f"Could not create annotated video: {output_path}")
detections: list[Detection] = []
frames: list[FrameSample] = []
processed_frames = 0
frame_index = -1
latest_detections: list[Detection] = []
LOGGER.info(
"Processing video=%s fps=%.2f size=%sx%s sample_stride=%s max_frames=%s",
video_path,
source_fps,
width,
height,
effective_frame_stride,
max_frames,
)
try:
while True:
ok, frame = capture.read()
if not ok:
break
frame_index += 1
if frame_index % effective_frame_stride == 0:
if processed_frames >= max_frames:
break
timestamp_sec = frame_index / source_fps
frames.append(FrameSample(frame_index=frame_index, timestamp_sec=timestamp_sec))
LOGGER.info(
"Detecting sampled frame %s/%s source_frame=%s timestamp=%.2fs",
processed_frames + 1,
max_frames,
frame_index,
timestamp_sec,
)
detect_started = time.perf_counter()
frame_detections = detector.detect(
frame.copy(),
frame_index=frame_index,
timestamp_sec=timestamp_sec,
confidence=confidence,
image_size=image_size,
max_detections=max_detections,
)
frame_detections = suppress_duplicate_detections(frame_detections)
latest_detections = frame_detections
detections.extend(latest_detections)
processed_frames += 1
tracked_count = sum(1 for detection in latest_detections if detection.track_id is not None)
LOGGER.info(
"Detected sampled frame %s/%s in %.2fs: detections=%s tracked=%s",
processed_frames,
max_frames,
time.perf_counter() - detect_started,
len(latest_detections),
tracked_count,
)
if progress:
progress(processed_frames, max_frames)
_draw_detections(frame, latest_detections)
_write_frame(writer, _fit_frame_to_output(frame, output_size))
finally:
writer.release()
capture.release()
LOGGER.info("Finalizing annotated video %s", output_path)
_finalize_browser_mp4(output_path)
LOGGER.info(
"Finished video processing: sampled_frames=%s detections=%s output=%s",
processed_frames,
len(detections),
output_path,
)
return VideoProcessResult(
output_video_path=str(output_path),
classes=classes,
detections=detections,
frames=frames,
processed_frames=processed_frames,
source_fps=source_fps,
output_fps=output_fps,
frame_stride=effective_frame_stride,
sample_interval_sec=sample_interval_sec,
)
def render_automation_video(
*,
source_video_path: str,
detections: list[Detection],
events: list[ActionEvent],
frame_stride: int,
sample_interval_sec: float | None = None,
max_frames: int,
output_dir: str | None = None,
) -> str:
"""Render detections plus fired automation events without rerunning inference."""
try:
import cv2
except ImportError as exc: # pragma: no cover - optional heavy dependency
raise RuntimeError("Install opencv-python-headless to render videos.") from exc
if frame_stride < 1:
raise ValueError("frame_stride must be at least 1.")
if sample_interval_sec is not None and sample_interval_sec <= 0:
raise ValueError("sample_interval_sec must be greater than 0.")
if max_frames < 1:
raise ValueError("max_frames must be at least 1.")
capture = cv2.VideoCapture(source_video_path)
if not capture.isOpened():
raise ValueError(f"Could not open video: {source_video_path}")
source_fps = float(capture.get(cv2.CAP_PROP_FPS) or 30.0)
effective_frame_stride = _sampling_frame_stride(
source_fps=source_fps,
frame_stride=frame_stride,
sample_interval_sec=sample_interval_sec,
)
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
output_fps = source_fps
output_size = _browser_frame_size(width, height)
output_path = _output_path(source_video_path, output_dir, suffix="automated")
writer = _create_browser_mp4_writer(output_path, output_fps, output_size)
if writer is None:
capture.release()
raise ValueError(f"Could not create automation video: {output_path}")
detections_by_frame = _group_detections_by_frame(detections)
events_by_frame = _group_events_by_frame(events)
processed_frames = 0
frame_index = -1
latest_detections: list[Detection] = []
latest_events: list[ActionEvent] = []
LOGGER.info(
"Rendering automation video=%s fps=%.2f sample_stride=%s max_frames=%s",
source_video_path,
source_fps,
effective_frame_stride,
max_frames,
)
try:
while True:
ok, frame = capture.read()
if not ok:
break
frame_index += 1
if frame_index % effective_frame_stride == 0:
if processed_frames >= max_frames:
break
latest_detections = detections_by_frame.get(frame_index, [])
latest_events = events_by_frame.get(frame_index, [])
processed_frames += 1
_draw_detections(frame, latest_detections)
if latest_events:
_draw_action_events(frame, latest_events)
_write_frame(writer, _fit_frame_to_output(frame, output_size))
finally:
writer.release()
capture.release()
LOGGER.info("Finalizing automation video %s", output_path)
_finalize_browser_mp4(output_path)
LOGGER.info("Finished automation render: output=%s", output_path)
return str(output_path)
def _output_path(video_path: str, output_dir: str | None, *, suffix: str = "annotated") -> Path:
base_dir = Path(output_dir) if output_dir else Path(tempfile.gettempdir()) / "tiny-trigger"
base_dir.mkdir(parents=True, exist_ok=True)
return base_dir / f"{Path(video_path).stem}-{uuid4().hex[:8]}-{suffix}.mp4"
def _sampling_frame_stride(
*,
source_fps: float,
frame_stride: int,
sample_interval_sec: float | None,
) -> int:
if sample_interval_sec is None:
return frame_stride
return max(1, round(source_fps * sample_interval_sec))
def _browser_frame_size(width: int, height: int) -> tuple[int, int]:
output_width = width - (width % 2)
output_height = height - (height % 2)
if output_width < 2 or output_height < 2:
raise ValueError("Video dimensions are too small to render.")
return (output_width, output_height)
def _create_browser_mp4_writer(output_path: Path, fps: float, frame_size: tuple[int, int]):
import cv2
writer = cv2.VideoWriter(str(output_path), cv2.VideoWriter_fourcc(*MP4_CODEC), fps, frame_size)
if writer.isOpened():
return writer
writer.release()
return None
def _finalize_browser_mp4(output_path: Path) -> None:
ffmpeg_executable = _ffmpeg_executable()
if not ffmpeg_executable or not output_path.exists():
return
faststart_path = output_path.with_name(f"{output_path.stem}-faststart-{uuid4().hex[:8]}{output_path.suffix}")
try:
subprocess.run(
[
ffmpeg_executable,
"-y",
"-loglevel",
"error",
"-i",
str(output_path),
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-preset",
"veryfast",
"-movflags",
"+faststart",
str(faststart_path),
],
check=True,
capture_output=True,
)
if faststart_path.exists() and faststart_path.stat().st_size > 0:
faststart_path.replace(output_path)
except (OSError, subprocess.CalledProcessError):
if faststart_path.exists():
faststart_path.unlink()
def _ffmpeg_executable() -> str | None:
if ffmpeg_path := shutil.which("ffmpeg"):
return ffmpeg_path
try:
import imageio_ffmpeg
except ImportError:
return None
return imageio_ffmpeg.get_ffmpeg_exe()
def _fit_frame_to_output(frame, output_size: tuple[int, int]):
output_width, output_height = output_size
height, width = frame.shape[:2]
if width == output_width and height == output_height:
return frame
return frame[:output_height, :output_width]
def _write_frame(writer, frame) -> None:
writer.write(frame)
def _draw_detections(frame, detections: list[Detection]) -> None:
import cv2
for detection in detections:
x1, y1, x2, y2 = [int(value) for value in detection.bbox_xyxy]
color = _color_for_label(detection.label)
track = f" #{detection.track_id}" if detection.track_id is not None else ""
label = f"{detection.label}{track} {detection.confidence:.2f}"
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
text_y = max(18, y1 - 8)
cv2.putText(frame, label, (x1, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2, cv2.LINE_AA)
def _draw_action_events(frame, events: list[ActionEvent]) -> None:
import cv2
height, width = frame.shape[:2]
banner_height = min(110, max(70, height // 9))
overlay = frame.copy()
cv2.rectangle(overlay, (0, 0), (width, banner_height), (0, 96, 255), -1)
cv2.addWeighted(overlay, 0.78, frame, 0.22, 0, frame)
cv2.putText(frame, "FIRED", (24, 44), cv2.FONT_HERSHEY_SIMPLEX, 1.15, (255, 255, 255), 3, cv2.LINE_AA)
details = " | ".join(f"{event.rule}: {event.action}" for event in events[:3])
cv2.putText(frame, details, (24, banner_height - 18), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 2, cv2.LINE_AA)
def _color_for_label(label: str) -> tuple[int, int, int]:
digest = hashlib.md5(label.encode("utf-8")).digest()
return (int(digest[0]), int(digest[1]), int(digest[2]))
def _group_detections_by_frame(detections: list[Detection]) -> dict[int, list[Detection]]:
grouped: dict[int, list[Detection]] = {}
for detection in detections:
grouped.setdefault(detection.frame_index, []).append(detection)
return grouped
def _group_events_by_frame(events: list[ActionEvent]) -> dict[int, list[ActionEvent]]:
grouped: dict[int, list[ActionEvent]] = {}
for event in events:
grouped.setdefault(event.frame_index, []).append(event)
return grouped
|