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
Motion Swap: replace yourself in a video with your 3D avatar
nirholas50dc095d2f21
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a9cff65e..20c5e38f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-19- **Docs · Assistant widget** (`/docs/assistant-widget`) — Add a 3D avatar assistant to any website: the one-tag script, the @three-ws/assistant npm package, and the assistant-widget MCP server for AI agents.+- **Motion Swap — Replace Yourself in Video with Your Avatar** (`/motion-swap`) — Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.- **Tutorial · Add a 3D Avatar Assistant** (`/tutorials/add-a-3d-assistant`) — Step-by-step: add a floating 3D avatar assistant to any website with one script tag, configure the avatar, background, and brand, drive it from your own code, or have an AI agent generate the embed via MCP.- **Agent economy self-funding fixed and scaled up** — The agent economy's money loops are back at full speed. We found and fixed the scheduling bug that let failing paid calls hog the autonomous loop and starve the recirculation pipelines, wired a revenue share from the x402 ring treasury into the economy's funding root so it can refuel its own SOL, and raised the daily activity caps. Tips, agent-to-agent payments, trades, and marketplace purchases on the Money Pulse all flow again, and the ring's audit trail now verifies every leg of the new split sweeps. (`/pulse`) `[fix, improvement, infra]`- **Coin pages for new launches, redesigned in the markets-hub style** — Every pump.fun launch on Coin Radar now links straight through to a full coin page at /oracle/coin/<mint>, rebuilt in the same clean editorial design as the /coin/bitcoin markets pages. The page keeps everything it had (Oracle conviction, live market intel from six sources, agent transactions, a live trade tape) and adds the complete Launch Intelligence read from the radar engine: quality score, organic vs bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. The live candles chart stays, joined by a native line view and an agent-trades overlay, and the whole page works in light and dark themes. (`/radar`) `[feature, improvement]`@@ -14,6 +15,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Concierge ships to npm and the MCP registry, with a full examples set** — The Concierge chat widget is now installable as the @three-ws/concierge npm package, and there is a companion Model Context Protocol server, @three-ws/concierge-mcp, on the official MCP registry. That server lets any AI assistant ask a website's concierge a question (it fetches the page and answers grounded in the real content), generate the copy-paste embed code for a site, and list the available 3D avatars. Six runnable examples now ship with the SDK, covering the one-tag install, the web component, the imperative API, a custom GLB avatar, a React wrapper, and pointing the widget at your own answer backend. (`/docs/concierge`) `[sdk, docs]`- **First autonomous agent trade, fully documented** — A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us. (`/blog/first-autonomous-trade`) `[feature, docs]`- **Language links now always win, and the switcher stays out of the way** — Two fixes for the new 41-language experience. Opening a link with a language in the URL (like ?lang=te for Telugu) now always shows that language, even if you had previously browsed in another one; before, your first visit's language silently overrode every shared link. The floating language switcher also joins the site's shared bottom-corner layout, so it no longer overlaps the Getting Started guide. (`/what-is?lang=te`) `[fix, improvement]`+- **Motion Swap: replace yourself in a video with your 3D avatar** — Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie. (`/motion-swap`) `[feature]`- **Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal** — The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme. (`/coin/bitcoin`) `[feature, improvement]`- **The assistant widget ships as an npm package and an MCP server** — The 3D avatar assistant widget is now installable three ways. Beyond the one-tag script, there is an npm package, @three-ws/assistant, for bundler projects (the one-tag build is generated from it, so they never drift), and a free MCP server, @three-ws/assistant-mcp, published to the official Model Context Protocol registry as io.github.nirholas/assistant-widget. Any AI agent (Claude Code, Cursor, Claude Desktop) can now ask for a widget in plain language and get back a paste-ready embed: build_assistant_widget turns a config into a script tag, a frame URL, and a ThreeAssistant.init() call, and list_assistant_options returns every avatar, background, and mode. Full developer docs at /docs/assistant-widget and a step-by-step tutorial walk through every option, the JavaScript API, and the agent workflow. (`/docs/assistant-widget`) `[sdk, feature, docs]`- **TradingView charts on every coin page** — Every /coin page (like /coin/bitcoin) now has a chart-source toggle. Keep the fast native line chart, or switch to a full advanced candlestick chart with indicators and drawing tools. Listed coins open on TradingView; Solana DEX tokens that TradingView doesn't carry open on DexScreener instead, so the advanced view works on every coin. Your choice is remembered across coins and visits, and the chart follows the site theme. (`/coin/bitcoin`) `[feature]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 769621c0e..49c3cc8d8 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -73,6 +73,7 @@ bottom.| Avatar Composer (modular studio generation) | [api/_lib/avatar-composer/](api/_lib/avatar-composer) | In-repo · wired into the studio seed lane | Assembles a rigged, ARKit-expression-ready GLB by mixing skinned parts (hair / top / bottom / footwear / glasses) across the RPM base bodies onto **one shared 67-joint skeleton**, then recolors each part and scales the rig — the Ready-Player-Me / Avaturn "one skeleton, many parts" architecture in pure JS on `@gltf-transform`, no GPU or external service. Replaces the recolor-one-of-five-bodies studio lane so two draws almost never look alike. Borrowed parts keep their own inverse binds but remap onto the identity skeleton; mixing is restricted to a base's rest-pose group so parts always fit. Consumed by [api/cron/avaturn-seed-cron.js](api/cron/avaturn-seed-cron.js) (legacy [studio-avatar.js](api/_lib/studio-avatar.js) recolor is the fallback) and the one-click [api/avatars/surprise.js](api/avatars/surprise.js) endpoint (instant avatar, previewed in [public/gallery/surprise.js](public/gallery/surprise.js)). Docs: [api/_lib/avatar-composer/README.md](api/_lib/avatar-composer/README.md). Tests: [tests/avatar-composer.test.js](tests/avatar-composer.test.js) || 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) |+| Motion Swap (avatar body-swap in video) | [pages/motion-swap.html](pages/motion-swap.html) `→ /motion-swap` + [src/motion-swap.js](src/motion-swap.js), API [api/motion-swap.js](api/motion-swap.js), worker [workers/model-video2motion/](workers/model-video2motion) | Live | Upload a video of one person, get it back with a 3D avatar performing their motion. The worker (CPU Cloud Run, MediaPipe pose + selfie segmentation, both Apache-2.0) tracks 33 world landmarks per frame, solves them onto the canonical Wolf3D skeleton with an in-house bend-plane IK solver ([pose_solver.py](workers/model-video2motion/pose_solver.py), pure NumPy, unit-tested), and emits a standard `AnimationClip.toJSON()` + person-mask video + per-frame screen anchors. The browser composites in one WebGL scene: footage on a shader quad with the subject pixelated under the mask, avatar retargeted via [src/animation-retarget.js](src/animation-retarget.js) and pinned to the subject's anchor each frame, MediaRecorder export with original audio. Provider mode `video2motion` (`GCP_VIDEO2MOTION_URL`) in [api/_providers/gcp.js](api/_providers/gcp.js). Docs: [docs/motion-swap.md](docs/motion-swap.md). Tests: [workers/model-video2motion/test_pose_solver.py](workers/model-video2motion/test_pose_solver.py). || 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) || Forge model categorization | Classifier [api/_lib/forge-classify.js](api/_lib/forge-classify.js), wired at generation in [api/_lib/forge-store.js](api/_lib/forge-store.js) (`createCreation`), backfill [scripts/backfill-forge-categories.mjs](scripts/backfill-forge-categories.mjs), coloured badges in [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin | Live | Assigns every forge model a `model_category` (avatar/accessory/item/scene/creature/vehicle/other) from its prompt with a deterministic, dependency-free keyword classifier — most-specific-first so "a knight riding a horse" is an avatar, not a creature. Nothing set the category before, so ~99.8% of the corpus was `other` and the category badges, filters, and Forge-Off category dimension were dead; the classifier now runs inline on every generation (all lanes) and reclassifies ~85% of the 9.8k-row back catalogue (dry-run verified). Coloured category pills render across the showcase/gallery/community feed. Tests: [tests/forge-classify.test.js](tests/forge-classify.test.js). || Forge thumbnail coverage | [api/_lib/forge-thumbs.js](api/_lib/forge-thumbs.js) + cron [api/cron/forge-thumbnail-backfill.js](api/cron/forge-thumbnail-backfill.js) (`*/5`) | Live | Gives every finished forge model a real picture. The dominant free NVIDIA/TRELLIS lane is geometry-first and paints no reference image, so ~83% of finished `forge_creations` land with `preview_image_url = NULL` and render as gradient placeholders on every browse surface (showcase, gallery, `/community`, `/search`, creator portfolios). This cron claims the newest previewless models, renders each GLB to a 768² PNG via the shared headless-chromium renderer ([api/_lib/render-glb.js](api/_lib/render-glb.js)), uploads it, and fills the preview slot — object confirmed in R2 **before** the key is committed (same ORB-safety invariant as avatars), and **fill-only** so a maker's captured poster always wins. Self-provisioning claim ledger (`forge_thumbnail_backfill`, created at runtime), bounded attempts, lease-based reclaim, browser-death batch abort with attempt refund. `?dry_run=1` reports coverage. Tests: [tests/forge-thumbs.test.js](tests/forge-thumbs.test.js). |diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex d8673967e..7faf1eb8b 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -28,6 +28,9 @@// video2scene → GCP_VIDEO2SCENE_URL (workers/model-video2scene, LingBot-Map)// Streaming video → 3D point cloud. Standard /infer + /tasks/:id// shape; the result is a .ply point cloud, not a GLB mesh.+// video2motion → GCP_VIDEO2MOTION_URL (workers/model-video2motion, MediaPipe)+// Video of a person → AnimationClip JSON + person-mask video ++// normalized video + per-frame screen anchors (body swap).//// All workers share the same bearer secret (GCP_RECONSTRUCTION_KEY).// Each worker exposes the same task shape:@@ -98,6 +101,12 @@ function serviceUrlForMode(mode) {// Streaming video → 3D point-cloud worker (workers/model-video2scene,// LingBot-Map). Standard /infer + /tasks/:id task shape; result is a PLY.return readEnv('GCP_VIDEO2SCENE_URL');+ case 'video2motion':+ // Video of a person → animation clip + body-swap plates+ // (workers/model-video2motion, MediaPipe pose + segmentation). Standard+ // /infer + /tasks/:id task shape; result is an AnimationClip JSON plus+ // mask/video/meta sidecar URLs.+ return readEnv('GCP_VIDEO2MOTION_URL');case 'rerig':// Rigging: prefer the standalone UniRig worker (workers/unirig — direct// /rig + /tasks/:id, `mesh_gcs_url` request schema) when GCP_UNIRIG_URL@@ -352,6 +361,21 @@ function buildWorkerRequest(request) {};}+ if (mode === 'video2motion') {+ // Video of a person → motion clip + compositing plates. The source is a+ // public video URL; capture params ride in `params`.+ const body = { video_url: sourceUrl };+ if (params?.fps !== undefined && params.fps !== null) body.fps = params.fps;+ if (params?.max_seconds !== undefined && params.max_seconds !== null) {+ body.max_seconds = params.max_seconds;+ }+ return {+ path: '/infer',+ resultKey: 'result_url',+ body,+ };+ }+if (mode === 'text2motion') {// Text→motion has no source mesh: the prompt rides in params. The worker// returns a three.js AnimationClip JSON URL (result_url), not a GLB.@@ -387,6 +411,9 @@ const MODE_ETA = {text2motion: 30,rerig: 45,video2scene: 240,+ // CPU pose+segmentation over every frame: scales with clip length; a 30 s+ // clip lands around this.+ video2motion: 120,};// `reconstructUrl` overrides where `reconstruct` jobs go. The forge Hunyuan3D@@ -546,6 +573,14 @@ export function createRegenProvider({ reconstructUrl } = {}) {result.resultClipUrl = url;if (typeof data.frames === 'number') result.frames = data.frames;if (typeof data.fps === 'number') result.fps = data.fps;+ } else if (mode === 'video2motion') {+ // Clip JSON plus the body-swap compositing plates.+ result.resultClipUrl = url;+ if (data.meta_url) result.metaUrl = data.meta_url;+ if (data.video_url) result.videoUrl = data.video_url;+ if (data.mask_url) result.maskUrl = data.mask_url;+ if (typeof data.frames === 'number') result.frames = data.frames;+ if (typeof data.fps === 'number') result.fps = data.fps;} else if (mode === 'video2scene') {// The result is a .ply point cloud, not a GLB mesh. Surface the// reconstruction telemetry so the client can show point/frame counts.diff --git a/api/motion-swap.js b/api/motion-swap.jsnew file mode 100644index 000000000..51c4605a3--- /dev/null+++ b/api/motion-swap.js@@ -0,0 +1,200 @@+/**+ * /api/motion-swap — video of a person → avatar body-swap capture job.+ *+ * POST /api/motion-swap { action: "upload", content_type, size_bytes }+ * → 200 { upload_url, public_url, method, headers, expires_in }+ * Presigns a direct-to-storage PUT for the source video so multi-MB+ * uploads never proxy through this handler (same flow as /api/forge-upload).+ *+ * POST /api/motion-swap { video_url: string, fps?: number, max_seconds?: number }+ * → 202 { job_id, status, eta_seconds }+ *+ * GET /api/motion-swap?job=<id>+ * → { job_id, status, clip_url?, meta_url?, video_url?, mask_url?,+ * frames?, fps?, error? }+ *+ * The worker (workers/model-video2motion) tracks the person with MediaPipe+ * pose, solves the motion onto the canonical Wolf3D skeleton (a three.js+ * AnimationClip JSON — the SAME format the animation library serves, so it+ * retargets onto any rigged avatar with src/animation-retarget.js), segments+ * the person into a mask video, and returns per-frame screen anchors. The+ * /motion-swap page composites: source video underneath, subject blurred via+ * the mask, the user's avatar pinned over them performing their motion.+ */++import { randomUUID } from 'node:crypto';+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { presignUpload, publicUrl } from './_lib/r2.js';+import { createRegenProvider } from './_providers/gcp.js';++const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;+const MAX_VIDEO_BYTES = 256 * 1024 * 1024;+const MAX_SECONDS = 90;++const VIDEO_CONTENT_TYPE_EXT = Object.freeze({+ 'video/mp4': 'mp4',+ 'video/quicktime': 'mov',+ 'video/webm': 'webm',+});++function storageConfigured() {+ return Boolean(+ process.env.S3_ENDPOINT &&+ process.env.S3_BUCKET &&+ process.env.S3_PUBLIC_DOMAIN &&+ process.env.S3_ACCESS_KEY_ID &&+ process.env.S3_SECRET_ACCESS_KEY,+ );+}++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Motion capture is not configured. Set GCP_VIDEO2MOTION_URL and GCP_RECONSTRUCTION_KEY ' ++ 'to the URL and bearer secret of your deployed workers/model-video2motion Cloud Run service.',+ });+}++async function presignVideo(req, res, body) {+ if (!storageConfigured()) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Video upload is not configured on this deployment (object storage missing). ' ++ 'Pass a public video URL to /api/motion-swap instead.',+ });+ }+ const rl = await limits.upload(`motion-swap:${clientIp(req)}`);+ if (!rl.success) {+ return rateLimited(res, rl, 'Upload limit reached. Try again shortly.');+ }++ const contentType =+ typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';+ const ext = VIDEO_CONTENT_TYPE_EXT[contentType];+ if (!ext) {+ return json(res, 400, {+ error: 'invalid_content_type',+ message: 'content_type must be video/mp4, video/quicktime, or video/webm.',+ });+ }+ const size = Number(body?.size_bytes);+ if (!Number.isFinite(size) || size <= 0 || size > MAX_VIDEO_BYTES) {+ return json(res, 400, {+ error: 'invalid_size',+ message: `size_bytes must be between 1 and ${MAX_VIDEO_BYTES} bytes (256 MB).`,+ });+ }++ const key = `motion-swap/uploads/${randomUUID()}.${ext}`;+ let uploadUrl;+ try {+ uploadUrl = await presignUpload({ key, contentType });+ } catch (err) {+ return json(res, 502, {+ error: 'presign_failed',+ message: err?.message || 'Could not create an upload URL.',+ });+ }+ return json(res, 200, {+ upload_url: uploadUrl,+ public_url: publicUrl(key),+ method: 'PUT',+ headers: { 'content-type': contentType },+ expires_in: 600,+ });+}++async function startJob(req, res, body) {+ const rl = await limits.mcp3dGenerate(clientIp(req));+ if (!rl.success) {+ return rateLimited(res, rl);+ }++ let videoUrl;+ try {+ videoUrl = new URL(String(body?.video_url || ''));+ if (videoUrl.protocol !== 'https:') throw new Error('https only');+ } catch {+ return json(res, 400, {+ error: 'invalid_video_url',+ message: 'Pass an https video_url (or use action:"upload" to get one).',+ });+ }+ const fps = Math.max(8, Math.min(30, Number(body?.fps) || 24));+ const maxSeconds = Math.max(1, Math.min(MAX_SECONDS, Number(body?.max_seconds) || MAX_SECONDS));++ let provider;+ try {+ provider = createRegenProvider();+ if (!provider.supportsMode('video2motion')) return unconfigured(res);+ } catch {+ return unconfigured(res);+ }++ try {+ const job = await provider.submit({+ mode: 'video2motion',+ sourceUrl: videoUrl.href,+ params: { fps, max_seconds: maxSeconds },+ });+ return json(res, 202, {+ job_id: job.extJobId,+ status: 'queued',+ eta_seconds: job.eta,+ });+ } catch (err) {+ return json(res, 502, {+ error: 'capture_failed',+ message: err?.message || 'Motion capture could not start.',+ });+ }+}++async function pollJob(req, res, jobId) {+ if (!JOB_ID_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });+ }+ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) {+ return rateLimited(res, rl);+ }++ let provider;+ try {+ provider = createRegenProvider();+ } catch {+ return unconfigured(res);+ }++ const result = await provider.status(jobId);+ return json(res, 200, {+ job_id: jobId,+ status: result.status,+ clip_url: result.resultClipUrl || null,+ meta_url: result.metaUrl || null,+ video_url: result.videoUrl || null,+ mask_url: result.maskUrl || null,+ frames: typeof result.frames === 'number' ? result.frames : null,+ fps: typeof result.fps === 'number' ? result.fps : null,+ error: result.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') {+ const body = await readJson(req, 4_000).catch(() => null);+ if (body?.action === 'upload') return presignVideo(req, res, body);+ return startJob(req, res, body);+ }++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });+ return pollJob(req, res, jobId);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 71a9171b3..3a67349c7 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -14847,6 +14847,15 @@"improvement"],"link": "/radar"+ },+ {+ "date": "2026-07-19",+ "title": "Motion Swap: replace yourself in a video with your 3D avatar",+ "summary": "Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie.",+ "tags": [+ "feature"+ ],+ "link": "/motion-swap"}]}diff --git a/data/pages.json b/data/pages.jsonindex 5c53e5b84..8bfb2f0d7 100644--- a/data/pages.json+++ b/data/pages.json@@ -436,6 +436,14 @@"changefreq": "monthly","added": "2026-06-27"},+ {+ "path": "/motion-swap",+ "title": "Motion Swap — Replace Yourself in Video with Your Avatar",+ "description": "Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-19"+ },{"path": "/forge-nim","title": "Forge · NIM — Self-Hosted Image to 3D",diff --git a/docs/motion-swap.md b/docs/motion-swap.mdnew file mode 100644index 000000000..26ff2f29f--- /dev/null+++ b/docs/motion-swap.md@@ -0,0 +1,79 @@+# Motion Swap — replace yourself in a video with your avatar++**Page:** [/motion-swap](https://three.ws/motion-swap) · **API:** `POST /api/motion-swap` · **Worker:** `workers/model-video2motion`++Upload a video of yourself (a house tour, a product demo, a talking+walk-through) and get it back with your 3D avatar performing your exact motion+instead of you. You stay pixelated under the avatar; the motion, framing, and+audio stay yours. Built for creators who want to publish video without+publishing their face.++## How to use it++1. Open [/motion-swap](https://three.ws/motion-swap) and drop in a video+ (MP4, MOV, or WebM, up to 256 MB; the first 90 seconds are processed).+ One person, full body in frame, tracks best.+2. Wait for capture (about 2 minutes for a 30-second clip). The server tracks+ your pose in every frame and masks you out.+3. Pick an avatar: a stock one, or paste the GLB URL of any rigged humanoid —+ one you [generated](https://three.ws/create), captured from a selfie, or+ rigged from a mesh. Swap avatars any time; the motion re-binds instantly.+4. Press **Export video** to record the composite (with the original audio) to+ a downloadable `.webm`.++The "Pixelate me under the avatar" toggle controls the privacy treatment of+the original subject beneath the avatar.++## How it works++Three stages, split between one CPU worker and your browser:++1. **Track (server).** MediaPipe PoseLandmarker follows 33 body landmarks+ through every frame; MediaPipe ImageSegmenter produces a per-frame person+ mask. Both models are Apache-2.0 and run without a GPU.+2. **Solve (server).** An in-house solver+ (`workers/model-video2motion/pose_solver.py`) converts the landmark+ sequence into local joint rotations on the canonical Wolf3D skeleton and+ emits a standard three.js `AnimationClip` JSON — the same format the+ [animation library](https://three.ws/animations) serves, so the clip+ retargets onto any rigged avatar with the platform's existing engine.+3. **Composite (browser).** One WebGL scene: the normalized footage on a+ fullscreen quad (subject pixelated under the mask in the shader), the+ avatar driven by the clip and pinned to the subject's on-screen position+ and size each frame via the capture's anchor track, and a+ `MediaRecorder` export of canvas + source audio.++Privacy properties: the motion clip contains no imagery (skeleton rotations+only), and processing artifacts live under an unguessable job id.++## API++```+POST /api/motion-swap { action: "upload", content_type, size_bytes }+ → { upload_url, public_url, ... } # presigned direct-to-storage PUT++POST /api/motion-swap { video_url, fps?, max_seconds? }+ → 202 { job_id, status, eta_seconds }++GET /api/motion-swap?job=<id>+ → { status, clip_url, meta_url, video_url, mask_url, frames, fps }+```++`clip_url` is a three.js `AnimationClip.toJSON()` document you can use+anywhere the platform accepts a clip. `meta_url` carries `fps`, dimensions,+and per-frame `anchors` (`{x, y, h, v}`: hip centre in normalized image+coordinates, subject height as a fraction of frame height, visibility).++## Operations++Deploy and wiring: see+[workers/model-video2motion/README.md](../workers/model-video2motion/README.md).+The API routes through the GCP provider's `video2motion` mode; unset+`GCP_VIDEO2MOTION_URL` degrades the endpoint to a clean 503 and the page shows+its error state.++## Related++- [/capture](https://three.ws/capture) — video → 3D point cloud (scene, not person)+- [/animations](https://three.ws/animations) — the clip library the output format matches+- [docs/animations.md](animations.md) · [docs/avatar-reconstruction.md](avatar-reconstruction.md)diff --git a/docs/start-here.md b/docs/start-here.mdindex 75ea76085..167e53fe0 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -76,6 +76,7 @@ Curious what happens between the prompt and the model? [How the Forge works](./h- **Placing agents in the real world?** → [IRL](./irl.md): pin an agent at a real GPS spot from your phone, and anyone who physically walks up can see it, talk to it, and pay it. Real crypto can be escrowed at places ([Money Drops](./irl.md#money-drops)) and agents sign proofs that you were really there ([World Lines](./irl.md#world-lines))- **Making 3D models?** → [The free 3D Studio MCP](./mcp-studio.md) turns a prompt into a model, avatar, or rigged character — and lets you refine it by talking to it (*"make it metallic"*) with a revertable version history. Publish a model as remixable and earn on-chain royalties when others build on it: [the remix economy](./remix.md). Vote on the best community models and win the weekly board: [Forge-Off](./forge-off.md)- **Using ChatGPT?** → [AR in ChatGPT](./chatgpt-ar.md) is how a sentence typed into ChatGPT becomes a 3D model standing in your room, from the free generation lane to the one-tap AR link; [your first prompt to 3D](/tutorials/first-prompt-to-3d) walks you through it in five minutes+- **Making videos without showing your face?** → [Motion Swap](./motion-swap.md) — upload a video of yourself and get it back with your 3D avatar performing your exact motion instead of you; pose tracking and masking run server-side, compositing and export happen in your browser at [/motion-swap](https://three.ws/motion-swap)- **Want a support chat with a face on your own site?** → [Concierge](./concierge.md) — a one-tag chat widget where a rigged 3D avatar lipsyncs streaming answers grounded in your live page, with voice in and out; [the build tutorial](./tutorials/build-a-site-concierge.md) shows how every part works- **Want a full-body avatar assistant on your site instead?** → [Assistant widget](./assistant-widget.md) — a launcher button opens an animated 3D character standing directly on your page (or a color/gradient), with a free-lane or bring-your-own-key chatbot and a speak mode that says whatever you type, out loud, in a speech bubble- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of itdiff --git a/pages/motion-swap.html b/pages/motion-swap.htmlnew file mode 100644index 000000000..d8273a00b--- /dev/null+++ b/pages/motion-swap.html@@ -0,0 +1,237 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Motion Swap — Replace Yourself in Video with Your Avatar · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Pose tracking, person masking, and avatar retargeting — composited and exported in your browser." />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://three.ws/motion-swap" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Motion Swap — Replace Yourself in Video with Your Avatar · three.ws" />+ <meta property="og:description" content="Stay off camera without staying off video. Your avatar performs your motion, pinned frame-by-frame over you." />+ <meta property="og:url" content="https://three.ws/motion-swap" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Motion+Swap+%E2%80%94+Your+Avatar%2C+Your+Motion&d=Upload+a+video+of+yourself+and+get+it+back+with+your+3D+avatar+performing+your+motion+instead+of+you.&p=%2Fmotion-swap" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Motion Swap — Replace Yourself in Video with Your Avatar · three.ws" />+ <meta name="twitter:description" content="Stay off camera without staying off video. Your avatar performs your motion, pinned frame-by-frame over you." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Motion+Swap+%E2%80%94+Your+Avatar%2C+Your+Motion&d=Upload+a+video+of+yourself+and+get+it+back+with+your+3D+avatar+performing+your+motion+instead+of+you.&p=%2Fmotion-swap" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ .ms-page {+ min-height: 100vh;+ background: var(--bg, #060606);+ color: var(--text, #f6f6f6);+ font-family: var(--font-body, 'Inter', system-ui, sans-serif);+ -webkit-font-smoothing: antialiased;+ }+ .ms-wrap { max-width: 1180px; margin: 0 auto; padding: 40px 24px 72px; }+ .ms-chip {+ display: inline-flex; align-items: center; gap: 7px;+ padding: 4px 11px; background: var(--surface-1, #141414);+ border: 1px solid var(--hairline, #1f1f1f); border-radius: 20px;+ font-size: 11px; color: var(--text-2, #b4b4b4); letter-spacing: 0.06em;+ text-transform: uppercase; margin-bottom: 16px;+ }+ .ms-chip-dot { width: 6px; height: 6px; border-radius: 50%; background: #6ee7a2; }+ .ms-head h1 { font-size: clamp(28px, 4.5vw, 44px); margin: 0 0 12px; letter-spacing: -0.02em; }+ .ms-head p { max-width: 680px; color: var(--text-2, #b4b4b4); line-height: 1.6; margin: 0 0 28px; }+ .ms-head a { color: var(--text, #f6f6f6); }++ .ms-stage {+ position: relative; border: 1px solid var(--hairline, #1f1f1f);+ border-radius: 14px; background: var(--surface-0, #0b0b0b); overflow: hidden;+ }+ #ms-canvas-wrap { width: 100%; min-height: 320px; display: flex; justify-content: center; }+ #ms-canvas { max-width: 100%; height: auto; display: block; }++ .ms-overlay {+ position: absolute; inset: 0; display: flex; flex-direction: column;+ align-items: center; justify-content: center; text-align: center;+ padding: 32px; gap: 10px; background: var(--surface-0, #0b0b0b);+ }+ .ms-overlay[hidden] { display: none; }+ .ms-overlay h3 { margin: 0; font-size: 18px; }+ .ms-overlay p { margin: 0; color: var(--text-2, #b4b4b4); max-width: 460px; line-height: 1.55; font-size: 14px; }++ .ms-dropzone {+ border: 1.5px dashed var(--hairline-2, #2c2c2c); border-radius: 12px;+ padding: 42px 32px; cursor: pointer; transition: border-color 0.18s, background 0.18s;+ display: flex; flex-direction: column; align-items: center; gap: 10px; width: min(520px, 90%);+ }+ .ms-dropzone:hover, .ms-dropzone:focus-visible, .ms-dropzone.is-drag {+ border-color: var(--text-2, #b4b4b4); background: var(--surface-1, #121212); outline: none;+ }+ .ms-glyph {+ width: 46px; height: 46px; border-radius: 12px; display: grid; place-items: center;+ background: var(--surface-1, #161616); border: 1px solid var(--hairline, #1f1f1f);+ }+ .ms-spinner {+ width: 26px; height: 26px; border-radius: 50%;+ border: 2.5px solid var(--hairline-2, #2c2c2c); border-top-color: var(--text, #f6f6f6);+ animation: ms-spin 0.9s linear infinite;+ }+ @keyframes ms-spin { to { transform: rotate(360deg); } }++ .ms-layout { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 20px; margin-top: 26px; }+ @media (max-width: 900px) { .ms-layout { grid-template-columns: 1fr; } }++ .ms-card {+ border: 1px solid var(--hairline, #1f1f1f); border-radius: 12px;+ background: var(--surface-0, #0d0d0d); padding: 18px;+ }+ .ms-card h2 { margin: 0 0 10px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.07em; color: var(--text-2, #b4b4b4); }+ .ms-note { color: var(--text-2, #b4b4b4); font-size: 13.5px; line-height: 1.6; margin: 0; }+ .ms-note + .ms-note { margin-top: 8px; }+ .ms-note code { font-size: 12px; }++ .ms-controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 12px 14px; border-top: 1px solid var(--hairline, #1f1f1f); }+ .ms-btn {+ appearance: none; border: 1px solid var(--hairline-2, #2c2c2c); border-radius: 8px;+ background: var(--surface-1, #151515); color: var(--text, #f6f6f6);+ padding: 8px 14px; font-size: 13px; cursor: pointer;+ transition: background 0.15s, border-color 0.15s, transform 0.08s;+ }+ .ms-btn:hover { background: var(--surface-2, #1d1d1d); border-color: var(--text-3, #555); }+ .ms-btn:active { transform: translateY(1px); }+ .ms-btn:focus-visible { outline: 2px solid var(--text-2, #b4b4b4); outline-offset: 1px; }+ .ms-btn[disabled] { opacity: 0.55; cursor: default; }+ .ms-btn--primary { background: var(--text, #f6f6f6); color: var(--bg, #060606); border-color: var(--text, #f6f6f6); font-weight: 600; }+ .ms-btn--primary:hover { background: #dcdcdc; }++ .ms-toggle { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-2, #b4b4b4); cursor: pointer; margin-left: auto; }+ .ms-toggle input { accent-color: #6ee7a2; }++ #ms-avatars { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 12px; }+ .ms-avatar-chip {+ appearance: none; border: 1px solid var(--hairline-2, #2c2c2c); border-radius: 18px;+ background: var(--surface-1, #141414); color: var(--text-2, #b4b4b4);+ padding: 6px 13px; font-size: 12.5px; cursor: pointer; transition: all 0.15s;+ }+ .ms-avatar-chip:hover { color: var(--text, #f6f6f6); border-color: var(--text-3, #555); }+ .ms-avatar-chip[aria-pressed='true'] { background: var(--text, #f6f6f6); color: var(--bg, #060606); border-color: var(--text, #f6f6f6); font-weight: 600; }+ .ms-url-row { display: flex; gap: 7px; }+ .ms-url-row input {+ flex: 1; min-width: 0; background: var(--surface-1, #121212); color: var(--text, #f6f6f6);+ border: 1px solid var(--hairline-2, #2c2c2c); border-radius: 8px; padding: 8px 10px; font-size: 12.5px;+ }+ .ms-url-row input:focus { outline: none; border-color: var(--text-3, #555); }++ #ms-status { margin-top: 12px; font-size: 13.5px; color: var(--text-2, #b4b4b4); }+ #ms-status[data-kind='error'] { color: #ff7a7a; }+ #ms-status[hidden] { display: none; }+ </style>+ </head>+ <body>+ <div class="ms-page">+ <div id="nav-container"></div>+ <script type="module" src="/nav.js"></script>++ <div class="ms-wrap">+ <div class="ms-head">+ <span class="ms-chip"><span class="ms-chip-dot"></span> Video motion capture · body swap</span>+ <h1>Your video. Your avatar. Not your face.</h1>+ <p>+ Upload a video of yourself — a house tour, a product demo, a talking walk-through — and get+ it back with your <a href="/create">3D avatar</a> performing your exact motion instead of you.+ Pose tracking runs server-side; you stay pixelated under the avatar. Compositing and export+ happen right here in your browser.+ </p>+ </div>++ <div class="ms-layout">+ <div>+ <div class="ms-stage">+ <div id="ms-canvas-wrap"><canvas id="ms-canvas" width="960" height="540" aria-label="Motion swap composite preview"></canvas></div>++ <div class="ms-overlay" id="ms-stage-empty">+ <div class="ms-dropzone" id="ms-drop" role="button" tabindex="0" aria-label="Upload a video">+ <div class="ms-glyph">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="m22 8-6 4 6 4V8Z"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>+ </div>+ <h3>Drop a video of one person</h3>+ <p>MP4, MOV, or WebM up to 256 MB. The first 90 seconds are processed. Full body in frame tracks best.</p>+ </div>+ <input id="ms-file" type="file" accept="video/mp4,video/quicktime,video/webm" hidden />+ </div>++ <div class="ms-overlay" id="ms-stage-processing" hidden>+ <div class="ms-spinner" role="status" aria-label="Processing"></div>+ <h3>Capturing your motion</h3>+ <p>Tracking your pose frame-by-frame and masking you out. A 30-second clip takes about two minutes.</p>+ </div>++ <div id="ms-stage-ready" hidden></div>++ <div class="ms-controls">+ <button class="ms-btn" id="ms-play" type="button">Play / Pause</button>+ <button class="ms-btn" id="ms-restart" type="button">Restart</button>+ <button class="ms-btn ms-btn--primary" id="ms-export" type="button">Export video</button>+ <button class="ms-btn" id="ms-new" type="button">New video</button>+ <label class="ms-toggle" for="ms-privacy">+ <input type="checkbox" id="ms-privacy" checked />+ Pixelate me under the avatar+ </label>+ </div>+ </div>+ <p id="ms-status" hidden></p>+ <video id="ms-video" playsinline hidden></video>+ <video id="ms-mask" playsinline muted hidden></video>+ </div>++ <aside>+ <div class="ms-card">+ <h2>Avatar</h2>+ <div id="ms-avatars"></div>+ <div class="ms-url-row">+ <input id="ms-avatar-url" type="url" placeholder="…or paste a rigged GLB URL" aria-label="Avatar GLB URL" />+ <button class="ms-btn" id="ms-avatar-url-go" type="button">Load</button>+ </div>+ <p class="ms-note" style="margin-top: 10px">+ Any rigged humanoid GLB works — one you <a href="/create">generated</a>,+ <a href="/capture-avatar">captured from a selfie</a>, or rigged from a mesh.+ </p>+ </div>+ <div class="ms-card" style="margin-top: 16px">+ <h2>How it works</h2>+ <p class="ms-note">+ A server worker tracks your body pose in every frame and solves it onto the platform's+ canonical skeleton — the same retarget engine that drives every avatar animation here.+ It also segments you out into a mask.+ </p>+ <p class="ms-note">+ Your browser then plays the original footage, pixelates you under the mask, and pins the+ avatar over you frame-by-frame, matching your position and size. Export records the+ composite with the original audio.+ </p>+ <p class="ms-note">+ The source video is processed transiently and the pose data contains no imagery —+ the motion clip is just skeleton rotations.+ </p>+ </div>+ </aside>+ </div>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js" defer></script>+ </div>++ <script type="module" src="/src/motion-swap.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex ddd957db7..fbe641137 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T07:06:32.397Z",+ "generated_at": "2026-07-19T07:10:14.653Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-07-19",+ "type": "launch",+ "title": "Motion Swap — Replace Yourself in Video with Your Avatar",+ "summary": "Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.",+ "link": "/motion-swap",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-19","type": "launch",@@ -93,6 +103,16 @@"improvement"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "Motion Swap: replace yourself in a video with your 3D avatar",+ "summary": "Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie.",+ "link": "/motion-swap",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cab355e8d..5289ce4c0 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>launch</category><description>Add a 3D avatar assistant to any website: the one-tag script, the @three-ws/assistant npm package, and the assistant-widget MCP server for AI agents.</description></item>+ <item>+ <title>Motion Swap — Replace Yourself in Video with Your Avatar</title>+ <link>https://three.ws/motion-swap</link>+ <guid isPermaLink="false">2026-07-19:Motion Swap — Replace Yourself in Video with Your Avatar</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.</description>+ </item><item><title>Tutorial · Add a 3D Avatar Assistant</title><link>https://three.ws/tutorials/add-a-3d-assistant</link>@@ -70,6 +78,14 @@<category>fix</category><description>Two fixes for the new 41-language experience. Opening a link with a language in the URL (like ?lang=te for Telugu) now always shows that language, even if you had previously browsed in another one; before, your first visit's language silently overrode every shared link. The floating language switcher also joins the site's shared bottom-corner layout, so it no longer overlaps the Getting Started guide.</description></item>+ <item>+ <title>Motion Swap: replace yourself in a video with your 3D avatar</title>+ <link>https://three.ws/motion-swap</link>+ <guid isPermaLink="false">2026-07-19:Motion Swap: replace yourself in a video with your 3D avatar</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie.</description>+ </item><item><title>Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal</title><link>https://three.ws/coin/bitcoin</link>diff --git a/public/features.json b/public/features.jsonindex de9b2e7c2..fb495aabe 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T07:05:14.397Z",+ "generated_at": "2026-07-19T07:10:14.638Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -532,6 +532,16 @@"tags": [],"showcase": false},+ {+ "path": "/motion-swap",+ "title": "Motion Swap — Replace Yourself in Video with Your Avatar",+ "description": "Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.",+ "added": "2026-07-19",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/forge-nim","title": "Forge · NIM — Self-Hosted Image to 3D",diff --git a/public/llms-full.txt b/public/llms-full.txtindex a3066688b..91c229203 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -328,6 +328,12 @@ URL: https://three.ws/captureTurn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.+### Motion Swap — Replace Yourself in Video with Your Avatar++URL: https://three.ws/motion-swap++Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.+### Forge · NIM — Self-Hosted Image to 3DURL: https://three.ws/forge-nimdiff --git a/public/llms.txt b/public/llms.txtindex f7ddff271..af25dab2a 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -64,6 +64,7 @@ Create and customize an agent.- [Avatar Engines Atlas](https://three.ws/avatar-engines): A curated, factual atlas of the open-source and commercial engines that build high-quality and photoreal 3D human avatars — Gaussian-splat heads, single-photo humans, text→avatar generators, and the rigs three.ws already animates. Technique, license, compute, and integration status for each.- [Splat Viewer — Photoreal Gaussian Avatars](https://three.ws/splat): Render Gaussian-splat and radiance-field avatars in the browser — the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.- [Scene Capture — Video to 3D Point Cloud](https://three.ws/capture): Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.+- [Motion Swap — Replace Yourself in Video with Your Avatar](https://three.ws/motion-swap): Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.- [Forge · NIM — Self-Hosted Image to 3D](https://three.ws/forge-nim): Drive a self-hosted TRELLIS NIM (nvcr.io/nim/microsoft/trellis) directly: drop a photo, hit /v1/infer, and get the textured GLB back synchronously as base64 — rendered live and downloadable.- [Text → 3D — Nemotron → FLUX → TRELLIS](https://three.ws/forge-spark): Describe an object and watch it become a textured 3D mesh: Nemotron sharpens the prompt, FLUX paints a clean reference, and TRELLIS reconstructs the model — served on NVIDIA NIM, quiet and always on.- [Studio — Object + Avatar from text](https://three.ws/forge-studio): One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex b9c44e338..0d9ce3473 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -58,7 +58,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 510 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 511 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -70,7 +70,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 510 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 511 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -329,7 +329,7 @@<section class="sm-section" id="build"><header>- <h2>Build<span class="sm-count" data-count>52</span></h2>+ <h2>Build<span class="sm-count" data-count>53</span></h2><p class="sm-section-desc">Create and customize an agent.</p></header><ul class="sm-list">@@ -459,6 +459,13 @@<span class="sm-desc">Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.</span></a></li>+ <li>+ <a href="/motion-swap">+ <span class="sm-title">Motion Swap — Replace Yourself in Video with Your Avatar</span>+ <span class="sm-path">/motion-swap</span>+ <span class="sm-desc">Upload a video of yourself and get it back with your 3D avatar performing your motion instead of you. Server-side pose tracking and person masking, browser-side compositing and export — stay off camera without staying off video.</span>+ </a>+ </li><li><a href="/forge-nim"><span class="sm-title">Forge · NIM — Self-Hosted Image to 3D</span>diff --git a/src/motion-swap.js b/src/motion-swap.jsnew file mode 100644index 000000000..599078f70--- /dev/null+++ b/src/motion-swap.js@@ -0,0 +1,526 @@+// /motion-swap — replace yourself in a video with your 3D avatar.+//+// Flow: upload a video → /api/motion-swap presigns storage and runs the+// video2motion worker (MediaPipe pose + person segmentation) → the job returns+// four artifacts: an AnimationClip JSON of the subject's motion on the+// canonical skeleton, a normalized video, a grayscale person-mask video, and+// per-frame screen anchors. This module composites them live in one WebGL+// scene: the video on a fullscreen quad (with the subject pixelated out under+// the mask), the chosen avatar retargeted onto the motion and pinned to the+// subject's on-screen anchor each frame, and a MediaRecorder export of the+// canvas + original audio to a downloadable .webm.++const STOCK_AVATARS = [+ { id: 'default', name: 'Standard', url: '/avatars/default.glb' },+ { id: 'michelle', name: 'Michelle', url: '/avatars/michelle.glb' },+ { id: 'mannequin', name: 'Mannequin', url: '/avatars/mannequin.glb' },+ { id: 'realistic-female', name: 'Realistic', url: '/avatars/realistic-female.glb' },+];++const POLL_MS = 3000;+const MAX_UPLOAD_BYTES = 256 * 1024 * 1024;++// Fraction of a standing figure's height at which the hip line sits; used to+// convert the anchor (hip centre) into a feet-on-ground placement.+const HIP_HEIGHT_FRACTION = 0.53;++const $ = (id) => document.getElementById(id);++const state = {+ three: null, // { THREE, renderer, scene, camera, quad, mixer, ... }+ job: null,+ artifacts: null, // { clip_url, meta_url, video_url, mask_url }+ meta: null,+ clipJSON: null,+ avatar: null, // { root, group, height, hipsRestY }+ avatarUrl: STOCK_AVATARS[0].url,+ privacy: true,+ recorder: null,+ recordedChunks: [],+ raf: 0,+};++function setStatus(text, kind = 'info') {+ const el = $('ms-status');+ if (!el) return;+ el.textContent = text;+ el.dataset.kind = kind;+ el.hidden = !text;+}++function showStage(stage) {+ for (const s of ['empty', 'processing', 'ready']) {+ const el = $(`ms-stage-${s}`);+ if (el) el.hidden = s !== stage;+ }+}++// ---------------------------------------------------------------------------+// Upload + job lifecycle+// ---------------------------------------------------------------------------++async function uploadVideo(file) {+ if (file.size > MAX_UPLOAD_BYTES) {+ throw new Error('Video is over 256 MB. Trim it down (90 seconds is the processing cap anyway).');+ }+ const type = file.type || 'video/mp4';+ setStatus('Requesting upload slot…');+ const presign = await fetch('/api/motion-swap', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action: 'upload', content_type: type, size_bytes: file.size }),+ });+ const slot = await presign.json();+ if (!presign.ok) throw new Error(slot?.message || 'Upload is unavailable right now.');++ setStatus('Uploading video…');+ const put = await fetch(slot.upload_url, {+ method: slot.method || 'PUT',+ headers: slot.headers || { 'content-type': type },+ body: file,+ });+ if (!put.ok) throw new Error(`Upload failed (${put.status}). Try again.`);+ return slot.public_url;+}++async function submitJob(videoUrl) {+ setStatus('Starting capture…');+ const res = await fetch('/api/motion-swap', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ video_url: videoUrl }),+ });+ const data = await res.json();+ if (!res.ok) throw new Error(data?.message || 'Capture could not start.');+ return data;+}++async function pollJob(jobId, etaSeconds) {+ const started = Date.now();+ for (;;) {+ await new Promise((r) => setTimeout(r, POLL_MS));+ const res = await fetch(`/api/motion-swap?job=${encodeURIComponent(jobId)}`);+ const data = await res.json().catch(() => ({}));+ if (data.status === 'done' && data.clip_url) return data;+ if (data.status === 'failed') {+ throw new Error(data.error || 'Capture failed. Make sure one person is clearly visible.');+ }+ const elapsed = Math.round((Date.now() - started) / 1000);+ const pct = etaSeconds ? Math.min(95, Math.round((elapsed / etaSeconds) * 100)) : null;+ setStatus(+ pct !== null+ ? `Tracking motion… ${pct}% (about ${Math.max(1, etaSeconds - elapsed)}s left)`+ : `Tracking motion… ${elapsed}s`,+ );+ }+}++async function handleFile(file) {+ try {+ showStage('processing');+ const videoUrl = await uploadVideo(file);+ const job = await submitJob(videoUrl);+ state.job = job.job_id;+ const done = await pollJob(job.job_id, job.eta_seconds);+ state.artifacts = done;+ setStatus('Loading composite…');+ await loadComposite(done);+ showStage('ready');+ setStatus('');+ } catch (err) {+ showStage('empty');+ setStatus(err?.message || 'Something went wrong. Try another video.', 'error');+ }+}++// ---------------------------------------------------------------------------+// three.js composite+// ---------------------------------------------------------------------------++async function bootThree() {+ if (state.three) return state.three;+ const [THREE, { GLTFLoader }] = await Promise.all([+ import('three'),+ import('three/addons/loaders/GLTFLoader.js'),+ ]);+ const canvas = $('ms-canvas');+ const renderer = new THREE.WebGLRenderer({+ canvas,+ antialias: true,+ preserveDrawingBuffer: true,+ });+ renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));+ renderer.outputColorSpace = THREE.SRGBColorSpace;++ const scene = new THREE.Scene();+ const camera = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5, 0.1, 50);+ camera.position.z = 10;++ scene.add(new THREE.HemisphereLight(0xffffff, 0x444455, 2.2));+ const key = new THREE.DirectionalLight(0xffffff, 1.6);+ key.position.set(1.5, 3, 4);+ scene.add(key);++ state.three = { THREE, GLTFLoader, renderer, scene, camera, quad: null, mixer: null, action: null };+ return state.three;+}++function makeBackdrop(t, videoEl, maskEl) {+ const { THREE, scene } = t;+ const videoTex = new THREE.VideoTexture(videoEl);+ videoTex.colorSpace = THREE.SRGBColorSpace;+ const maskTex = new THREE.VideoTexture(maskEl);++ const material = new THREE.ShaderMaterial({+ uniforms: {+ tVideo: { value: videoTex },+ tMask: { value: maskTex },+ uPrivacy: { value: state.privacy ? 1.0 : 0.0 },+ uPixels: { value: 42.0 },+ },+ vertexShader: /* glsl */ `+ varying vec2 vUv;+ void main() {+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ }+ `,+ fragmentShader: /* glsl */ `+ uniform sampler2D tVideo;+ uniform sampler2D tMask;+ uniform float uPrivacy;+ uniform float uPixels;+ varying vec2 vUv;+ void main() {+ vec3 base = texture2D(tVideo, vUv).rgb;+ float m = texture2D(tMask, vUv).r;+ vec2 cell = floor(vUv * uPixels) / uPixels + 0.5 / uPixels;+ vec3 pix = texture2D(tVideo, cell).rgb;+ // Feathered mask edge so the pixelation doesn't halo hard.+ float k = smoothstep(0.35, 0.65, m) * uPrivacy;+ gl_FragColor = vec4(mix(base, pix, k), 1.0);+ }+ `,+ depthWrite: false,+ });++ if (t.quad) {+ t.quad.material.dispose();+ t.quad.material = material;+ } else {+ t.quad = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), material);+ t.quad.position.z = 0;+ t.quad.renderOrder = -1;+ scene.add(t.quad);+ }+ return t.quad;+}++function layout(t, meta) {+ const { renderer, camera } = t;+ const holder = $('ms-canvas-wrap');+ const aspect = meta.width / meta.height;+ const w = holder.clientWidth || 960;+ const h = Math.round(w / aspect);+ renderer.setSize(w, h, false);+ // World units: backdrop height 1, width = aspect.+ camera.left = -aspect / 2;+ camera.right = aspect / 2;+ camera.top = 0.5;+ camera.bottom = -0.5;+ camera.updateProjectionMatrix();+ t.quad.scale.set(aspect, 1, 1);+}++async function loadAvatar(t, url) {+ const { THREE, GLTFLoader, scene } = t;+ setStatus('Loading avatar…');+ const [buf, canonMod, retargetMod] = await Promise.all([+ fetch(url).then((r) => {+ if (!r.ok) throw new Error(`Avatar fetch failed (${r.status}).`);+ return r.arrayBuffer();+ }),+ import('./glb-canonicalize.js'),+ import('./animation-retarget.js'),+ ]);+ let glb = buf;+ try {+ const canon = canonMod.canonicalizeGLBBones(buf);+ if (canon?.buffer) glb = canon.buffer;+ else if (canon instanceof ArrayBuffer) glb = canon;+ } catch {+ // Not canonicalizable (already canonical or unusual container) — retarget+ // still resolves bone names through the same mapping at clip-bind time.+ }+ const gltf = await new GLTFLoader().parseAsync(glb, '');+ const root = gltf.scene;++ if (state.avatar?.group) scene.remove(state.avatar.group);+ if (t.mixer) {+ t.mixer.stopAllAction();+ t.mixer = null;+ t.action = null;+ }++ const group = new THREE.Group();+ group.add(root);+ scene.add(group);+ root.updateMatrixWorld(true);++ const bbox = new THREE.Box3().setFromObject(root);+ const height = Math.max(0.01, bbox.max.y - bbox.min.y);+ let hipsRestY = bbox.min.y + height * HIP_HEIGHT_FRACTION;+ root.traverse((n) => {+ if (n.name === 'Hips') {+ const p = new THREE.Vector3();+ n.getWorldPosition(p);+ hipsRestY = p.y;+ }+ });++ state.avatar = { root, group, height, hipsRestY, baseMinY: bbox.min.y, retargetMod };++ if (state.clipJSON) bindClip(t);+ setStatus('');+}++function bindClip(t) {+ const { retargetMod } = state.avatar;+ const clip = retargetMod.parseClipJSON(state.clipJSON, 'motion-swap');+ const result = retargetMod.retargetClipToObject(clip, state.avatar.root, { minCoverage: 0.3 });+ const bound = result?.clip || result; // retarget result carries the clip+ t.mixer = new t.THREE.AnimationMixer(state.avatar.root);+ t.action = t.mixer.clipAction(bound);+ t.action.play();+ t.mixer.setTime(0);+}++function anchorAt(timeSec) {+ const meta = state.meta;+ if (!meta?.anchors?.length) return null;+ const idx = Math.max(0, Math.min(meta.anchors.length - 1, Math.floor(timeSec * meta.fps)));+ return meta.anchors[idx];+}++function placeAvatar(t, timeSec) {+ const a = anchorAt(timeSec);+ const av = state.avatar;+ if (!a || !av) return;+ const aspect = state.meta.width / state.meta.height;+ av.group.visible = a.v === 1;+ if (!av.group.visible) return;++ // Anchor: hip centre in normalized image coords (y down) + subject height+ // as a fraction of frame height. Backdrop is height-1 world units.+ const scale = Math.max(0.02, a.h / av.height);+ const hipWorldX = (a.x - 0.5) * aspect;+ const hipWorldY = 0.5 - a.y;+ av.group.scale.setScalar(scale);+ av.group.position.set(hipWorldX, hipWorldY - av.hipsRestY * scale, 1.0);+}++async function loadComposite(artifacts) {+ const t = await bootThree();+ const videoEl = $('ms-video');+ const maskEl = $('ms-mask');+ videoEl.crossOrigin = 'anonymous';+ maskEl.crossOrigin = 'anonymous';+ videoEl.src = artifacts.video_url;+ maskEl.src = artifacts.mask_url;+ maskEl.muted = true;++ const [meta, clipJSON] = await Promise.all([+ fetch(artifacts.meta_url).then((r) => r.json()),+ fetch(artifacts.clip_url).then((r) => r.json()),+ ]);+ state.meta = meta;+ state.clipJSON = clipJSON;++ makeBackdrop(t, videoEl, maskEl);+ layout(t, meta);+ await loadAvatar(t, state.avatarUrl);++ await Promise.all([+ new Promise((r) => (videoEl.readyState >= 2 ? r() : videoEl.addEventListener('loadeddata', r, { once: true }))),+ new Promise((r) => (maskEl.readyState >= 2 ? r() : maskEl.addEventListener('loadeddata', r, { once: true }))),+ ]);++ // Keep the mask clock glued to the main video.+ videoEl.addEventListener('play', () => maskEl.play().catch(() => {}));+ videoEl.addEventListener('pause', () => maskEl.pause());+ videoEl.addEventListener('seeked', () => {+ maskEl.currentTime = videoEl.currentTime;+ });++ cancelAnimationFrame(state.raf);+ const tick = () => {+ state.raf = requestAnimationFrame(tick);+ const time = videoEl.currentTime || 0;+ if (Math.abs(maskEl.currentTime - time) > 0.12 && !maskEl.seeking) {+ maskEl.currentTime = time;+ }+ if (t.mixer) t.mixer.setTime(Math.min(time, state.clipDuration ?? time));+ placeAvatar(t, time);+ t.renderer.render(t.scene, t.camera);+ };+ state.clipDuration = clipJSON.duration;+ tick();++ videoEl.play().catch(() => {+ // Autoplay refused — the play button drives it.+ });+}++// ---------------------------------------------------------------------------+// Export+// ---------------------------------------------------------------------------++function startExport() {+ const t = state.three;+ const videoEl = $('ms-video');+ if (!t || !videoEl?.src) return;+ const btn = $('ms-export');+ btn.disabled = true;+ btn.textContent = 'Recording…';++ const stream = t.renderer.domElement.captureStream(30);+ // Mix the source audio in when the browser exposes it.+ try {+ const audio = videoEl.captureStream?.() || videoEl.mozCaptureStream?.();+ for (const track of audio?.getAudioTracks?.() || []) stream.addTrack(track);+ } catch {+ // Cross-origin audio unavailable — export video-only.+ }++ const mime = MediaRecorder.isTypeSupported('video/webm;codecs=vp9,opus')+ ? 'video/webm;codecs=vp9,opus'+ : 'video/webm';+ state.recordedChunks = [];+ state.recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 8_000_000 });+ state.recorder.ondataavailable = (e) => {+ if (e.data.size) state.recordedChunks.push(e.data);+ };+ state.recorder.onstop = () => {+ const blob = new Blob(state.recordedChunks, { type: 'video/webm' });+ const a = document.createElement('a');+ a.href = URL.createObjectURL(blob);+ a.download = 'motion-swap.webm';+ a.click();+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);+ btn.disabled = false;+ btn.textContent = 'Export video';+ };++ videoEl.onended = () => {+ if (state.recorder?.state === 'recording') state.recorder.stop();+ videoEl.onended = null;+ };+ videoEl.currentTime = 0;+ state.recorder.start(250);+ videoEl.play();+}++// ---------------------------------------------------------------------------+// UI wiring+// ---------------------------------------------------------------------------++function wireUI() {+ const drop = $('ms-drop');+ const input = $('ms-file');++ drop.addEventListener('click', () => input.click());+ drop.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ input.click();+ }+ });+ input.addEventListener('change', () => {+ if (input.files?.[0]) handleFile(input.files[0]);+ input.value = '';+ });+ for (const evt of ['dragover', 'dragenter']) {+ drop.addEventListener(evt, (e) => {+ e.preventDefault();+ drop.classList.add('is-drag');+ });+ }+ for (const evt of ['dragleave', 'drop']) {+ drop.addEventListener(evt, (e) => {+ e.preventDefault();+ drop.classList.remove('is-drag');+ });+ }+ drop.addEventListener('drop', (e) => {+ const file = e.dataTransfer?.files?.[0];+ if (file && file.type.startsWith('video/')) handleFile(file);+ else if (file) setStatus('That is not a video file.', 'error');+ });++ // Avatar picker.+ const picker = $('ms-avatars');+ for (const av of STOCK_AVATARS) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'ms-avatar-chip';+ b.textContent = av.name;+ b.dataset.url = av.url;+ if (av.url === state.avatarUrl) b.setAttribute('aria-pressed', 'true');+ b.addEventListener('click', async () => {+ picker.querySelectorAll('[aria-pressed]').forEach((x) => x.removeAttribute('aria-pressed'));+ b.setAttribute('aria-pressed', 'true');+ state.avatarUrl = av.url;+ if (state.three && state.artifacts) {+ try {+ await loadAvatar(state.three, av.url);+ } catch (err) {+ setStatus(err?.message || 'Avatar failed to load.', 'error');+ }+ }+ });+ picker.appendChild(b);+ }+ $('ms-avatar-url-go').addEventListener('click', async () => {+ const url = $('ms-avatar-url').value.trim();+ if (!url) return;+ picker.querySelectorAll('[aria-pressed]').forEach((x) => x.removeAttribute('aria-pressed'));+ state.avatarUrl = url;+ if (state.three && state.artifacts) {+ try {+ await loadAvatar(state.three, url);+ } catch (err) {+ setStatus(err?.message || 'Avatar failed to load. Is it a rigged humanoid GLB?', 'error');+ }+ }+ });++ $('ms-privacy').addEventListener('change', (e) => {+ state.privacy = e.target.checked;+ const quad = state.three?.quad;+ if (quad) quad.material.uniforms.uPrivacy.value = state.privacy ? 1.0 : 0.0;+ });++ $('ms-play').addEventListener('click', () => {+ const v = $('ms-video');+ if (v.paused) v.play();+ else v.pause();+ });+ $('ms-restart').addEventListener('click', () => {+ const v = $('ms-video');+ v.currentTime = 0;+ v.play();+ });+ $('ms-export').addEventListener('click', startExport);+ $('ms-new').addEventListener('click', () => {+ $('ms-video').pause();+ showStage('empty');+ setStatus('');+ });++ window.addEventListener('resize', () => {+ if (state.three && state.meta) layout(state.three, state.meta);+ });+}++wireUI();+showStage('empty');diff --git a/vercel.json b/vercel.jsonindex 01fa34cc0..78208b663 100644--- a/vercel.json+++ b/vercel.json@@ -2226,6 +2226,14 @@"src": "/capture/","dest": "/capture.html"},+ {+ "src": "/motion-swap",+ "dest": "/motion-swap.html"+ },+ {+ "src": "/motion-swap/",+ "dest": "/motion-swap.html"+ },{"src": "/integrations","dest": "/integrations.html"diff --git a/vite.config.js b/vite.config.jsindex 9b678f12c..7bec46b5b 100644--- a/vite.config.js+++ b/vite.config.js@@ -571,6 +571,7 @@ const appConfig = {'avatar-engines': resolve(__dirname, 'pages/avatar-engines.html'),splat: resolve(__dirname, 'pages/splat.html'),capture: resolve(__dirname, 'pages/capture.html'),+ 'motion-swap': resolve(__dirname, 'pages/motion-swap.html'),club: resolve(__dirname, 'pages/club.html'),theater: resolve(__dirname, 'pages/theater.html'),stage: resolve(__dirname, 'pages/stage.html'),@@ -1245,6 +1246,8 @@ support: resolve(__dirname, 'pages/support.html'),'/splat/': resolve(root, 'pages/splat.html'),'/capture': resolve(root, 'pages/capture.html'),'/capture/': resolve(root, 'pages/capture.html'),+ '/motion-swap': resolve(root, 'pages/motion-swap.html'),+ '/motion-swap/': resolve(root, 'pages/motion-swap.html'),'/brain': resolve(root, 'pages/brain.html'),'/brain/': resolve(root, 'pages/brain.html'),'/lipsync': resolve(root, 'public/demos/lipsync-tts.html'),diff --git a/workers/model-video2motion/Dockerfile b/workers/model-video2motion/Dockerfilenew file mode 100644index 000000000..228a18ac5--- /dev/null+++ b/workers/model-video2motion/Dockerfile@@ -0,0 +1,28 @@+FROM python:3.11-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ ffmpeg libgl1 libglib2.0-0 curl \+ && rm -rf /var/lib/apt/lists/*++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++# MediaPipe model bundles (Apache-2.0), baked into the image so the service+# has no weights-bucket dependency and cold-starts ready.+RUN mkdir -p /models \+ && curl -fsSL -o /models/pose_landmarker_heavy.task \+ https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_heavy/float16/latest/pose_landmarker_heavy.task \+ && curl -fsSL -o /models/selfie_segmenter.task \+ https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.task++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY pose_solver.py /app/pose_solver.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/model-video2motion/README.md b/workers/model-video2motion/README.mdnew file mode 100644index 000000000..d30ccaa77--- /dev/null+++ b/workers/model-video2motion/README.md@@ -0,0 +1,73 @@+# model-video2motion++Video of a person → **retargetable animation clip + body-swap plates**. A+CPU-only FastAPI worker (no GPU, deploys like the segment/rembg lanes) that+powers the **Motion Swap** page (`/motion-swap`): upload a video of yourself,+get it back with your avatar performing your motion.++## What it produces++For one input video, four artifacts land in GCS under `motion-swap/<task_id>/`:++| Artifact | What it is |+|---|---|+| `clip.json` | three.js `AnimationClip.toJSON()` on the canonical Wolf3D skeleton — the SAME document shape the animation library and `model-text2motion` serve, so it retargets onto any rigged avatar via `src/animation-retarget.js` |+| `video.mp4` | the normalized source (≤720p-class, capped fps/duration, audio kept) |+| `mask.mp4` | grayscale per-frame person mask aligned with `video.mp4` |+| `meta.json` | fps, frame count, dimensions, and per-frame screen `anchors` (hip position + subject height + visibility) for pinning the avatar over the subject |++The browser compositor does the rest: original footage underneath, subject+pixelated via the mask, avatar retargeted onto the clip and pinned per frame.++## Models (both Apache-2.0, baked into the image)++- **MediaPipe PoseLandmarker (heavy)** — 33 world landmarks per frame, VIDEO+ mode with tracking.+- **MediaPipe ImageSegmenter (selfie)** — per-frame person confidence mask.++The landmark → joint-rotation solve is ours: `pose_solver.py` builds global+orientations for pelvis/chest/head from body lines, solves each limb with its+bend-plane to fix twist, converts to locals against the parent chain, and emits+hemisphere-continuous quaternion tracks. Pure NumPy, unit-tested from synthetic+poses (`test_pose_solver.py`) without mediapipe installed.++## API++```+POST /infer { video_url, fps?=24, max_seconds?, job_id? } → 202 { task_id }+GET /tasks/:id → { status, result_url?, meta_url?, video_url?, mask_url?, frames?, fps?, error? }+GET /health → { ok, models_loaded }+```++Bearer auth on `/infer` and `/tasks/:id` (`Authorization: Bearer $API_KEY`).+Input is fetched through the SSRF-hardened `worker_security.fetch_remote_bytes`+(https-only, private/loopback/metadata IPs rejected), capped at 256 MiB, and+processing is capped at `MAX_SECONDS` (default 90).++The platform reaches this worker through the GCP provider's `video2motion`+mode (`GCP_VIDEO2MOTION_URL`), exposed as `POST /api/motion-swap`+(+ `GET /api/motion-swap?job=<id>`).++## Deploy++```bash+gcloud builds submit --config workers/model-video2motion/cloudbuild.yaml \+ --region us-central1 --project aerial-vehicle-466722-p5 \+ --substitutions=SHORT_SHA=manual$(date +%s)+```++Then point the API at it:++```bash+gcloud run services update three-ws-api --region us-central1 \+ --update-env-vars GCP_VIDEO2MOTION_URL=<service url>+```++Shares the `avatar-reconstruction-key` bearer secret (`GCP_RECONSTRUCTION_KEY`+on the API side) with the other reconstruction-family workers.++## Tests++```bash+cd workers/model-video2motion && python -m pytest test_pose_solver.py -q+```diff --git a/workers/model-video2motion/cloudbuild.yaml b/workers/model-video2motion/cloudbuild.yamlnew file mode 100644index 000000000..289e7ddb2--- /dev/null+++ b/workers/model-video2motion/cloudbuild.yaml@@ -0,0 +1,64 @@+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-video2motion+ _REPO: model-video2motion+ _GCS_BUCKET: three-ws-avatar-reconstructions+ # Scale-to-zero: motion capture is a batch submit-and-poll job, not an+ # interactive edit loop — a cold start disappears inside the processing time.+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "5"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/model-video2motion+ 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+ - --cpu=8+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=900+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MAX_CONCURRENT=2,MAX_SECONDS=90+ - --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_8+ logging: CLOUD_LOGGING_ONLY++timeout: 3600sdiff --git a/workers/model-video2motion/main.py b/workers/model-video2motion/main.pynew file mode 100644index 000000000..b48796458--- /dev/null+++ b/workers/model-video2motion/main.py@@ -0,0 +1,363 @@+"""Video-to-motion service — a video of a person → retargetable animation clip+plus the compositing plates for an avatar body swap.++Given an https video URL, the worker:+ 1. normalizes the video with ffmpeg (≤720p, capped fps + duration, H.264,+ original audio preserved),+ 2. runs MediaPipe PoseLandmarker (VIDEO mode, heavy model, Apache-2.0) over+ every frame → 33 world landmarks + image landmarks + visibility,+ 3. solves the landmarks into local joint rotations on the canonical Wolf3D+ skeleton (pose_solver.py) and emits a three.js AnimationClip JSON — the+ SAME document shape the animation library and text2motion lane serve, so+ the platform retargets it onto any rigged avatar with the existing engine+ (src/animation-retarget.js),+ 4. runs MediaPipe ImageSegmenter (selfie model, Apache-2.0) per frame and+ encodes a grayscale person-mask video aligned with the normalized video,+ 5. uploads clip + mask + normalized video + per-frame screen anchors to GCS.++The browser compositor (/motion-swap) then plays the normalized video as the+backdrop, drives the user's avatar with the clip, pins it to the subject via+the anchors, and hides the subject under the mask. All model inference is+CPU-friendly — this worker deploys like the segment/rembg lanes, no GPU.++API contract (identical shape to the other model-* workers):+ POST /infer { video_url: str, fps?: int=24, max_seconds?: float, job_id?: str }+ → 202 { task_id, status: "queued" }+ GET /tasks/:id → { task_id, status, result_url?, meta_url?, video_url?,+ mask_url?, frames?, fps?, error? }+ GET /health → { ok, models_loaded }++Environment:+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)+ MAX_CONCURRENT — default 2+ MAX_SECONDS — hard cap on processed duration (default 90)+ MODELS_DIR — directory with the .task model bundles (default /models)+"""++from __future__ import annotations++import asyncio+import json+import logging+import os+import shutil+import subprocess+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import numpy as np+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException+from google.cloud import storage+from pydantic import BaseModel, Field++from pose_solver import image_anchors, landmarks_to_clip+from worker_security import fetch_remote_bytes, require_api_key, safe_error++logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")+log = logging.getLogger("video2motion")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))+MAX_SECONDS = float(os.environ.get("MAX_SECONDS", "90"))+MODELS_DIR = os.environ.get("MODELS_DIR", "/models")+MAX_VIDEO_BYTES = 256 * 1024 * 1024+DEFAULT_FPS = 24+MAX_EDGE = 1280 # normalized video long-edge cap (720p-class)++_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+_models_loaded = False+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem, _models_loaded+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ # Fail fast if the model bundles are missing from the image.+ for f in ("pose_landmarker_heavy.task", "selfie_segmenter.task"):+ path = os.path.join(MODELS_DIR, f)+ if not os.path.exists(path):+ raise RuntimeError(f"model bundle missing: {path}")+ _models_loaded = True+ log.info("video2motion ready — max_concurrent=%d max_seconds=%.0f", MAX_CONCURRENT, MAX_SECONDS)+ yield+++app = FastAPI(title="model-video2motion", 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+++class InferRequest(BaseModel):+ video_url: str = Field(..., min_length=12, max_length=2048)+ fps: int = Field(default=DEFAULT_FPS, ge=8, le=30)+ max_seconds: Optional[float] = Field(default=None, gt=0)+ job_id: Optional[str] = None++[email protected]("/infer", status_code=202)+async def infer(body: InferRequest, background_tasks: BackgroundTasks, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task_id = body.job_id or str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "blazepose-heavy"}+ seconds = min(body.max_seconds or MAX_SECONDS, MAX_SECONDS)+ background_tasks.add_task(_run, task_id, body.video_url, body.fps, seconds)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {"ok": True, "models_loaded": _models_loaded}+++async def _run(task_id: str, video_url: str, fps: int, seconds: float) -> None:+ assert _sem is not None and _bucket is not None+ async with _sem:+ _tasks[task_id]["status"] = "running"+ started = time.time()+ loop = asyncio.get_event_loop()+ try:+ result = await loop.run_in_executor(None, _process, task_id, video_url, fps, seconds)+ result["status"] = "done"+ result["elapsed_ms"] = int((time.time() - started) * 1000)+ _tasks[task_id].update(result)+ log.info(+ "task %s done — %s frames in %dms",+ task_id,+ result.get("frames"),+ result["elapsed_ms"],+ )+ except Exception as exc:+ msg = safe_error(exc, context=f"video2motion task {task_id}")+ _tasks[task_id].update({"status": "failed", "error": msg})+ log.exception("task %s failed", task_id)+++def _ffmpeg(args: list[str]) -> None:+ proc = subprocess.run(+ ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *args],+ capture_output=True,+ text=True,+ timeout=600,+ )+ if proc.returncode != 0:+ raise RuntimeError(f"ffmpeg failed: {proc.stderr[-400:]}")+++def _process(task_id: str, video_url: str, fps: int, seconds: float) -> dict:+ workdir = tempfile.mkdtemp(prefix="v2m-")+ try:+ raw_path = os.path.join(workdir, "raw")+ data = fetch_remote_bytes(video_url, timeout=180, max_bytes=MAX_VIDEO_BYTES)+ with open(raw_path, "wb") as f:+ f.write(data)++ # Normalize: cap duration, fps and resolution; keep audio; strip metadata.+ norm_path = os.path.join(workdir, "video.mp4")+ _ffmpeg(+ [+ "-i", raw_path,+ "-t", f"{seconds:.2f}",+ "-vf",+ f"fps={fps},scale='if(gt(iw,ih),min(iw,{MAX_EDGE}),-2)':'if(gt(iw,ih),-2,min(ih,{MAX_EDGE}))'",+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "22",+ "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "128k",+ "-map_metadata", "-1",+ "-movflags", "+faststart",+ norm_path,+ ]+ )++ world, image, vis, masks, width, height = _analyze(norm_path, fps)+ n_frames = world.shape[0]+ if n_frames < 2:+ raise RuntimeError("no person detected in the video")++ clip = landmarks_to_clip(world, fps=fps, name=f"capture-{task_id[:8]}")+ anchors = image_anchors(image, vis)++ mask_path = os.path.join(workdir, "mask.mp4")+ _encode_mask_video(masks, fps, mask_path, workdir)++ meta = {+ "version": 1,+ "fps": fps,+ "frames": n_frames,+ "width": width,+ "height": height,+ "anchors": anchors,+ }++ prefix = f"motion-swap/{task_id}"+ urls = {}+ uploads = [+ ("clip.json", json.dumps(clip).encode("utf-8"), "application/json"),+ ("meta.json", json.dumps(meta).encode("utf-8"), "application/json"),+ ]+ for name, payload, ctype in uploads:+ blob = _bucket.blob(f"{prefix}/{name}")+ blob.upload_from_string(payload, content_type=ctype)+ urls[name] = f"https://storage.googleapis.com/{GCS_BUCKET}/{prefix}/{name}"+ for name, path, ctype in (("video.mp4", norm_path, "video/mp4"), ("mask.mp4", mask_path, "video/mp4")):+ blob = _bucket.blob(f"{prefix}/{name}")+ blob.upload_from_filename(path, content_type=ctype)+ urls[name] = f"https://storage.googleapis.com/{GCS_BUCKET}/{prefix}/{name}"++ return {+ "result_url": urls["clip.json"],+ "meta_url": urls["meta.json"],+ "video_url": urls["video.mp4"],+ "mask_url": urls["mask.mp4"],+ "frames": int(n_frames),+ "fps": int(fps),+ }+ finally:+ shutil.rmtree(workdir, ignore_errors=True)+++def _analyze(video_path: str, fps: int):+ """Run pose + segmentation over every frame of the normalized video.++ Returns (world (T,33,3), image (T,33,2), visibility (T,33), masks list of+ uint8 HxW arrays, width, height). Frames where no person is detected reuse+ the previous frame's landmarks and get visibility 0 (the anchor marks them+ hidden; the solver stays continuous instead of snapping to rest).+ """+ import cv2+ import mediapipe as mp+ from mediapipe.tasks import python as mp_python+ from mediapipe.tasks.python import vision++ pose_opts = vision.PoseLandmarkerOptions(+ base_options=mp_python.BaseOptions(+ model_asset_path=os.path.join(MODELS_DIR, "pose_landmarker_heavy.task")+ ),+ running_mode=vision.RunningMode.VIDEO,+ num_poses=1,+ min_pose_detection_confidence=0.4,+ min_tracking_confidence=0.4,+ )+ seg_opts = vision.ImageSegmenterOptions(+ base_options=mp_python.BaseOptions(+ model_asset_path=os.path.join(MODELS_DIR, "selfie_segmenter.task")+ ),+ running_mode=vision.RunningMode.VIDEO,+ output_confidence_masks=True,+ )++ cap = cv2.VideoCapture(video_path)+ if not cap.isOpened():+ raise RuntimeError("could not open normalized video")+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))++ world_frames: list[np.ndarray] = []+ image_frames: list[np.ndarray] = []+ vis_frames: list[np.ndarray] = []+ masks: list[np.ndarray] = []+ prev_world: Optional[np.ndarray] = None+ prev_image: Optional[np.ndarray] = None++ with vision.PoseLandmarker.create_from_options(pose_opts) as pose, vision.ImageSegmenter.create_from_options(+ seg_opts+ ) as segmenter:+ frame_idx = 0+ while True:+ ok, frame_bgr = cap.read()+ if not ok:+ break+ ts_ms = int(frame_idx * 1000.0 / fps)+ rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)+ mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)++ pose_result = pose.detect_for_video(mp_image, ts_ms)+ if pose_result.pose_world_landmarks:+ wl = pose_result.pose_world_landmarks[0]+ il = pose_result.pose_landmarks[0]+ world = np.array([[lm.x, lm.y, lm.z] for lm in wl])+ image = np.array([[lm.x, lm.y] for lm in il])+ vis = np.array([lm.visibility for lm in il])+ prev_world, prev_image = world, image+ elif prev_world is not None:+ world, image, vis = prev_world, prev_image, np.zeros(33)+ else:+ frame_idx += 1+ masks.append(np.zeros((height, width), dtype=np.uint8))+ continue+ world_frames.append(world)+ image_frames.append(image)+ vis_frames.append(vis)++ seg_result = segmenter.segment_for_video(mp_image, ts_ms)+ conf = seg_result.confidence_masks[0].numpy_view()+ masks.append((np.clip(conf, 0.0, 1.0) * 255).astype(np.uint8))+ frame_idx += 1+ cap.release()++ if not world_frames:+ return np.zeros((0, 33, 3)), np.zeros((0, 33, 2)), np.zeros((0, 33)), masks, width, height++ # Leading undetected frames produced masks but no landmarks; pad the+ # landmark arrays at the front with the first detection so lengths match.+ pad = len(masks) - len(world_frames)+ world = np.stack(world_frames)+ image = np.stack(image_frames)+ vis = np.stack(vis_frames)+ if pad > 0:+ world = np.concatenate([np.repeat(world[:1], pad, axis=0), world])+ image = np.concatenate([np.repeat(image[:1], pad, axis=0), image])+ vis = np.concatenate([np.zeros((pad, 33)), vis])+ return world, image, vis, masks, width, height+++def _encode_mask_video(masks: list[np.ndarray], fps: int, out_path: str, workdir: str) -> None:+ """Encode uint8 person masks as a grayscale H.264 video via an ffmpeg pipe."""+ if not masks:+ raise RuntimeError("no mask frames to encode")+ h, w = masks[0].shape+ proc = subprocess.Popen(+ [+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",+ "-f", "rawvideo", "-pix_fmt", "gray", "-s", f"{w}x{h}", "-r", str(fps),+ "-i", "-",+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "24",+ "-pix_fmt", "yuv420p",+ "-movflags", "+faststart",+ out_path,+ ],+ stdin=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ try:+ for m in masks:+ proc.stdin.write(m.tobytes())+ proc.stdin.close()+ proc.wait(timeout=600)+ except Exception:+ proc.kill()+ raise+ if proc.returncode != 0:+ err = proc.stderr.read().decode("utf-8", "replace")[-400:] if proc.stderr else ""+ raise RuntimeError(f"mask encode failed: {err}")diff --git a/workers/model-video2motion/pose_solver.py b/workers/model-video2motion/pose_solver.pynew file mode 100644index 000000000..4240ad6ca--- /dev/null+++ b/workers/model-video2motion/pose_solver.py@@ -0,0 +1,472 @@+"""Solve BlazePose world landmarks into canonical-skeleton joint rotations.++MediaPipe's PoseLandmarker (VIDEO mode) emits, per frame, 33 world landmarks in+metres with the origin at the hip centre (x right, y DOWN, z toward the camera+in image convention). This module converts a (T, 33, 3) landmark sequence into+per-frame LOCAL joint rotations on the canonical Wolf3D humanoid and emits the+exact ``THREE.AnimationClip.toJSON()`` document the rest of the platform+consumes (identical track shape to workers/model-text2motion/smpl_to_clip.py),+so a motion captured from video retargets onto any rigged avatar with the SAME+engine (src/animation-retarget.js) as a curated preset.++Method: per frame,+ 1. flip landmarks into the rig's y-up right-handed space,+ 2. build a global orientation for the pelvis and the chest from the hip and+ shoulder lines plus the spine direction,+ 3. for each limb segment, build a global orientation that carries its rest+ direction onto the observed parent→child landmark direction, using the+ limb's bend plane (upper/lower segment cross product) to fix the twist+ about the bone axis where the geometry defines it,+ 4. convert globals to locals against the parent chain,+ 5. smooth landmarks with a fps-aware exponential filter and keep quaternion+ hemisphere continuity across frames.++In the rig's rest space the character stands in a T-pose facing +Z: spine +Y,+legs -Y, left arm +X, right arm -X, feet +Z. Zero local rotation everywhere+reproduces the rest pose, matching the SMPL-rest convention the text2motion+lane already emits (rest-offset calibration happens downstream, same as there).++Pure NumPy — no mediapipe, no GPU — so the solve is unit-tested+deterministically from synthetic landmark sequences without the model.+"""++from __future__ import annotations++import hashlib+from typing import Optional++import numpy as np++# BlazePose 33-landmark indices (subset used by the solver).+NOSE = 0+LEFT_EAR, RIGHT_EAR = 7, 8+LEFT_SHOULDER, RIGHT_SHOULDER = 11, 12+LEFT_ELBOW, RIGHT_ELBOW = 13, 14+LEFT_WRIST, RIGHT_WRIST = 15, 16+LEFT_PINKY, RIGHT_PINKY = 17, 18+LEFT_INDEX, RIGHT_INDEX = 19, 20+LEFT_HIP, RIGHT_HIP = 23, 24+LEFT_KNEE, RIGHT_KNEE = 25, 26+LEFT_ANKLE, RIGHT_ANKLE = 27, 28+LEFT_HEEL, RIGHT_HEEL = 29, 30+LEFT_FOOT_INDEX, RIGHT_FOOT_INDEX = 31, 32++# three.js AnimationBlendMode.NormalAnimationBlendMode+_NORMAL_BLEND_MODE = 2500++_IDENTITY = np.array([0.0, 0.0, 0.0, 1.0])+++def _normalize(v: np.ndarray) -> np.ndarray:+ n = np.linalg.norm(v)+ if n < 1e-8:+ return np.zeros_like(v)+ return v / n+++def _quat_from_matrix(m: np.ndarray) -> np.ndarray:+ """3x3 rotation matrix → [x,y,z,w] quaternion (Shepperd's method)."""+ t = np.trace(m)+ if t > 0.0:+ s = np.sqrt(t + 1.0) * 2.0+ return np.array(+ [(m[2, 1] - m[1, 2]) / s, (m[0, 2] - m[2, 0]) / s, (m[1, 0] - m[0, 1]) / s, 0.25 * s]+ )+ i = int(np.argmax(np.diag(m)))+ if i == 0:+ s = np.sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]) * 2.0+ return np.array(+ [0.25 * s, (m[0, 1] + m[1, 0]) / s, (m[0, 2] + m[2, 0]) / s, (m[2, 1] - m[1, 2]) / s]+ )+ if i == 1:+ s = np.sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]) * 2.0+ return np.array(+ [(m[0, 1] + m[1, 0]) / s, 0.25 * s, (m[1, 2] + m[2, 1]) / s, (m[0, 2] - m[2, 0]) / s]+ )+ s = np.sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]) * 2.0+ return np.array(+ [(m[0, 2] + m[2, 0]) / s, (m[1, 2] + m[2, 1]) / s, 0.25 * s, (m[1, 0] - m[0, 1]) / s]+ )+++def _quat_multiply(a: np.ndarray, b: np.ndarray) -> np.ndarray:+ ax, ay, az, aw = a+ bx, by, bz, bw = b+ return np.array(+ [+ aw * bx + ax * bw + ay * bz - az * by,+ aw * by - ax * bz + ay * bw + az * bx,+ aw * bz + ax * by - ay * bx + az * bw,+ aw * bw - ax * bx - ay * by - az * bz,+ ]+ )+++def _quat_conjugate(q: np.ndarray) -> np.ndarray:+ return np.array([-q[0], -q[1], -q[2], q[3]])+++def _quat_normalize(q: np.ndarray) -> np.ndarray:+ n = np.linalg.norm(q)+ if n < 1e-8:+ return _IDENTITY.copy()+ return q / n+++def _quat_slerp(a: np.ndarray, b: np.ndarray, t: float) -> np.ndarray:+ dot = float(np.dot(a, b))+ if dot < 0.0:+ b = -b+ dot = -dot+ if dot > 0.9995:+ return _quat_normalize(a + t * (b - a))+ theta = np.arccos(np.clip(dot, -1.0, 1.0))+ s = np.sin(theta)+ return _quat_normalize((np.sin((1.0 - t) * theta) / s) * a + (np.sin(t * theta) / s) * b)+++def _shortest_arc(frm: np.ndarray, to: np.ndarray) -> np.ndarray:+ """Quaternion rotating unit vector `frm` onto unit vector `to`."""+ d = float(np.dot(frm, to))+ if d > 1.0 - 1e-9:+ return _IDENTITY.copy()+ if d < -1.0 + 1e-9:+ # 180°: rotate about any axis perpendicular to `frm`.+ axis = np.cross(frm, np.array([1.0, 0.0, 0.0]))+ if np.linalg.norm(axis) < 1e-6:+ axis = np.cross(frm, np.array([0.0, 1.0, 0.0]))+ axis = _normalize(axis)+ return np.array([axis[0], axis[1], axis[2], 0.0])+ axis = np.cross(frm, to)+ q = np.array([axis[0], axis[1], axis[2], 1.0 + d])+ return _quat_normalize(q)+++def _frame_quat(direction: np.ndarray, bend_normal: np.ndarray, rest_dir: np.ndarray, rest_normal: np.ndarray) -> np.ndarray:+ """Global orientation carrying (rest_dir, rest_normal) onto (direction, bend_normal).++ `direction` fixes the bone axis; `bend_normal` (projected perpendicular to+ the axis) fixes the twist about it. Falls back to swing-only when the+ normal is degenerate (straight limb).+ """+ swing = _shortest_arc(rest_dir, direction)+ n = bend_normal - direction * float(np.dot(bend_normal, direction))+ if np.linalg.norm(n) < 1e-5:+ return swing+ n = _normalize(n)+ carried = _rotate_vec(swing, rest_normal)+ carried = carried - direction * float(np.dot(carried, direction))+ if np.linalg.norm(carried) < 1e-5:+ return swing+ carried = _normalize(carried)+ twist = _shortest_arc(carried, n)+ # Constrain the correction to a pure twist about the bone axis.+ axis_dot = float(np.dot(twist[:3], direction))+ twist = _quat_normalize(np.array([direction[0] * axis_dot, direction[1] * axis_dot, direction[2] * axis_dot, twist[3]]))+ return _quat_multiply(twist, swing)+++def _rotate_vec(q: np.ndarray, v: np.ndarray) -> np.ndarray:+ qv = np.array([v[0], v[1], v[2], 0.0])+ return _quat_multiply(_quat_multiply(q, qv), _quat_conjugate(q))[:3]+++def _basis_quat(x_axis: np.ndarray, y_hint: np.ndarray) -> np.ndarray:+ """Orthonormal basis quaternion from a trusted X axis and an up hint."""+ x = _normalize(x_axis)+ z = _normalize(np.cross(x, _normalize(y_hint)))+ if np.linalg.norm(z) < 1e-6:+ return _IDENTITY.copy()+ y = np.cross(z, x)+ m = np.stack([x, y, z], axis=1)+ return _quat_normalize(_quat_from_matrix(m))+++def _hemisphere(prev: Optional[np.ndarray], q: np.ndarray) -> np.ndarray:+ if prev is not None and float(np.dot(prev, q)) < 0.0:+ return -q+ return q+++# (bone, parent, landmarks (a→b) giving the bone direction, rest_dir, rest bend normal or None)+_LIMBS = [+ ("LeftUpLeg", "Hips", LEFT_HIP, LEFT_KNEE, np.array([0.0, -1.0, 0.0])),+ ("LeftLeg", "LeftUpLeg", LEFT_KNEE, LEFT_ANKLE, np.array([0.0, -1.0, 0.0])),+ ("RightUpLeg", "Hips", RIGHT_HIP, RIGHT_KNEE, np.array([0.0, -1.0, 0.0])),+ ("RightLeg", "RightUpLeg", RIGHT_KNEE, RIGHT_ANKLE, np.array([0.0, -1.0, 0.0])),+ ("LeftArm", "Spine2", LEFT_SHOULDER, LEFT_ELBOW, np.array([1.0, 0.0, 0.0])),+ ("LeftForeArm", "LeftArm", LEFT_ELBOW, LEFT_WRIST, np.array([1.0, 0.0, 0.0])),+ ("RightArm", "Spine2", RIGHT_SHOULDER, RIGHT_ELBOW, np.array([-1.0, 0.0, 0.0])),+ ("RightForeArm", "RightArm", RIGHT_ELBOW, RIGHT_WRIST, np.array([-1.0, 0.0, 0.0])),+]++# Bones written to the clip, in a stable order.+CLIP_BONES = [+ "Hips",+ "Spine",+ "Spine1",+ "Spine2",+ "Neck",+ "Head",+ "LeftUpLeg",+ "LeftLeg",+ "LeftFoot",+ "RightUpLeg",+ "RightLeg",+ "RightFoot",+ "LeftArm",+ "LeftForeArm",+ "LeftHand",+ "RightArm",+ "RightForeArm",+ "RightHand",+]+++def smooth_landmarks(world: np.ndarray, fps: float, cutoff_hz: float = 4.0) -> np.ndarray:+ """fps-aware exponential smoothing over the time axis of (T, 33, 3)."""+ world = np.asarray(world, dtype=np.float64)+ if world.shape[0] < 2 or fps <= 0:+ return world+ alpha = 1.0 - np.exp(-2.0 * np.pi * cutoff_hz / fps)+ alpha = float(np.clip(alpha, 0.05, 1.0))+ out = world.copy()+ for t in range(1, world.shape[0]):+ out[t] = out[t - 1] + alpha * (world[t] - out[t - 1])+ return out+++def _to_rig_space(world: np.ndarray) -> np.ndarray:+ """MediaPipe world space (x right, y down, z toward camera) → rig space+ (y up, character facing the camera along +Z)."""+ out = world.copy()+ out[..., 1] *= -1.0+ out[..., 2] *= -1.0+ return out+++def solve_frame(p: np.ndarray, prev: Optional[dict] = None) -> dict:+ """Solve one frame of rig-space landmarks (33, 3) → {bone: [x,y,z,w]} locals."""+ hip_c = 0.5 * (p[LEFT_HIP] + p[RIGHT_HIP])+ sho_c = 0.5 * (p[LEFT_SHOULDER] + p[RIGHT_SHOULDER])+ spine_up = _normalize(sho_c - hip_c)+ if np.linalg.norm(spine_up) < 1e-6:+ spine_up = np.array([0.0, 1.0, 0.0])++ g = {} # bone → global quaternion+ g["Hips"] = _basis_quat(p[LEFT_HIP] - p[RIGHT_HIP], spine_up)+ chest = _basis_quat(p[LEFT_SHOULDER] - p[RIGHT_SHOULDER], spine_up)++ # Distribute the pelvis→chest relative rotation across the spine chain.+ rel = _quat_multiply(_quat_conjugate(g["Hips"]), chest)+ step = _quat_slerp(_IDENTITY, rel, 1.0 / 3.0)+ g["Spine"] = _quat_multiply(g["Hips"], step)+ g["Spine1"] = _quat_multiply(g["Spine"], step)+ g["Spine2"] = chest++ # Head from the ear line and the ear-midpoint→nose forward vector.+ ear_c = 0.5 * (p[LEFT_EAR] + p[RIGHT_EAR])+ head_fwd = _normalize(p[NOSE] - ear_c)+ head_x = p[LEFT_EAR] - p[RIGHT_EAR]+ if np.linalg.norm(head_fwd) > 1e-6 and np.linalg.norm(head_x) > 1e-6:+ head_up = _normalize(np.cross(head_fwd, _normalize(head_x)))+ if float(np.dot(head_up, spine_up)) < 0.0:+ head_up = -head_up+ head_g = _basis_quat(head_x, head_up)+ else:+ head_g = chest.copy()+ g["Neck"] = _quat_slerp(chest, head_g, 0.5)+ g["Head"] = head_g++ # Limbs: bend-plane normal from the upper/lower segment cross product.+ limb_pairs = {+ "LeftUpLeg": ("LeftLeg", LEFT_HIP, LEFT_KNEE, LEFT_ANKLE),+ "RightUpLeg": ("RightLeg", RIGHT_HIP, RIGHT_KNEE, RIGHT_ANKLE),+ "LeftArm": ("LeftForeArm", LEFT_SHOULDER, LEFT_ELBOW, LEFT_WRIST),+ "RightArm": ("RightForeArm", RIGHT_SHOULDER, RIGHT_ELBOW, RIGHT_WRIST),+ }+ bend_normals = {}+ for upper, (lower, a, b, c) in limb_pairs.items():+ d_up = _normalize(p[b] - p[a])+ d_lo = _normalize(p[c] - p[b])+ n = np.cross(d_up, d_lo)+ bend_normals[upper] = n+ bend_normals[lower] = n++ # Rest bend normals in T-pose: knees hinge about the pelvis X axis; elbows+ # about the world -Z when arms are out (forearm folds toward the chest).+ rest_normals = {+ "LeftUpLeg": np.array([1.0, 0.0, 0.0]),+ "LeftLeg": np.array([1.0, 0.0, 0.0]),+ "RightUpLeg": np.array([1.0, 0.0, 0.0]),+ "RightLeg": np.array([1.0, 0.0, 0.0]),+ "LeftArm": np.array([0.0, 0.0, -1.0]),+ "LeftForeArm": np.array([0.0, 0.0, -1.0]),+ "RightArm": np.array([0.0, 0.0, -1.0]),+ "RightForeArm": np.array([0.0, 0.0, -1.0]),+ }++ for bone, parent, a, b, rest_dir in _LIMBS:+ d = _normalize(p[b] - p[a])+ if np.linalg.norm(d) < 1e-6:+ g[bone] = g[parent].copy()+ continue+ n = bend_normals.get(bone, np.zeros(3))+ if np.linalg.norm(n) < 1e-4 and prev is not None and bone in prev.get("globals", {}):+ # Straight limb: keep last frame's twist rather than snapping.+ swing = _shortest_arc(_rotate_vec(prev["globals"][bone], rest_dir), d)+ g[bone] = _quat_multiply(swing, prev["globals"][bone])+ else:+ g[bone] = _frame_quat(d, n, rest_dir, rest_normals[bone])++ # Feet: ankle → foot-index. The rest foot bone points forward and ~27°+ # down (ankle sits above the toes), matching humanoid rig conventions.+ foot_rest = _normalize(np.array([0.0, -0.5, 1.0]))+ for foot, parent, a, b, rest_dir in (+ ("LeftFoot", "LeftLeg", LEFT_ANKLE, LEFT_FOOT_INDEX, foot_rest),+ ("RightFoot", "RightLeg", RIGHT_ANKLE, RIGHT_FOOT_INDEX, foot_rest),+ ):+ d = _normalize(p[b] - p[a])+ g[foot] = _frame_quat(d, np.array([0.0, 1.0, 0.0]), rest_dir, np.array([0.0, 1.0, 0.0])) if np.linalg.norm(d) > 1e-6 else g[parent].copy()++ # Hands: wrist → mid(index, pinky), swing only.+ for hand, parent, w, i, k, rest_dir in (+ ("LeftHand", "LeftForeArm", LEFT_WRIST, LEFT_INDEX, LEFT_PINKY, np.array([1.0, 0.0, 0.0])),+ ("RightHand", "RightForeArm", RIGHT_WRIST, RIGHT_INDEX, RIGHT_PINKY, np.array([-1.0, 0.0, 0.0])),+ ):+ d = _normalize(0.5 * (p[i] + p[k]) - p[w])+ if np.linalg.norm(d) < 1e-6:+ g[hand] = g[parent].copy()+ else:+ swing = _shortest_arc(_rotate_vec(g[parent], rest_dir), d)+ g[hand] = _quat_multiply(swing, g[parent])++ parents = {+ "Hips": None,+ "Spine": "Hips",+ "Spine1": "Spine",+ "Spine2": "Spine1",+ "Neck": "Spine2",+ "Head": "Neck",+ "LeftUpLeg": "Hips",+ "LeftLeg": "LeftUpLeg",+ "LeftFoot": "LeftLeg",+ "RightUpLeg": "Hips",+ "RightLeg": "RightUpLeg",+ "RightFoot": "RightLeg",+ "LeftArm": "Spine2",+ "LeftForeArm": "LeftArm",+ "LeftHand": "LeftForeArm",+ "RightArm": "Spine2",+ "RightForeArm": "RightArm",+ "RightHand": "RightForeArm",+ }+ locals_ = {}+ for bone in CLIP_BONES:+ parent = parents[bone]+ if parent is None:+ locals_[bone] = _quat_normalize(g[bone])+ else:+ locals_[bone] = _quat_normalize(_quat_multiply(_quat_conjugate(g[parent]), g[bone]))+ return {"locals": locals_, "globals": g}+++def landmarks_to_clip(+ world: np.ndarray,+ *,+ fps: float,+ name: str = "captured",+ smooth: bool = True,+) -> dict:+ """(T, 33, 3) MediaPipe world landmarks → three.js AnimationClip JSON."""+ world = np.asarray(world, dtype=np.float64)+ if world.ndim != 3 or world.shape[1] < 33 or world.shape[2] != 3:+ raise ValueError(f"landmarks must be (T, 33, 3); got {world.shape}")+ if fps <= 0:+ raise ValueError("fps must be > 0")+ n_frames = world.shape[0]+ if n_frames < 1:+ raise ValueError("motion has no frames")++ rig = _to_rig_space(world)+ if smooth:+ rig = smooth_landmarks(rig, fps)++ per_bone: dict[str, list[np.ndarray]] = {b: [] for b in CLIP_BONES}+ prev_solution: Optional[dict] = None+ prev_quats: dict[str, np.ndarray] = {}+ for t in range(n_frames):+ sol = solve_frame(rig[t], prev_solution)+ for bone in CLIP_BONES:+ q = _hemisphere(prev_quats.get(bone), sol["locals"][bone])+ prev_quats[bone] = q+ per_bone[bone].append(q)+ prev_solution = sol++ times = (np.arange(n_frames, dtype=np.float64) / float(fps)).tolist()+ duration = (n_frames - 1) / float(fps) if n_frames > 1 else 0.0+ tracks = []+ for bone in CLIP_BONES:+ values = np.stack(per_bone[bone], axis=0)+ tracks.append(+ {+ "type": "quaternion",+ "name": f"{bone}.quaternion",+ "times": times,+ "values": values.reshape(-1).tolist(),+ }+ )+ # Root motion stays at the origin: the compositor pins the avatar to the+ # subject's on-screen anchor each frame (see anchors in the worker meta).+ tracks.append(+ {+ "type": "vector",+ "name": "Hips.position",+ "times": [0.0],+ "values": [0.0, 0.0, 0.0],+ }+ )+ return {+ "name": name,+ "duration": duration,+ "tracks": tracks,+ "uuid": _stable_uuid(name, n_frames),+ "blendMode": _NORMAL_BLEND_MODE,+ }+++def image_anchors(image_landmarks: np.ndarray, visibility: Optional[np.ndarray] = None) -> list:+ """Per-frame on-screen placement anchors from normalized image landmarks.++ `image_landmarks` is (T, 33, 2+) in normalized [0,1] image coordinates.+ Returns one dict per frame: hip-centre position, the subject's on-screen+ height (head-to-ankle span), and a visibility flag — everything the browser+ compositor needs to pin and scale the avatar over the subject.+ """+ image_landmarks = np.asarray(image_landmarks, dtype=np.float64)+ anchors = []+ for t in range(image_landmarks.shape[0]):+ p = image_landmarks[t]+ vis = visibility[t] if visibility is not None else None+ key = [LEFT_HIP, RIGHT_HIP, LEFT_SHOULDER, RIGHT_SHOULDER]+ visible = True+ if vis is not None:+ visible = bool(np.mean([vis[i] for i in key]) > 0.35)+ hip = 0.5 * (p[LEFT_HIP, :2] + p[RIGHT_HIP, :2])+ top = float(min(p[NOSE, 1], p[LEFT_EAR, 1], p[RIGHT_EAR, 1]))+ bottom = float(max(p[LEFT_ANKLE, 1], p[RIGHT_ANKLE, 1]))+ height = max(0.05, bottom - top)+ anchors.append(+ {+ "x": round(float(hip[0]), 4),+ "y": round(float(hip[1]), 4),+ "h": round(height, 4),+ "v": 1 if visible else 0,+ }+ )+ return anchors+++def _stable_uuid(name: str, n_frames: int) -> str:+ h = hashlib.sha256(f"{name}:{n_frames}:v2m".encode("utf-8")).hexdigest()+ return f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}".upper()diff --git a/workers/model-video2motion/requirements.txt b/workers/model-video2motion/requirements.txtnew file mode 100644index 000000000..173e43ff7--- /dev/null+++ b/workers/model-video2motion/requirements.txt@@ -0,0 +1,8 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+numpy==1.26.4+mediapipe==0.10.21+opencv-python-headless==4.10.0.84+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3diff --git a/workers/model-video2motion/test_pose_solver.py b/workers/model-video2motion/test_pose_solver.pynew file mode 100644index 000000000..0d4b8f1fd--- /dev/null+++ b/workers/model-video2motion/test_pose_solver.py@@ -0,0 +1,187 @@+"""Deterministic tests for the landmark → rotation solver (no mediapipe)."""++import numpy as np+import pytest++from pose_solver import (+ CLIP_BONES,+ LEFT_ANKLE,+ LEFT_ELBOW,+ LEFT_FOOT_INDEX,+ LEFT_HEEL,+ LEFT_HIP,+ LEFT_INDEX,+ LEFT_KNEE,+ LEFT_PINKY,+ LEFT_SHOULDER,+ LEFT_WRIST,+ LEFT_EAR,+ NOSE,+ RIGHT_ANKLE,+ RIGHT_ELBOW,+ RIGHT_EAR,+ RIGHT_FOOT_INDEX,+ RIGHT_HEEL,+ RIGHT_HIP,+ RIGHT_INDEX,+ RIGHT_KNEE,+ RIGHT_PINKY,+ RIGHT_SHOULDER,+ RIGHT_WRIST,+ image_anchors,+ landmarks_to_clip,+ solve_frame,+)+++def t_pose_world() -> np.ndarray:+ """A synthetic T-pose in MEDIAPIPE world convention (y DOWN, z toward+ camera), person facing the camera. Hip centre at the origin.++ Facing the camera, the person's left side sits at image/world -x is wrong:+ mediapipe world x is right in IMAGE space, so the subject's left hand+ appears on the image right → positive x.+ """+ p = np.zeros((33, 3))+ # y is DOWN: head negative, feet positive.+ p[LEFT_HIP] = [0.10, 0.0, 0.0]+ p[RIGHT_HIP] = [-0.10, 0.0, 0.0]+ p[LEFT_SHOULDER] = [0.18, -0.50, 0.0]+ p[RIGHT_SHOULDER] = [-0.18, -0.50, 0.0]+ p[NOSE] = [0.0, -0.72, -0.10]+ p[LEFT_EAR] = [0.07, -0.70, 0.0]+ p[RIGHT_EAR] = [-0.07, -0.70, 0.0]+ # Arms straight out along ±x (T-pose).+ p[LEFT_ELBOW] = [0.45, -0.50, 0.0]+ p[LEFT_WRIST] = [0.70, -0.50, 0.0]+ p[LEFT_INDEX] = [0.80, -0.50, 0.0]+ p[LEFT_PINKY] = [0.79, -0.50, 0.02]+ p[RIGHT_ELBOW] = [-0.45, -0.50, 0.0]+ p[RIGHT_WRIST] = [-0.70, -0.50, 0.0]+ p[RIGHT_INDEX] = [-0.80, -0.50, 0.0]+ p[RIGHT_PINKY] = [-0.79, -0.50, 0.02]+ # Legs straight down (y-down: knees/ankles positive y).+ p[LEFT_KNEE] = [0.10, 0.45, 0.0]+ p[LEFT_ANKLE] = [0.10, 0.90, 0.0]+ p[LEFT_HEEL] = [0.10, 0.95, 0.03]+ p[LEFT_FOOT_INDEX] = [0.10, 0.95, -0.12]+ p[RIGHT_KNEE] = [-0.10, 0.45, 0.0]+ p[RIGHT_ANKLE] = [-0.10, 0.90, 0.0]+ p[RIGHT_HEEL] = [-0.10, 0.95, 0.03]+ p[RIGHT_FOOT_INDEX] = [-0.10, 0.95, -0.12]+ return p+++def _rig(p_world: np.ndarray) -> np.ndarray:+ from pose_solver import _to_rig_space++ return _to_rig_space(p_world[None, ...])[0]+++def _angle(q: np.ndarray) -> float:+ return float(2.0 * np.arccos(np.clip(abs(q[3]), -1.0, 1.0)))+++def test_t_pose_is_near_identity():+ sol = solve_frame(_rig(t_pose_world()))+ for bone in CLIP_BONES:+ q = sol["locals"][bone]+ assert _angle(q) < np.deg2rad(12.0), f"{bone} deviates {np.rad2deg(_angle(q)):.1f}° in T-pose"+++def test_squat_bends_knees_not_arms():+ p = t_pose_world()+ # Deep knee bend: knees come forward (toward camera = world -z), ankles stay.+ p[LEFT_KNEE] = [0.10, 0.30, -0.30]+ p[RIGHT_KNEE] = [-0.10, 0.30, -0.30]+ sol = solve_frame(_rig(p))+ assert _angle(sol["locals"]["LeftUpLeg"]) > np.deg2rad(20.0)+ assert _angle(sol["locals"]["LeftLeg"]) > np.deg2rad(20.0)+ assert _angle(sol["locals"]["LeftArm"]) < np.deg2rad(12.0)+++def test_arm_raise_isolated_to_arm():+ p = t_pose_world()+ # Left arm straight up (y-down world: up = negative y).+ p[LEFT_ELBOW] = [0.18, -0.80, 0.0]+ p[LEFT_WRIST] = [0.18, -1.05, 0.0]+ p[LEFT_INDEX] = [0.18, -1.15, 0.0]+ p[LEFT_PINKY] = [0.20, -1.14, 0.0]+ sol = solve_frame(_rig(p))+ assert _angle(sol["locals"]["LeftArm"]) > np.deg2rad(60.0)+ assert _angle(sol["locals"]["RightArm"]) < np.deg2rad(12.0)+ assert _angle(sol["locals"]["LeftUpLeg"]) < np.deg2rad(12.0)+++def test_turned_person_rotates_hips():+ p = t_pose_world()+ # Rotate everything 90° about the vertical axis (person faces image left).+ c, s = 0.0, 1.0+ rot = np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])+ p = p @ rot.T+ sol = solve_frame(_rig(p))+ assert _angle(sol["locals"]["Hips"]) > np.deg2rad(60.0)+++def test_clip_shape_and_continuity():+ frames = []+ base = t_pose_world()+ for t in range(30):+ p = base.copy()+ lift = 0.25 * np.sin(t / 29.0 * np.pi)+ p[LEFT_ELBOW][1] -= lift+ p[LEFT_WRIST][1] -= 1.6 * lift+ p[LEFT_INDEX][1] -= 1.7 * lift+ p[LEFT_PINKY][1] -= 1.7 * lift+ frames.append(p)+ clip = landmarks_to_clip(np.stack(frames), fps=30, name="wave test")+ assert clip["duration"] == pytest.approx(29 / 30)+ track_names = {t["name"] for t in clip["tracks"]}+ assert f"Hips.quaternion" in track_names+ assert "Hips.position" in track_names+ assert len(track_names) == len(CLIP_BONES) + 1+ for track in clip["tracks"]:+ if track["type"] != "quaternion":+ continue+ vals = np.asarray(track["values"]).reshape(-1, 4)+ assert np.allclose(np.linalg.norm(vals, axis=1), 1.0, atol=1e-6)+ # Hemisphere continuity: consecutive quaternions never anti-parallel.+ dots = np.sum(vals[1:] * vals[:-1], axis=1)+ assert np.all(dots > -0.5)+++def test_clip_deterministic():+ frames = np.stack([t_pose_world()] * 5)+ a = landmarks_to_clip(frames, fps=24, name="same")+ b = landmarks_to_clip(frames, fps=24, name="same")+ assert a == b+++def test_rejects_bad_shapes():+ with pytest.raises(ValueError):+ landmarks_to_clip(np.zeros((5, 10, 3)), fps=30)+ with pytest.raises(ValueError):+ landmarks_to_clip(np.zeros((0, 33, 3)), fps=30)+ with pytest.raises(ValueError):+ landmarks_to_clip(np.zeros((5, 33, 3)), fps=0)+++def test_image_anchors():+ img = np.zeros((2, 33, 2))+ img[:, LEFT_HIP] = [0.55, 0.55]+ img[:, RIGHT_HIP] = [0.45, 0.55]+ img[:, LEFT_SHOULDER] = [0.57, 0.35]+ img[:, RIGHT_SHOULDER] = [0.43, 0.35]+ img[:, NOSE] = [0.5, 0.2]+ img[:, LEFT_EAR] = [0.52, 0.21]+ img[:, RIGHT_EAR] = [0.48, 0.21]+ img[:, LEFT_ANKLE] = [0.54, 0.92]+ img[:, RIGHT_ANKLE] = [0.46, 0.93]+ vis = np.ones((2, 33))+ vis[1, LEFT_HIP] = vis[1, RIGHT_HIP] = vis[1, LEFT_SHOULDER] = vis[1, RIGHT_SHOULDER] = 0.1+ anchors = image_anchors(img, vis)+ assert anchors[0]["x"] == pytest.approx(0.5)+ assert anchors[0]["y"] == pytest.approx(0.55)+ assert anchors[0]["h"] == pytest.approx(0.73, abs=0.01)+ assert anchors[0]["v"] == 1+ assert anchors[1]["v"] == 0diff --git a/workers/model-video2motion/worker_security.py b/workers/model-video2motion/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/model-video2motion/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})"