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
feat(rig): rebuild the auto-rigging lane on Make-It-Animatable with real ARKit-52 blendshapes
nirholas81882f3b198b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2cb606548..aea3af497 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-17+- **Avatars you generate now come out truly animation-ready** — We rebuilt the auto-rigging engine that turns a generated 3D character into a living avatar. Rigging now finishes in seconds instead of stalling for 20 minutes, produces a full standard skeleton with fingers that our entire animation library (walk, wave, dance, emotes) can drive immediately, keeps the model's original textures perfectly intact, and adds the 52 facial expression shapes used for emotions and lip-sync. Every piece of the new pipeline is MIT-licensed open source, so it works for everyone, everywhere. (`/forge`) `[feature, improvement, fix]`- **Creator profile pages work again, plus a site-wide reliability sweep** — A full automated sweep of every page and API endpoint on the site caught a bug that replaced creator profile pages (three.ws/u/yourname) with an error message. That is fixed. The sweep also repaired the login captcha for rate-limited sign-ins, fixed dead links in the dashboard and two blog posts, and added two dozen previously unlisted pages to the site index so search engines and the sitemap can find them. The audit now runs with deeper checks (blank-page detection, visible error detection, and link crawling) so regressions like these get caught before anyone hits them. (`/changelog`) `[fix, improvement]`## 2026-07-16diff --git a/STRUCTURE.md b/STRUCTURE.mdindex a88f0f2d0..086430b66 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -65,6 +65,7 @@ bottom.| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html`, [agent-native-3d/](examples/agent-native-3d) (below) || Agent-native 3D + embeddable distribution | MCP tool [api/_mcp/tools/agents.js](api/_mcp/tools/agents.js) (`attach_avatar_to_agent`); shared oEmbed provider [api/agent-oembed.js](api/agent-oembed.js) `→ /api/oembed` + builder [api/_lib/embed.js](api/_lib/embed.js) (`forgeEmbedTarget`, shared by `get_embed_code` in [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js)); Forge share page oEmbed discovery [api/forge-share.js](api/forge-share.js) `→ /forge/share/:id`; distribution snippet builders [src/forge-embed-snippets.js](src/forge-embed-snippets.js) + panel [src/forge-embed-panel.js](src/forge-embed-panel.js); autonomous demo [examples/agent-native-3d/](examples/agent-native-3d) | In-repo | Closes the loop: create → own → discover/remix → **use everywhere**. `attach_avatar_to_agent` gives a registered agent identity a persistent body (chains into `register_agent` for on-chain identity + `anchor_provenance` for a signed authenticity credential). Any Forge creation now unfurls via real oEmbed (paste `/forge/share/:id` into Notion/Discord/Slack) with the same `type:rich` iframe payload `get_embed_code` returns via MCP. The Forge "Embed this model" panel hands out five real distribution flavours from one GLB — iframe, `<model-viewer>`, `<agent-3d>`, a `@three-ws/page-agent` talking guide, and a `@three-ws/walk` companion — all built from one shared, pure snippet module so every surface stays byte-identical. `examples/agent-native-3d/run.mjs` drives the full agent-native chain live against `/api/mcp-studio` (mesh_forge → rig_mesh → create_agent_persona → persona_say → get_agent_persona → every distribution snippet) with zero mocks and a documented, logged fallback if the shared free-tier generation lane is rate-limited at run time. Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#share-routes-on-chain-agents). Docs: [docs/mcp.md#attach_avatar_to_agent](docs/mcp.md#attach_avatar_to_agent). Roadmap prompt 10 (closes the roadmap campaign). || Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) |+| Auto-rigging worker (Mixamo skeleton + ARKit-52 blendshapes) | [workers/rig/](workers/rig) | Code-complete · deploy pending (asset staging + Cloud Build, see its README) | Make-It-Animatable engine (MIT) predicts the 52-bone Mixamo skeleton + weights; [workers/rig/rig_glb.py](workers/rig/rig_glb.py) grafts them into the original GLB (textures untouched); ICT-FaceKit (MIT) ARKit-52 expression transfer for emotions/lipsync. Contract-compatible replacement for the retired `unirig` service behind `GCP_UNIRIG_URL`; cutover is one env-var update. Canonicalization proof: `rig worker skeleton` cases in [tests/glb-canonicalize.test.js](tests/glb-canonicalize.test.js) || Animation gallery | [pages/animations.html](pages/animations.html) + [src/animations-gallery.js](src/animations-gallery.js) | Live at `/animations` | 2,100+ clips with poster thumbnails ([scripts/build-animation-thumbnails.mjs](scripts/build-animation-thumbnails.mjs)), derived categories ([src/animation-categories.js](src/animation-categories.js)), shared live-preview engine ([src/animations-live-preview.js](src/animations-live-preview.js)) · see [docs/animations.md](docs/animations.md) || Avatar thumbnail coverage | [api/_lib/avatar-thumbs.js](api/_lib/avatar-thumbs.js) + crons [api/cron/avatar-thumbnail-backfill.js](api/cron/avatar-thumbnail-backfill.js) (absent thumbnails, `*/5`) and [api/cron/avatar-thumbnail-render.js](api/cron/avatar-thumbnail-render.js) (stale marketplace thumbnails, `*/10`) | Live | The single owner of `avatars.thumbnail_key`. Enforces the invariant that a thumbnail key is persisted **only after** its R2 object is confirmed to exist — a key pointing at a missing object makes R2 return 404 `text/plain`, which Chrome blocks as `ERR_BLOCKED_BY_ORB` inside an `<img>`. Fills coverage cheapest-first: zero-copy adoption of `forge_creations.preview_key`, then a headless-chromium GLB→PNG render to `thumb/<avatarId>.png` ([api/_lib/render-glb.js](api/_lib/render-glb.js)). Bounded retries via the `avatar_thumbnail_backfill` claim ledger ([migration](api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql)), with `isBrowserInfrastructureError()` separating an OOM-killed browser from a genuinely broken model so a crash never retires healthy avatars. Bulk runner: [scripts/backfill-avatar-thumbnails.mjs](scripts/backfill-avatar-thumbnails.mjs) (`--status`, `--adopt-only`, `--loop`, `--reset-infra`). Docs: [docs/avatar-thumbnails.md](docs/avatar-thumbnails.md). Tests: [tests/avatar-thumbs.test.js](tests/avatar-thumbs.test.js), [tests/home-thumbnail-orb.test.js](tests/home-thumbnail-orb.test.js) || Sketchfab showcase (community models → official account) | Cron [api/cron/sketchfab-showcase.js](api/cron/sketchfab-showcase.js), lib [api/_lib/sketchfab.js](api/_lib/sketchfab.js), ledger migration [api/_lib/migrations/20260714130000_sketchfab_uploads.sql](api/_lib/migrations/20260714130000_sketchfab_uploads.sql) | Live · dormant until `SKETCHFAB_API_TOKEN` is set | Publishes the best community forge models to the official three.ws Sketchfab account, prompt and backlink included. Selection order: forge-board winners, then top-voted (>=1 vote), then creator-accepted (accepted or downloaded, refinement children excluded, title-quality heuristic). Brand safety is two layers: a SQL denylist plus NemoGuard re-moderation; blocked rows park as `blocked` in the `sketchfab_uploads` ledger (states `pending`/`uploaded`/`live`/`failed`/`blocked`). `?dry_run=1` exercises selection before the token is wired; `SKETCHFAB_UPLOADS_PER_RUN` clamps 1-5 (default 2). Docs: [docs/sketchfab.md](docs/sketchfab.md) |diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 038b89c16..02ef60177 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -319,10 +319,12 @@ function buildWorkerRequest(request) {if (mode === 'rerig') {// Two rig backends share the /rig path but disagree on the schema. The- // standalone UniRig worker (GCP_UNIRIG_URL) takes `mesh_gcs_url` (any- // https URL — the name is historical) and reports `rigged_gcs_url`; the- // legacy pipeline controller takes `mesh_url`/`rig_type` and reports- // `glb_url`. Branch on which env the rerig URL resolved from.+ // standalone rig worker behind GCP_UNIRIG_URL (workers/rig, the+ // Make-It-Animatable service; the env name predates it) takes+ // `mesh_gcs_url` (any https URL, the name is historical) and reports+ // `rigged_gcs_url`; the legacy pipeline controller takes+ // `mesh_url`/`rig_type` and reports `glb_url`. Branch on which env the+ // rerig URL resolved from.if (readEnv('GCP_UNIRIG_URL')) {return {path: '/rig',diff --git a/data/changelog.json b/data/changelog.jsonindex e9b433331..df76d7b9e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -14067,6 +14067,17 @@"improvement"],"link": "/changelog"+ },+ {+ "date": "2026-07-17",+ "title": "Avatars you generate now come out truly animation-ready",+ "summary": "We rebuilt the auto-rigging engine that turns a generated 3D character into a living avatar. Rigging now finishes in seconds instead of stalling for 20 minutes, produces a full standard skeleton with fingers that our entire animation library (walk, wave, dance, emotes) can drive immediately, keeps the model's original textures perfectly intact, and adds the 52 facial expression shapes used for emotions and lip-sync. Every piece of the new pipeline is MIT-licensed open source, so it works for everyone, everywhere.",+ "tags": [+ "feature",+ "improvement",+ "fix"+ ],+ "link": "/forge"}]}diff --git a/docs/avatar-pipeline.md b/docs/avatar-pipeline.mdindex bd6d593e0..81153bad8 100644--- a/docs/avatar-pipeline.md+++ b/docs/avatar-pipeline.md@@ -40,6 +40,15 @@ skeleton to a GLB. A **humanoid gate** decides whether the mesh can carry acanonical humanoid rig; non-humanoid props are left unrigged rather than forcedinto a broken skeleton.+The rigging engine is the `model-rig` worker ([workers/rig/](../workers/rig)):+Make-It-Animatable (MIT) predicts the 52-bone Mixamo skeleton, fingers+included, plus per-vertex weights; the worker grafts them into the original+GLB bytes (materials and PBR textures untouched) and transfers the ARKit-52+expression blendshapes from the MIT-licensed ICT-FaceKit template head, so+generated avatars support emotions and lipsync out of the box. Bones come out+`mixamorig:*`-named, which stage ③ maps onto the canonical set at 100%+coverage.+### ③ Canonicalize bones`src/glb-canonicalize.js` maps an incoming skeleton's bone names onto three.ws'sdiff --git a/public/changelog.json b/public/changelog.jsonindex 0cc7c3e9b..338d8a2a4 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,23 @@{- "generated_at": "2026-07-17T06:01:48.217Z",+ "generated_at": "2026-07-17T06:13:43.576Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-17",+ "type": "update",+ "title": "Avatars you generate now come out truly animation-ready",+ "summary": "We rebuilt the auto-rigging engine that turns a generated 3D character into a living avatar. Rigging now finishes in seconds instead of stalling for 20 minutes, produces a full standard skeleton with fingers that our entire animation library (walk, wave, dance, emotes) can drive immediately, keeps the model's original textures perfectly intact, and adds the 52 facial expression shapes used for emotions and lip-sync. Every piece of the new pipeline is MIT-licensed open source, so it works for everyone, everywhere.",+ "link": "/forge",+ "tags": [+ "feature",+ "improvement",+ "fix"+ ]+ },{"date": "2026-07-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 446216b4e..98045a3fb 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Avatars you generate now come out truly animation-ready</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-07-17:Avatars you generate now come out truly animation-ready</guid>+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>We rebuilt the auto-rigging engine that turns a generated 3D character into a living avatar. Rigging now finishes in seconds instead of stalling for 20 minutes, produces a full standard skeleton with fingers that our entire animation library (walk, wave, dance, emotes) can drive immediately, keeps the model's original textures perfectly intact, and adds the 52 facial expression shapes used for emotions and lip-sync. Every piece of the new pipeline is MIT-licensed open source, so it works for everyone, everywhere.</description>+ </item><item><title>Creator profile pages work again, plus a site-wide reliability sweep</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 1be7e46d7..a4c882c24 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T06:01:48.204Z",+ "generated_at": "2026-07-17T06:13:43.564Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.jsindex 4293e349f..7f2ae8938 100644--- a/tests/glb-canonicalize.test.js+++ b/tests/glb-canonicalize.test.js@@ -726,3 +726,63 @@ describe('real-fixture: michelle.glb (Mixamo rig normalization)', () => {expect(nonCanon).toHaveLength(0);});});++describe('rig worker skeleton (workers/rig, Make-It-Animatable output)', () => {+ // The exact 52-bone skeleton the auto-rig worker emits (Mixamo names, see+ // workers/rig/engine_mia.py). Every bone must map onto the canonical set so+ // a freshly rigged avatar can drive the full clip library with 100%+ // coverage; a rename miss here silently breaks retargeting in production.+ const MIA_JOINTS = [+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',+ 'LeftHandThumb1', 'LeftHandThumb2', 'LeftHandThumb3',+ 'LeftHandIndex1', 'LeftHandIndex2', 'LeftHandIndex3',+ 'LeftHandMiddle1', 'LeftHandMiddle2', 'LeftHandMiddle3',+ 'LeftHandRing1', 'LeftHandRing2', 'LeftHandRing3',+ 'LeftHandPinky1', 'LeftHandPinky2', 'LeftHandPinky3',+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',+ 'RightHandThumb1', 'RightHandThumb2', 'RightHandThumb3',+ 'RightHandIndex1', 'RightHandIndex2', 'RightHandIndex3',+ 'RightHandMiddle1', 'RightHandMiddle2', 'RightHandMiddle3',+ 'RightHandRing1', 'RightHandRing2', 'RightHandRing3',+ 'RightHandPinky1', 'RightHandPinky2', 'RightHandPinky3',+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',+ ].map((n) => `mixamorig:${n}`);++ it('every worker bone name canonicalizes', () => {+ for (const name of MIA_JOINTS) {+ expect(canonicalizeBoneName(name), name).not.toBeNull();+ }+ });++ it('the worker skeleton covers the canonical bone set completely', () => {+ const mapped = new Set(MIA_JOINTS.map((n) => canonicalizeBoneName(n)));+ for (const bone of CANONICAL_BONES) {+ expect(mapped.has(bone), bone).toBe(true);+ }+ expect(mapped.size).toBe(CANONICAL_BONES.length);+ });++ it('a worker-shaped GLB rewrites to canonical names in place', () => {+ const nodes = MIA_JOINTS.map((name, i) => ({+ name,+ translation: [0, i * 0.01, 0],+ }));+ // Chain children linearly; the canonicalizer only needs skins[].joints.+ const json = {+ asset: { version: '2.0' },+ scenes: [{ nodes: [0] }],+ scene: 0,+ nodes,+ skins: [{ joints: nodes.map((_, i) => i) }],+ };+ const out = canonicalizeGLBBones(buildGLB(json));+ expect(out.renamed).toBe(MIA_JOINTS.length);+ const after = readGLBJson(out.buffer);+ const names = after.nodes.map((n) => n.name);+ for (const bone of CANONICAL_BONES) {+ expect(names).toContain(bone);+ }+ });+});diff --git a/workers/rig/Dockerfile b/workers/rig/Dockerfilenew file mode 100644index 000000000..81693d569--- /dev/null+++ b/workers/rig/Dockerfile@@ -0,0 +1,45 @@+FROM nvidia/cuda:12.1.1-runtime-ubuntu22.04++# runtime (not devel) base: every heavy dependency (torch, torch-cluster,+# pytorch3d) installs from prebuilt cu121 wheels, so no nvcc is needed.+# Python 3.11 is a hard requirement of the bpy==4.3.0 wheel MIA imports while+# building its Mixamo kinematic tree.+ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive \+ MPLBACKEND=Agg++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.11 python3.11-dev python3.11-venv python3-pip \+ git curl \+ libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \+ libxi6 libxxf86vm1 libxfixes3 libxkbcommon0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.11 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.11 /usr/bin/python \+ && python3 -m pip install --upgrade pip setuptools wheel++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++# Make-It-Animatable (MIT), pinned. Vendored as source because upstream has no+# package layout; engine_mia.py imports its app module directly. The empty+# util/auto_rig_pro directory only matters for the animation-baking path we+# never call.+ARG MIA_COMMIT=d60cc7e01ff8da46448e458dbf450e8967b34e77+RUN git clone https://github.com/jasongzy/Make-It-Animatable.git /app/mia \+ && git -C /app/mia checkout ${MIA_COMMIT} \+ && rm -rf /app/mia/.git++WORKDIR /app+COPY worker_security.py rig_glb.py blendshapes.py engine_mia.py main.py entrypoint.sh /app/+RUN chmod +x /app/entrypoint.sh++# Weights, Mixamo bone templates, and the baked ARKit template are staged in+# GCS (stage-assets.sh) and mounted at /weights by Cloud Run; entrypoint.sh+# links them into the MIA tree before serving.++EXPOSE 8080++CMD ["/app/entrypoint.sh"]diff --git a/workers/rig/README.md b/workers/rig/README.mdnew file mode 100644index 000000000..398e2ffc9--- /dev/null+++ b/workers/rig/README.md@@ -0,0 +1,116 @@+# model-rig: auto-rigging worker (Make-It-Animatable engine)++Turns a static humanoid GLB into a fully animation-ready avatar: Mixamo-named+skeleton, per-vertex skinning weights, and the ARKit-52 expression blendshapes,+with the original materials and PBR textures preserved byte-for-byte.++This service replaces the retired `workers/unirig` deployment, whose live+instance produced generically named 22-bone skeletons (unusable by the+platform retargeter), no blendshapes, and 20-minute latencies. Same API+contract, so the platform cutover is one env-var change (see Cutover below).++## How it works++1. **Predict**: [Make-It-Animatable](https://github.com/jasongzy/Make-It-Animatable)+ (MIT, CVPR 2025) infers joint positions, skinning weights, and pose for the+ 52-bone Mixamo skeleton, fingers included, in under a second of GPU time+ (`engine_mia.py`). MIA is used purely as a predictor; its Blender/FBX export+ path is never invoked, so the visual mesh never round-trips through a+ converter that would degrade materials.+2. **Graft**: `rig_glb.py` writes the skeleton, `JOINTS_0`/`WEIGHTS_0`, and+ inverse bind matrices straight into the original GLB bytes (pure+ pygltflib/numpy; unit-tested without a GPU). Bones are named `mixamorig:*`,+ which `src/glb-canonicalize.js` maps 1:1 onto the platform's canonical bone+ set (proven by the `rig worker skeleton` cases in+ `tests/glb-canonicalize.test.js`) so a freshly rigged avatar drives the+ entire pre-baked clip library at 100% coverage.+3. **Expressions**: `blendshapes.py` transfers the 52 ARKit expression shapes+ from the [ICT-FaceKit](https://github.com/ICT-VGL/ICT-FaceKit) template head+ (MIT) onto the avatar's head region (nearest-surface correspondence with+ distance falloff), written as glTF morph targets with `targetNames`. This+ powers emotions and lipsync (`src/voice/arkit-blendshapes.js`,+ the embodiment stage) on generated avatars.++## API++Identical to the previous rig worker so `api/_providers/gcp.js` needs no code+change:++```+POST /rig { mesh_gcs_url, template?, blendshapes?, job_id? }+ -> 202 { task_id, status: "queued" } (Bearer API_KEY)+GET /tasks/:id -> { task_id, status, rigged_gcs_url?, error?, elapsed_ms? }+GET /health -> { ok, model, gpu_available, gpu_name, model_loaded, queued }+```++Every task runs under a hard timeout (`TASK_TIMEOUT_S`, default 420 s): a task+finishes or fails, it can never sit in `running` forever. Task state is+in-memory by design; run with `min-instances = max-instances` so pollers reach+the owning instance (a restart 404s the poll and the platform fails the job+cleanly).++## Deploy++One-time asset staging (checkpoints ~a few hundred MB from Hugging Face, plus+the baked ARKit template):++```bash+bash workers/rig/stage-assets.sh+```++Build + deploy (Cloud Build pins the `three-ws-build@` service account):++```bash+gcloud builds submit --config workers/rig/cloudbuild.yaml \+ --substitutions=SHORT_SHA=manual$(date +%s) .+```++Service: `model-rig`, us-central1, 1x L4 (`--no-gpu-zonal-redundancy`),+min=max instances per the L4 quota plan in `docs/ops/gcp-credits-plan.md`.++## Cutover++```bash+gcloud run services update three-ws-api --region us-central1 \+ --update-env-vars GCP_UNIRIG_URL=$(gcloud run services describe model-rig \+ --region us-central1 --format='value(status.url)')+```++Then verify end-to-end (a static humanoid in, canonical rigged GLB out):++```bash+curl -sX POST "https://three.ws/api/forge?action=rig" \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/mannequin.glb"}'+# poll the returned job_id via /api/forge?job=... and inspect the GLB:+# skins=1, bones named mixamorig:* (canonicalized at ingest), morph targets+# with ARKit targetNames present.+```++After cutover, retire the old `unirig` Cloud Run service to free one L4 toward+the quota ceiling.++## Local tests (no GPU needed)++```bash+python3 workers/rig/test_rig_glb.py+python3 workers/rig/test_blendshapes.py+npx vitest run tests/glb-canonicalize.test.js+```++## Licensing++Every component is commercially clean, worldwide: Make-It-Animatable (MIT),+ICT-FaceKit (MIT), and this service's own code. No SMPL/FLAME research+licenses, no Hunyuan territory carve-outs, in the rigging path.++## Environment++| Var | Default | Meaning |+|---|---|---|+| `API_KEY` | (secret) | shared bearer secret (`avatar-reconstruction-key`) |+| `GCS_BUCKET` | (required) | output bucket for rigged GLBs |+| `MIA_DIR` | `/app/mia` | Make-It-Animatable checkout |+| `ARKIT_TEMPLATE` | `/app/assets/arkit_template.npz` | baked ICT template |+| `MAX_CONCURRENT` | `1` | parallel rig jobs per instance |+| `TASK_TIMEOUT_S` | `420` | per-task hard timeout |diff --git a/workers/rig/blendshapes.py b/workers/rig/blendshapes.pynew file mode 100644index 000000000..726507b76--- /dev/null+++ b/workers/rig/blendshapes.py@@ -0,0 +1,118 @@+"""+ARKit-52 blendshape transfer for generated avatars.++Takes the ICT-FaceKit template head (MIT-licensed, 53 FACS expression shapes+following Apple ARKit naming; see build_arkit_template.py, which bakes the OBJ+set into a single arkit_template.npz) and transfers its per-vertex expression+deltas onto the head region of an arbitrary rigged humanoid mesh.++Method: similarity-align the template to the target head (translation from+centroid, uniform scale from vertical extent), find nearest template vertex+for each target head vertex, copy that vertex's deltas scaled to target size,+and attenuate by correspondence distance so vertices far from the template+surface (hair, hats, glasses) receive no deformation.++This is deliberately dependency-light (numpy/scipy) and GPU-free so it is unit+testable anywhere; see test_blendshapes.py.+"""++from __future__ import annotations++import logging++import numpy as np+from scipy.spatial import cKDTree++log = logging.getLogger("rig.blendshapes")++# Fraction of head height used as the falloff sigma for delta attenuation.+_FALLOFF_SIGMA_RATIO = 0.08+# Correspondences farther than this many sigmas contribute nothing.+_FALLOFF_CUTOFF_SIGMAS = 3.0+++def load_template(path: str) -> dict:+ """Load the baked ARKit template (see build_arkit_template.py).++ Returns {names: [K], verts: (V,3), deltas: (K,V,3)} with verts centered on+ the template head centroid, Y-up, facing +Z."""+ data = np.load(path, allow_pickle=False)+ names = [str(n) for n in data["names"]]+ verts = np.asarray(data["verts"], dtype=np.float32)+ deltas = np.asarray(data["deltas"], dtype=np.float32)+ if deltas.shape[0] != len(names) or deltas.shape[1] != verts.shape[0] or deltas.shape[2] != 3:+ raise RuntimeError(+ f"malformed template: names={len(names)} verts={verts.shape} deltas={deltas.shape}"+ )+ return {"names": names, "verts": verts, "deltas": deltas}+++def head_mask_from_weights(weights: np.ndarray, joint_names: list[str],+ head_bone: str = "mixamorig:Head",+ min_weight: float = 0.35) -> np.ndarray:+ """Boolean mask of vertices bound to the head: any vertex whose skinning+ weight on the head bone (or its children, e.g. eyes) passes the threshold.++ `weights` is (V,J) aligned to `joint_names`."""+ head_cols = [+ i for i, n in enumerate(joint_names)+ if n == head_bone or ("Head" in n and "HeadTop" not in n) or "Eye" in n+ ]+ if not head_cols:+ raise RuntimeError(f"no head bone found in joint names (looked for {head_bone})")+ w = np.asarray(weights, dtype=np.float32)[:, head_cols].sum(axis=1)+ return w >= min_weight+++def transfer_blendshapes(template: dict, target_verts: np.ndarray,+ head_mask: np.ndarray) -> dict:+ """Transfer template expression deltas onto the target mesh.++ template from load_template()+ target_verts (V,3) target mesh vertices, same space as the skeleton+ head_mask (V,) boolean, True where the vertex belongs to the head++ Returns {"names": [K], "deltas": (K,V,3)} with zeros outside the head,+ suitable for rig_glb.build_rigged_glb's blendshape_data argument."""+ target_verts = np.asarray(target_verts, dtype=np.float32)+ head_mask = np.asarray(head_mask, dtype=bool)+ n_verts = target_verts.shape[0]+ names = template["names"]+ out = np.zeros((len(names), n_verts, 3), dtype=np.float32)++ head_pts = target_verts[head_mask]+ if head_pts.shape[0] < 16:+ log.warning("head region too small (%d verts); skipping blendshape transfer",+ head_pts.shape[0])+ return {"names": names, "deltas": out}++ # Similarity alignment: template is centered and Y-up; move it onto the+ # target head and match vertical extent.+ tpl_verts = template["verts"]+ tpl_height = float(tpl_verts[:, 1].max() - tpl_verts[:, 1].min())+ head_height = float(head_pts[:, 1].max() - head_pts[:, 1].min())+ if tpl_height <= 0 or head_height <= 0:+ raise RuntimeError("degenerate head or template extent")+ scale = head_height / tpl_height+ offset = head_pts.mean(axis=0) - tpl_verts.mean(axis=0) * scale+ aligned = tpl_verts * scale + offset++ kdt = cKDTree(aligned)+ dist, nearest = kdt.query(head_pts, k=1)+ nearest = np.asarray(nearest).reshape(-1)++ # Distance falloff: a head vertex sitting on the template surface keeps the+ # full delta; hair/accessory vertices far from any facial surface fade out.+ sigma = max(head_height * _FALLOFF_SIGMA_RATIO, 1e-6)+ fall = np.exp(-(dist / sigma) ** 2).astype(np.float32)+ fall[dist > _FALLOFF_CUTOFF_SIGMAS * sigma] = 0.0++ # Deltas scale with the head, and attenuate per correspondence quality.+ head_idx = np.flatnonzero(head_mask)+ tpl_deltas = template["deltas"][:, nearest, :] * scale # (K,H,3)+ out[:, head_idx, :] = tpl_deltas * fall[None, :, None]++ active = int((np.abs(out).max(axis=(0, 2)) > 1e-7).sum())+ log.info("blendshape transfer: %d/%d head verts active, scale=%.3f sigma=%.4f",+ active, head_pts.shape[0], scale, sigma)+ return {"names": names, "deltas": out}diff --git a/workers/rig/build_arkit_template.py b/workers/rig/build_arkit_template.pynew file mode 100644index 000000000..effa7caa9--- /dev/null+++ b/workers/rig/build_arkit_template.py@@ -0,0 +1,154 @@+"""+Bake the ICT-FaceKit expression set into arkit_template.npz for blendshapes.py.++ICT-FaceKit (https://github.com/ICT-VGL/ICT-FaceKit, MIT) ships a generic+neutral head (FaceXModel/generic_neutral_mesh.obj) plus one OBJ per FACS+expression shape following Apple ARKit naming with _L/_R suffixes+(e.g. browDown_L.obj). This script maps them onto the canonical ARKit-52 list+(combining the _L/_R pairs ARKit treats as a single shape, like browInnerUp)+and writes a single npz the worker loads at startup.++Run once during asset staging (see stage-assets.sh), not at runtime:++ git clone --depth 1 https://github.com/ICT-VGL/ICT-FaceKit /tmp/ict-facekit+ python build_arkit_template.py --facekit /tmp/ict-facekit --out arkit_template.npz++Output npz: names [K] (ARKit-52 order), verts (V,3) neutral head centered on+its centroid (Y-up, +Z facing, ICT's native orientation), deltas (K,V,3).+Shapes ICT does not provide (tongueOut has no ICT source mesh in some+releases) are written as zero deltas so the full 52-name contract holds.+"""++from __future__ import annotations++import argparse+import os+import sys++import numpy as np++# ARKit-52 name -> ICT-FaceKit source shape(s). Multi-source entries are+# summed (the regions are disjoint halves of one ARKit shape).+ICT_SOURCES = {+ "browDownLeft": ["browDown_L"],+ "browDownRight": ["browDown_R"],+ "browInnerUp": ["browInnerUp_L", "browInnerUp_R"],+ "browOuterUpLeft": ["browOuterUp_L"],+ "browOuterUpRight": ["browOuterUp_R"],+ "cheekPuff": ["cheekPuff_L", "cheekPuff_R"],+ "cheekSquintLeft": ["cheekSquint_L"],+ "cheekSquintRight": ["cheekSquint_R"],+ "eyeBlinkLeft": ["eyeBlink_L"],+ "eyeBlinkRight": ["eyeBlink_R"],+ "eyeLookDownLeft": ["eyeLookDown_L"],+ "eyeLookDownRight": ["eyeLookDown_R"],+ "eyeLookInLeft": ["eyeLookIn_L"],+ "eyeLookInRight": ["eyeLookIn_R"],+ "eyeLookOutLeft": ["eyeLookOut_L"],+ "eyeLookOutRight": ["eyeLookOut_R"],+ "eyeLookUpLeft": ["eyeLookUp_L"],+ "eyeLookUpRight": ["eyeLookUp_R"],+ "eyeSquintLeft": ["eyeSquint_L"],+ "eyeSquintRight": ["eyeSquint_R"],+ "eyeWideLeft": ["eyeWide_L"],+ "eyeWideRight": ["eyeWide_R"],+ "jawForward": ["jawForward"],+ "jawLeft": ["jawLeft"],+ "jawOpen": ["jawOpen"],+ "jawRight": ["jawRight"],+ "mouthClose": ["mouthClose"],+ "mouthDimpleLeft": ["mouthDimple_L"],+ "mouthDimpleRight": ["mouthDimple_R"],+ "mouthFrownLeft": ["mouthFrown_L"],+ "mouthFrownRight": ["mouthFrown_R"],+ "mouthFunnel": ["mouthFunnel"],+ "mouthLeft": ["mouthLeft"],+ "mouthLowerDownLeft": ["mouthLowerDown_L"],+ "mouthLowerDownRight": ["mouthLowerDown_R"],+ "mouthPressLeft": ["mouthPress_L"],+ "mouthPressRight": ["mouthPress_R"],+ "mouthPucker": ["mouthPucker"],+ "mouthRight": ["mouthRight"],+ "mouthRollLower": ["mouthRollLower"],+ "mouthRollUpper": ["mouthRollUpper"],+ "mouthShrugLower": ["mouthShrugLower"],+ "mouthShrugUpper": ["mouthShrugUpper"],+ "mouthSmileLeft": ["mouthSmile_L"],+ "mouthSmileRight": ["mouthSmile_R"],+ "mouthStretchLeft": ["mouthStretch_L"],+ "mouthStretchRight": ["mouthStretch_R"],+ "mouthUpperUpLeft": ["mouthUpperUp_L"],+ "mouthUpperUpRight": ["mouthUpperUp_R"],+ "noseSneerLeft": ["noseSneer_L"],+ "noseSneerRight": ["noseSneer_R"],+ "tongueOut": ["tongueOut"],+}+++def _load_obj_vertices(path: str) -> np.ndarray:+ """Minimal OBJ vertex reader; ICT shapes share the neutral's topology so+ only the `v` lines matter and vertex order is the correspondence."""+ verts = []+ with open(path, "r", encoding="utf-8", errors="replace") as fh:+ for line in fh:+ if line.startswith("v "):+ parts = line.split()+ verts.append((float(parts[1]), float(parts[2]), float(parts[3])))+ if not verts:+ raise RuntimeError(f"no vertices in {path}")+ return np.asarray(verts, dtype=np.float32)+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--facekit", required=True, help="path to a clone of ICT-VGL/ICT-FaceKit")+ ap.add_argument("--out", default="arkit_template.npz")+ args = ap.parse_args()++ model_dir = os.path.join(args.facekit, "FaceXModel")+ neutral_path = os.path.join(model_dir, "generic_neutral_mesh.obj")+ if not os.path.isfile(neutral_path):+ print(f"error: {neutral_path} not found; is --facekit a full clone?", file=sys.stderr)+ return 1++ neutral = _load_obj_vertices(neutral_path)+ center = neutral.mean(axis=0)+ verts = neutral - center++ names, deltas, missing = [], [], []+ for arkit_name, sources in ICT_SOURCES.items():+ delta = np.zeros_like(neutral)+ found_any = False+ for src in sources:+ src_path = os.path.join(model_dir, f"{src}.obj")+ if not os.path.isfile(src_path):+ continue+ shape = _load_obj_vertices(src_path)+ if shape.shape != neutral.shape:+ raise RuntimeError(+ f"{src}.obj vertex count {shape.shape[0]} != neutral {neutral.shape[0]}"+ )+ delta += shape - neutral+ found_any = True+ if not found_any:+ missing.append(arkit_name)+ names.append(arkit_name)+ deltas.append(delta)++ deltas = np.stack(deltas, axis=0).astype(np.float32)+ np.savez_compressed(args.out, names=np.array(names), verts=verts, deltas=deltas)++ print(f"wrote {args.out}: {len(names)} shapes over {verts.shape[0]} verts")+ if missing:+ # tongueOut is the only expected absentee; anything else means the+ # FaceXModel layout changed and the bake must be fixed, not shipped.+ print(f"zero-filled (no ICT source found): {', '.join(missing)}")+ unexpected = [m for m in missing if m != "tongueOut"]+ if unexpected:+ print(f"error: unexpected missing shapes: {unexpected}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/workers/rig/cloudbuild.yaml b/workers/rig/cloudbuild.yamlnew file mode 100644index 000000000..e43b1dcdc--- /dev/null+++ b/workers/rig/cloudbuild.yaml@@ -0,0 +1,73 @@+# Build + deploy the auto-rig worker (Make-It-Animatable engine).+# Manual submit (SHORT_SHA is only auto-set by triggers):+# gcloud builds submit --config workers/rig/cloudbuild.yaml \+# --substitutions=SHORT_SHA=manual$(date +%s) .+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: model-rig+ _REPO: model-rig+ _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/rig+ 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},MAX_CONCURRENT=1,TASK_TIMEOUT_S=420+ - --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++timeout: 3600sdiff --git a/workers/rig/engine_mia.py b/workers/rig/engine_mia.pynew file mode 100644index 000000000..1e3500277--- /dev/null+++ b/workers/rig/engine_mia.py@@ -0,0 +1,150 @@+"""+Make-It-Animatable driver: mesh in, skeleton + skinning weights out.++Wraps jasongzy/Make-It-Animatable (MIT, CVPR 2025) as a pure predictor. We run+its prepare/preprocess/infer/vis stages headlessly and read the results off+its DB state object; we deliberately do NOT run its Blender/FBX export stage.+The visual mesh never round-trips through Blender, so the original GLB's+materials and PBR textures survive untouched; rig_glb.py grafts the predicted+skeleton straight into the original bytes.++MIA specifics this module encodes:+ - init must happen on the MAIN thread: importing MIA's app module builds the+ Mixamo kinematic tree through bpy, and bpy crashes when scene data is+ touched from a child thread. Per-job prediction never touches bpy.+ - MIA normalizes the input into its own working frame and composes the+ transform onto db.global_transform; we invert it to bring joints and+ working vertices back into the caller's GLB space.+ - Output skeleton is the 65-bone Mixamo hierarchy (fingers included), names+ prefixed "mixamorig:". The platform's glb-canonicalize maps these onto the+ canonical clip skeleton at ingest, so every clip in the library retargets.++Environment:+ MIA_DIR path to the Make-It-Animatable checkout (default /app/mia); its+ output/best/new/*.pth weights and data/Mixamo/bones.fbx template+ must be in place before init() (see stage_assets.py).+"""++from __future__ import annotations++import logging+import os+import sys++import numpy as np++log = logging.getLogger("rig.engine_mia")++MIA_DIR = os.environ.get("MIA_DIR", "/app/mia")++_mia = None+_names: list[str] | None = None+_parents: list[int] | None = None+++def init() -> None:+ """Import MIA and load its six checkpoints. Main thread only; ~seconds."""+ global _mia, _names, _parents+ if _mia is not None:+ return+ if not os.path.isdir(MIA_DIR):+ raise RuntimeError(f"MIA_DIR not found: {MIA_DIR}")+ sys.path.insert(0, MIA_DIR)++ import app as mia_app # noqa: PLC0415 (heavy import by design, once)++ mia_app.init_models()+ # The stage functions return Gradio component-update dicts keyed by UI+ # globals that only exist after init_blocks(); build the (unlaunched)+ # Blocks so those names resolve. No server is started here.+ mia_app.init_blocks()++ from util.dataset_mixamo import BONES_IDX_DICT, KINEMATIC_TREE # noqa: PLC0415++ ordered = sorted(BONES_IDX_DICT.items(), key=lambda kv: kv[1])+ _names = [name for name, _ in ordered]+ _parents = list(KINEMATIC_TREE.parent_indices)+ if len(_parents) != len(_names):+ raise RuntimeError(+ f"kinematic tree size {len(_parents)} != bone count {len(_names)}"+ )+ _mia = mia_app+ log.info("MIA ready: %d bones, root=%s", len(_names), _names[0])+++def is_ready() -> bool:+ return _mia is not None+++def joint_names() -> list[str]:+ if _names is None:+ raise RuntimeError("engine not initialized")+ return list(_names)+++def predict(glb_path: str) -> dict:+ """Run MIA on a GLB file and return predictions in the GLB's own space.++ Returns:+ verts (V,3) MIA's working vertices, back in input space (weight rows+ align to these; rig_glb KD-trees them onto the GLB primitives)+ weights (V,J)+ joints (J,3) bone heads, input space+ joints_tail (J,3)+ parents (J,) with -1 for the root+ names [J] "mixamorig:*" bone names+ """+ if _mia is None:+ raise RuntimeError("engine not initialized")+ import shutil # noqa: PLC0415+ import torch # noqa: PLC0415++ db = _mia.DB()+ try:+ _mia.prepare_input(glb_path, False, 0.0, db, export_temp=True)+ _mia.preprocess(db)+ _mia.infer(False, db)+ # bw_fix applies MIA's weight post-process (head/finger cleanups);+ # vis also converts db fields to numpy and fills joints_tail.+ _mia.vis(True, "LeftArm", False, db)+ finally:+ # MIA caches GPU tensors on the DB and writes stage visualizations into+ # a per-job temp dir; drop both even on failure so a poison mesh cannot+ # leak VRAM or disk across jobs.+ torch.cuda.empty_cache()+ if db.output_dir:+ shutil.rmtree(db.output_dir, ignore_errors=True)++ if db.bw is None or db.joints is None or db.joints_tail is None:+ raise RuntimeError("MIA produced no rig prediction")++ # db.global_transform maps input space -> MIA's normalized frame (it was+ # composed across prepare_input and infer); invert to go home.+ inv = db.global_transform.inverse()++ def _back(points: np.ndarray) -> np.ndarray:+ t = torch.as_tensor(np.asarray(points, dtype=np.float32)).reshape(1, -1, 3)+ return inv.transform_points(t).squeeze(0).cpu().numpy().astype(np.float32)++ verts = _back(db.verts)+ joints = _back(db.joints)+ joints_tail = _back(db.joints_tail)+ weights = np.asarray(db.bw, dtype=np.float32)++ if weights.shape[0] != verts.shape[0]:+ raise RuntimeError(+ f"weights ({weights.shape[0]}) misaligned with working verts ({verts.shape[0]})"+ )+ if weights.shape[1] != len(_names):+ raise RuntimeError(+ f"weight columns ({weights.shape[1]}) != bone count ({len(_names)})"+ )++ return {+ "verts": verts,+ "weights": weights,+ "joints": joints,+ "joints_tail": joints_tail,+ "parents": np.asarray(_parents, dtype=np.int64),+ "names": list(_names),+ }diff --git a/workers/rig/entrypoint.sh b/workers/rig/entrypoint.shnew file mode 100755index 000000000..6cad9a208--- /dev/null+++ b/workers/rig/entrypoint.sh@@ -0,0 +1,28 @@+#!/bin/sh+# Wire the GCS-FUSE weights mount into the Make-It-Animatable checkout, then+# serve. The mount (see cloudbuild.yaml) exposes the bucket at /weights; MIA+# resolves its checkpoints and Mixamo templates relative to its own tree.+set -eu++WEIGHTS_ROOT="${WEIGHTS_ROOT:-/weights/make-it-animatable}"+MIA_DIR="${MIA_DIR:-/app/mia}"++for rel in output/best/new data/Mixamo; do+ src="$WEIGHTS_ROOT/$rel"+ dst="$MIA_DIR/$rel"+ if [ ! -e "$src" ]; then+ echo "fatal: expected staged assets at $src (run workers/rig/stage-assets.sh)" >&2+ exit 1+ fi+ mkdir -p "$(dirname "$dst")"+ rm -rf "$dst"+ ln -s "$src" "$dst"+done++if [ ! -f "${ARKIT_TEMPLATE:-/app/assets/arkit_template.npz}" ]; then+ # The template also lives in the weights bucket; link it into place.+ mkdir -p /app/assets+ ln -sf "$WEIGHTS_ROOT/arkit_template.npz" /app/assets/arkit_template.npz+fi++exec uvicorn main:app --host 0.0.0.0 --port 8080 --workers 1 --timeout-keep-alive 300diff --git a/workers/rig/main.py b/workers/rig/main.pynew file mode 100644index 000000000..e12695e95--- /dev/null+++ b/workers/rig/main.py@@ -0,0 +1,238 @@+"""+Auto-rigging service: adds a Mixamo-standard skeleton, skinning weights, and+ARKit-52 blendshapes to raw humanoid meshes from the 3D generation models.++Engine: jasongzy/Make-It-Animatable (MIT, CVPR 2025) predicts joint placement+and per-vertex weights (see engine_mia.py); rig_glb.py grafts them into the+original GLB bytes so materials/PBR textures are preserved exactly;+blendshapes.py transfers the ICT-FaceKit (MIT) ARKit-52 expression set onto+the head so emotions and lipsync work out of the box.++API contract (identical to the retired unirig worker, so the platform's+GCP_UNIRIG_URL wiring is a config-only cutover):+ 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?, elapsed_ms? }+ GET /health -> { ok, model, gpu_available, model_loaded }++Design notes vs the service this replaces:+ - Every task runs under a hard timeout (TASK_TIMEOUT_S, default 420s): a task+ can finish or fail, but never hang in "running" forever.+ - Bones are named (mixamorig:*), so the platform canonicalizer can retarget+ the full clip library; generic bone_N output is a bug, not a fallback.+ - Task state is in-memory by design: run with min-instances = max-instances+ so pollers always reach the instance that owns the task. A restart 404s+ the poll and the platform fails the job cleanly instead of hanging.++Environment variables:+ API_KEY shared bearer secret (Secret Manager)+ GCS_BUCKET output bucket for rigged GLBs+ MIA_DIR Make-It-Animatable checkout (default /app/mia)+ ARKIT_TEMPLATE baked template npz (default /app/assets/arkit_template.npz)+ MAX_CONCURRENT parallel rigging jobs (default 1)+ TASK_TIMEOUT_S per-task hard timeout in seconds (default 420)+"""++from __future__ import annotations++import asyncio+import logging+import os+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from types import SimpleNamespace+from typing import Optional++import httpx+import torch+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException+from google.cloud import storage+from pydantic import BaseModel++import engine_mia+import rig_glb+from blendshapes import head_mask_from_weights, load_template, transfer_blendshapes+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("rig")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+ARKIT_TEMPLATE = os.environ.get("ARKIT_TEMPLATE", "/app/assets/arkit_template.npz")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))+TASK_TIMEOUT_S = float(os.environ.get("TASK_TIMEOUT_S", "420"))+# Tasks older than this are pruned from the in-memory store.+TASK_TTL_S = 3600.0++_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_template: Optional[dict] = None+_tasks: dict[str, dict] = {}+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem, _template+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ # bpy (used while building MIA's kinematic tree) must run on the main+ # thread, so init happens here, synchronously, before serving. Cloud Run's+ # startup probe covers the load window.+ engine_mia.init()+ _template = load_template(ARKIT_TEMPLATE)+ log.info(+ "Service ready: max_concurrent=%d task_timeout=%.0fs template_shapes=%d",+ MAX_CONCURRENT, TASK_TIMEOUT_S, len(_template["names"]),+ )+ yield+++app = FastAPI(title="rig", 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+++def _prune_tasks() -> None:+ cutoff = time.time() - TASK_TTL_S+ for tid in [t for t, v in _tasks.items() if v.get("created_at", 0) < cutoff]:+ _tasks.pop(tid, None)+++def _rig_sync(mesh_bytes: bytes, want_blendshapes: bool) -> bytes:+ """The blocking rig pipeline; runs in a worker thread."""+ with tempfile.TemporaryDirectory() as tmp:+ glb_path = os.path.join(tmp, "input.glb")+ with open(glb_path, "wb") as fh:+ fh.write(mesh_bytes)+ pred = engine_mia.predict(glb_path)++ blend = None+ if want_blendshapes:+ mask = head_mask_from_weights(pred["weights"], pred["names"])+ blend = transfer_blendshapes(_template, pred["verts"], mask)++ # rig_glb only needs .vertices off the mesh argument; hand it MIA's working+ # vertices (already back in input space) rather than re-parsing the GLB.+ return rig_glb.build_rigged_glb(+ mesh_bytes,+ SimpleNamespace(vertices=pred["verts"]),+ pred["joints"],+ pred["parents"],+ pred["weights"],+ blendshape_data=blend,+ joint_names=pred["names"],+ )+++async def _run_task(task_id: str, mesh_gcs_url: str, want_blendshapes: bool) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ async def _work() -> str:+ 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++ rigged = await loop.run_in_executor(+ None, _rig_sync, mesh_bytes, want_blendshapes+ )++ 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, content_type="model/gltf-binary"+ ),+ )+ return f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ gcs_url = await asyncio.wait_for(_work(), timeout=TASK_TIMEOUT_S)+ 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 -> %s", task_id, elapsed, gcs_url)+ except asyncio.TimeoutError:+ _tasks[task_id].update({+ "status": "failed",+ "error": f"rigging timed out after {TASK_TIMEOUT_S:.0f}s",+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+ log.error("[%s] rigging timed out", task_id)+ 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+ # Accepted for wire compatibility with the old worker; the ICT template is+ # the only one shipped and `template` no longer selects anything.+ template: str = "arkit_ict"+ 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)+ _prune_tasks()+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "created_at": time.time(),+ }+ background_tasks.add_task(_run_task, task_id, body.mesh_gcs_url, 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 {k: v for k, v in task.items() if k != "created_at"}++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "make-it-animatable",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "model_loaded": engine_mia.is_ready(),+ "queued": sum(1 for t in _tasks.values() if t.get("status") in ("queued", "running")),+ }diff --git a/workers/rig/requirements.txt b/workers/rig/requirements.txtnew file mode 100644index 000000000..0d001380c--- /dev/null+++ b/workers/rig/requirements.txt@@ -0,0 +1,39 @@+# Make-It-Animatable (jasongzy, MIT) runtime set, mirrored from its+# requirements.txt at the commit pinned in the Dockerfile, minus training-only+# extras (tensorboard, ipykernel, ipympl, fake-bpy-module).+--extra-index-url https://download.pytorch.org/whl/cu121+torch==2.1.2+torchvision==0.16.2++-f https://data.pyg.org/whl/torch-2.1.2+cu121.html+torch-cluster++--extra-index-url https://miropsota.github.io/torch_packages_builder+pytorch3d==0.7.7+pt2.1.2cu121++einops+timm+PyMCubes+bpy==4.3.0+gradio>=5.25.0+matplotlib+numpy~=1.26.4+plyfile+potpourri3d+shapely+spaces+tqdm+trimesh>=4.4.0++# Rig authoring + blendshape transfer (rig_glb.py / blendshapes.py)+pygltflib==1.16.2+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/rig/rig_glb.py b/workers/rig/rig_glb.pynew file mode 100644index 000000000..9d7cf5944--- /dev/null+++ b/workers/rig/rig_glb.py@@ -0,0 +1,379 @@+"""+Pure glTF skin authoring: turns a raw mesh GLB plus a 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 the predictor's working vertices)+ - optional ARKit-named morph targets from blendshape deltas; primitives whose+ vertices carry no deltas (body, clothes) are skipped so 52 zero targets do+ not bloat every primitive++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.++This file began as workers/unirig/rig_glb.py and generalizes it: the caller+supplies explicit `joint_names` (the rig worker passes Mixamo names, which the+platform's glb-canonicalize maps onto the canonical clip skeleton).+"""++from __future__ import annotations++import logging++import numpy as np+import pygltflib+from scipy.spatial import cKDTree++log = logging.getLogger("rig.rig_glb")++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 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, joint_names=None):+ """Author a fully rigged GLB from the raw mesh and the model's predictions.+ Returns the serialized GLB bytes. `mesh` is the trimesh (or any object with+ a .vertices array) the weights were computed over, in the SAME world space+ as the original GLB; `joints` (J,3) world-space, `parents` (J,) with -1 (or+ any out-of-range value) marking roots, `weights` (V,J). `joint_names` is an+ optional list of J bone names; unnamed joints fall back to joint_i."""+ 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}); "+ "predictor output is not aligned to the input mesh"+ )+ if joint_names is not None and len(joint_names) != n_joints:+ raise RuntimeError(+ f"joint_names length ({len(joint_names)}) != joints ({n_joints})"+ )++ 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])+ 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=str(joint_names[i]) if joint_names is not None 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), column-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 65 Mixamo 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 to 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:+ prim_deltas = bs_deltas[:, nearest, :] # (K,M,3)+ # Morph targets are only meaningful where deltas exist (the+ # head). Skip primitives whose verts carry no deformation so+ # body/clothing primitives don't gain 52 all-zero targets.+ if np.abs(prim_deltas).max() > 1e-7:+ targets = []+ for d in prim_deltas:+ d = np.ascontiguousarray(np.asarray(d, dtype=np.float32))+ 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/rig/stage-assets.sh b/workers/rig/stage-assets.shnew file mode 100755index 000000000..497fdfdf1--- /dev/null+++ b/workers/rig/stage-assets.sh@@ -0,0 +1,42 @@+#!/usr/bin/env bash+# Stage everything the rig worker needs into the model-weights bucket.+# Run once (from any machine with gcloud + git-lfs + python3) before the first+# deploy, and again only when bumping the MIA commit or template.+#+# bash workers/rig/stage-assets.sh+#+# Layout produced under gs://three-ws-model-weights/make-it-animatable/:+# output/best/new/*.pth Make-It-Animatable checkpoints (HF, MIT)+# data/Mixamo/bones.fbx Mixamo skeleton template (HF dataset)+# data/Mixamo/bones_vroid.fbx+# arkit_template.npz baked ICT-FaceKit ARKit-52 template (MIT)+set -euo pipefail++BUCKET="${BUCKET:-gs://three-ws-model-weights/make-it-animatable}"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT+HERE="$(cd "$(dirname "$0")" && pwd)"++echo "==> Make-It-Animatable checkpoints (HF: jasongzy/Make-It-Animatable)"+GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 \+ https://huggingface.co/jasongzy/Make-It-Animatable "$WORK/hf-mia"+git -C "$WORK/hf-mia" lfs pull -I output/best/new++echo "==> Mixamo bone templates (HF dataset: jasongzy/Mixamo)"+GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 \+ https://huggingface.co/datasets/jasongzy/Mixamo "$WORK/hf-mixamo"+git -C "$WORK/hf-mixamo" lfs pull -I 'bones*.fbx'++echo "==> ICT-FaceKit ARKit template bake"+git clone --depth 1 https://github.com/ICT-VGL/ICT-FaceKit "$WORK/ict"+python3 "$HERE/build_arkit_template.py" \+ --facekit "$WORK/ict" --out "$WORK/arkit_template.npz"++echo "==> Upload to $BUCKET"+gcloud storage cp -r "$WORK/hf-mia/output/best/new" "$BUCKET/output/best/new"+gcloud storage cp "$WORK/hf-mixamo/bones.fbx" "$WORK/hf-mixamo/bones_vroid.fbx" \+ "$BUCKET/data/Mixamo/"+gcloud storage cp "$WORK/arkit_template.npz" "$BUCKET/arkit_template.npz"++echo "==> Staged. Verify:"+gcloud storage ls -r "$BUCKET" | sed 's/^/ /'diff --git a/workers/rig/test_blendshapes.py b/workers/rig/test_blendshapes.pynew file mode 100644index 000000000..31bb7639b--- /dev/null+++ b/workers/rig/test_blendshapes.py@@ -0,0 +1,167 @@+"""+Isolated test for blendshapes.py: template loading, head masking, and delta+transfer onto a synthetic humanoid head. No GPU / torch / GCP:+`python3 test_blendshapes.py`.++Uses a fabricated template (a small sphere with a known "jawOpen" delta) and a+synthetic target whose head is a displaced, rescaled copy of that sphere, so+the expected transferred deltas are known analytically.+"""++import os+import sys+import tempfile++import numpy as np++from blendshapes import head_mask_from_weights, load_template, transfer_blendshapes+++def _check(cond, msg):+ if not cond:+ print(f" FAIL {msg}")+ raise AssertionError(msg)+ print(f" ok {msg}")+++def _sphere(n=400, radius=1.0, seed=7):+ rng = np.random.default_rng(seed)+ v = rng.normal(size=(n, 3))+ v /= np.linalg.norm(v, axis=1, keepdims=True)+ return (v * radius).astype(np.float32)+++def _write_template(path):+ verts = _sphere()+ verts -= verts.mean(axis=0)+ # One real shape (downward jaw delta on the lower hemisphere) and one+ # zero shape (like tongueOut when ICT lacks a source mesh).+ jaw = np.zeros_like(verts)+ lower = verts[:, 1] < 0+ jaw[lower, 1] = -0.1+ deltas = np.stack([jaw, np.zeros_like(verts)], axis=0)+ np.savez_compressed(path, names=np.array(["jawOpen", "tongueOut"]),+ verts=verts, deltas=deltas)+ return verts, deltas+++def test_load_template():+ print("test_load_template")+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "tpl.npz")+ _write_template(path)+ tpl = load_template(path)+ _check(tpl["names"] == ["jawOpen", "tongueOut"], "names round-trip")+ _check(tpl["verts"].shape[1] == 3 and tpl["deltas"].shape[0] == 2,+ "shapes round-trip")++ # A malformed template (delta/vert mismatch) must fail loudly.+ bad = os.path.join(tmp, "bad.npz")+ np.savez_compressed(bad, names=np.array(["a"]),+ verts=np.zeros((10, 3), np.float32),+ deltas=np.zeros((1, 9, 3), np.float32))+ try:+ load_template(bad)+ except RuntimeError:+ _check(True, "malformed template raises")+ else:+ _check(False, "expected RuntimeError for malformed template")+++def test_head_mask():+ print("test_head_mask")+ names = ["mixamorig:Hips", "mixamorig:Spine", "mixamorig:Head",+ "mixamorig:LeftEye"]+ w = np.zeros((5, 4), np.float32)+ w[0, 0] = 1.0 # hips vertex+ w[1, 2] = 0.9 # head vertex+ w[2, 2] = 0.2 # weak head influence: below threshold+ w[3, 3] = 0.8 # eye vertex counts as head+ w[4, 1] = 1.0 # spine vertex+ mask = head_mask_from_weights(w, names)+ _check(mask.tolist() == [False, True, False, True, False],+ f"head mask selects head+eye verts only ({mask.tolist()})")++ try:+ head_mask_from_weights(w, ["a", "b", "c", "d"])+ except RuntimeError:+ _check(True, "missing head bone raises")+ else:+ _check(False, "expected RuntimeError when no head bone present")+++def test_transfer_geometry():+ print("test_transfer_geometry")+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "tpl.npz")+ tpl_verts, tpl_deltas = _write_template(path)+ tpl = load_template(path)++ # Target: body verts far below, head = the template sphere scaled 2x+ # and moved up to y ~ 3.+ scale, offset = 2.0, np.array([0.0, 3.0, 0.0], np.float32)+ head = tpl_verts * scale + offset+ body = _sphere(300, radius=0.8, seed=11) + np.array([0, 0.8, 0], np.float32)+ target = np.concatenate([body, head], axis=0)+ mask = np.zeros(len(target), dtype=bool)+ mask[len(body):] = True++ out = transfer_blendshapes(tpl, target, mask)+ deltas = out["deltas"]+ _check(deltas.shape == (2, len(target), 3), "output covers all verts")+ _check(np.abs(deltas[:, :len(body), :]).max() == 0.0,+ "body verts receive zero delta")++ # Head verts correspond 1:1 with template verts (exact overlap after+ # alignment), so the transferred jaw delta is the template's, scaled.+ head_deltas = deltas[0, len(body):, :]+ expected = tpl_deltas[0] * scale+ err = np.abs(head_deltas - expected).max()+ _check(err < 1e-3, f"jaw deltas transferred and scaled (max err {err:.2e})")+ _check(np.abs(deltas[1]).max() == 0.0, "zero template shape stays zero")+++def test_transfer_falloff():+ print("test_transfer_falloff")+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "tpl.npz")+ _write_template(path)+ tpl = load_template(path)++ # Head region includes an outlier "hair" vertex far off the template+ # surface; falloff must zero it.+ head = tpl["verts"].copy()+ hair = np.array([[0.0, 5.0, 0.0]], np.float32)+ target = np.concatenate([head, hair], axis=0)+ mask = np.ones(len(target), dtype=bool)++ out = transfer_blendshapes(tpl, target, mask)+ _check(np.abs(out["deltas"][0, -1, :]).max() == 0.0,+ "far-off vertex receives zero delta (falloff)")+++def test_tiny_head_skipped():+ print("test_tiny_head_skipped")+ with tempfile.TemporaryDirectory() as tmp:+ path = os.path.join(tmp, "tpl.npz")+ _write_template(path)+ tpl = load_template(path)+ target = _sphere(100, seed=3)+ mask = np.zeros(len(target), dtype=bool)+ mask[:4] = True # too few head verts to align against+ out = transfer_blendshapes(tpl, target, mask)+ _check(np.abs(out["deltas"]).max() == 0.0,+ "degenerate head yields all-zero deltas instead of garbage")+++if __name__ == "__main__":+ try:+ test_load_template()+ test_head_mask()+ test_transfer_geometry()+ test_transfer_falloff()+ test_tiny_head_skipped()+ except AssertionError:+ print("\nFAILED")+ sys.exit(1)+ print("\nALL PASSED")diff --git a/workers/rig/test_rig_glb.py b/workers/rig/test_rig_glb.pynew file mode 100644index 000000000..100dabec0--- /dev/null+++ b/workers/rig/test_rig_glb.py@@ -0,0 +1,301 @@+"""+Isolated test for rig_glb.build_rigged_glb: verifies it turns a raw mesh GLB+plus a fabricated 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+ - morph-target (blendshape) injection wires targets + names+ - explicit joint_names land on the joint nodes (the Mixamo contract)+ - primitives whose vertices carry all-zero deltas get NO morph targets+"""++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 _make_two_mesh_glb():+ # Two separated boxes as two meshes: a stand-in for head + body primitives,+ # so the zero-delta skip has a primitive to skip.+ top = trimesh.creation.box(extents=(1.0, 1.0, 1.0))+ top.apply_translation((0.0, 1.5, 0.0))+ bottom = trimesh.creation.box(extents=(1.0, 1.0, 1.0))+ scene = trimesh.Scene()+ scene.add_geometry(top, node_name="top", geom_name="top")+ scene.add_geometry(bottom, node_name="bottom", geom_name="bottom")+ glb_bytes = scene.export(file_type="glb")+ merged = trimesh.load(io.BytesIO(glb_bytes), file_type="glb", force="mesh")+ return glb_bytes, merged+++def _fake_prediction(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" FAIL {msg}")+ raise AssertionError(msg)+ print(f" ok {msg}")+++def test_skeleton_and_skinning():+ print("test_skeleton_and_skinning")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_prediction(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 x 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_named_joints():+ print("test_named_joints")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_prediction(mesh, n_joints=3)+ names = ["mixamorig:Hips", "mixamorig:Spine", "mixamorig:Head"]++ out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None,+ joint_names=names)+ glb = pygltflib.GLTF2.load_from_bytes(out)+ skin = glb.skins[0]+ got = [glb.nodes[j].name for j in skin.joints]+ _check(got == names, f"joint nodes carry the given names ({got})")++ # Mismatched name count must fail loudly, not misname bones.+ try:+ build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None,+ joint_names=names[:2])+ except RuntimeError as exc:+ _check("joint_names" in str(exc), "name-count mismatch raises")+ else:+ _check(False, "expected RuntimeError for joint_names mismatch")+++def test_blendshape_targets():+ print("test_blendshape_targets")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_prediction(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_zero_delta_primitives_skipped():+ """Body/clothing primitives whose vertices carry no facial deltas must not+ be bloated with all-zero morph targets."""+ print("test_zero_delta_primitives_skipped")+ glb_bytes, merged = _make_two_mesh_glb()+ joints, parents, weights = _fake_prediction(merged, n_joints=3)+ V = len(merged.vertices)++ # Deltas only on the upper half ("head"): vertices above y = 0.75.+ deltas = np.zeros((1, V, 3), dtype=np.float32)+ upper = merged.vertices[:, 1] > 0.75+ _check(upper.any() and (~upper).any(), "test mesh split into upper/lower verts")+ deltas[0, upper, 1] = 0.05++ out = build_rigged_glb(glb_bytes, merged, joints, parents, weights,+ {"names": ["jawOpen"], "deltas": deltas})+ glb = pygltflib.GLTF2.load_from_bytes(out)+ blob = bytearray(glb.binary_blob())++ with_targets, without_targets = 0, 0+ for gmesh in glb.meshes:+ for prim in gmesh.primitives:+ if getattr(prim.attributes, "POSITION", None) is None:+ continue+ pos = _decode(glb, blob, prim.attributes.POSITION)[:, :3].astype(np.float32)+ if prim.targets:+ with_targets += 1+ _check(pos[:, 1].mean() > 0.5, "targets landed on the upper (head) primitive")+ else:+ without_targets += 1+ _check(pos[:, 1].mean() < 0.5, "the lower (body) primitive was skipped")+ _check(with_targets == 1, "exactly one primitive carries morph targets")+ _check(without_targets >= 1, "at least one primitive skipped (no zero bloat)")+++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_prediction(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_prediction(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_named_joints()+ test_blendshape_targets()+ test_zero_delta_primitives_skipped()+ test_dirty_weights_no_collapse()+ test_nonidentity_node_rejected()+ except AssertionError:+ print("\nFAILED")+ sys.exit(1)+ print("\nALL PASSED")diff --git a/workers/rig/worker_security.py b/workers/rig/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/rig/worker_security.py@@ -0,0 +1,222 @@+"""+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})"diff --git a/workers/unirig/README.md b/workers/unirig/README.mdindex 39f48d7e4..414bbe9d5 100644--- a/workers/unirig/README.md+++ b/workers/unirig/README.md@@ -1,5 +1,17 @@# 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 itanimation-ready. Wraps [UniRig](https://github.com/VAST-AI-Research/UniRig)(VAST-AI, MIT, SIGGRAPH 2025), which predicts: