Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,43 +1,26 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
| 3 |
import cv2
|
| 4 |
import numpy as np
|
| 5 |
import mediapipe as mp
|
| 6 |
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
import shutil
|
| 10 |
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# -----------------------
|
| 15 |
-
def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated_out_path: str | None = None):
|
| 16 |
-
"""
|
| 17 |
-
Runs MediaPipe Pose on a video, counts pushup reps, and returns:
|
| 18 |
-
{
|
| 19 |
-
"ok": bool,
|
| 20 |
-
"error": str | None,
|
| 21 |
-
"rep_count": int,
|
| 22 |
-
"rep_events": list[dict],
|
| 23 |
-
"annotated_video_path": str | None
|
| 24 |
-
}
|
| 25 |
-
"""
|
| 26 |
if not os.path.exists(video_path):
|
| 27 |
-
return {
|
| 28 |
-
|
| 29 |
-
"error": f"Could not find input video: {video_path}",
|
| 30 |
-
"rep_count": 0,
|
| 31 |
-
"rep_events": [],
|
| 32 |
-
"annotated_video_path": None,
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
# ---------- Math helpers ----------
|
| 36 |
def clamp(x, lo=0.0, hi=1.0):
|
| 37 |
return max(lo, min(hi, x))
|
| 38 |
|
| 39 |
def angle_deg(a, b, c):
|
| 40 |
-
"""Angle ABC in degrees using points a,b,c as (x,y)."""
|
| 41 |
a = np.array(a, dtype=np.float32)
|
| 42 |
b = np.array(b, dtype=np.float32)
|
| 43 |
c = np.array(c, dtype=np.float32)
|
|
@@ -49,21 +32,15 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 49 |
return float(np.degrees(np.arccos(cosang)))
|
| 50 |
|
| 51 |
def score_from_range(val, good_lo, good_hi, ok_lo, ok_hi):
|
| 52 |
-
"""
|
| 53 |
-
Returns 1 if val in [good_lo, good_hi],
|
| 54 |
-
fades to 0 by the time it reaches ok_lo/ok_hi.
|
| 55 |
-
"""
|
| 56 |
if good_lo <= val <= good_hi:
|
| 57 |
return 1.0
|
| 58 |
if val < good_lo:
|
| 59 |
return clamp((val - ok_lo) / (good_lo - ok_lo))
|
| 60 |
-
|
| 61 |
-
return clamp((ok_hi - val) / (ok_hi - good_hi))
|
| 62 |
|
| 63 |
def ema(prev, x, a=0.25):
|
| 64 |
return x if prev is None else (a * x + (1 - a) * prev)
|
| 65 |
|
| 66 |
-
# ---------- Pose setup ----------
|
| 67 |
mp_pose = mp.solutions.pose
|
| 68 |
pose = mp_pose.Pose(
|
| 69 |
static_image_mode=False,
|
|
@@ -74,23 +51,15 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 74 |
min_tracking_confidence=0.5,
|
| 75 |
)
|
| 76 |
|
| 77 |
-
# ---------- Video I/O ----------
|
| 78 |
cap = cv2.VideoCapture(video_path)
|
| 79 |
if not cap.isOpened():
|
| 80 |
pose.close()
|
| 81 |
-
return {
|
| 82 |
-
"ok": False,
|
| 83 |
-
"error": "OpenCV could not open the video. Try a different mp4 encoding.",
|
| 84 |
-
"rep_count": 0,
|
| 85 |
-
"rep_events": [],
|
| 86 |
-
"annotated_video_path": None,
|
| 87 |
-
}
|
| 88 |
|
| 89 |
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
| 90 |
W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 0
|
| 91 |
H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 0
|
| 92 |
|
| 93 |
-
# Output path handling
|
| 94 |
annotated_path = None
|
| 95 |
writer = None
|
| 96 |
if save_annotated:
|
|
@@ -100,9 +69,8 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 100 |
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 101 |
writer = cv2.VideoWriter(annotated_path, fourcc, fps, (W, H))
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
rep_events = []
|
| 106 |
current_rep = None
|
| 107 |
rep_count = 0
|
| 108 |
|
|
@@ -129,12 +97,10 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 129 |
res = pose.process(rgb)
|
| 130 |
|
| 131 |
frame_prob = 0.0
|
| 132 |
-
debug_txt = "No pose"
|
| 133 |
|
| 134 |
if res.pose_landmarks:
|
| 135 |
lms = res.pose_landmarks.landmark
|
| 136 |
|
| 137 |
-
# Choose side: whichever shoulder has higher visibility
|
| 138 |
Ls = lms[mp_pose.PoseLandmark.LEFT_SHOULDER.value]
|
| 139 |
Rs = lms[mp_pose.PoseLandmark.RIGHT_SHOULDER.value]
|
| 140 |
left_side = (Ls.visibility >= Rs.visibility)
|
|
@@ -180,12 +146,7 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 180 |
if ema_elbow <= DOWN_ELBOW_DEG and frame_prob >= 0.45:
|
| 181 |
state = "DOWN"
|
| 182 |
if current_rep is None:
|
| 183 |
-
current_rep = {
|
| 184 |
-
"start_f": frame_idx,
|
| 185 |
-
"frame_probs": [],
|
| 186 |
-
"min_elbow": float(ema_elbow),
|
| 187 |
-
"min_straight": float(ema_straight),
|
| 188 |
-
}
|
| 189 |
|
| 190 |
elif state == "DOWN":
|
| 191 |
if ema_elbow >= UP_ELBOW_DEG and frame_prob >= 0.35:
|
|
@@ -196,11 +157,8 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 196 |
rep_count += 1
|
| 197 |
probs = current_rep["frame_probs"] if current_rep["frame_probs"] else [frame_prob]
|
| 198 |
rep_prob = float(np.mean(probs))
|
| 199 |
-
|
| 200 |
rep_events.append({
|
| 201 |
"rep": rep_count,
|
| 202 |
-
"start_f": int(current_rep["start_f"]),
|
| 203 |
-
"end_f": int(end_f),
|
| 204 |
"start_t": float(current_rep["start_f"] / fps),
|
| 205 |
"end_t": float(end_f / fps),
|
| 206 |
"prob": float(rep_prob),
|
|
@@ -215,20 +173,6 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 215 |
current_rep["min_elbow"] = float(min(current_rep["min_elbow"], ema_elbow))
|
| 216 |
current_rep["min_straight"] = float(min(current_rep["min_straight"], ema_straight))
|
| 217 |
|
| 218 |
-
debug_txt = f"{'L' if left_side else 'R'} vis={ema_vis:.2f} elbow={ema_elbow:.0f} straight={ema_straight:.0f} p={frame_prob:.2f} state={state}"
|
| 219 |
-
|
| 220 |
-
# Simple overlay
|
| 221 |
-
cv2.putText(frame, f"Reps: {rep_count}", (20, 40),
|
| 222 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)
|
| 223 |
-
cv2.putText(frame, debug_txt[:90], (20, 75),
|
| 224 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2, cv2.LINE_AA)
|
| 225 |
-
|
| 226 |
-
else:
|
| 227 |
-
cv2.putText(frame, f"Reps: {rep_count}", (20, 40),
|
| 228 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)
|
| 229 |
-
cv2.putText(frame, debug_txt[:90], (20, 75),
|
| 230 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2, cv2.LINE_AA)
|
| 231 |
-
|
| 232 |
if writer is not None:
|
| 233 |
writer.write(frame)
|
| 234 |
|
|
@@ -237,65 +181,30 @@ def analyze_pushup_video(video_path: str, save_annotated: bool = True, annotated
|
|
| 237 |
if writer is not None:
|
| 238 |
writer.release()
|
| 239 |
pose.close()
|
| 240 |
-
return {
|
| 241 |
-
"ok": False,
|
| 242 |
-
"error": f"Runtime error: {type(e).__name__}: {e}",
|
| 243 |
-
"rep_count": rep_count,
|
| 244 |
-
"rep_events": rep_events,
|
| 245 |
-
"annotated_video_path": annotated_path,
|
| 246 |
-
}
|
| 247 |
|
| 248 |
cap.release()
|
| 249 |
if writer is not None:
|
| 250 |
writer.release()
|
| 251 |
pose.close()
|
| 252 |
|
| 253 |
-
return {
|
| 254 |
-
"ok": True,
|
| 255 |
-
"error": None,
|
| 256 |
-
"rep_count": rep_count,
|
| 257 |
-
"rep_events": rep_events,
|
| 258 |
-
"annotated_video_path": annotated_path,
|
| 259 |
-
}
|
| 260 |
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
# -----------------------
|
| 265 |
-
def gradio_run(video_file):
|
| 266 |
-
# video_file is a temp path provided by Gradio
|
| 267 |
workdir = tempfile.mkdtemp()
|
| 268 |
in_path = os.path.join(workdir, "input.mp4")
|
| 269 |
-
shutil.copy(video_file, in_path)
|
| 270 |
-
|
| 271 |
-
out_path = os.path.join(workdir, "annotated.mp4")
|
| 272 |
-
result = analyze_pushup_video(in_path, save_annotated=True, annotated_out_path=out_path)
|
| 273 |
-
|
| 274 |
-
if not result["ok"]:
|
| 275 |
-
return "Error: " + str(result["error"]), None, []
|
| 276 |
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
avg_prob = sum(r["prob"] for r in result["rep_events"]) / len(result["rep_events"])
|
| 280 |
-
summary += f"Avg rep probability: {avg_prob:.2f}\n"
|
| 281 |
|
| 282 |
-
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
# ... your gradio_run stays the same ...
|
| 288 |
-
|
| 289 |
-
demo = gr.Interface(
|
| 290 |
-
fn=gradio_run,
|
| 291 |
-
inputs=gr.Video(label="Upload pushup video"),
|
| 292 |
-
outputs=[
|
| 293 |
-
gr.Textbox(label="Results"),
|
| 294 |
-
gr.Video(label="Annotated output"),
|
| 295 |
-
gr.JSON(label="Per-rep details"),
|
| 296 |
-
],
|
| 297 |
-
allow_flagging="never",
|
| 298 |
-
)
|
| 299 |
-
|
| 300 |
-
if __name__ == "__main__":
|
| 301 |
-
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import tempfile
|
| 4 |
+
from typing import Optional, Dict, Any, List
|
| 5 |
+
|
| 6 |
import cv2
|
| 7 |
import numpy as np
|
| 8 |
import mediapipe as mp
|
| 9 |
|
| 10 |
+
from fastapi import FastAPI, UploadFile, File
|
| 11 |
+
from fastapi.responses import JSONResponse
|
|
|
|
| 12 |
|
| 13 |
+
app = FastAPI()
|
| 14 |
|
| 15 |
+
|
| 16 |
+
def analyze_pushup_video(video_path: str, save_annotated: bool = False, annotated_out_path: Optional[str] = None) -> Dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
if not os.path.exists(video_path):
|
| 18 |
+
return {"ok": False, "error": f"Could not find input video: {video_path}", "rep_count": 0, "rep_events": [], "annotated_video_path": None}
|
| 19 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
def clamp(x, lo=0.0, hi=1.0):
|
| 21 |
return max(lo, min(hi, x))
|
| 22 |
|
| 23 |
def angle_deg(a, b, c):
|
|
|
|
| 24 |
a = np.array(a, dtype=np.float32)
|
| 25 |
b = np.array(b, dtype=np.float32)
|
| 26 |
c = np.array(c, dtype=np.float32)
|
|
|
|
| 32 |
return float(np.degrees(np.arccos(cosang)))
|
| 33 |
|
| 34 |
def score_from_range(val, good_lo, good_hi, ok_lo, ok_hi):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
if good_lo <= val <= good_hi:
|
| 36 |
return 1.0
|
| 37 |
if val < good_lo:
|
| 38 |
return clamp((val - ok_lo) / (good_lo - ok_lo))
|
| 39 |
+
return clamp((ok_hi - val) / (ok_hi - good_hi))
|
|
|
|
| 40 |
|
| 41 |
def ema(prev, x, a=0.25):
|
| 42 |
return x if prev is None else (a * x + (1 - a) * prev)
|
| 43 |
|
|
|
|
| 44 |
mp_pose = mp.solutions.pose
|
| 45 |
pose = mp_pose.Pose(
|
| 46 |
static_image_mode=False,
|
|
|
|
| 51 |
min_tracking_confidence=0.5,
|
| 52 |
)
|
| 53 |
|
|
|
|
| 54 |
cap = cv2.VideoCapture(video_path)
|
| 55 |
if not cap.isOpened():
|
| 56 |
pose.close()
|
| 57 |
+
return {"ok": False, "error": "OpenCV could not open the video. Try a different mp4 encoding.", "rep_count": 0, "rep_events": [], "annotated_video_path": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
| 60 |
W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 0
|
| 61 |
H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 0
|
| 62 |
|
|
|
|
| 63 |
annotated_path = None
|
| 64 |
writer = None
|
| 65 |
if save_annotated:
|
|
|
|
| 69 |
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 70 |
writer = cv2.VideoWriter(annotated_path, fourcc, fps, (W, H))
|
| 71 |
|
| 72 |
+
state = "UNKNOWN"
|
| 73 |
+
rep_events: List[Dict[str, Any]] = []
|
|
|
|
| 74 |
current_rep = None
|
| 75 |
rep_count = 0
|
| 76 |
|
|
|
|
| 97 |
res = pose.process(rgb)
|
| 98 |
|
| 99 |
frame_prob = 0.0
|
|
|
|
| 100 |
|
| 101 |
if res.pose_landmarks:
|
| 102 |
lms = res.pose_landmarks.landmark
|
| 103 |
|
|
|
|
| 104 |
Ls = lms[mp_pose.PoseLandmark.LEFT_SHOULDER.value]
|
| 105 |
Rs = lms[mp_pose.PoseLandmark.RIGHT_SHOULDER.value]
|
| 106 |
left_side = (Ls.visibility >= Rs.visibility)
|
|
|
|
| 146 |
if ema_elbow <= DOWN_ELBOW_DEG and frame_prob >= 0.45:
|
| 147 |
state = "DOWN"
|
| 148 |
if current_rep is None:
|
| 149 |
+
current_rep = {"start_f": frame_idx, "frame_probs": [], "min_elbow": float(ema_elbow), "min_straight": float(ema_straight)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
elif state == "DOWN":
|
| 152 |
if ema_elbow >= UP_ELBOW_DEG and frame_prob >= 0.35:
|
|
|
|
| 157 |
rep_count += 1
|
| 158 |
probs = current_rep["frame_probs"] if current_rep["frame_probs"] else [frame_prob]
|
| 159 |
rep_prob = float(np.mean(probs))
|
|
|
|
| 160 |
rep_events.append({
|
| 161 |
"rep": rep_count,
|
|
|
|
|
|
|
| 162 |
"start_t": float(current_rep["start_f"] / fps),
|
| 163 |
"end_t": float(end_f / fps),
|
| 164 |
"prob": float(rep_prob),
|
|
|
|
| 173 |
current_rep["min_elbow"] = float(min(current_rep["min_elbow"], ema_elbow))
|
| 174 |
current_rep["min_straight"] = float(min(current_rep["min_straight"], ema_straight))
|
| 175 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
if writer is not None:
|
| 177 |
writer.write(frame)
|
| 178 |
|
|
|
|
| 181 |
if writer is not None:
|
| 182 |
writer.release()
|
| 183 |
pose.close()
|
| 184 |
+
return {"ok": False, "error": f"Runtime error: {type(e).__name__}: {e}", "rep_count": rep_count, "rep_events": rep_events, "annotated_video_path": annotated_path}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
cap.release()
|
| 187 |
if writer is not None:
|
| 188 |
writer.release()
|
| 189 |
pose.close()
|
| 190 |
|
| 191 |
+
return {"ok": True, "error": None, "rep_count": rep_count, "rep_events": rep_events, "annotated_video_path": annotated_path}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
|
| 194 |
+
@app.post("/analyze")
|
| 195 |
+
async def analyze(video: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
| 196 |
workdir = tempfile.mkdtemp()
|
| 197 |
in_path = os.path.join(workdir, "input.mp4")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
with open(in_path, "wb") as f:
|
| 200 |
+
shutil.copyfileobj(video.file, f)
|
|
|
|
|
|
|
| 201 |
|
| 202 |
+
result = analyze_pushup_video(in_path, save_annotated=False)
|
| 203 |
|
| 204 |
+
# clean temp (optional)
|
| 205 |
+
try:
|
| 206 |
+
shutil.rmtree(workdir)
|
| 207 |
+
except:
|
| 208 |
+
pass
|
| 209 |
|
| 210 |
+
return JSONResponse(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|