Skip to content

Type a motion, watch a rigged character perform it: fast video model + GVHMR + live Mixamo retargeting

JavaScript

WiLoR finger tracking: batched backend, setup script, tuned limits, docs

blendi-remade60687ba4e2c7
diff --git a/.gitignore b/.gitignore
index 744aeb1..f5c7ee9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,4 @@ bench/.venv/
bench/clips/
bench/out/
*.task
+captures_hands/
diff --git a/README.md b/README.md
index d4e89ef..c585c61 100644
--- a/README.md
+++ b/README.md
@@ -25,6 +25,7 @@ flowchart LR
| | fal · FLUX 3 Max (720p) | ~8–9s wall (4.5s GPU) |
| **Live** preview — MediaPipe Pose, retargeted per frame | browser | immediate |
| **HQ** motion — GVHMR → SMPL rotations → Mixamo | local GPU worker | ~3.5–4s (0.7–0.8× real time) |
+| **Fingers** — WiLoR hand model (MediaPipe fallback), in parallel with GVHMR | local GPU worker | +~0.3s |
The live pass hides the wait; the HQ pass is the real result. GVHMR sees the whole clip at once, outputs joint *rotations* on a fixed-proportion body, and recovers a gravity-aware root path — so there's no jitter, limb stretching, or twisted forearms.
@@ -46,7 +47,15 @@ node server.mjs # → http://localhost:5177 (live preview works n
hq\setup.ps1 # venv, CUDA PyTorch, GVHMR + ~5 GB checkpoints
```
-Then download **SMPL-X v1.1 (NPZ)** from [smpl-x.is.tue.mpg.de](https://smpl-x.is.tue.mpg.de/) (free registration) and put `SMPLX_NEUTRAL.npz` in `hq/body_models/smplx/`. Start the worker next to the web server:
+Then download **SMPL-X v1.1 (NPZ)** from [smpl-x.is.tue.mpg.de](https://smpl-x.is.tue.mpg.de/) (free registration) and put `SMPLX_NEUTRAL.npz` in `hq/body_models/smplx/`.
+
+**Finger tracking (optional):** WiLoR needs the MANO hand model — register at [mano.is.tue.mpg.de](https://mano.is.tue.mpg.de) and download *Models & Code* (`mano_v1_2.zip`), then:
+
+```powershell
+hq\.venv\Scripts\python hq\setup_hands.py $HOME\Downloads\mano_v1_2.zip # WiLoR weights + MANO (converted for modern Python)
+```
+
+Without MANO, fingers fall back to MediaPipe Hands (less accurate depth). Start the worker next to the web server:
```powershell
hq\.venv\Scripts\python hq\worker.py # → 127.0.0.1:5178, loads once and stays warm
@@ -57,6 +66,7 @@ hq\.venv\Scripts\python hq\worker.py # → 127.0.0.1:5178, loads once and sta
- **Generate** a prompt or click a preset. By default every clip starts from the same flux-generated *performer* (one person, full body, plain backdrop, static camera — ideal pose-estimation input).
- **Video model** — *H3 Max Turbo* for the snappiest loop and Stream mode; *FLUX 3 Max* for more realistic motion (best for single takes — at ~9s per 5s clip it can't keep a chained stream fed yet).
- **Character** — X Bot, Michelle or Soldier (textured Mixamo rigs from the three.js examples), or **Load Mixamo file…** for any Mixamo `.fbx`/`.glb` (download from [mixamo.com](https://www.mixamo.com), T-pose).
+- **Track fingers** — the HQ pass also recovers hands: WiLoR (MANO-based) on the full-resolution clip, assigned to the body's wrists, rotated into the motion's world frame and smoothed; the rig gets palm orientation plus all 15 finger joints. Untracked hands rest in a natural curl.
- **Swap character every loop** — X Bot → Michelle → Soldier, cutting on each loop (or each new clip in Stream mode). The motion lives on one hidden driver rig; the character on stage copies its pose, so swapping is instant.
- **Cinematic camera** — slow arc and push-in around the performer on a studio stage (environment lighting, warm key + cool rim, soft reflective floor, contact shadows). Drag to take over; it resumes after a few seconds.
- **Orientation** — portrait 9:16 (default) or landscape 16:9. Portrait gives the performer ~70% more pixels of height at 480P, which helps pose estimation.
@@ -83,7 +93,9 @@ Writes `renders/<take>.mp4` (1080×1920 by default, `--res 1920x1080` for landsc
| `public/app.js` | UI, generation queue, live pose loop, playback & blending, stream mode, GLB export |
| `public/stage.js` | studio stage: lighting, reflective floor, contact shadows, cinematic camera |
| `public/retarget.js` | Mixamo rig wrapper: MediaPipe landmarks → bones, SMPL rotations → bones, rig-to-rig pose copy, grounding |
+| `hq/hands.py` | finger tracking: WiLoR (batched) / MediaPipe backends, wrist assignment, camera→world, smoothing |
| `tools/render_blender.py` | headless Blender (5.x) renderer for exported takes |
+| `bench/` | hand-pose test bench: detection/jitter metrics, 2D overlays, source-vs-rig close-up reviews |
| `hq/worker.py` | FastAPI worker around the `gvhmr` package, tuned for single-person generated clips |
<details>
@@ -114,6 +126,8 @@ It runs alongside third-party components that keep their own licenses — none a
|---|---|---|
| [GVHMR](https://github.com/zju3dv/GVHMR) — the HQ motion pass | educational / research / non-profit only | ❌ |
| [SMPL-X](https://smpl-x.is.tue.mpg.de/) body model | non-commercial, registration required | ❌ (separate commercial license from Meshcapade) |
+| [WiLoR](https://github.com/rolpotamias/WiLoR) — finger tracking | CC-BY-NC-ND | ❌ |
+| [MANO](https://mano.is.tue.mpg.de) hand model | non-commercial, registration required | ❌ |
| [Ultralytics YOLO](https://github.com/ultralytics/ultralytics) — person detector in the HQ worker | AGPL-3.0 | ⚠️ copyleft, or an Ultralytics enterprise license |
| MediaPipe · three.js | Apache-2.0 · MIT | ✅ |
| Mixamo characters | Adobe Mixamo terms (loaded from the three.js CDN, not redistributed) | ✅ in your own projects |
diff --git a/hq/hands.py b/hq/hands.py
index 4425f81..6de9d23 100644
--- a/hq/hands.py
+++ b/hq/hands.py
@@ -80,13 +80,54 @@ class WiLoRHands:
self.pipe = WiLorHandPose3dEstimationPipeline(device=torch.device("cuda"), dtype=torch.float16, verbose=False,
wilor_pretrained_dir=str(root), WILOR_MINI_REPO_ID="__offline__")
- def __call__(self, frames, fps):
- out = []
- for f in frames:
- rets = self.pipe.predict(cv2.cvtColor(f, cv2.COLOR_BGR2RGB), hand_conf=0.3)
- out.append([(r["wilor_preds"]["pred_keypoints_2d"][0].astype(np.float32),
- r["wilor_preds"]["pred_keypoints_3d"][0].astype(np.float32), 1.0)
- for r in rets if "wilor_preds" in r])
+ def __call__(self, frames, fps, det_batch=16, model_batch=32):
+ """Batched WiLoR: same weights/maths as WiLoR-mini's predict(), ~3x faster than per-frame calls."""
+ import torch
+ from wilor_mini.utils import utils as wu
+
+ P = self.pipe
+ rgb = [cv2.cvtColor(f, cv2.COLOR_BGR2RGB) for f in frames]
+ H, W = rgb[0].shape[:2]
+ # 1) hand boxes, batched and padded to a fixed batch shape
+ dets = []
+ for i in range(0, len(rgb), det_batch):
+ chunk = rgb[i:i + det_batch]
+ res = P.hand_detector(chunk + [chunk[-1]] * (det_batch - len(chunk)), conf=0.3, verbose=False, half=True)
+ for r in res[:len(chunk)]:
+ b = r.boxes
+ dets.append(list(zip(b.xyxy.cpu().numpy(), b.cls.cpu().numpy(), b.conf.cpu().numpy())))
+ # 2) 256px crops (left hands mirrored, as the model expects right hands)
+ patches, meta = [], []
+ for t, ds in enumerate(dets):
+ for box, cls, conf in sorted(ds, key=lambda d: -d[2])[:4]:
+ c = (box[:2] + box[2:]) / 2.0
+ size = 2.5 * float((box[2:] - box[:2]).max())
+ right = int(cls > 0.5)
+ patch, _ = wu.generate_image_patch_cv2(rgb[t], c[0], c[1], size, size, 256, 256, right == 0, 1.0, 0,
+ border_mode=cv2.BORDER_CONSTANT)
+ patches.append(patch); meta.append((t, c, size, right, float(conf)))
+ out = [[] for _ in frames]
+ if not patches:
+ return out
+ # 3) model, batched
+ cams, kps = [], []
+ with torch.no_grad():
+ for i in range(0, len(patches), model_batch):
+ x = torch.from_numpy(np.stack(patches[i:i + model_batch])).to(P.device, dtype=P.dtype)
+ o = P.wilor_model(x)
+ cams.append(o["pred_cam"].float().cpu().numpy()); kps.append(o["pred_keypoints_3d"].float().cpu().numpy())
+ cams, kps = np.concatenate(cams), np.concatenate(kps)
+ # 4) un-mirror left hands, place in the full frame, project to 2D (for assigning hands to wrists)
+ focal = P.FOCAL_LENGTH / P.IMAGE_SIZE * max(W, H)
+ for j, (t, c, size, right, conf) in enumerate(meta):
+ k3 = kps[j].copy(); pc = cams[j:j + 1].copy()
+ pc[:, 1] *= (2 * right - 1)
+ if right == 0:
+ k3[:, 0] = -k3[:, 0]
+ cam_t = wu.cam_crop_to_full(pc, c[None], size, np.array([[W, H]], np.float32), focal)
+ k2 = wu.perspective_projection(k3[None], translation=cam_t, focal_length=np.array([[focal, focal]]),
+ camera_center=np.array([[W / 2.0, H / 2.0]]))[0]
+ out[t].append((k2.astype(np.float32), k3.astype(np.float32), conf))
return out
diff --git a/hq/requirements.txt b/hq/requirements.txt
index 8b43f60..7f0de64 100644
--- a/hq/requirements.txt
+++ b/hq/requirements.txt
@@ -5,3 +5,7 @@ gvhmr==1.6.1
ultralytics>=8.3
fastapi>=0.110
uvicorn[standard]>=0.29
+# finger tracking (hq/hands.py): MediaPipe Hands fallback + WiLoR deps. WiLoR-mini itself is
+# installed with --no-deps by setup.ps1 (its pins conflict with GVHMR's torch/ultralytics).
+mediapipe>=0.10
+roma
diff --git a/hq/setup.ps1 b/hq/setup.ps1
index 8e4da22..6c8920b 100644
--- a/hq/setup.ps1
+++ b/hq/setup.ps1
@@ -12,6 +12,8 @@ uv pip install "torch==2.7.1" "torchvision==0.22.1" --index-url https://download
uv pip install pip setuptools wheel "numpy>=1.26"
uv pip install --no-build-isolation "chumpy==0.70"
uv pip install -r requirements.txt
+# Finger tracking model code (weights come from setup_hands.py)
+uv pip install --no-deps "git+https://github.com/warmshao/WiLoR-mini"
# GVHMR / HMR2 / ViTPose checkpoints (~5 GB) into hq/weights.
$env:GVHMR_CHECKPOINTS = Join-Path $PSScriptRoot "weights"
@@ -19,3 +21,4 @@ $env:GVHMR_BODY_MODELS = Join-Path $PSScriptRoot "body_models"
& .venv\Scripts\gvhmr.exe download demo
New-Item -ItemType Directory -Force body_models\smplx | Out-Null
Write-Host "Done. Now add body_models\smplx\SMPLX_NEUTRAL.npz (https://smpl-x.is.tue.mpg.de/, v1.1)."
+Write-Host "Optional fingers: download mano_v1_2.zip (https://mano.is.tue.mpg.de) and run: .venv\Scripts\python setup_hands.py <zip>"
diff --git a/hq/setup_hands.py b/hq/setup_hands.py
new file mode 100644
index 0000000..d0dd49d
--- /dev/null
+++ b/hq/setup_hands.py
@@ -0,0 +1,79 @@
+"""One-time setup for finger tracking.
+
+ hq/.venv/Scripts/python hq/setup_hands.py path/to/mano_v1_2.zip
+
+- extracts MANO_RIGHT.pkl from the official MANO download (mano.is.tue.mpg.de — registration, non-commercial)
+ and re-saves it without chumpy objects (chumpy doesn't run on Python ≥ 3.11 / NumPy ≥ 1.24)
+- downloads the WiLoR checkpoint, hand detector and MANO mean params from the WiLoR authors' Hugging Face Space
+- downloads MediaPipe's hand landmarker (fallback backend)
+"""
+
+import inspect
+import pickle
+import shutil
+import sys
+import urllib.request
+import zipfile
+from pathlib import Path
+
+import numpy as np
+
+HQ = Path(__file__).resolve().parent
+WILOR = HQ / "weights" / "wilor" / "pretrained_models"
+SPACE = "https://huggingface.co/spaces/rolpotamias/WiLoR/resolve/main"
+FILES = {
+ "detector.pt": f"{SPACE}/pretrained_models/detector.pt",
+ "wilor_final.ckpt": f"{SPACE}/pretrained_models/wilor_final.ckpt", # ~2.5 GB
+ "mano_mean_params.npz": f"{SPACE}/mano_data/mano_mean_params.npz",
+}
+MP_TASK = "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/latest/hand_landmarker.task"
+
+
+def fetch(url: str, dst: Path) -> None:
+ if dst.exists():
+ print(f" have {dst.name}")
+ return
+ print(f" downloading {dst.name} …")
+ tmp = dst.with_suffix(dst.suffix + ".part")
+ with urllib.request.urlopen(url) as r, open(tmp, "wb") as f:
+ shutil.copyfileobj(r, f, 1 << 20)
+ tmp.replace(dst)
+
+
+def convert_mano(zip_path: Path) -> None:
+ out = WILOR / "MANO_RIGHT.pkl"
+ raw = WILOR / "MANO_RIGHT.chumpy.pkl"
+ with zipfile.ZipFile(zip_path) as z:
+ name = next(n for n in z.namelist() if n.endswith("models/MANO_RIGHT.pkl"))
+ raw.write_bytes(z.read(name))
+ # chumpy shims: inspect.getargspec (removed in 3.11) and NumPy aliases (removed in 1.24)
+ inspect.getargspec = inspect.getfullargspec
+ for alias, t in (("bool", bool), ("int", int), ("float", float), ("complex", complex), ("object", object), ("unicode", str), ("str", str)):
+ if alias not in np.__dict__:
+ setattr(np, alias, t)
+ import chumpy
+
+ data = pickle.load(open(raw, "rb"), encoding="latin1")
+ data = {k: (np.array(v.r) if isinstance(v, chumpy.Ch) else v) for k, v in data.items()}
+ pickle.dump(data, open(out, "wb"))
+ print(f" MANO_RIGHT.pkl converted ({len(data)} arrays)")
+
+
+def main() -> int:
+ if len(sys.argv) != 2:
+ print(__doc__)
+ return 1
+ WILOR.mkdir(parents=True, exist_ok=True)
+ print("MANO:")
+ convert_mano(Path(sys.argv[1]))
+ print("WiLoR:")
+ for name, url in FILES.items():
+ fetch(url, WILOR / name)
+ print("MediaPipe:")
+ fetch(MP_TASK, HQ / "weights" / "hand_landmarker.task")
+ print("done — restart hq/worker.py; it picks WiLoR automatically")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/hq/worker.py b/hq/worker.py
index cfd31aa..ad7c55c 100644
--- a/hq/worker.py
+++ b/hq/worker.py
@@ -173,6 +173,12 @@ def warmup() -> None:
shutil.rmtree(CACHE / "_warmup", ignore_errors=True) # cached stages would skip the warm-up
result, _ = recover(clip, CACHE / "_warmup")
leg_length(result.smpl_params_world)
+ method = hands_method(None)
+ if method: # load + warm the hand model too (WiLoR's checkpoint is 2.5 GB)
+ import hands as handmod
+
+ frames, fps = handmod.read_frames(clip)
+ HANDS_EXEC.submit(lambda: handmod.backend(method)(frames[:32], fps)).result()
if DETECTOR == "fast": # first YOLO call per input shape is slow: cover both orientations
det = FastSingleDetector.get()
for h, w in ((480, 832), (832, 480), (470, 854), (854, 470)): # H3 480P, FLUX 3 720p (downscaled)
diff --git a/public/app.js b/public/app.js
index 3f8fb1a..855ee17 100644
--- a/public/app.js
+++ b/public/app.js
@@ -6,7 +6,7 @@ import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { FilesetResolver, PoseLandmarker, DrawingUtils } from '@mediapipe/tasks-vision';
import { createStage } from './stage.js';
-import { Rig, OneEuro, Track, trackToClip, blendSnapshots, smplGlobals, aaToQuat } from './retarget.js';
+import { HAND_LIMITS, Rig, OneEuro, Track, trackToClip, blendSnapshots, smplGlobals, aaToQuat } from './retarget.js';
const $ = (s) => document.querySelector(s);
// Mixamo-rigged characters from the three.js examples (loaded from the CDN, not redistributed here).
@@ -353,6 +353,8 @@ function runHQ(take) {
// Finger tracking from the HQ worker: per hand, 21 wrist-relative keypoints per frame (GVHMR world axes).
const _kp = Array.from({ length: 21 }, () => new THREE.Vector3());
function applyHandsFrame(hands, f, yawFix) {
+ // WiLoR's MANO hands are anatomically valid already; joint limits only help MediaPipe's noisy depth.
+ HAND_LIMITS.enabled = hands?.method !== 'wilor';
for (const [src, side] of [['R', 'Right'], ['L', 'Left']]) {
const h = hands?.[src];
if (settings.hands !== false && h?.valid[f]) {
@@ -674,7 +676,7 @@ $('#file-vid').onchange = (e) => {
// Debug handle for the console.
window.p2r = {
get current() { return current; }, get rig() { return rig; }, takes, video, stats,
- stage,
+ stage, HAND_LIMITS, rebake() { for (const t of takes) if (t.hqRaw) t.hq = bakeSmpl(t.hqRaw); },
/** Debug: frame the camera on a bone (e.g. 'RightHand') at distance d. */
focusBone(name, d = 0.6, dir = [0.15, 0.1, 1]) {
const r = onStage ? cast[onStage].rig : rig;
diff --git a/public/retarget.js b/public/retarget.js
index 6a944eb..036bd24 100644
--- a/public/retarget.js
+++ b/public/retarget.js
@@ -45,21 +45,23 @@ const HAND_CHAINS = [
];
/**
- * Anatomical finger limits. Middle/end joints (PIP/DIP) are hinges: keep only the curl toward the palm,
- * 0°–100°, no sideways or backward bending. Knuckles (MCP) keep their sideways spread but can't
- * hyperextend more than ~20°. Removes most single-camera depth noise from tracked fingers.
+ * Anatomical finger limits: fingers fold the way they're measured, but never backwards. A joint
+ * bending away from the palm is straightened (knuckles may hyperextend ~20°), and bends are capped
+ * (knuckle ~90°, middle/end joints ~100°). The fold plane itself is left free — real fingers don't
+ * fold exactly along the palm normal, so forcing it skews the curl.
*/
+export const HAND_LIMITS = { enabled: true, knuckle: 1.6, joint: 1.75, backKnuckle: 0.35, backJoint: 0.05 };
+
function hinge(dir, parentDir, palm, isKnuckle) {
- const u = palm.clone().sub(parentDir.clone().multiplyScalar(palm.dot(parentDir))).normalize(); // palm side, ⟂ parent
- const along = dir.dot(parentDir), curl = dir.dot(u);
- if (isKnuckle) {
- const lateral = dir.clone().sub(parentDir.clone().multiplyScalar(along)).sub(u.clone().multiplyScalar(curl));
- const flex = Math.min(1.6, Math.max(-0.35, Math.atan2(curl, along)));
- return parentDir.clone().multiplyScalar(Math.cos(flex)).add(u.clone().multiplyScalar(Math.sin(flex)))
- .add(lateral.clampLength(0, 0.45)).normalize();
- }
- const flex = Math.min(1.75, Math.max(0, Math.atan2(curl, along)));
- return parentDir.clone().multiplyScalar(Math.cos(flex)).add(u.multiplyScalar(Math.sin(flex))).normalize();
+ if (!HAND_LIMITS.enabled) return dir;
+ const along = dir.dot(parentDir);
+ const perp = dir.clone().sub(parentDir.clone().multiplyScalar(along));
+ if (perp.lengthSq() < 1e-10) return dir;
+ let bend = Math.atan2(perp.length(), along);
+ const L = HAND_LIMITS;
+ if (perp.dot(palm) < 0) bend = Math.min(bend, isKnuckle ? L.backKnuckle : L.backJoint); // bending backwards
+ bend = Math.min(bend, isKnuckle ? L.knuckle : L.joint);
+ return parentDir.clone().multiplyScalar(Math.cos(bend)).add(perp.normalize().multiplyScalar(Math.sin(bend))).normalize();
}
const FOOT_POINTS = ['LeftToe_End', 'RightToe_End', 'LeftToeBase', 'RightToeBase', 'LeftFoot', 'RightFoot'];
diff --git a/tools/capture.mjs b/tools/capture.mjs
index 230ee28..f3757ed 100644
--- a/tools/capture.mjs
+++ b/tools/capture.mjs
@@ -42,6 +42,7 @@ const browser = await puppeteer.launch({
args: [`--window-size=${W},${H}`, '--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist',
'--autoplay-policy=no-user-gesture-required', '--hide-scrollbars', '--mute-audio'],
defaultViewport: { width: W, height: H, deviceScaleFactor: 1 },
+ protocolTimeout: 900000,
});
const results = [];
try {