Spaces:
Running on Zero
Running on Zero
File size: 11,238 Bytes
b7e61ea 06aef73 f3a29a9 1df1423 b7e61ea 1df1423 b7e61ea 06aef73 b7e61ea 1df1423 06aef73 1df1423 b7e61ea 99f3843 b7e61ea 1df1423 b7e61ea 1df1423 bfe8d80 1df1423 8c7116a 1df1423 8c7116a c8f5fea 8c7116a c8f5fea 8c7116a 06aef73 1df1423 bfe8d80 1df1423 bfe8d80 06aef73 1df1423 06aef73 f083cf4 f3a29a9 aefa805 8780d53 aefa805 f083cf4 aefa805 06aef73 1df1423 f3a29a9 1df1423 06aef73 1df1423 b7e61ea 06aef73 8c7116a 1df1423 bfe8d80 8c7116a 1df1423 b7e61ea 06aef73 8780d53 06aef73 f083cf4 06aef73 8780d53 06aef73 f083cf4 06aef73 b7e61ea 1df1423 | 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 | from __future__ import annotations
import json
from queue import Queue
import re
import shutil
import sys
import tempfile
from pathlib import Path
from threading import Thread
from typing import Any
import gradio as gr
from fastapi import File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
sys.path.insert(0, str(Path(__file__).parent / "src"))
from pozify.exercise_catalog import USER_SELECTABLE_EXERCISES
from pozify.pipeline import run_pipeline
BASE_DIR = Path(__file__).parent
WEB_DIR = BASE_DIR / "web"
RUNS_ROOT = BASE_DIR / "runs"
APP_DESCRIPTION = (
"Upload a short workout clip, tune the athlete context, and generate an annotated "
"form-review report with structured artifacts."
)
server = gr.Server(
title="Pozify",
summary="Video-based workout form review API",
description=APP_DESCRIPTION,
)
server.mount("/static", StaticFiles(directory=WEB_DIR), name="static")
@server.get("/healthz", include_in_schema=False)
def healthz() -> dict[str, str]:
return {"status": "ok", "service": "pozify"}
@server.get("/", response_class=HTMLResponse, include_in_schema=False)
def index() -> FileResponse:
return FileResponse(WEB_DIR / "index.html")
@server.get("/api/config")
def config() -> dict[str, Any]:
return {
"description": APP_DESCRIPTION,
"goals": [
"strength",
"hypertrophy",
"endurance",
"mobility",
"beginner_practice",
],
"experience_levels": ["beginner", "intermediate"],
"exercises": ["auto", *USER_SELECTABLE_EXERCISES],
"limitations": ["wrist_discomfort", "knee_discomfort", "shoulder_discomfort"],
"equipment": ["bodyweight", "dumbbell", "barbell", "unknown"],
}
@server.get("/api/artifacts/{run_id}/{filename}", include_in_schema=False)
def artifact(run_id: str, filename: str) -> FileResponse:
artifact_path = (RUNS_ROOT / run_id / filename).resolve()
runs_root = RUNS_ROOT.resolve()
if runs_root not in artifact_path.parents or not artifact_path.is_file():
raise HTTPException(status_code=404, detail="Artifact not found.")
return FileResponse(artifact_path)
def _artifact_url(run_id: str, path: str | None) -> str | None:
if not path:
return None
if not isinstance(path, str):
return None
artifact_path = Path(path).resolve()
run_root = (RUNS_ROOT / run_id).resolve()
if run_root not in artifact_path.parents or not artifact_path.is_file():
return None
return f"/api/artifacts/{run_id}/{artifact_path.name}"
def _artifact_link(run_id: str, name: str, path: str | None) -> dict[str, str] | None:
url = _artifact_url(run_id, path)
if url is None:
return None
return {"name": name, "url": url}
def _artifact_urls(result: dict[str, Any]) -> list[dict[str, str]]:
run_id = result["run_id"]
run_dir = Path(str(result["run_dir"]))
links: list[dict[str, str]] = []
artifact_files = [
"final_report.json",
"video_manifest.json",
"pose_sequence.json",
"exercise_classification.json",
"reps.json",
"rep_debug.json",
"rep_analysis.json",
"variation.json",
"issue_markers.json",
"coach_summary.json",
"verification.json",
"manifest.json",
]
for filename in artifact_files:
link = _artifact_link(run_id, filename, str(run_dir / filename))
if link is not None:
links.append(link)
video_link = _artifact_link(
run_id,
"annotated_video.mp4",
result.get("annotated_video_path"),
)
if video_link is not None:
links.append(video_link)
for thumbnail in result.get("issue_thumbnail_paths", []):
if not isinstance(thumbnail, dict):
continue
path = thumbnail.get("path")
issue = thumbnail.get("issue", "issue")
rep_id = thumbnail.get("rep_id", "?")
if not isinstance(path, str):
continue
link = _artifact_link(run_id, f"thumbnail_rep_{rep_id}_{issue}.jpg", path)
if link is not None:
links.append(link)
for clip in result.get("issue_clip_paths", []):
if not isinstance(clip, dict):
continue
path = clip.get("path")
issue = clip.get("issue", "issue")
rep_id = clip.get("rep_id", "?")
if not isinstance(path, str):
continue
link = _artifact_link(run_id, f"clip_rep_{rep_id}_{issue}.mp4", path)
if link is not None:
links.append(link)
return links
def _parse_limitations(limitations: str) -> list[str]:
try:
parsed_limitations = json.loads(limitations)
except json.JSONDecodeError as exc:
raise HTTPException(
status_code=400, detail="Limitations must be valid JSON."
) from exc
if not isinstance(parsed_limitations, list) or not all(
isinstance(item, str) for item in parsed_limitations
):
raise HTTPException(
status_code=400, detail="Limitations must be a JSON list of strings."
)
return parsed_limitations
def _profile_input(
*,
goal: str,
experience_level: str,
intended_exercise: str,
intended_variation: str,
limitations: str,
equipment: str,
) -> dict[str, Any]:
return {
"goal": goal,
"experience_level": experience_level,
"intended_exercise": intended_exercise,
"intended_variation": intended_variation or None,
"known_limitations": _parse_limitations(limitations),
"equipment": equipment,
}
def _parse_bool_form(value: str) -> bool:
return value.strip().lower() in {"1", "true", "yes", "on"}
def _safe_upload_stem(filename: str) -> str:
stem = Path(filename).stem or "upload"
safe_stem = re.sub(r"[^A-Za-z0-9_.-]+", "-", stem).strip(".-_")
return safe_stem[:48] or "upload"
def _run_analysis_pipeline(
video_path: str | None,
profile_input: dict[str, Any],
bypass_verifier: bool = True,
progress: Any | None = None,
) -> dict[str, Any]:
return run_pipeline(
video_path=video_path,
profile_input=profile_input,
bypass_verifier=bypass_verifier,
progress=progress,
)
async def _save_upload(video: UploadFile | None) -> str | None:
video_path: str | None = None
if video is not None and video.filename:
suffix = Path(video.filename).suffix or ".mp4"
prefix = f"pozify-{_safe_upload_stem(video.filename)}-"
with tempfile.NamedTemporaryFile(
delete=False,
prefix=prefix,
suffix=suffix,
) as temp_video:
shutil.copyfileobj(video.file, temp_video)
video_path = temp_video.name
return video_path
def _analysis_response(result: dict[str, Any]) -> dict[str, Any]:
issue_thumbnail_urls = []
for thumbnail in result.get("issue_thumbnail_paths", []):
if not isinstance(thumbnail, dict):
continue
path = thumbnail.get("path")
if not isinstance(path, str):
continue
url = _artifact_url(result["run_id"], path)
if url is not None:
issue_thumbnail_urls.append({**thumbnail, "url": url})
issue_clip_urls = []
for clip in result.get("issue_clip_paths", []):
if not isinstance(clip, dict):
continue
path = clip.get("path")
if not isinstance(path, str):
continue
url = _artifact_url(result["run_id"], path)
if url is not None:
issue_clip_urls.append({**clip, "url": url})
return {
"run_id": result["run_id"],
"run_dir": result["run_dir"],
"annotated_video_url": _artifact_url(
result["run_id"], result["annotated_video_path"]
),
"issue_thumbnail_urls": issue_thumbnail_urls,
"issue_clip_urls": issue_clip_urls,
"artifact_urls": _artifact_urls(result),
"final_report_url": f"/api/artifacts/{result['run_id']}/final_report.json",
"report": result["final_report"],
}
@server.post("/api/analyze")
async def analyze_api(
video: UploadFile | None = File(default=None),
goal: str = Form(default="beginner_practice"),
experience_level: str = Form(default="beginner"),
intended_exercise: str = Form(default="auto"),
intended_variation: str = Form(default=""),
limitations: str = Form(default="[]"),
equipment: str = Form(default="bodyweight"),
bypass_verifier: str = Form(default="true"),
) -> dict[str, Any]:
profile = _profile_input(
goal=goal,
experience_level=experience_level,
intended_exercise=intended_exercise,
intended_variation=intended_variation,
limitations=limitations,
equipment=equipment,
)
video_path = await _save_upload(video)
try:
result = _run_analysis_pipeline(
video_path,
profile,
_parse_bool_form(bypass_verifier),
)
finally:
if video_path is not None:
Path(video_path).unlink(missing_ok=True)
return _analysis_response(result)
@server.post("/api/analyze/stream")
async def analyze_stream_api(
video: UploadFile | None = File(default=None),
goal: str = Form(default="beginner_practice"),
experience_level: str = Form(default="beginner"),
intended_exercise: str = Form(default="auto"),
intended_variation: str = Form(default=""),
limitations: str = Form(default="[]"),
equipment: str = Form(default="bodyweight"),
bypass_verifier: str = Form(default="true"),
) -> StreamingResponse:
profile = _profile_input(
goal=goal,
experience_level=experience_level,
intended_exercise=intended_exercise,
intended_variation=intended_variation,
limitations=limitations,
equipment=equipment,
)
video_path = await _save_upload(video)
events: Queue[dict[str, Any] | None] = Queue()
def worker() -> None:
try:
result = _run_analysis_pipeline(
video_path,
profile,
_parse_bool_form(bypass_verifier),
events.put,
)
events.put({"type": "complete", "result": _analysis_response(result)})
except Exception as exc: # pragma: no cover - surfaced to browser clients
events.put({"type": "error", "detail": str(exc)})
finally:
if video_path is not None:
Path(video_path).unlink(missing_ok=True)
events.put(None)
def event_stream() -> Any:
thread = Thread(target=worker, daemon=True)
thread.start()
while True:
event = events.get()
if event is None:
break
yield f"{json.dumps(event)}\n"
thread.join(timeout=1)
return StreamingResponse(
event_stream(),
media_type="application/x-ndjson",
headers={"Cache-Control": "no-cache"},
)
if __name__ == "__main__":
server.launch(_frontend=False)
|