Koom759 commited on
Commit
ff5916c
·
verified ·
1 Parent(s): a5b4e8e

Add Gradio stickman demo app

Browse files
README.md CHANGED
@@ -1,14 +1,24 @@
1
  ---
2
  title: Rowing Validator
3
- emoji: 👁
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 6.19.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
- short_description: rowing-validator
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Rowing Validator
3
+ emoji: 🚣
4
+ colorFrom: blue
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.44.1
 
8
  app_file: app.py
9
  pinned: false
10
+ license: other
11
+ short_description: Upload rowing video and generate YOLO11x stickman playback
12
  ---
13
 
14
+ # Rowing Validator
15
+
16
+ This Space is a simple test demo for rowing pose processing.
17
+
18
+ Upload a rowing video, run YOLO11x pose estimation, and generate a playable stickman video.
19
+
20
+ Notes:
21
+
22
+ - CPU Basic can be slow for YOLO11x, so the default settings process a limited number of frames.
23
+ - Increase `Max frames` or lower `Frame stride` for more complete output.
24
+ - For real user testing, upgrade the Space to GPU hardware.
__pycache__/app.cpython-310.pyc ADDED
Binary file (6.93 kB). View file
 
__pycache__/app.cpython-313.pyc ADDED
Binary file (12 kB). View file
 
app.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import tempfile
5
+ import time
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import gradio as gr
11
+ import numpy as np
12
+ from ultralytics import YOLO
13
+
14
+
15
+ MODEL_PATH = Path("Weight/yolo11x-pose.pt")
16
+
17
+ KEYPOINT_NAMES = [
18
+ "nose",
19
+ "left_eye",
20
+ "right_eye",
21
+ "left_ear",
22
+ "right_ear",
23
+ "left_shoulder",
24
+ "right_shoulder",
25
+ "left_elbow",
26
+ "right_elbow",
27
+ "left_wrist",
28
+ "right_wrist",
29
+ "left_hip",
30
+ "right_hip",
31
+ "left_knee",
32
+ "right_knee",
33
+ "left_ankle",
34
+ "right_ankle",
35
+ ]
36
+
37
+ SKELETON = [
38
+ (15, 13),
39
+ (13, 11),
40
+ (16, 14),
41
+ (14, 12),
42
+ (11, 12),
43
+ (5, 11),
44
+ (6, 12),
45
+ (5, 6),
46
+ (5, 7),
47
+ (7, 9),
48
+ (6, 8),
49
+ (8, 10),
50
+ (1, 2),
51
+ (0, 1),
52
+ (0, 2),
53
+ (1, 3),
54
+ (2, 4),
55
+ (3, 5),
56
+ (4, 6),
57
+ ]
58
+
59
+ JOINT_COLOR = (255, 230, 120)
60
+ LINE_COLOR = (80, 220, 255)
61
+ TEXT_COLOR = (230, 240, 255)
62
+
63
+
64
+ @lru_cache(maxsize=1)
65
+ def load_model() -> YOLO:
66
+ if not MODEL_PATH.exists():
67
+ raise FileNotFoundError(f"Missing YOLO model: {MODEL_PATH}")
68
+ return YOLO(str(MODEL_PATH))
69
+
70
+
71
+ def readable_seconds(seconds: float) -> str:
72
+ if seconds < 60:
73
+ return f"{seconds:.1f}s"
74
+ minutes = int(seconds // 60)
75
+ remain = seconds - minutes * 60
76
+ return f"{minutes}m {remain:.0f}s"
77
+
78
+
79
+ def draw_person(
80
+ canvas: np.ndarray,
81
+ keypoints: np.ndarray,
82
+ point_conf: float,
83
+ line_width: int,
84
+ ) -> None:
85
+ points = keypoints[:, :2]
86
+ confs = keypoints[:, 2]
87
+
88
+ for a, b in SKELETON:
89
+ if confs[a] < point_conf or confs[b] < point_conf:
90
+ continue
91
+ pa = tuple(np.round(points[a]).astype(int))
92
+ pb = tuple(np.round(points[b]).astype(int))
93
+ cv2.line(canvas, pa, pb, LINE_COLOR, line_width, lineType=cv2.LINE_AA)
94
+
95
+ radius = max(3, line_width + 2)
96
+ for idx, (x, y) in enumerate(points):
97
+ if confs[idx] < point_conf:
98
+ continue
99
+ cv2.circle(canvas, (int(round(x)), int(round(y))), radius, JOINT_COLOR, -1, lineType=cv2.LINE_AA)
100
+ if idx in (0, 5, 6, 11, 12, 15, 16):
101
+ cv2.putText(
102
+ canvas,
103
+ KEYPOINT_NAMES[idx].replace("_", " "),
104
+ (int(x) + 5, int(y) - 5),
105
+ cv2.FONT_HERSHEY_SIMPLEX,
106
+ 0.36,
107
+ TEXT_COLOR,
108
+ 1,
109
+ cv2.LINE_AA,
110
+ )
111
+
112
+
113
+ def build_stickman_video(
114
+ video_path: str | dict,
115
+ conf: float,
116
+ point_conf: float,
117
+ max_frames: int,
118
+ frame_stride: int,
119
+ line_width: int,
120
+ progress: gr.Progress = gr.Progress(track_tqdm=False),
121
+ ) -> tuple[str, str, str]:
122
+ if video_path is None:
123
+ raise gr.Error("Please upload a video first.")
124
+
125
+ if isinstance(video_path, dict):
126
+ video_path = video_path.get("path") or video_path.get("name")
127
+ source = Path(str(video_path))
128
+ if not source.exists():
129
+ raise gr.Error(f"Video file not found: {source}")
130
+
131
+ model = load_model()
132
+ cap = cv2.VideoCapture(str(source))
133
+ if not cap.isOpened():
134
+ raise gr.Error("Could not open the uploaded video.")
135
+
136
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
137
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
138
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
139
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
140
+
141
+ frame_stride = max(1, int(frame_stride))
142
+ max_frames = int(max_frames)
143
+ if max_frames <= 0:
144
+ frame_limit = total_frames if total_frames > 0 else math.inf
145
+ else:
146
+ frame_limit = min(max_frames, total_frames) if total_frames > 0 else max_frames
147
+
148
+ output_fps = max(1.0, fps / frame_stride)
149
+ workdir = Path(tempfile.mkdtemp(prefix="rowing_space_"))
150
+ output_path = workdir / f"{source.stem}_stickman.mp4"
151
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
152
+ writer = cv2.VideoWriter(str(output_path), fourcc, output_fps, (width, height))
153
+
154
+ if not writer.isOpened():
155
+ cap.release()
156
+ raise gr.Error("Could not create the output video.")
157
+
158
+ start_time = time.time()
159
+ read_count = 0
160
+ written_count = 0
161
+ detected_person_frames = 0
162
+
163
+ progress(0, desc="Loading YOLO11x model and opening video...")
164
+
165
+ while read_count < frame_limit:
166
+ ok, frame = cap.read()
167
+ if not ok:
168
+ break
169
+
170
+ if read_count % frame_stride != 0:
171
+ read_count += 1
172
+ continue
173
+
174
+ result = model.predict(frame, conf=conf, verbose=False, device=None)[0]
175
+ canvas = np.zeros_like(frame)
176
+
177
+ person_count = 0
178
+ if result.keypoints is not None and len(result.keypoints) > 0:
179
+ kpts = result.keypoints.data.cpu().numpy()
180
+ boxes_conf = result.boxes.conf.cpu().numpy() if result.boxes is not None else np.ones(len(kpts))
181
+ order = np.argsort(boxes_conf)[::-1]
182
+ for person_idx in order[:3]:
183
+ draw_person(canvas, kpts[person_idx], point_conf, line_width)
184
+ person_count += 1
185
+
186
+ if person_count:
187
+ detected_person_frames += 1
188
+
189
+ cv2.putText(
190
+ canvas,
191
+ f"frame {read_count} | persons {person_count}",
192
+ (18, 34),
193
+ cv2.FONT_HERSHEY_SIMPLEX,
194
+ 0.85,
195
+ TEXT_COLOR,
196
+ 2,
197
+ cv2.LINE_AA,
198
+ )
199
+ writer.write(canvas)
200
+ written_count += 1
201
+ read_count += 1
202
+
203
+ denom = frame_limit if frame_limit != math.inf else max(read_count + 1, total_frames or read_count + 1)
204
+ pct = min(1.0, float(read_count) / float(denom))
205
+ progress(pct, desc=f"Processing frame {read_count}/{int(denom) if denom != math.inf else '?'}")
206
+
207
+ cap.release()
208
+ writer.release()
209
+
210
+ elapsed = time.time() - start_time
211
+ if written_count == 0:
212
+ raise gr.Error("No frames were processed. Try lowering frame stride or uploading a different video.")
213
+
214
+ summary = (
215
+ f"Done.\n"
216
+ f"- Source: {source.name}\n"
217
+ f"- Resolution: {width}x{height}, FPS: {fps:.2f}\n"
218
+ f"- Read frames: {read_count}\n"
219
+ f"- Output frames: {written_count}\n"
220
+ f"- Frames with detected person: {detected_person_frames}\n"
221
+ f"- Elapsed: {readable_seconds(elapsed)}\n"
222
+ f"- Model: {MODEL_PATH.name}"
223
+ )
224
+ progress(1, desc="Finished.")
225
+ return str(output_path), str(output_path), summary
226
+
227
+
228
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), title="Rowing Stickman Demo") as demo:
229
+ gr.Markdown(
230
+ """
231
+ # Rowing Stickman Video Demo
232
+
233
+ Upload a rowing video, run YOLO11x pose estimation, and generate a playable stickman video.
234
+ For the free CPU Space, start with a short clip or keep the default frame limit.
235
+ """
236
+ )
237
+
238
+ with gr.Row():
239
+ with gr.Column(scale=1):
240
+ video_input = gr.Video(label="Upload video", sources=["upload"])
241
+ conf_input = gr.Slider(0.05, 0.90, value=0.30, step=0.05, label="YOLO detection confidence")
242
+ point_conf_input = gr.Slider(0.05, 0.90, value=0.25, step=0.05, label="Keypoint drawing confidence")
243
+ max_frames_input = gr.Slider(
244
+ 0,
245
+ 1200,
246
+ value=300,
247
+ step=30,
248
+ label="Max frames to process (0 = whole video)",
249
+ )
250
+ stride_input = gr.Slider(1, 10, value=2, step=1, label="Frame stride (higher = faster)")
251
+ line_width_input = gr.Slider(1, 8, value=3, step=1, label="Stickman line width")
252
+ run_button = gr.Button("Process video", variant="primary")
253
+ with gr.Column(scale=1):
254
+ video_output = gr.Video(label="Stickman output")
255
+ file_output = gr.File(label="Download MP4")
256
+ summary_output = gr.Textbox(label="Processing summary", lines=10)
257
+
258
+ run_button.click(
259
+ fn=build_stickman_video,
260
+ inputs=[
261
+ video_input,
262
+ conf_input,
263
+ point_conf_input,
264
+ max_frames_input,
265
+ stride_input,
266
+ line_width_input,
267
+ ],
268
+ outputs=[video_output, file_output, summary_output],
269
+ show_progress="full",
270
+ )
271
+
272
+
273
+ if __name__ == "__main__":
274
+ demo.queue(default_concurrency_limit=1).launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ultralytics>=8.3.0
2
+ opencv-python-headless>=4.10.0
3
+ numpy>=1.26.0
4
+ torch
5
+ torchvision