Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore(rig): delete the retired unirig worker now that model-rig serves every call
nirholas113bad7b8a10
diff --git a/workers/unirig/Dockerfile b/workers/unirig/Dockerfiledeleted file mode 100644index f605539ad..000000000--- a/workers/unirig/Dockerfile+++ /dev/null@@ -1,42 +0,0 @@-FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04--# devel (not runtime) base: the git-sourced UniRig package compiles CUDA point--# cloud / sparse-conv ops at install time and needs nvcc + a C++ toolchain.-# TORCH_CUDA_ARCH_LIST targets the Cloud Run L4 (compute capability 8.9).-ENV PYTHONDONTWRITEBYTECODE=1 \- PYTHONUNBUFFERED=1 \- PIP_NO_CACHE_DIR=1 \- DEBIAN_FRONTEND=noninteractive \- TORCH_CUDA_ARCH_LIST="8.9+PTX"--RUN apt-get update && apt-get install -y --no-install-recommends \- python3.10 python3.10-dev python3-pip \- git curl wget build-essential ninja-build \- libgl1 libglib2.0-0 \- && rm -rf /var/lib/apt/lists/* \- && ln -sf /usr/bin/python3.10 /usr/bin/python3 \- && ln -sf /usr/bin/python3.10 /usr/bin/python \- && pip install --upgrade pip setuptools wheel--# torch + torchvision first (cached layer), matching the CUDA 12.1 base. UniRig's-# image/render utilities import torchvision, which isn't pulled in transitively.-RUN pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121--COPY requirements.txt /app/requirements.txt-RUN pip install -r /app/requirements.txt--WORKDIR /app-COPY worker_security.py /app/worker_security.py-COPY rig_glb.py /app/rig_glb.py-COPY main.py /app/main.py--# Wolf3D skeleton templates for blendshape transfer (added in Phase 2).-RUN mkdir -p /app/templates--EXPOSE 8080--CMD ["uvicorn", "main:app", \- "--host", "0.0.0.0", \- "--port", "8080", \- "--workers", "1", \- "--timeout-keep-alive", "300"]diff --git a/workers/unirig/README.md b/workers/unirig/README.mddeleted file mode 100644index 414bbe9d5..000000000--- a/workers/unirig/README.md+++ /dev/null@@ -1,196 +0,0 @@-# unirig — auto-rigging (skeleton, skin weights, blendshapes)--> **DEPRECATED (2026-07-17).** Superseded by [workers/rig/](../rig/), a-> contract-compatible replacement built on Make-It-Animatable. Findings that-> forced the replacement: the live `unirig` Cloud Run service was deployed-> from code that never landed in this repo (its `/health` payload does not-> match any commit); the checked-in image cannot build (upstream UniRig has-> no pip packaging, and `main.py` calls a `UniRigModel.from_pretrained()` API-> that does not exist upstream); the live service produced generically named-> `bone_N` skeletons the platform retargeter cannot drive, zero blendshapes-> (the Dockerfile ships an empty templates dir), and ~21-minute latencies.-> After the `GCP_UNIRIG_URL` cutover to `model-rig`, delete the old Cloud Run-> service to free one L4 toward the quota ceiling, then remove this directory.--Takes a raw, unrigged mesh from one of the 3D generation models and makes it-animation-ready. Wraps [UniRig](https://github.com/VAST-AI-Research/UniRig)-(VAST-AI, MIT, SIGGRAPH 2025), which predicts:--- humanoid skeleton joint placement,-- per-vertex skinning weights,-- ARKit-named blendshapes, transferred from a template head mesh.--It is the rigging stage of the avatar pipeline: the-[avatar-pipeline-controller](../avatar-pipeline-controller/) generates a mesh-(TRELLIS / Hunyuan3D / TripoSG / …) and then hands that mesh to this service to-get a rigged GLB back. The output drops straight into the three.ws animation-library — bone names are canonicalized on import by-[`src/glb-canonicalize.js`](../../src/glb-canonicalize.js), so the pre-baked-idle/walk clips retarget onto it, legs included.--The GPU inference (`main.py` → `_model.rig(...)`) is separated from the pure-glTF skin authoring (`rig_glb.py` → `build_rigged_glb`), which uses only-numpy/scipy/pygltflib/trimesh so it can be unit-tested with no GPU.--## API--FastAPI service on port `8080`. All routes require-`Authorization: Bearer $API_KEY` except `/health`. Jobs run in the background;-poll `/tasks/{id}` for the result.--### `POST /rig` → `202`--```bash-curl -X POST https://$SERVICE_URL/rig \- -H "Authorization: Bearer $API_KEY" -H 'Content-Type: application/json' \- -d '{"mesh_gcs_url":"https://storage.googleapis.com/three-ws-avatar-reconstructions/…/mesh.glb","blendshapes":true}'-# → { "task_id": "…", "status": "queued" }-```--| Field | Required | Default | Notes |-|---|---|---|---|-| `mesh_gcs_url` | yes | — | The unrigged mesh to rig |-| `template` | no | `wolf3d_neutral` | Template head mesh used for blendshape transfer |-| `blendshapes` | no | `true` | Set `false` to skip ARKit blendshape transfer and rig faster |-| `job_id` | no | — | Accepted for request-shape compatibility with the controller; not stored or echoed |--`mesh_gcs_url` is fetched through the SSRF guard in-[`worker_security.py`](./worker_security.py): https-only, private/loopback/-link-local/metadata IPs rejected after DNS resolution, redirects re-validated-per hop, response size bounded.--### `GET /tasks/{task_id}`--```json-{ "task_id": "…", "status": "done", "rigged_gcs_url": "https://storage.googleapis.com/three-ws-avatar-reconstructions/rigged-meshes/….glb", "elapsed_ms": 41200 }-```--`status` is `queued` | `running` | `done` | `failed`. On `failed` the object-carries a sanitized `error` string instead of `rigged_gcs_url`. Note the success-field is `rigged_gcs_url`, not the `result_gcs_url` the mesh workers return — the-controller reads either. Tasks are held in memory, so a `404` after a restart is-expected.--### `GET /health`--```json-{ "ok": true, "model": "unirig", "gpu_available": true, "gpu_name": "NVIDIA L4", "model_loaded": true }-```--## Env--| Var | Required | Default | Notes |-|---|---|---|---|-| `API_KEY` | yes | — | Shared bearer secret (Secret Manager: `avatar-reconstruction-key`) |-| `GCS_BUCKET` | yes | — | Output bucket for rigged GLBs (`three-ws-avatar-reconstructions`) |-| `WEIGHTS_DIR` | no | `/weights/unirig` | UniRig weights, served from the mounted `three-ws-model-weights` GCS volume |-| `TEMPLATES_DIR` | no | `/app/templates` | Skeleton/blendshape templates |-| `MAX_CONCURRENT` | no | `1` | Parallel rig jobs — one L4 fits one rig |--## Deploy--Cloud Run service **`unirig`** in **`us-central1`**, built by Cloud Build from-[`cloudbuild.yaml`](./cloudbuild.yaml):--Submit from the **repo root** — the build step declares `dir: workers/unirig`, so-the upload source is the whole repo:--```bash-gcloud builds submit --config workers/unirig/cloudbuild.yaml .-```--The build compiles UniRig's CUDA ops (spconv / torch-scatter) from a-`cuda:12.1.1-cudnn8-devel` base, so it uses a 3600 s build timeout. The deployed-service runs 1× `nvidia-l4`, 4 vCPU, 16 GiB, 900 s request timeout,-`min-instances=1` (kept warm — it is on the critical path of every avatar-generation), `max-instances=2`, no CPU throttling. Model weights are populated-once into `gs://three-ws-model-weights/unirig/`:--```bash-pip install huggingface_hub-huggingface-cli download VAST-AI/UniRig --local-dir /tmp/unirig-gsutil -m cp -r /tmp/unirig gs://three-ws-model-weights/unirig/-```--> **Deploy trap:** point the caller env vars at *this* `unirig` service. The-> `three-ws-avatar-reconstructions` service exposes no `/rig`, so pointing a rig-> caller there returns 404 — the two are separate Cloud Run services that only-> share a GCS bucket name. See-> [`docs/ops/gcp-model-workers.md`](../../docs/ops/gcp-model-workers.md) and the-> production runbook [`docs/ops/gcp-production.md`](../../docs/ops/gcp-production.md).--## Callers--Two upstreams call `POST /rig` + `GET /tasks/{id}`:--- **[avatar-pipeline-controller](../avatar-pipeline-controller/)** via its- `UNIRIG_URL` env var, after a mesh backend returns. Set `SKIP_RIGGING=true` on- the controller to return the raw mesh and bypass this stage.-- **The platform API** rig provider ([`api/_providers/gcp.js`](../../api/_providers/gcp.js))- via `GCP_UNIRIG_URL`, which powers the `rerig` path. Without it, `rerig` falls- back to `GCP_RECONSTRUCTION_URL` (which has no `/rig`) and every rig submit- 404s.--Both authenticate with the shared `avatar-reconstruction-key` secret.--## Example — rig a mesh, poll, fetch--Feeds the GLB from a mesh worker (e.g. [model-trellis](../model-trellis/)) straight-into `/rig`:--```bash-BASE=https://unirig-xxxxxxxx-uc.a.run.app-KEY=your-api-key-MESH=https://storage.googleapis.com/three-ws-avatar-reconstructions/raw-meshes/trellis/3f2c….glb--TASK=$(curl -s -X POST "$BASE/rig" \- -H "Authorization: Bearer $KEY" \- -H 'Content-Type: application/json' \- -d "{\"mesh_gcs_url\":\"$MESH\",\"blendshapes\":true}" \- | python3 -c 'import sys,json; print(json.load(sys.stdin)["task_id"])')--while :; do- STATE=$(curl -s "$BASE/tasks/$TASK" -H "Authorization: Bearer $KEY")- echo "$STATE"- echo "$STATE" | grep -q '"status": *"done"' && break- echo "$STATE" | grep -q '"status": *"failed"' && exit 1- sleep 5-done--curl -s "$BASE/tasks/$TASK" -H "Authorization: Bearer $KEY" \- | python3 -c 'import sys,json; print(json.load(sys.stdin)["rigged_gcs_url"])'-```--## Tests--`rig_glb.py` holds the GPU-free glTF authoring; `test_rig_glb.py` covers it.--```bash-cd workers/unirig && python -m pytest test_rig_glb.py-```--## Run locally--Requires a CUDA GPU and local UniRig weights. UniRig compiles CUDA ops at install-time, so the reproducible path is the image:--```bash-cd workers/unirig-docker build -t unirig .--docker run --rm --gpus all -p 8080:8080 \- -e API_KEY=dev-secret \- -e GCS_BUCKET=your-dev-bucket \- -e WEIGHTS_DIR=/weights/unirig \- -e GOOGLE_APPLICATION_CREDENTIALS=/gcp/sa.json \- -v /path/to/unirig:/weights/unirig:ro \- -v /path/to/sa.json:/gcp/sa.json:ro \- unirig-```--With the UniRig environment already installed you can run the server directly:--```bash-API_KEY=dev-secret GCS_BUCKET=your-dev-bucket WEIGHTS_DIR=/path/to/unirig \- uvicorn main:app --host 0.0.0.0 --port 8080-```diff --git a/workers/unirig/__pycache__/main.cpython-312.pyc b/workers/unirig/__pycache__/main.cpython-312.pycdeleted file mode 100644index 939c4e556..000000000Binary files a/workers/unirig/__pycache__/main.cpython-312.pyc and /dev/null differdiff --git a/workers/unirig/__pycache__/rig_glb.cpython-312.pyc b/workers/unirig/__pycache__/rig_glb.cpython-312.pycdeleted file mode 100644index b5a9fb157..000000000Binary files a/workers/unirig/__pycache__/rig_glb.cpython-312.pyc and /dev/null differdiff --git a/workers/unirig/__pycache__/test_rig_glb.cpython-312.pyc b/workers/unirig/__pycache__/test_rig_glb.cpython-312.pycdeleted file mode 100644index c26ed0da3..000000000Binary files a/workers/unirig/__pycache__/test_rig_glb.cpython-312.pyc and /dev/null differdiff --git a/workers/unirig/__pycache__/worker_security.cpython-312.pyc b/workers/unirig/__pycache__/worker_security.cpython-312.pycdeleted file mode 100644index 62088f518..000000000Binary files a/workers/unirig/__pycache__/worker_security.cpython-312.pyc and /dev/null differdiff --git a/workers/unirig/cloudbuild.yaml b/workers/unirig/cloudbuild.yamldeleted file mode 100644index aabd74bf2..000000000--- a/workers/unirig/cloudbuild.yaml+++ /dev/null@@ -1,73 +0,0 @@-# Builds run as the pinned three-ws-build service account: the project's default-# compute service account was deleted, so an unpinned submit fails with-# "Unknown service account".-serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]--substitutions:- _REGION: us-central1- _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com- _SERVICE: unirig- _REPO: unirig- _GCS_BUCKET: three-ws-avatar-reconstructions- _WEIGHTS_BUCKET: three-ws-model-weights- _MIN_INSTANCES: "1"- _MAX_INSTANCES: "2"--steps:- - id: build- name: gcr.io/cloud-builders/docker- dir: workers/unirig- args:- - build- - --tag- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA- - --tag- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest- - --cache-from- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest- - .-- - id: push- name: gcr.io/cloud-builders/docker- args:- - push- - --all-tags- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server-- - id: deploy- name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim- entrypoint: gcloud- args:- - run- - deploy- - ${_SERVICE}- - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA- - --region=${_REGION}- - --service-account=${_RUN_SA}- - --platform=managed- - --port=8080- - --gpu=1- - --gpu-type=nvidia-l4- - --no-gpu-zonal-redundancy- - --no-cpu-throttling- - --cpu=4- - --memory=16Gi- - --min-instances=${_MIN_INSTANCES}- - --max-instances=${_MAX_INSTANCES}- - --timeout=900- - --allow-unauthenticated- - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}- - --add-volume-mount=volume=weights,mount-path=/weights- - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/unirig,MAX_CONCURRENT=1- - --set-secrets=API_KEY=avatar-reconstruction-key:latest--images:- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA- - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest--options:- machineType: E2_HIGHCPU_32- logging: CLOUD_LOGGING_ONLY--# UniRig compiles CUDA ops (spconv / torch-scatter) — past the 10-minute default.-timeout: 3600sdiff --git a/workers/unirig/main.py b/workers/unirig/main.pydeleted file mode 100644index 8419adc3c..000000000--- a/workers/unirig/main.py+++ /dev/null@@ -1,215 +0,0 @@-"""-UniRig auto-rigging service — adds skeleton, skinning weights, and ARKit-52-blendshapes to raw meshes from the 3D generation models.--VAST-AI-Research/UniRig (MIT, SIGGRAPH 2025) predicts:- - Skeleton joint placement (humanoid hierarchy)- - Per-vertex skinning weights- - Blendshape transfer from a template head mesh--API contract (consumed by the Pipeline Controller):- POST /rig { mesh_gcs_url: str, template?: str, blendshapes?: bool, job_id?: str }- → 202 { task_id, status: "queued" }-- GET /tasks/:id → { task_id, status, rigged_gcs_url?, error? }-- GET /health → { ok, model, gpu_available }--Model weights pre-population:- pip install huggingface_hub- huggingface-cli download VAST-AI/UniRig --local-dir /tmp/unirig- gsutil -m cp -r /tmp/unirig gs://three-ws-model-weights/unirig/--Environment variables:- API_KEY — shared bearer secret- GCS_BUCKET — Cloud Storage bucket for output rigged GLBs- WEIGHTS_DIR — local path to UniRig model weights (default: /weights/unirig)- TEMPLATES_DIR — local path to skeleton/blendshape templates (default: /app/templates)- MAX_CONCURRENT — max parallel rigging jobs (default: 1)-"""--from __future__ import annotations--import asyncio-import io-import logging-import os-import time-import uuid-from contextlib import asynccontextmanager-from typing import Optional--import torch-import trimesh-from fastapi import FastAPI, HTTPException, Header, BackgroundTasks-from google.cloud import storage-from pydantic import BaseModel, Field--from rig_glb import build_rigged_glb-from worker_security import (- UnsafeUrlError,- fetch_remote_bytes_async,- require_api_key,- safe_error,-)--logging.basicConfig(- level=logging.INFO,- format="%(asctime)s %(levelname)s %(name)s %(message)s",-)-log = logging.getLogger("unirig")--API_KEY = os.environ["API_KEY"]-GCS_BUCKET = os.environ["GCS_BUCKET"]-WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/unirig")-TEMPLATES_DIR = os.environ.get("TEMPLATES_DIR", "/app/templates")-MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))--_model = None-_bucket: Optional[storage.Bucket] = None-_sem: Optional[asyncio.Semaphore] = None-_tasks: dict[str, dict] = {}---def _load_model():- global _model- from unirig import UniRigModel-- log.info("Loading UniRig model from %s", WEIGHTS_DIR)- _model = UniRigModel.from_pretrained(WEIGHTS_DIR)- _model = _model.to("cuda")- _model.eval()- log.info("UniRig model loaded")---@asynccontextmanager-async def lifespan(app: FastAPI):- global _bucket, _sem- _bucket = storage.Client().bucket(GCS_BUCKET)- _sem = asyncio.Semaphore(MAX_CONCURRENT)- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, _load_model)- log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)- yield---app = FastAPI(title="unirig", lifespan=lifespan)---def _require_api_key(authorization: str) -> None:- try:- require_api_key(authorization, API_KEY)- except PermissionError as exc:- raise HTTPException(status_code=401, detail=str(exc)) from exc----async def _run_rigging(- task_id: str,- mesh_gcs_url: str,- template: str,- blendshapes: bool,-) -> None:- async with _sem:- _tasks[task_id]["status"] = "running"- loop = asyncio.get_event_loop()- t0 = time.time()- try:- # Download the raw mesh from GCS. SSRF-hardened: https-only,- # private/loopback/link-local/metadata IPs rejected after DNS- # resolution, redirects re-validated per hop, response size bounded.- import httpx- async with httpx.AsyncClient(timeout=60, follow_redirects=False) as client:- try:- mesh_bytes = await fetch_remote_bytes_async(client, mesh_gcs_url)- except UnsafeUrlError as exc:- raise RuntimeError(f"refused to fetch mesh url: {exc}") from exc-- def _rig():- mesh = trimesh.load(io.BytesIO(mesh_bytes), file_type="glb", force="mesh")-- with torch.no_grad():- result = _model.rig(- vertices=torch.tensor(mesh.vertices, dtype=torch.float32, device="cuda"),- faces=torch.tensor(mesh.faces, dtype=torch.long, device="cuda"),- )-- skeleton = result["skeleton"]- skinning_weights = result["skinning_weights"]-- joints = skeleton["joints"].cpu().numpy()- parents = skeleton["parents"].cpu().numpy()- weights = skinning_weights.cpu().numpy()-- blendshape_data = result.get("blendshapes") if blendshapes else None- return build_rigged_glb(- mesh_bytes, mesh, joints, parents, weights, blendshape_data,- )-- rigged_bytes = await loop.run_in_executor(None, _rig)-- blob_name = f"rigged-meshes/{task_id}.glb"- blob = _bucket.blob(blob_name)- await loop.run_in_executor(- None,- lambda: blob.upload_from_string(rigged_bytes, content_type="model/gltf-binary"),- )- gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"-- elapsed = time.time() - t0- _tasks[task_id].update({- "status": "done",- "rigged_gcs_url": gcs_url,- "elapsed_ms": int(elapsed * 1000),- })- log.info("[%s] rigging done in %.1fs — %d bytes → %s", task_id, elapsed, len(rigged_bytes), gcs_url)-- except Exception as exc:- _tasks[task_id].update({- "status": "failed",- "error": safe_error(exc, context=f"[{task_id}] rigging"),- "elapsed_ms": int((time.time() - t0) * 1000),- })----class RigRequest(BaseModel):- mesh_gcs_url: str- template: str = "wolf3d_neutral"- blendshapes: bool = True- job_id: str | None = None--[email protected]("/rig", status_code=202)-async def rig(- body: RigRequest,- background_tasks: BackgroundTasks,- authorization: str = Header(...),-) -> dict:- _require_api_key(authorization)- task_id = str(uuid.uuid4())- _tasks[task_id] = {"task_id": task_id, "status": "queued"}- background_tasks.add_task(- _run_rigging, task_id, body.mesh_gcs_url, body.template, body.blendshapes,- )- return {"task_id": task_id, "status": "queued"}--[email protected]("/tasks/{task_id}")-async def get_task(task_id: str, authorization: str = Header(...)) -> dict:- _require_api_key(authorization)- task = _tasks.get(task_id)- if task is None:- raise HTTPException(status_code=404, detail="task not found")- return task--[email protected]("/health")-async def health() -> dict:- return {- "ok": True,- "model": "unirig",- "gpu_available": torch.cuda.is_available(),- "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,- "model_loaded": _model is not None,- }diff --git a/workers/unirig/requirements.txt b/workers/unirig/requirements.txtdeleted file mode 100644index 5fd39974f..000000000--- a/workers/unirig/requirements.txt+++ /dev/null@@ -1,18 +0,0 @@-# ── UniRig (VAST-AI, SIGGRAPH 2025) ──────────────────────────────────────────-unirig @ git+https://github.com/VAST-AI-Research/UniRig.git@main--torch>=2.3.0-trimesh>=4.4.0-numpy<2.0-pygltflib==1.16.2-Pillow>=10.3.0-scipy>=1.11.0--# ── Server ────────────────────────────────────────────────────────────────────-fastapi==0.115.0-uvicorn[standard]==0.32.0-pydantic>=2.0.0-httpx>=0.27.0--# ── GCP ───────────────────────────────────────────────────────────────────────-google-cloud-storage==2.18.0diff --git a/workers/unirig/rig_glb.py b/workers/unirig/rig_glb.pydeleted file mode 100644index 6a94d06e9..000000000--- a/workers/unirig/rig_glb.py+++ /dev/null@@ -1,373 +0,0 @@-"""-Pure glTF skin authoring — turns a raw mesh GLB + UniRig's predicted skeleton-and skinning weights into a spec-valid *rigged* GLB.--Kept dependency-light on purpose (numpy / scipy / pygltflib / trimesh only, no-torch / CUDA / GCP) so it can be unit-tested without a GPU — see test_rig_glb.py.--What `build_rigged_glb` produces, preserving all original geometry/materials:- • a joint-node hierarchy (parent-relative translations, identity bind rotations)- • an inverseBindMatrices accessor- • a `skin` bound to every node that draws a mesh- • JOINTS_0 / WEIGHTS_0 vertex attributes (top-4 normalized influences) on each- primitive, aligned to that primitive's exact vertex order via a KD-tree- (the model's GLB vertex set need not match UniRig's working vertices)- • optional ARKit-named morph targets when UniRig supplies blendshape deltas--Robustness: model output is sanitized (NaN/Inf/negative weights dropped), every-vertex is guaranteed a unit weight sum (no skinning collapse), JOINTS_0 uses the-smallest legal integer width, and a non-identity skinned-node transform — which-would silently misplace the skeleton — fails loudly instead of corrupting output.-"""--from __future__ import annotations--import logging--import numpy as np-import pygltflib-from scipy.spatial import cKDTree--log = logging.getLogger("unirig.rig_glb")--# Wolf3D / ARKit-52 skeleton joint names. UniRig predicts joint placement; when-# it returns exactly this many joints we name them in this canonical order so-# the three.ws avatar runtime can retarget; otherwise joints are named joint_i.-WOLF3D_JOINTS = [- "Hips", "Spine", "Spine1", "Spine2", "Neck", "Head",- "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",- "RightShoulder", "RightArm", "RightForeArm", "RightHand",- "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase",- "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase",- "LeftEye", "RightEye", "Jaw",-]--ARKIT_52_BLENDSHAPES = [- "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft",- "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight",- "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",- "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight",- "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",- "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",- "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight",- "mouthFrownLeft", "mouthFrownRight", "mouthFunnel", "mouthLeft",- "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft",- "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower",- "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft",- "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight",- "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight",- "tongueOut",-]--# glTF constant codes (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html).-_GLTF_FLOAT = 5126-_GLTF_UBYTE = 5121-_GLTF_USHORT = 5123-_GLTF_ARRAY_BUFFER = 34962-_MAX_INFLUENCES = 4 # glTF JOINTS_0/WEIGHTS_0 carry 4 influences per set---def _append_view(glb, blob: bytearray, data: bytes, target: int | None = None) -> int:- """Append `data` to the GLB binary buffer (4-byte aligned) and return the- index of a new bufferView covering it."""- while len(blob) % 4 != 0:- blob.append(0)- offset = len(blob)- blob.extend(data)- bv = pygltflib.BufferView(buffer=0, byteOffset=offset, byteLength=len(data))- if target is not None:- bv.target = target- glb.bufferViews.append(bv)- return len(glb.bufferViews) - 1---def _add_accessor(glb, view: int, comp: int, count: int, typ: str,- mn=None, mx=None) -> int:- acc = pygltflib.Accessor(- bufferView=view, byteOffset=0, componentType=comp, count=count, type=typ,- )- if mn is not None:- acc.min = mn- if mx is not None:- acc.max = mx- glb.accessors.append(acc)- return len(glb.accessors) - 1---def _read_positions(glb, blob: bytearray, acc_idx: int) -> np.ndarray:- """Decode a VEC3/FLOAT POSITION accessor from the binary buffer. Handles- both tightly packed and interleaved (byteStride) layouts, vectorized."""- acc = glb.accessors[acc_idx]- if acc.componentType != _GLTF_FLOAT or acc.type != "VEC3":- raise RuntimeError(- f"unsupported POSITION accessor (componentType={acc.componentType}, type={acc.type}); "- "skinning expects float32 VEC3 positions"- )- bv = glb.bufferViews[acc.bufferView]- base = (bv.byteOffset or 0) + (acc.byteOffset or 0)- n = acc.count- stride = bv.byteStride or 12- if stride == 12:- return np.frombuffer(bytes(blob[base:base + 12 * n]), dtype="<f4").reshape(n, 3).copy()- # Interleaved: lift the first 12 bytes (the VEC3) out of each stride slot.- raw = np.frombuffer(bytes(blob[base:base + stride * n]), dtype=np.uint8).reshape(n, stride)- return raw[:, :12].copy().view("<f4").reshape(n, 3)---def _quat_to_mat3(x, y, z, w):- n = x * x + y * y + z * z + w * w- if n < 1e-12:- return np.eye(3)- s = 2.0 / n- return np.array([- [1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)],- [s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)],- [s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)],- ])---def _local_matrix(node) -> np.ndarray:- if node.matrix:- # glTF stores matrices column-major; transpose to math (row-major) form.- return np.array(node.matrix, dtype=np.float64).reshape(4, 4).T- m = np.eye(4)- if node.rotation:- m[:3, :3] = _quat_to_mat3(*node.rotation)- if node.scale:- m[:3, :3] = m[:3, :3] @ np.diag(node.scale)- if node.translation:- m[:3, 3] = node.translation- return m---def _world_matrices(glb) -> list[np.ndarray]:- """World transform of every node, composed down the hierarchy."""- n = len(glb.nodes)- local = [_local_matrix(glb.nodes[i]) for i in range(n)]- parent = {}- for i, nd in enumerate(glb.nodes):- for c in (nd.children or []):- parent[c] = i- world: list[np.ndarray | None] = [None] * n-- def compute(i):- if world[i] is None:- p = parent.get(i)- world[i] = local[i] if p is None else compute(p) @ local[i]- return world[i]-- return [compute(i) for i in range(n)]---def _normalize_blendshapes(data):- """Coerce UniRig's blendshape output into (names, deltas[K,V,3]). Accepts a- {name: (V,3)} dict, a {"names":[...], "deltas": array} dict, or a bare- (K,V,3) array (named positionally from ARKIT_52_BLENDSHAPES)."""- if isinstance(data, dict):- if "deltas" in data:- deltas = np.asarray(data["deltas"], dtype=np.float32)- names = list(data.get("names") or ARKIT_52_BLENDSHAPES[: len(deltas)])- else:- names = list(data.keys())- deltas = np.stack([np.asarray(data[k], dtype=np.float32) for k in names], axis=0)- else:- deltas = np.asarray(data, dtype=np.float32)- names = list(ARKIT_52_BLENDSHAPES[: len(deltas)])- if deltas.ndim != 3 or deltas.shape[-1] != 3:- raise RuntimeError(f"blendshape deltas must be (K,V,3); got {deltas.shape}")- if len(names) < len(deltas):- names += [f"blendshape_{i}" for i in range(len(names), len(deltas))]- return names[: len(deltas)], deltas---def _top_influences(weights, n_joints):- """Sanitize the (V,J) weight matrix and reduce it to (V,4) joint indices +- (V,4) normalized weights. Every vertex is guaranteed a unit weight sum: a- vertex the model left empty is pinned to joint 0 rather than collapsing to- the origin under linear-blend skinning."""- w = np.nan_to_num(np.asarray(weights, dtype=np.float32),- nan=0.0, posinf=0.0, neginf=0.0)- np.clip(w, 0.0, None, out=w)- if w.shape[1] < _MAX_INFLUENCES:- w = np.pad(w, ((0, 0), (0, _MAX_INFLUENCES - w.shape[1])))-- order = np.argsort(-w, axis=1)[:, :_MAX_INFLUENCES]- top = np.take_along_axis(w, order, axis=1).astype(np.float32)-- empty = top.sum(axis=1) <= 0.0- if empty.any():- order[empty] = 0- top[empty] = 0.0- top[empty, 0] = 1.0-- top /= top.sum(axis=1, keepdims=True)- joint_idx = np.clip(order, 0, max(n_joints - 1, 0))- return joint_idx, top---def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights, blendshape_data=None):- """Author a fully rigged GLB from the raw mesh and UniRig's predictions.- Returns the serialized GLB bytes. `mesh` is the trimesh the weights were- computed over; `joints` (J,3) world-space, `parents` (J,), `weights` (V,J)."""- glb = pygltflib.GLTF2.load_from_bytes(mesh_bytes)- blob = bytearray(glb.binary_blob() or b"")-- joints = np.asarray(joints, dtype=np.float32).reshape(-1, 3) # (J,3) world-space- parents = np.asarray(parents).astype(np.int64).reshape(-1) # (J,)- n_joints = joints.shape[0]- n_verts = len(mesh.vertices)- weights = np.asarray(weights, dtype=np.float32) # (V,J)- if parents.shape[0] != n_joints:- raise RuntimeError(f"joints/parents length mismatch: {n_joints} vs {parents.shape[0]}")- if weights.ndim != 2 or weights.shape[1] != n_joints:- raise RuntimeError(f"skinning weights must be (V,{n_joints}); got {weights.shape}")- if weights.shape[0] != n_verts:- raise RuntimeError(- f"weights rows ({weights.shape[0]}) != mesh vertices ({n_verts}); "- "UniRig output is not aligned to the input mesh"- )-- if not glb.scenes:- glb.scenes.append(pygltflib.Scene(nodes=[]))- scene = glb.scenes[glb.scene if glb.scene is not None else 0]-- # World transforms of the ORIGINAL nodes (before we add joint nodes), used- # to (a) match weights in the same space the joints live in and (b) reject- # a transformed skinned node whose bind pose we cannot honor.- world_mats = _world_matrices(glb)-- # ── joint nodes (parent-relative translations; identity bind rotations) ──- base_node = len(glb.nodes)- joint_nodes = [base_node + i for i in range(n_joints)]- child_map: dict[int, list[int]] = {i: [] for i in range(n_joints)}- for i in range(n_joints):- p = int(parents[i])- if 0 <= p < n_joints:- child_map[p].append(joint_nodes[i])- named = n_joints == len(WOLF3D_JOINTS)- for i in range(n_joints):- p = int(parents[i])- origin = joints[p] if 0 <= p < n_joints else np.zeros(3, dtype=np.float32)- local = (joints[i] - origin).astype(float)- node = pygltflib.Node(- name=WOLF3D_JOINTS[i] if named else f"joint_{i}",- translation=[local[0], local[1], local[2]],- )- if child_map[i]:- node.children = child_map[i]- glb.nodes.append(node)- roots = [joint_nodes[i] for i in range(n_joints) if not 0 <= int(parents[i]) < n_joints]- for r in roots:- if r not in scene.nodes:- scene.nodes.append(r)-- # ── inverseBindMatrices: inverse(world bind) = translate(-world), col-major ──- ibm = np.zeros((n_joints, 16), dtype=np.float32)- ibm[:, 0] = ibm[:, 5] = ibm[:, 10] = ibm[:, 15] = 1.0- ibm[:, 12] = -joints[:, 0]- ibm[:, 13] = -joints[:, 1]- ibm[:, 14] = -joints[:, 2]- ibm_acc = _add_accessor(glb, _append_view(glb, blob, ibm.tobytes()), _GLTF_FLOAT, n_joints, "MAT4")-- skin = pygltflib.Skin(joints=joint_nodes, inverseBindMatrices=ibm_acc)- if roots:- skin.skeleton = roots[0]- glb.skins.append(skin)- skin_idx = len(glb.skins) - 1-- # Smallest legal integer width for joint indices (u8 covers our 25 joints).- if n_joints <= 256:- joint_comp, joint_dtype = _GLTF_UBYTE, np.uint8- elif n_joints <= 65536:- joint_comp, joint_dtype = _GLTF_USHORT, np.uint16- else:- raise RuntimeError(f"too many joints for glTF skinning: {n_joints}")-- joint_idx, top_w = _top_influences(weights, n_joints) # (V,4) over mesh vertex order- kdt = cKDTree(np.asarray(mesh.vertices, dtype=np.float32))- blend = _normalize_blendshapes(blendshape_data) if blendshape_data is not None else None- bs_deltas = blend[1] if blend else None-- # ── map original nodes → meshes, so we can attach the skin to the right node ──- mesh_to_nodes: dict[int, list[int]] = {}- for ni in range(base_node):- node = glb.nodes[ni]- if node.mesh is not None:- mesh_to_nodes.setdefault(node.mesh, []).append(ni)-- skinned_any = False- for mi, gmesh in enumerate(glb.meshes):- nodes = mesh_to_nodes.get(mi, [])- # Joints are world-space; if the drawing node carries a transform, the- # primitive's local positions live in a different frame. Honor that for- # weight matching, and refuse a non-identity transform we can't bake- # into the bind pose (our generators export identity, so this is a- # loud guard, not a silent corruption).- wm = world_mats[nodes[0]] if nodes else np.eye(4)- if not np.allclose(wm, np.eye(4), atol=1e-4):- raise RuntimeError(- f"mesh {mi} is drawn by a node with a non-identity transform; "- "bake the transform into the geometry before rigging"- )-- mesh_targets = 0- for prim in gmesh.primitives:- pos_acc = getattr(prim.attributes, "POSITION", None)- if pos_acc is None:- continue- verts = _read_positions(glb, blob, pos_acc) # (M,3) primitive order- world_pos = verts @ wm[:3, :3].T + wm[:3, 3]- _, nearest = kdt.query(world_pos, k=1) # (M,) → mesh vertex index- nearest = np.asarray(nearest).reshape(-1)-- j0 = np.ascontiguousarray(joint_idx[nearest].astype(joint_dtype))- w0 = np.ascontiguousarray(top_w[nearest].astype(np.float32))- prim.attributes.JOINTS_0 = _add_accessor(- glb, _append_view(glb, blob, j0.tobytes(), _GLTF_ARRAY_BUFFER),- joint_comp, verts.shape[0], "VEC4")- prim.attributes.WEIGHTS_0 = _add_accessor(- glb, _append_view(glb, blob, w0.tobytes(), _GLTF_ARRAY_BUFFER),- _GLTF_FLOAT, verts.shape[0], "VEC4")-- if bs_deltas is not None:- targets = []- for dlt in bs_deltas:- d = np.ascontiguousarray(np.asarray(dlt, dtype=np.float32)[nearest]) # (M,3)- acc = _add_accessor(- glb, _append_view(glb, blob, d.tobytes(), _GLTF_ARRAY_BUFFER),- _GLTF_FLOAT, verts.shape[0], "VEC3",- mn=d.min(axis=0).tolist(), mx=d.max(axis=0).tolist())- targets.append(pygltflib.Attributes(POSITION=acc))- prim.targets = targets- mesh_targets = len(targets)- skinned_any = True-- if mesh_targets:- gmesh.weights = [0.0] * mesh_targets- gmesh.extras = {**(gmesh.extras or {}), "targetNames": blend[0]}-- # Bind the skin to every node that draws this mesh (create one if none).- if not nodes:- new_ni = len(glb.nodes)- glb.nodes.append(pygltflib.Node(mesh=mi, skin=skin_idx))- scene.nodes.append(new_ni)- else:- for ni in nodes:- glb.nodes[ni].skin = skin_idx-- if not skinned_any:- raise RuntimeError("no mesh primitive with POSITION found — cannot rig")-- log.info(- "Rigged GLB: %d joints (%s indices), 4 influences/vertex, %d morph targets",- n_joints, "u8" if joint_comp == _GLTF_UBYTE else "u16",- len(blend[0]) if blend else 0,- )-- # ── serialize (pygltflib 1.16.x returns a list of chunks) ──- glb.set_binary_blob(bytes(blob))- if not glb.buffers:- glb.buffers.append(pygltflib.Buffer())- glb.buffers[0].byteLength = len(blob)- out = glb.save_to_bytes()- return b"".join(out) if isinstance(out, (list, tuple)) else outdiff --git a/workers/unirig/test_rig_glb.py b/workers/unirig/test_rig_glb.pydeleted file mode 100644index 6f769c719..000000000--- a/workers/unirig/test_rig_glb.py+++ /dev/null@@ -1,225 +0,0 @@-"""-Isolated test for rig_glb.build_rigged_glb — verifies it turns a raw mesh GLB-plus a (fabricated) UniRig skeleton/weights prediction into a spec-valid skinned-glTF. Runs with no GPU / torch / GCP: `python3 test_rig_glb.py`.--Validates the things that actually make a GLB "rigged":- • exactly one skin, joints + inverseBindMatrices present and sized to J- • JOINTS_0 / WEIGHTS_0 on every primitive, counts == vertex count- • per-vertex weights sum to 1 and joint indices are in range- • the drawing node references the skin; a joint root is in the scene- • original geometry (vertex count) preserved; buffer length consistent- • optional morph-target (blendshape) injection wires targets + names-"""--import io-import sys--import numpy as np-import pygltflib-import trimesh--from rig_glb import build_rigged_glb--_COMP = {5126: ("<f4", 4), 5121: ("<u1", 1), 5123: ("<u2", 2), 5125: ("<u4", 4)}-_NCOMP = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}---def _decode(glb, blob, acc_idx):- acc = glb.accessors[acc_idx]- bv = glb.bufferViews[acc.bufferView]- base = (bv.byteOffset or 0) + (acc.byteOffset or 0)- dt, size = _COMP[acc.componentType]- nc = _NCOMP[acc.type]- stride = bv.byteStride or (size * nc)- out = np.empty((acc.count, nc), dtype=dt)- for i in range(acc.count):- off = base + i * stride- out[i] = np.frombuffer(bytes(blob[off:off + size * nc]), dtype=dt)- return out---def _make_mesh_glb():- # A box subdivided so weights vary across vertices; exported as a GLB the- # same way the model services emit one.- mesh = trimesh.creation.box(extents=(1.0, 2.0, 1.0))- mesh = mesh.subdivide().subdivide()- glb_bytes = trimesh.Scene(mesh).export(file_type="glb")- loaded = trimesh.load(io.BytesIO(glb_bytes), file_type="glb", force="mesh")- return glb_bytes, loaded---def _fake_unirig(mesh, n_joints=3):- # A vertical spine of n_joints joints; weights blend by vertical position.- ys = mesh.vertices[:, 1]- lo, hi = ys.min(), ys.max()- centers = np.linspace(lo, hi, n_joints)- joints = np.zeros((n_joints, 3), dtype=np.float32)- joints[:, 1] = centers- parents = np.array([-1] + list(range(n_joints - 1)), dtype=np.int64)- span = (hi - lo) / max(n_joints - 1, 1)- d = np.abs(ys[:, None] - centers[None, :])- weights = np.maximum(0.0, 1.0 - d / span).astype(np.float32) # (V, J) tent weights- weights[weights.sum(1) == 0, 0] = 1.0- return joints, parents, weights---def _check(cond, msg):- if not cond:- print(f" ✗ {msg}")- raise AssertionError(msg)- print(f" ✓ {msg}")---def test_skeleton_and_skinning():- print("test_skeleton_and_skinning")- glb_bytes, mesh = _make_mesh_glb()- joints, parents, weights = _fake_unirig(mesh, n_joints=3)- in_pos_count = len(mesh.vertices)-- out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None)- _check(isinstance(out, (bytes, bytearray)) and len(out) > len(glb_bytes),- "produced a larger GLB (skin data appended)")-- glb = pygltflib.GLTF2.load_from_bytes(out)- blob = bytearray(glb.binary_blob())-- _check(len(glb.skins) == 1, "exactly one skin")- skin = glb.skins[0]- _check(len(skin.joints) == 3, "skin.joints has J entries")- _check(skin.inverseBindMatrices is not None, "inverseBindMatrices present")- ibm = glb.accessors[skin.inverseBindMatrices]- _check(ibm.type == "MAT4" and ibm.count == 3, "IBM accessor is MAT4 × J")-- scene = glb.scenes[glb.scene or 0]- _check(any(r in scene.nodes for r in skin.joints), "a joint node is in the scene")-- skinned_nodes = [n for n in glb.nodes if n.mesh is not None and n.skin is not None]- _check(len(skinned_nodes) >= 1, "a drawing node references the skin")-- total_prims = 0- for gmesh in glb.meshes:- for prim in gmesh.primitives:- if getattr(prim.attributes, "POSITION", None) is None:- continue- total_prims += 1- pos = glb.accessors[prim.attributes.POSITION]- _check(prim.attributes.JOINTS_0 is not None, "primitive has JOINTS_0")- _check(prim.attributes.WEIGHTS_0 is not None, "primitive has WEIGHTS_0")- jacc = glb.accessors[prim.attributes.JOINTS_0]- wacc = glb.accessors[prim.attributes.WEIGHTS_0]- _check(jacc.count == pos.count and wacc.count == pos.count,- "JOINTS_0/WEIGHTS_0 counts match POSITION")- _check(jacc.componentType == 5121,- "JOINTS_0 uses compact UNSIGNED_BYTE for <=256 joints")- _check(pos.count == in_pos_count, "vertex count preserved")-- jv = _decode(glb, blob, prim.attributes.JOINTS_0)- wv = _decode(glb, blob, prim.attributes.WEIGHTS_0)- _check(jv.min() >= 0 and jv.max() < len(skin.joints),- "all joint indices in range")- sums = wv.sum(axis=1)- _check(np.allclose(sums, 1.0, atol=1e-4),- f"every vertex's weights sum to 1 (max err {np.abs(sums-1).max():.2e})")- _check(total_prims >= 1, "at least one primitive skinned")-- _check(glb.buffers[0].byteLength == len(blob), "buffer byteLength matches binary blob")---def test_blendshape_targets():- print("test_blendshape_targets")- glb_bytes, mesh = _make_mesh_glb()- joints, parents, weights = _fake_unirig(mesh, n_joints=3)- V = len(mesh.vertices)- deltas = np.stack([- np.tile(np.array([0.0, 0.05, 0.0], np.float32), (V, 1)), # "jawOpen"-ish- np.tile(np.array([0.03, 0.0, 0.0], np.float32), (V, 1)),- ], axis=0)-- out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights,- {"names": ["jawOpen", "mouthLeft"], "deltas": deltas})- glb = pygltflib.GLTF2.load_from_bytes(out)-- found = False- for gmesh in glb.meshes:- for prim in gmesh.primitives:- if getattr(prim.attributes, "POSITION", None) is None:- continue- _check(prim.targets is not None and len(prim.targets) == 2,- "primitive has 2 morph targets")- # pygltflib reloads morph targets as plain dicts ({"POSITION": n}).- tgt_pos = [t["POSITION"] if isinstance(t, dict) else t.POSITION for t in prim.targets]- _check(all(p is not None for p in tgt_pos),- "each morph target has a POSITION delta accessor")- found = True- if found:- _check(gmesh.weights == [0.0, 0.0], "mesh.weights initialized per target")- _check((gmesh.extras or {}).get("targetNames") == ["jawOpen", "mouthLeft"],- "targetNames recorded in mesh.extras")- _check(found, "blendshape primitive found")---def test_dirty_weights_no_collapse():- """NaN/Inf/negative weights are sanitized and empty vertices are pinned to a- joint, so every vertex keeps a unit weight sum (no skinning collapse)."""- print("test_dirty_weights_no_collapse")- glb_bytes, mesh = _make_mesh_glb()- joints, parents, weights = _fake_unirig(mesh, n_joints=3)- # Corrupt the model output: a block of all-zero rows, plus NaN/Inf/negative.- weights[: len(weights) // 4] = 0.0- weights[len(weights) // 4] = [np.nan, np.inf, -5.0]-- out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None)- glb = pygltflib.GLTF2.load_from_bytes(out)- blob = bytearray(glb.binary_blob())- checked = 0- for gmesh in glb.meshes:- for prim in gmesh.primitives:- if getattr(prim.attributes, "WEIGHTS_0", None) is None:- continue- wv = _decode(glb, blob, prim.attributes.WEIGHTS_0)- jv = _decode(glb, blob, prim.attributes.JOINTS_0)- _check(np.all(np.isfinite(wv)), "no NaN/Inf in output weights")- _check(np.all(wv >= 0), "no negative output weights")- _check(np.allclose(wv.sum(axis=1), 1.0, atol=1e-4),- "every vertex sums to 1 even from corrupt input (no collapse)")- _check(jv.max() < len(glb.skins[0].joints), "joint indices in range")- checked += 1- _check(checked >= 1, "weights validated")---def test_nonidentity_node_rejected():- """A skinned mesh node with a non-identity transform must fail loudly rather- than silently misplacing the skeleton."""- print("test_nonidentity_node_rejected")- glb_bytes, mesh = _make_mesh_glb()- g = pygltflib.GLTF2.load_from_bytes(glb_bytes)- moved = False- for node in g.nodes:- if node.mesh is not None:- node.translation = [0.5, 0.0, 0.0]- moved = True- _check(moved, "test set a transform on the mesh node")- chunks = g.save_to_bytes()- moved_bytes = b"".join(chunks) if isinstance(chunks, (list, tuple)) else chunks- moved_mesh = trimesh.load(io.BytesIO(moved_bytes), file_type="glb", force="mesh")- joints, parents, weights = _fake_unirig(moved_mesh, n_joints=3)-- try:- build_rigged_glb(moved_bytes, moved_mesh, joints, parents, weights, None)- except RuntimeError as exc:- _check("non-identity" in str(exc), "raised a clear non-identity transform error")- return- _check(False, "expected RuntimeError for non-identity node transform")---if __name__ == "__main__":- try:- test_skeleton_and_skinning()- test_blendshape_targets()- test_dirty_weights_no_collapse()- test_nonidentity_node_rejected()- except AssertionError:- print("\nFAILED")- sys.exit(1)- print("\nALL PASSED")diff --git a/workers/unirig/worker_security.py b/workers/unirig/worker_security.pydeleted file mode 100644index 1e569c4e2..000000000--- a/workers/unirig/worker_security.py+++ /dev/null@@ -1,222 +0,0 @@-"""-Shared security helpers for the three.ws GPU/CPU workers.--This module is intentionally dependency-light (stdlib only) so it can be-COPYed verbatim into every worker's Docker build context. The same canonical-file lives in each worker directory; keep them byte-identical when editing.--It provides three primitives that every worker needs:-- 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).- 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied- URLs: https-only, DNS resolution with private/loopback/link-local/metadata- IP rejection, per-hop redirect re-validation, and a bounded response size.- 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged- message safe to persist/return to callers, after logging the full- traceback server-side only.-"""--from __future__ import annotations--import hmac-import ipaddress-import logging-import socket-import uuid-from typing import Iterable, Optional-from urllib.parse import urlsplit--import httpx--log = logging.getLogger("worker_security")--# ── auth ────────────────────────────────────────────────────────────────────────---def require_api_key(authorization: Optional[str], api_key: str) -> None:- """Validate a ``Bearer <token>`` header in constant time.-- Raises ``PermissionError`` on any failure so callers can translate it into- the framework's 401 (FastAPI workers map this to HTTPException(401)).- """- if not authorization or not authorization.startswith("Bearer "):- raise PermissionError("missing bearer token")- token = authorization[len("Bearer "):].strip()- # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.- if not hmac.compare_digest(token, api_key):- raise PermissionError("invalid api key")---# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────--# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes-# are comfortably under this; anything larger is almost certainly abuse.-DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB-_MAX_REDIRECTS = 4---class UnsafeUrlError(ValueError):- """Raised when a URL targets a disallowed scheme or a private/internal IP."""---def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:- """Reject any address that could reach internal infrastructure.-- Covers loopback, RFC1918 private ranges, link-local (incl. the cloud- metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),- multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses- are unwrapped first so a mapped private v4 can't slip through.- """- if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:- ip = ip.ipv4_mapped- return (- ip.is_private- or ip.is_loopback- or ip.is_link_local- or ip.is_multicast- or ip.is_reserved- or ip.is_unspecified- )---def _resolve_safe_host(host: str) -> None:- """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.-- Resolving and checking every returned address closes the gap where a name- resolves to both a public and a private address.- """- if not host:- raise UnsafeUrlError("missing host")- try:- infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)- except socket.gaierror as exc:- raise UnsafeUrlError(f"could not resolve host: {host}") from exc-- addrs = {info[4][0] for info in infos}- if not addrs:- raise UnsafeUrlError(f"no addresses for host: {host}")- for addr in addrs:- ip = ipaddress.ip_address(addr)- if _is_blocked_ip(ip):- raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")---def assert_safe_url(url: str, *, allow_http: bool = False) -> str:- """Validate scheme + resolved IPs for a single URL. Returns it unchanged.-- https is required by default; ``allow_http`` exists only for callers that- legitimately need cleartext (not used by the workers).- """- parts = urlsplit(url)- scheme = parts.scheme.lower()- allowed = ("https", "http") if allow_http else ("https",)- if scheme not in allowed:- raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")- if not parts.hostname:- raise UnsafeUrlError("missing host")- _resolve_safe_host(parts.hostname)- return url---def fetch_remote_bytes(- url: str,- *,- timeout: float = 30.0,- max_bytes: int = DEFAULT_MAX_BYTES,- allow_http: bool = False,- headers: Optional[dict] = None,-) -> bytes:- """Fetch ``url`` safely and return its body bytes.-- Hardening applied:- * https-only (unless ``allow_http``).- * every URL — including each redirect target — is DNS-resolved and- rejected if it maps to a private/loopback/link-local/metadata address.- * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is- re-validated; httpx's own redirect following is disabled.- * the response body is streamed and aborted once it exceeds ``max_bytes``.-- Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /- ``ValueError`` for transport or size failures.- """- current = assert_safe_url(url, allow_http=allow_http)- with httpx.Client(follow_redirects=False, timeout=timeout) as client:- for _ in range(_MAX_REDIRECTS + 1):- with client.stream("GET", current, headers=headers) as resp:- if resp.is_redirect:- location = resp.headers.get("location")- if not location:- raise UnsafeUrlError("redirect without Location header")- current = assert_safe_url(- str(resp.url.join(location)), allow_http=allow_http- )- continue- resp.raise_for_status()- declared = resp.headers.get("content-length")- if declared is not None and declared.isdigit() and int(declared) > max_bytes:- raise ValueError(f"response too large: {declared} bytes")- chunks: list[bytes] = []- total = 0- for chunk in resp.iter_bytes(65536):- total += len(chunk)- if total > max_bytes:- raise ValueError(f"response exceeded {max_bytes} bytes")- chunks.append(chunk)- return b"".join(chunks)- raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")---async def fetch_remote_bytes_async(- client: "httpx.AsyncClient",- url: str,- *,- max_bytes: int = DEFAULT_MAX_BYTES,- allow_http: bool = False,- headers: Optional[dict] = None,-) -> bytes:- """Async variant of ``fetch_remote_bytes`` using a caller-provided client.-- The provided ``client`` MUST be constructed with ``follow_redirects=False``- so this function can re-validate each redirect hop itself.- """- current = assert_safe_url(url, allow_http=allow_http)- for _ in range(_MAX_REDIRECTS + 1):- async with client.stream("GET", current, headers=headers) as resp:- if resp.is_redirect:- location = resp.headers.get("location")- if not location:- raise UnsafeUrlError("redirect without Location header")- current = assert_safe_url(- str(resp.url.join(location)), allow_http=allow_http- )- continue- resp.raise_for_status()- declared = resp.headers.get("content-length")- if declared is not None and declared.isdigit() and int(declared) > max_bytes:- raise ValueError(f"response too large: {declared} bytes")- chunks: list[bytes] = []- total = 0- async for chunk in resp.aiter_bytes(65536):- total += len(chunk)- if total > max_bytes:- raise ValueError(f"response exceeded {max_bytes} bytes")- chunks.append(chunk)- return b"".join(chunks)- raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")---# ── opaque error handling ───────────────────────────────────────────────────────---def safe_error(exc: BaseException, *, context: str = "") -> str:- """Log the full traceback server-side and return an opaque client message.-- Never leak ``traceback.format_exc()`` (absolute paths, library versions,- internal hostnames, fragments of upstream responses) to callers. A short- correlation id is embedded in both the log line and the returned string so- operators can join a client-reported failure to the server log.- """- correlation_id = uuid.uuid4().hex[:12]- label = f"{context} " if context else ""- log.exception("%serror [correlation_id=%s]", label, correlation_id)- return f"internal error (ref {correlation_id})"