Spaces:
Sleeping
Sleeping
Add segment selection auto ROI and stop button
Browse files
app.py
CHANGED
|
@@ -61,6 +61,7 @@ JOINT_COLOR = (255, 230, 120)
|
|
| 61 |
LINE_COLOR = (80, 220, 255)
|
| 62 |
TEXT_COLOR = (230, 240, 255)
|
| 63 |
UPLOAD_WAIT_SECONDS = 60
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
@lru_cache(maxsize=1)
|
|
@@ -112,6 +113,27 @@ def encode_browser_mp4(input_path: Path, output_path: Path, fps: float) -> Path:
|
|
| 112 |
return output_path if output_path.exists() and output_path.stat().st_size > 0 else input_path
|
| 113 |
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
def resolve_uploaded_video_path(video_input) -> Path | None:
|
| 116 |
if video_input is None:
|
| 117 |
return None
|
|
@@ -130,6 +152,61 @@ def resolve_uploaded_video_path(video_input) -> Path | None:
|
|
| 130 |
return Path(path) if path else None
|
| 131 |
|
| 132 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
def smooth_keypoints(buffer: list[np.ndarray], keypoints: np.ndarray, window_size: int) -> np.ndarray:
|
| 134 |
if window_size <= 1:
|
| 135 |
return keypoints
|
|
@@ -178,8 +255,67 @@ def draw_person(
|
|
| 178 |
)
|
| 179 |
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
def build_stickman_video(
|
| 182 |
video_path,
|
|
|
|
|
|
|
| 183 |
conf,
|
| 184 |
point_conf,
|
| 185 |
process_full_video,
|
|
@@ -190,7 +326,7 @@ def build_stickman_video(
|
|
| 190 |
upload_guard,
|
| 191 |
progress: gr.Progress = gr.Progress(track_tqdm=False),
|
| 192 |
):
|
| 193 |
-
source = resolve_uploaded_video_path(video_path)
|
| 194 |
if source is None:
|
| 195 |
if upload_guard == "uploading":
|
| 196 |
print("WAIT rowing-stickman upload_in_progress", flush=True)
|
|
@@ -218,6 +354,18 @@ def build_stickman_video(
|
|
| 218 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
|
| 219 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
|
| 220 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
frame_stride = max(1, int(frame_stride))
|
| 223 |
smoothing_window = max(1, int(smoothing_window))
|
|
@@ -233,7 +381,7 @@ def build_stickman_video(
|
|
| 233 |
raw_output_path = workdir / f"{source.stem}_stickman_raw.mp4"
|
| 234 |
output_path = workdir / f"{source.stem}_stickman.mp4"
|
| 235 |
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 236 |
-
writer = cv2.VideoWriter(str(raw_output_path), fourcc, output_fps, (
|
| 237 |
|
| 238 |
if not writer.isOpened():
|
| 239 |
cap.release()
|
|
@@ -250,7 +398,7 @@ def build_stickman_video(
|
|
| 250 |
"START rowing-stickman "
|
| 251 |
f"source={source.name} size={width}x{height} fps={fps:.2f} "
|
| 252 |
f"total_frames={total_frames} full={process_full_video} "
|
| 253 |
-
f"max_frames={max_frames} stride={frame_stride} smoothing_window={smoothing_window}",
|
| 254 |
flush=True,
|
| 255 |
)
|
| 256 |
|
|
@@ -263,8 +411,13 @@ def build_stickman_video(
|
|
| 263 |
read_count += 1
|
| 264 |
continue
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
person_count = 0
|
| 270 |
if result.keypoints is not None and len(result.keypoints) > 0:
|
|
@@ -314,7 +467,9 @@ def build_stickman_video(
|
|
| 314 |
summary = (
|
| 315 |
f"Done.\n"
|
| 316 |
f"- Source: {source.name}\n"
|
| 317 |
-
f"-
|
|
|
|
|
|
|
| 318 |
f"- Read frames: {read_count}\n"
|
| 319 |
f"- Output frames: {written_count}\n"
|
| 320 |
f"- Frames with detected person: {detected_person_frames}\n"
|
|
@@ -330,7 +485,7 @@ def build_stickman_video(
|
|
| 330 |
f"source={source.name} read_frames={read_count} output_frames={written_count} "
|
| 331 |
f"detected_frames={detected_person_frames} elapsed={elapsed:.2f}s "
|
| 332 |
f"full={process_full_video} stride={frame_stride} smoothing_window={smoothing_window} "
|
| 333 |
-
f"output={final_output_path.name} output_mb={output_size_mb:.1f}",
|
| 334 |
flush=True,
|
| 335 |
)
|
| 336 |
progress(1, desc="Finished.")
|
|
@@ -338,12 +493,14 @@ def build_stickman_video(
|
|
| 338 |
|
| 339 |
|
| 340 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), title="Rowing Stickman Demo") as demo:
|
|
|
|
|
|
|
|
|
|
| 341 |
gr.Markdown(
|
| 342 |
"""
|
| 343 |
# Rowing Stickman Video Demo
|
| 344 |
|
| 345 |
-
Upload a rowing video,
|
| 346 |
-
For the free CPU Space, start with a short clip or keep the default frame limit.
|
| 347 |
"""
|
| 348 |
)
|
| 349 |
|
|
@@ -355,6 +512,14 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), ti
|
|
| 355 |
format=None,
|
| 356 |
include_audio=False,
|
| 357 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
conf_input = gr.Slider(0.05, 0.90, value=0.30, step=0.05, label="YOLO detection confidence")
|
| 359 |
point_conf_input = gr.Slider(0.05, 0.90, value=0.25, step=0.05, label="Keypoint drawing confidence")
|
| 360 |
process_full_input = gr.Checkbox(value=True, label="Process full video")
|
|
@@ -369,16 +534,46 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), ti
|
|
| 369 |
smoothing_input = gr.Slider(1, 15, value=5, step=1, label="Moving average smoothing window")
|
| 370 |
line_width_input = gr.Slider(1, 8, value=3, step=1, label="Stickman line width")
|
| 371 |
upload_guard_input = gr.Textbox(value="empty", visible=False, container=False)
|
| 372 |
-
|
|
|
|
|
|
|
| 373 |
with gr.Column(scale=1):
|
| 374 |
video_output = gr.Video(label="Stickman playback", format="mp4", include_audio=False)
|
| 375 |
file_output = gr.File(label="Download MP4")
|
| 376 |
summary_output = gr.Textbox(label="Processing summary", lines=10)
|
| 377 |
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
fn=build_stickman_video,
|
| 380 |
inputs=[
|
| 381 |
video_input,
|
|
|
|
|
|
|
| 382 |
conf_input,
|
| 383 |
point_conf_input,
|
| 384 |
process_full_input,
|
|
@@ -392,18 +587,20 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), ti
|
|
| 392 |
show_progress="full",
|
| 393 |
api_name=False,
|
| 394 |
js="""
|
| 395 |
-
(video, conf, point_conf, process_full, max_frames, stride, smoothing, line_width, upload_guard) => {
|
| 396 |
const fileInputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
| 397 |
const hasSelectedFile = fileInputs.some((input) => input.files && input.files.length > 0);
|
| 398 |
let guard = "ready";
|
| 399 |
if (video === null || video === undefined) {
|
| 400 |
guard = hasSelectedFile ? "uploading" : "empty";
|
| 401 |
}
|
| 402 |
-
return [video, conf, point_conf, process_full, max_frames, stride, smoothing, line_width, guard];
|
| 403 |
}
|
| 404 |
""",
|
| 405 |
)
|
| 406 |
|
|
|
|
|
|
|
| 407 |
|
| 408 |
if __name__ == "__main__":
|
| 409 |
demo.queue(default_concurrency_limit=1).launch(
|
|
|
|
| 61 |
LINE_COLOR = (80, 220, 255)
|
| 62 |
TEXT_COLOR = (230, 240, 255)
|
| 63 |
UPLOAD_WAIT_SECONDS = 60
|
| 64 |
+
ROI_SAMPLE_FRAMES = 30
|
| 65 |
|
| 66 |
|
| 67 |
@lru_cache(maxsize=1)
|
|
|
|
| 113 |
return output_path if output_path.exists() and output_path.stat().st_size > 0 else input_path
|
| 114 |
|
| 115 |
|
| 116 |
+
def ffmpeg_clip(input_path: Path, output_path: Path, start_sec: float, end_sec: float | None) -> Path:
|
| 117 |
+
ffmpeg = shutil.which("ffmpeg")
|
| 118 |
+
if ffmpeg is None:
|
| 119 |
+
raise gr.Error("FFmpeg is required to create a monitored clip.")
|
| 120 |
+
|
| 121 |
+
cmd = [ffmpeg, "-y", "-ss", f"{max(0.0, start_sec):.3f}", "-i", str(input_path)]
|
| 122 |
+
if end_sec is not None and end_sec > start_sec:
|
| 123 |
+
cmd.extend(["-t", f"{end_sec - start_sec:.3f}"])
|
| 124 |
+
cmd.extend(["-an", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(output_path)])
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 128 |
+
except subprocess.CalledProcessError as exc:
|
| 129 |
+
print(f"FFmpeg clip failed. {exc.stderr[-1200:]}", flush=True)
|
| 130 |
+
raise gr.Error("Could not create the monitored clip. Please try a shorter segment.")
|
| 131 |
+
|
| 132 |
+
if not output_path.exists() or output_path.stat().st_size == 0:
|
| 133 |
+
raise gr.Error("The monitored clip was empty. Please check the start/end time.")
|
| 134 |
+
return output_path
|
| 135 |
+
|
| 136 |
+
|
| 137 |
def resolve_uploaded_video_path(video_input) -> Path | None:
|
| 138 |
if video_input is None:
|
| 139 |
return None
|
|
|
|
| 152 |
return Path(path) if path else None
|
| 153 |
|
| 154 |
|
| 155 |
+
def expand_roi(x1: int, y1: int, x2: int, y2: int, width: int, height: int, margin: float) -> tuple[int, int, int, int]:
|
| 156 |
+
box_w = x2 - x1
|
| 157 |
+
box_h = y2 - y1
|
| 158 |
+
pad_x = int(round(box_w * margin))
|
| 159 |
+
pad_y = int(round(box_h * margin))
|
| 160 |
+
return (
|
| 161 |
+
max(0, x1 - pad_x),
|
| 162 |
+
max(0, y1 - pad_y),
|
| 163 |
+
min(width, x2 + pad_x),
|
| 164 |
+
min(height, y2 + pad_y),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def estimate_auto_roi(video_path: Path, conf: float, margin: float, progress: gr.Progress) -> dict | None:
|
| 169 |
+
model = load_model()
|
| 170 |
+
cap = cv2.VideoCapture(str(video_path))
|
| 171 |
+
if not cap.isOpened():
|
| 172 |
+
return None
|
| 173 |
+
|
| 174 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 0
|
| 175 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 0
|
| 176 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
|
| 177 |
+
sample_stride = max(1, total_frames // ROI_SAMPLE_FRAMES) if total_frames else 1
|
| 178 |
+
|
| 179 |
+
boxes: list[np.ndarray] = []
|
| 180 |
+
read_count = 0
|
| 181 |
+
sampled = 0
|
| 182 |
+
while sampled < ROI_SAMPLE_FRAMES:
|
| 183 |
+
ok, frame = cap.read()
|
| 184 |
+
if not ok:
|
| 185 |
+
break
|
| 186 |
+
if read_count % sample_stride == 0:
|
| 187 |
+
progress(min(0.95, sampled / ROI_SAMPLE_FRAMES), desc=f"Estimating ROI {sampled + 1}/{ROI_SAMPLE_FRAMES}")
|
| 188 |
+
result = model.predict(frame, conf=conf, verbose=False, device=None)[0]
|
| 189 |
+
if result.boxes is not None and len(result.boxes) > 0:
|
| 190 |
+
xyxy = result.boxes.xyxy.cpu().numpy()
|
| 191 |
+
scores = result.boxes.conf.cpu().numpy()
|
| 192 |
+
boxes.append(xyxy[int(np.argmax(scores))])
|
| 193 |
+
sampled += 1
|
| 194 |
+
read_count += 1
|
| 195 |
+
|
| 196 |
+
cap.release()
|
| 197 |
+
if not boxes or width <= 0 or height <= 0:
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
union = np.array(boxes)
|
| 201 |
+
x1, y1 = np.floor(union[:, :2].min(axis=0)).astype(int)
|
| 202 |
+
x2, y2 = np.ceil(union[:, 2:].max(axis=0)).astype(int)
|
| 203 |
+
x1, y1, x2, y2 = expand_roi(x1, y1, x2, y2, width, height, margin)
|
| 204 |
+
if x2 <= x1 or y2 <= y1:
|
| 205 |
+
return None
|
| 206 |
+
|
| 207 |
+
return {"x1": x1, "y1": y1, "x2": x2, "y2": y2, "width": width, "height": height, "margin": margin}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
def smooth_keypoints(buffer: list[np.ndarray], keypoints: np.ndarray, window_size: int) -> np.ndarray:
|
| 211 |
if window_size <= 1:
|
| 212 |
return keypoints
|
|
|
|
| 255 |
)
|
| 256 |
|
| 257 |
|
| 258 |
+
def create_monitored_clip(
|
| 259 |
+
video_path,
|
| 260 |
+
start_sec,
|
| 261 |
+
end_sec,
|
| 262 |
+
conf,
|
| 263 |
+
roi_margin,
|
| 264 |
+
upload_guard,
|
| 265 |
+
progress: gr.Progress = gr.Progress(track_tqdm=False),
|
| 266 |
+
):
|
| 267 |
+
source = resolve_uploaded_video_path(video_path)
|
| 268 |
+
if source is None:
|
| 269 |
+
if upload_guard == "uploading":
|
| 270 |
+
print("WAIT rowing-clip upload_in_progress", flush=True)
|
| 271 |
+
for second in range(UPLOAD_WAIT_SECONDS):
|
| 272 |
+
progress(
|
| 273 |
+
second / UPLOAD_WAIT_SECONDS,
|
| 274 |
+
desc=f"Waiting for video upload to finish... {second + 1}/{UPLOAD_WAIT_SECONDS}s",
|
| 275 |
+
)
|
| 276 |
+
time.sleep(1)
|
| 277 |
+
raise gr.Error("The video is still uploading. Please wait until the upload preview appears, then create the clip again.")
|
| 278 |
+
|
| 279 |
+
print(f"ERROR rowing-clip missing_upload guard={upload_guard!r} value={video_path!r}", flush=True)
|
| 280 |
+
raise gr.Error("No video was uploaded. Please choose a video first.")
|
| 281 |
+
|
| 282 |
+
if not source.exists():
|
| 283 |
+
raise gr.Error(f"Video file not found: {source}")
|
| 284 |
+
|
| 285 |
+
start_sec = max(0.0, float(start_sec or 0.0))
|
| 286 |
+
end_sec = float(end_sec or 0.0)
|
| 287 |
+
end_value = end_sec if end_sec > start_sec else None
|
| 288 |
+
roi_margin = max(0.0, min(1.0, float(roi_margin)))
|
| 289 |
+
|
| 290 |
+
workdir = Path(tempfile.mkdtemp(prefix="rowing_clip_"))
|
| 291 |
+
clip_path = workdir / f"{source.stem}_monitored_clip.mp4"
|
| 292 |
+
|
| 293 |
+
progress(0, desc="Creating monitored clip...")
|
| 294 |
+
clip_path = ffmpeg_clip(source, clip_path, start_sec, end_value)
|
| 295 |
+
|
| 296 |
+
progress(0.05, desc="Estimating automatic ROI...")
|
| 297 |
+
roi = estimate_auto_roi(clip_path, float(conf), roi_margin, progress)
|
| 298 |
+
roi_text = f"{roi}" if roi else "not found, processing full frame"
|
| 299 |
+
summary = (
|
| 300 |
+
f"Clip ready.\n"
|
| 301 |
+
f"- Source: {source.name}\n"
|
| 302 |
+
f"- Start: {start_sec:.2f}s\n"
|
| 303 |
+
f"- End: {end_value:.2f}s\n" if end_value is not None else
|
| 304 |
+
f"Clip ready.\n"
|
| 305 |
+
f"- Source: {source.name}\n"
|
| 306 |
+
f"- Start: {start_sec:.2f}s\n"
|
| 307 |
+
f"- End: video end\n"
|
| 308 |
+
)
|
| 309 |
+
summary += f"- Auto ROI: {roi_text}"
|
| 310 |
+
print(f"CLIP rowing-stickman source={source.name} clip={clip_path.name} start={start_sec} end={end_value} roi={roi}", flush=True)
|
| 311 |
+
progress(1, desc="Clip and ROI ready.")
|
| 312 |
+
return str(clip_path), roi, str(clip_path), summary
|
| 313 |
+
|
| 314 |
+
|
| 315 |
def build_stickman_video(
|
| 316 |
video_path,
|
| 317 |
+
clip_path,
|
| 318 |
+
roi_state,
|
| 319 |
conf,
|
| 320 |
point_conf,
|
| 321 |
process_full_video,
|
|
|
|
| 326 |
upload_guard,
|
| 327 |
progress: gr.Progress = gr.Progress(track_tqdm=False),
|
| 328 |
):
|
| 329 |
+
source = Path(clip_path) if clip_path else resolve_uploaded_video_path(video_path)
|
| 330 |
if source is None:
|
| 331 |
if upload_guard == "uploading":
|
| 332 |
print("WAIT rowing-stickman upload_in_progress", flush=True)
|
|
|
|
| 354 |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
|
| 355 |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
|
| 356 |
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
|
| 357 |
+
roi = roi_state if isinstance(roi_state, dict) else None
|
| 358 |
+
if roi:
|
| 359 |
+
x1 = max(0, min(width - 1, int(roi["x1"])))
|
| 360 |
+
y1 = max(0, min(height - 1, int(roi["y1"])))
|
| 361 |
+
x2 = max(x1 + 1, min(width, int(roi["x2"])))
|
| 362 |
+
y2 = max(y1 + 1, min(height, int(roi["y2"])))
|
| 363 |
+
roi = {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
|
| 364 |
+
output_width = x2 - x1
|
| 365 |
+
output_height = y2 - y1
|
| 366 |
+
else:
|
| 367 |
+
output_width = width
|
| 368 |
+
output_height = height
|
| 369 |
|
| 370 |
frame_stride = max(1, int(frame_stride))
|
| 371 |
smoothing_window = max(1, int(smoothing_window))
|
|
|
|
| 381 |
raw_output_path = workdir / f"{source.stem}_stickman_raw.mp4"
|
| 382 |
output_path = workdir / f"{source.stem}_stickman.mp4"
|
| 383 |
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 384 |
+
writer = cv2.VideoWriter(str(raw_output_path), fourcc, output_fps, (output_width, output_height))
|
| 385 |
|
| 386 |
if not writer.isOpened():
|
| 387 |
cap.release()
|
|
|
|
| 398 |
"START rowing-stickman "
|
| 399 |
f"source={source.name} size={width}x{height} fps={fps:.2f} "
|
| 400 |
f"total_frames={total_frames} full={process_full_video} "
|
| 401 |
+
f"max_frames={max_frames} stride={frame_stride} smoothing_window={smoothing_window} roi={roi}",
|
| 402 |
flush=True,
|
| 403 |
)
|
| 404 |
|
|
|
|
| 411 |
read_count += 1
|
| 412 |
continue
|
| 413 |
|
| 414 |
+
if roi:
|
| 415 |
+
model_frame = frame[roi["y1"] : roi["y2"], roi["x1"] : roi["x2"]]
|
| 416 |
+
else:
|
| 417 |
+
model_frame = frame
|
| 418 |
+
|
| 419 |
+
result = model.predict(model_frame, conf=conf, verbose=False, device=None)[0]
|
| 420 |
+
canvas = np.zeros_like(model_frame)
|
| 421 |
|
| 422 |
person_count = 0
|
| 423 |
if result.keypoints is not None and len(result.keypoints) > 0:
|
|
|
|
| 467 |
summary = (
|
| 468 |
f"Done.\n"
|
| 469 |
f"- Source: {source.name}\n"
|
| 470 |
+
f"- Source resolution: {width}x{height}, FPS: {fps:.2f}\n"
|
| 471 |
+
f"- Processing resolution: {output_width}x{output_height}\n"
|
| 472 |
+
f"- Auto ROI: {roi if roi else 'off'}\n"
|
| 473 |
f"- Read frames: {read_count}\n"
|
| 474 |
f"- Output frames: {written_count}\n"
|
| 475 |
f"- Frames with detected person: {detected_person_frames}\n"
|
|
|
|
| 485 |
f"source={source.name} read_frames={read_count} output_frames={written_count} "
|
| 486 |
f"detected_frames={detected_person_frames} elapsed={elapsed:.2f}s "
|
| 487 |
f"full={process_full_video} stride={frame_stride} smoothing_window={smoothing_window} "
|
| 488 |
+
f"roi={roi} output={final_output_path.name} output_mb={output_size_mb:.1f}",
|
| 489 |
flush=True,
|
| 490 |
)
|
| 491 |
progress(1, desc="Finished.")
|
|
|
|
| 493 |
|
| 494 |
|
| 495 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), title="Rowing Stickman Demo") as demo:
|
| 496 |
+
clip_state = gr.State("")
|
| 497 |
+
roi_state = gr.State(None)
|
| 498 |
+
|
| 499 |
gr.Markdown(
|
| 500 |
"""
|
| 501 |
# Rowing Stickman Video Demo
|
| 502 |
|
| 503 |
+
Upload a rowing video, select the segment to monitor, then generate a YOLO11x stickman video.
|
|
|
|
| 504 |
"""
|
| 505 |
)
|
| 506 |
|
|
|
|
| 512 |
format=None,
|
| 513 |
include_audio=False,
|
| 514 |
)
|
| 515 |
+
gr.Markdown("### Please select the segment to monitor")
|
| 516 |
+
with gr.Row():
|
| 517 |
+
start_input = gr.Number(value=0, precision=2, label="Start time (seconds)")
|
| 518 |
+
end_input = gr.Number(value=0, precision=2, label="End time (0 = video end)")
|
| 519 |
+
roi_margin_input = gr.Slider(0.05, 0.80, value=0.25, step=0.05, label="Auto ROI margin")
|
| 520 |
+
create_clip_button = gr.Button("Create monitored clip and auto ROI")
|
| 521 |
+
clip_preview = gr.Video(label="Monitored clip preview", format="mp4", include_audio=False)
|
| 522 |
+
clip_summary = gr.Textbox(label="Clip and ROI summary", lines=5)
|
| 523 |
conf_input = gr.Slider(0.05, 0.90, value=0.30, step=0.05, label="YOLO detection confidence")
|
| 524 |
point_conf_input = gr.Slider(0.05, 0.90, value=0.25, step=0.05, label="Keypoint drawing confidence")
|
| 525 |
process_full_input = gr.Checkbox(value=True, label="Process full video")
|
|
|
|
| 534 |
smoothing_input = gr.Slider(1, 15, value=5, step=1, label="Moving average smoothing window")
|
| 535 |
line_width_input = gr.Slider(1, 8, value=3, step=1, label="Stickman line width")
|
| 536 |
upload_guard_input = gr.Textbox(value="empty", visible=False, container=False)
|
| 537 |
+
with gr.Row():
|
| 538 |
+
run_button = gr.Button("Process video", variant="primary")
|
| 539 |
+
stop_button = gr.Button("Stop processing", variant="stop")
|
| 540 |
with gr.Column(scale=1):
|
| 541 |
video_output = gr.Video(label="Stickman playback", format="mp4", include_audio=False)
|
| 542 |
file_output = gr.File(label="Download MP4")
|
| 543 |
summary_output = gr.Textbox(label="Processing summary", lines=10)
|
| 544 |
|
| 545 |
+
clip_event = create_clip_button.click(
|
| 546 |
+
fn=create_monitored_clip,
|
| 547 |
+
inputs=[
|
| 548 |
+
video_input,
|
| 549 |
+
start_input,
|
| 550 |
+
end_input,
|
| 551 |
+
conf_input,
|
| 552 |
+
roi_margin_input,
|
| 553 |
+
upload_guard_input,
|
| 554 |
+
],
|
| 555 |
+
outputs=[clip_state, roi_state, clip_preview, clip_summary],
|
| 556 |
+
show_progress="full",
|
| 557 |
+
api_name=False,
|
| 558 |
+
js="""
|
| 559 |
+
(video, start, end, conf, roi_margin, upload_guard) => {
|
| 560 |
+
const fileInputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
| 561 |
+
const hasSelectedFile = fileInputs.some((input) => input.files && input.files.length > 0);
|
| 562 |
+
let guard = "ready";
|
| 563 |
+
if (video === null || video === undefined) {
|
| 564 |
+
guard = hasSelectedFile ? "uploading" : "empty";
|
| 565 |
+
}
|
| 566 |
+
return [video, start, end, conf, roi_margin, guard];
|
| 567 |
+
}
|
| 568 |
+
""",
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
process_event = run_button.click(
|
| 572 |
fn=build_stickman_video,
|
| 573 |
inputs=[
|
| 574 |
video_input,
|
| 575 |
+
clip_state,
|
| 576 |
+
roi_state,
|
| 577 |
conf_input,
|
| 578 |
point_conf_input,
|
| 579 |
process_full_input,
|
|
|
|
| 587 |
show_progress="full",
|
| 588 |
api_name=False,
|
| 589 |
js="""
|
| 590 |
+
(video, clip, roi, conf, point_conf, process_full, max_frames, stride, smoothing, line_width, upload_guard) => {
|
| 591 |
const fileInputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
| 592 |
const hasSelectedFile = fileInputs.some((input) => input.files && input.files.length > 0);
|
| 593 |
let guard = "ready";
|
| 594 |
if (video === null || video === undefined) {
|
| 595 |
guard = hasSelectedFile ? "uploading" : "empty";
|
| 596 |
}
|
| 597 |
+
return [video, clip, roi, conf, point_conf, process_full, max_frames, stride, smoothing, line_width, guard];
|
| 598 |
}
|
| 599 |
""",
|
| 600 |
)
|
| 601 |
|
| 602 |
+
stop_button.click(fn=None, inputs=None, outputs=None, cancels=[clip_event, process_event])
|
| 603 |
+
|
| 604 |
|
| 605 |
if __name__ == "__main__":
|
| 606 |
demo.queue(default_concurrency_limit=1).launch(
|