Koom759 commited on
Commit
3c4e035
·
verified ·
1 Parent(s): 7a6f1a8

Add upload guard and full-video smoothing

Browse files
Files changed (1) hide show
  1. app.py +67 -8
app.py CHANGED
@@ -60,6 +60,7 @@ SKELETON = [
60
  JOINT_COLOR = (255, 230, 120)
61
  LINE_COLOR = (80, 220, 255)
62
  TEXT_COLOR = (230, 240, 255)
 
63
 
64
 
65
  @lru_cache(maxsize=1)
@@ -129,6 +130,20 @@ def resolve_uploaded_video_path(video_input) -> Path | None:
129
  return Path(path) if path else None
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def draw_person(
133
  canvas: np.ndarray,
134
  keypoints: np.ndarray,
@@ -167,15 +182,28 @@ def build_stickman_video(
167
  video_path,
168
  conf,
169
  point_conf,
 
170
  max_frames,
171
  frame_stride,
 
172
  line_width,
 
173
  progress: gr.Progress = gr.Progress(track_tqdm=False),
174
  ):
175
  source = resolve_uploaded_video_path(video_path)
176
  if source is None:
177
- print(f"ERROR rowing-stickman missing_upload value={video_path!r}", flush=True)
178
- raise gr.Error("No uploaded video was received. Please wait until the upload preview appears, then click Process video.")
 
 
 
 
 
 
 
 
 
 
179
 
180
  if not source.exists():
181
  print(f"ERROR rowing-stickman missing_file value={video_path!r} source={source}", flush=True)
@@ -192,8 +220,10 @@ def build_stickman_video(
192
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
193
 
194
  frame_stride = max(1, int(frame_stride))
 
195
  max_frames = int(max_frames)
196
- if max_frames <= 0:
 
197
  frame_limit = total_frames if total_frames > 0 else math.inf
198
  else:
199
  frame_limit = min(max_frames, total_frames) if total_frames > 0 else max_frames
@@ -213,12 +243,14 @@ def build_stickman_video(
213
  read_count = 0
214
  written_count = 0
215
  detected_person_frames = 0
 
216
 
217
  progress(0, desc="Loading YOLO11x model and opening video...")
218
  print(
219
  "START rowing-stickman "
220
  f"source={source.name} size={width}x{height} fps={fps:.2f} "
221
- f"total_frames={total_frames} max_frames={max_frames} stride={frame_stride}",
 
222
  flush=True,
223
  )
224
 
@@ -239,12 +271,18 @@ def build_stickman_video(
239
  kpts = result.keypoints.data.cpu().numpy()
240
  boxes_conf = result.boxes.conf.cpu().numpy() if result.boxes is not None else np.ones(len(kpts))
241
  order = np.argsort(boxes_conf)[::-1]
242
- for person_idx in order[:3]:
243
- draw_person(canvas, kpts[person_idx], point_conf, line_width)
 
244
  person_count += 1
245
 
246
  if person_count:
247
  detected_person_frames += 1
 
 
 
 
 
248
 
249
  cv2.putText(
250
  canvas,
@@ -280,6 +318,9 @@ def build_stickman_video(
280
  f"- Read frames: {read_count}\n"
281
  f"- Output frames: {written_count}\n"
282
  f"- Frames with detected person: {detected_person_frames}\n"
 
 
 
283
  f"- Elapsed: {readable_seconds(elapsed)}\n"
284
  f"- Output size: {output_size_mb:.1f} MB\n"
285
  f"- Model: {MODEL_PATH.name}"
@@ -288,6 +329,7 @@ def build_stickman_video(
288
  "DONE rowing-stickman "
289
  f"source={source.name} read_frames={read_count} output_frames={written_count} "
290
  f"detected_frames={detected_person_frames} elapsed={elapsed:.2f}s "
 
291
  f"output={final_output_path.name} output_mb={output_size_mb:.1f}",
292
  flush=True,
293
  )
@@ -315,15 +357,18 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), ti
315
  )
316
  conf_input = gr.Slider(0.05, 0.90, value=0.30, step=0.05, label="YOLO detection confidence")
317
  point_conf_input = gr.Slider(0.05, 0.90, value=0.25, step=0.05, label="Keypoint drawing confidence")
 
318
  max_frames_input = gr.Slider(
319
  0,
320
  1200,
321
  value=300,
322
  step=30,
323
- label="Max frames to process (0 = whole video)",
324
  )
325
- stride_input = gr.Slider(1, 10, value=2, step=1, label="Frame stride (higher = faster)")
 
326
  line_width_input = gr.Slider(1, 8, value=3, step=1, label="Stickman line width")
 
327
  run_button = gr.Button("Process video", variant="primary")
328
  with gr.Column(scale=1):
329
  video_output = gr.Video(label="Stickman playback", format="mp4", include_audio=False)
@@ -336,13 +381,27 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), ti
336
  video_input,
337
  conf_input,
338
  point_conf_input,
 
339
  max_frames_input,
340
  stride_input,
 
341
  line_width_input,
 
342
  ],
343
  outputs=[video_output, file_output, summary_output],
344
  show_progress="full",
345
  api_name=False,
 
 
 
 
 
 
 
 
 
 
 
346
  )
347
 
348
 
 
60
  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)
 
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
136
+
137
+ buffer.append(keypoints.copy())
138
+ del buffer[:-window_size]
139
+
140
+ stacked = np.stack(buffer, axis=0)
141
+ smoothed = keypoints.copy()
142
+ smoothed[:, :2] = stacked[:, :, :2].mean(axis=0)
143
+ smoothed[:, 2] = stacked[:, :, 2].mean(axis=0)
144
+ return smoothed
145
+
146
+
147
  def draw_person(
148
  canvas: np.ndarray,
149
  keypoints: np.ndarray,
 
182
  video_path,
183
  conf,
184
  point_conf,
185
+ process_full_video,
186
  max_frames,
187
  frame_stride,
188
+ smoothing_window,
189
  line_width,
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)
197
+ for second in range(UPLOAD_WAIT_SECONDS):
198
+ progress(
199
+ second / UPLOAD_WAIT_SECONDS,
200
+ desc=f"Waiting for video upload to finish... {second + 1}/{UPLOAD_WAIT_SECONDS}s",
201
+ )
202
+ time.sleep(1)
203
+ raise gr.Error("The video is still uploading. Please wait until the upload preview appears, then click Process video again.")
204
+
205
+ print(f"ERROR rowing-stickman missing_upload guard={upload_guard!r} value={video_path!r}", flush=True)
206
+ raise gr.Error("No video was uploaded. Please choose a video first.")
207
 
208
  if not source.exists():
209
  print(f"ERROR rowing-stickman missing_file value={video_path!r} source={source}", flush=True)
 
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))
224
  max_frames = int(max_frames)
225
+ process_full_video = bool(process_full_video)
226
+ if process_full_video or max_frames <= 0:
227
  frame_limit = total_frames if total_frames > 0 else math.inf
228
  else:
229
  frame_limit = min(max_frames, total_frames) if total_frames > 0 else max_frames
 
243
  read_count = 0
244
  written_count = 0
245
  detected_person_frames = 0
246
+ smoothing_buffers: list[list[np.ndarray]] = [[], [], []]
247
 
248
  progress(0, desc="Loading YOLO11x model and opening video...")
249
  print(
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
 
 
271
  kpts = result.keypoints.data.cpu().numpy()
272
  boxes_conf = result.boxes.conf.cpu().numpy() if result.boxes is not None else np.ones(len(kpts))
273
  order = np.argsort(boxes_conf)[::-1]
274
+ for rank, person_idx in enumerate(order[:3]):
275
+ smoothed_kpts = smooth_keypoints(smoothing_buffers[rank], kpts[person_idx], smoothing_window)
276
+ draw_person(canvas, smoothed_kpts, point_conf, line_width)
277
  person_count += 1
278
 
279
  if person_count:
280
  detected_person_frames += 1
281
+ for empty_rank in range(person_count, len(smoothing_buffers)):
282
+ smoothing_buffers[empty_rank].clear()
283
+ else:
284
+ for buffer in smoothing_buffers:
285
+ buffer.clear()
286
 
287
  cv2.putText(
288
  canvas,
 
318
  f"- Read frames: {read_count}\n"
319
  f"- Output frames: {written_count}\n"
320
  f"- Frames with detected person: {detected_person_frames}\n"
321
+ f"- Full video: {'yes' if process_full_video else 'no'}\n"
322
+ f"- Frame stride: {frame_stride}\n"
323
+ f"- Moving average window: {smoothing_window}\n"
324
  f"- Elapsed: {readable_seconds(elapsed)}\n"
325
  f"- Output size: {output_size_mb:.1f} MB\n"
326
  f"- Model: {MODEL_PATH.name}"
 
329
  "DONE rowing-stickman "
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
  )
 
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")
361
  max_frames_input = gr.Slider(
362
  0,
363
  1200,
364
  value=300,
365
  step=30,
366
+ label="Max frames to process when full video is off",
367
  )
368
+ stride_input = gr.Slider(1, 10, value=1, step=1, label="Frame stride")
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
  run_button = gr.Button("Process video", variant="primary")
373
  with gr.Column(scale=1):
374
  video_output = gr.Video(label="Stickman playback", format="mp4", include_audio=False)
 
381
  video_input,
382
  conf_input,
383
  point_conf_input,
384
+ process_full_input,
385
  max_frames_input,
386
  stride_input,
387
+ smoothing_input,
388
  line_width_input,
389
+ upload_guard_input,
390
  ],
391
  outputs=[video_output, file_output, summary_output],
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