Spaces:
Running

Shoraky commited on
Commit
cb83a8a
·
1 Parent(s): 324f589

Load vendored ViTPose core at analysis time

Browse files
Files changed (3) hide show
  1. README.md +4 -2
  2. app.py +3 -30
  3. requirements.txt +0 -2
README.md CHANGED
@@ -26,6 +26,8 @@ Fill in `.env` before starting. Both processes share this file. The default loca
26
 
27
  Upload the contents of `Backend/` as the root of a Docker Space, including this README and Dockerfile. Exclude `.env`, `node_modules`, and local build/cache directories. The Space downloads Core from its private dataset repository; local development uses the root `Core/` directory.
28
 
 
 
29
  Set these Space variables/secrets from `.env.example`:
30
 
31
  - `PORT=7860`, `NODE_ENV=production`, `TRUST_PROXY_HOPS=1` (adjust to the actual trusted proxy chain).
@@ -42,8 +44,8 @@ Store tokens, the service-role key, and proxy secret as Space secrets. `HF_TOKEN
42
  Analysis automatically uses Colab for inference when its worker lease is healthy. If no worker is registered, Colab is on CPU, or its connection is lost, the backend falls back to its existing local analysis pipeline. Colab returns analysis reports only; the backend still prepares playback videos, writes the normal `sessions/{session_id}` dataset folder, and updates Supabase.
43
 
44
  1. Generate a separate random secret with at least 32 characters. Add it to the Hugging Face Space as `COLAB_WORKER_SECRET`. Do not reuse `ANALYSIS_PROXY_SECRET`.
45
- 2. Open [`Colab Server/worker.ipynb`](../Colab%20Server/worker.ipynb) in Colab and set the fixed variables at the top of the first code cell. Use a fine-grained GitHub token with read-only Contents access to the private Sporalize repository. The Hugging Face token needs read access to Core and read/write access to the private storage dataset; the repository IDs must match the backend values. Set `CORE_REVISION` too if the backend pins one. The backend URL is the public Space origin, such as `https://shoraky-sporalize-api.hf.space`; the worker secret must match `COLAB_WORKER_SECRET` exactly. Keep real token and secret values out of Git commits.
46
- 3. Select a GPU runtime and run the notebook. It starts the worker and Cloudflare quick tunnel, waits for model initialization, then registers the generated URL automatically. Keep the notebook cell running while analyses should use Colab.
47
  4. The notebook refreshes the worker lease every 20 seconds. The backend treats it as offline after 75 seconds without a heartbeat. Stopping or disconnecting Colab returns new jobs to the normal backend pipeline.
48
 
49
  The worker accepts one analysis at a time. The backend stages inputs and receives reports through temporary folders in the private Hugging Face dataset; large files and report payloads do not cross the tunnel. A job already running on Colab can resume on the backend if the tunnel is lost; Colab does not write final session records or artifacts, so fallback does not create duplicate saved sessions. Temporary handoff folders are deleted when the job completes or falls back. The backend still retains its usual CPU processing requirements for fallback. No Supabase schema change is needed.
 
26
 
27
  Upload the contents of `Backend/` as the root of a Docker Space, including this README and Dockerfile. Exclude `.env`, `node_modules`, and local build/cache directories. The Space downloads Core from its private dataset repository; local development uses the root `Core/` directory.
28
 
29
+ Core includes the ViTPose implementation. The ViTPose-H `coco_25` checkpoint is fetched from the public JunkyByte/easy_ViTPose model repository when the first analysis starts, then reused from the Hugging Face cache. It is not included in the Core dataset or Docker image.
30
+
31
  Set these Space variables/secrets from `.env.example`:
32
 
33
  - `PORT=7860`, `NODE_ENV=production`, `TRUST_PROXY_HOPS=1` (adjust to the actual trusted proxy chain).
 
44
  Analysis automatically uses Colab for inference when its worker lease is healthy. If no worker is registered, Colab is on CPU, or its connection is lost, the backend falls back to its existing local analysis pipeline. Colab returns analysis reports only; the backend still prepares playback videos, writes the normal `sessions/{session_id}` dataset folder, and updates Supabase.
45
 
46
  1. Generate a separate random secret with at least 32 characters. Add it to the Hugging Face Space as `COLAB_WORKER_SECRET`. Do not reuse `ANALYSIS_PROXY_SECRET`.
47
+ 2. Open [`Colab Server/worker.ipynb`](../Colab%20Server/worker.ipynb) in Colab and set its non-secret configuration. Add `GITHUB_TOKEN`, `HF_TOKEN`, and `WORKER_SECRET` to Colab Secrets and grant notebook access. Use a fine-grained GitHub token with read-only Contents access to the private Sporalize repository. The Hugging Face token needs read access to Core and read/write access to the private storage dataset; the repository IDs must match the backend values. Set `CORE_REVISION` too if the backend pins one. The backend URL is the public Space origin, such as `https://shoraky-sporalize-api.hf.space`; the worker secret must match `COLAB_WORKER_SECRET` exactly.
48
+ 3. Select a GPU runtime and run the notebook. It starts the worker and Cloudflare quick tunnel, then registers the generated URL automatically. ViTPose weights download when the first analysis starts. Keep the notebook cell running while analyses should use Colab.
49
  4. The notebook refreshes the worker lease every 20 seconds. The backend treats it as offline after 75 seconds without a heartbeat. Stopping or disconnecting Colab returns new jobs to the normal backend pipeline.
50
 
51
  The worker accepts one analysis at a time. The backend stages inputs and receives reports through temporary folders in the private Hugging Face dataset; large files and report payloads do not cross the tunnel. A job already running on Colab can resume on the backend if the tunnel is lost; Colab does not write final session records or artifacts, so fallback does not create duplicate saved sessions. Temporary handoff folders are deleted when the job completes or falls back. The backend still retains its usual CPU processing requirements for fallback. No Supabase schema change is needed.
app.py CHANGED
@@ -16,9 +16,7 @@ from contextlib import asynccontextmanager
16
  from datetime import datetime, timezone
17
  from functools import lru_cache
18
  from pathlib import Path
19
- from urllib.request import urlretrieve
20
  from uuid import UUID, uuid5
21
- from zipfile import ZipFile
22
 
23
  import httpx
24
  import numpy as np
@@ -40,10 +38,6 @@ jobs = {}
40
  jobs_lock = threading.RLock()
41
  executor = ThreadPoolExecutor(max_workers=1)
42
  logger = logging.getLogger("sporalize")
43
- POSE_MODEL_FILE = "Weights/rtmpose-x-halpe26.onnx"
44
- POSE_MODEL_REPO_ID = ""
45
- POSE_MODEL_HUB_FILE = "rtmpose-x-halpe26.onnx"
46
- POSE_MODEL_REPO_TYPE = "model"
47
  YOLO_MODEL_FILE = "Weights/yolo11x.pt"
48
  YOLO_MODEL_REPO_ID = "Ultralytics/YOLO11"
49
  YOLO_MODEL_HUB_FILE = "yolo11x.pt"
@@ -260,39 +254,18 @@ def runtime():
260
  raise RuntimeError("CORE_REPO_ID is required when Core is not included locally")
261
  root = Path(snapshot_download(repo_id=os.environ["CORE_REPO_ID"], repo_type="dataset",
262
  revision=os.environ.get("CORE_REVISION"), token=os.environ["HF_TOKEN"],
263
- allow_patterns=["pipeline.py", "Weights/*"]))
264
  spec = importlib.util.spec_from_file_location("sporalize_core", root / "pipeline.py")
265
  module = importlib.util.module_from_spec(spec)
266
  spec.loader.exec_module(module)
267
- pose_file = POSE_MODEL_FILE
268
  yolo_file = YOLO_MODEL_FILE
269
- pose = (root / pose_file).resolve()
270
  yolo = (root / yolo_file).resolve()
271
- if root.resolve() not in pose.parents or root.resolve() not in yolo.parents:
272
  raise RuntimeError("Model files must be inside the Core repository")
273
- if not pose.is_file():
274
- cache = Path(os.environ.get("HF_HOME", str(Path.home() / ".cache/huggingface"))) / "sporalize"
275
- cache.mkdir(parents=True, exist_ok=True)
276
- if not (cache / Path(pose_file).name).is_file():
277
- if POSE_MODEL_REPO_ID:
278
- downloaded = hf_hub_download(POSE_MODEL_REPO_ID, POSE_MODEL_HUB_FILE,
279
- repo_type=POSE_MODEL_REPO_TYPE, token=os.environ["HF_TOKEN"])
280
- shutil.copyfile(downloaded, cache / Path(pose_file).name)
281
- elif pose_file == "Weights/rtmpose-x-halpe26.onnx":
282
- with tempfile.TemporaryDirectory() as temporary:
283
- archive = Path(temporary) / "pose.zip"
284
- urlretrieve("https://download.openmmlab.com/mmpose/v1/projects/rtmposev1/onnx_sdk/rtmpose-x_simcc-body7_pt-body7-halpe26_700e-384x288-7fb6e239_20230606.zip", archive)
285
- with ZipFile(archive) as bundle:
286
- member = next(name for name in bundle.namelist() if name.endswith("end2end.onnx"))
287
- with bundle.open(member) as source, (cache / Path(pose_file).name).open("wb") as target:
288
- shutil.copyfileobj(source, target)
289
- else:
290
- raise RuntimeError("Configured pose model is missing from Core and no pose model repository was configured")
291
- pose = cache / Path(pose_file).name
292
  if not yolo.is_file():
293
  yolo = Path(hf_hub_download(YOLO_MODEL_REPO_ID, YOLO_MODEL_HUB_FILE,
294
  repo_type=YOLO_MODEL_REPO_TYPE, token=os.environ["HF_TOKEN"]))
295
- return module.run_pipeline, {"POSE_PATH": str(pose), "YOLO_PATH": str(yolo)}
296
 
297
 
298
  @asynccontextmanager
 
16
  from datetime import datetime, timezone
17
  from functools import lru_cache
18
  from pathlib import Path
 
19
  from uuid import UUID, uuid5
 
20
 
21
  import httpx
22
  import numpy as np
 
38
  jobs_lock = threading.RLock()
39
  executor = ThreadPoolExecutor(max_workers=1)
40
  logger = logging.getLogger("sporalize")
 
 
 
 
41
  YOLO_MODEL_FILE = "Weights/yolo11x.pt"
42
  YOLO_MODEL_REPO_ID = "Ultralytics/YOLO11"
43
  YOLO_MODEL_HUB_FILE = "yolo11x.pt"
 
254
  raise RuntimeError("CORE_REPO_ID is required when Core is not included locally")
255
  root = Path(snapshot_download(repo_id=os.environ["CORE_REPO_ID"], repo_type="dataset",
256
  revision=os.environ.get("CORE_REVISION"), token=os.environ["HF_TOKEN"],
257
+ allow_patterns=["pipeline.py", "ViTPose/**", "Weights/*"]))
258
  spec = importlib.util.spec_from_file_location("sporalize_core", root / "pipeline.py")
259
  module = importlib.util.module_from_spec(spec)
260
  spec.loader.exec_module(module)
 
261
  yolo_file = YOLO_MODEL_FILE
 
262
  yolo = (root / yolo_file).resolve()
263
+ if root.resolve() not in yolo.parents:
264
  raise RuntimeError("Model files must be inside the Core repository")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  if not yolo.is_file():
266
  yolo = Path(hf_hub_download(YOLO_MODEL_REPO_ID, YOLO_MODEL_HUB_FILE,
267
  repo_type=YOLO_MODEL_REPO_TYPE, token=os.environ["HF_TOKEN"]))
268
+ return module.run_pipeline, {"YOLO_PATH": str(yolo)}
269
 
270
 
271
  @asynccontextmanager
requirements.txt CHANGED
@@ -7,8 +7,6 @@ httpx>=0.27.0
7
  numpy
8
  scipy
9
  opencv-python-headless
10
- onnxruntime
11
- rtmlib>=0.0.14
12
  torch
13
  ultralytics
14
  lap>=0.5.12
 
7
  numpy
8
  scipy
9
  opencv-python-headless
 
 
10
  torch
11
  ultralytics
12
  lap>=0.5.12