Turn any video into a Mixamo-rig animation - GVHMR estimator, spec-driven retarget, FK apply in Blender via MCP. Works with any Mixamo character; built to be operated end-to-end by an AI agent.
Add run_in_blender.py and render_preview.py — full loop with zero hand-written snippets
Sachae52d5c17ebcb
diff --git a/README.md b/README.mdindex c556539..a129625 100644--- a/README.md+++ b/README.md@@ -77,10 +77,14 @@ airborne beats), when fists close, where the clip locks back to rest.tools\GVHMR\.venv\Scripts\python.exe pipeline\analyze_landmarks.py --landmarks plates\<name>\landmarks.json# beat sheet → action_specs\<name>.json (schema: docs/PIPELINE.md)tools\GVHMR\.venv\Scripts\python.exe pipeline\lift_to_mixamo.py --spec action_specs\<name>.json- # in Blender: import apply_mixamo_fk; apply_mixamo_fk.run("action_specs/<name>.json")+ python pipeline\run_in_blender.py all action_specs\<name>.jsontools\GVHMR\.venv\Scripts\python.exe pipeline\qa_clip.py --spec action_specs\<name>.json+ tools\GVHMR\.venv\Scripts\python.exe pipeline\render_preview.py action_specs\<name>.json --showcase```+ The last command produces `preview.mp4` and the side-by-side+ `showcase.mp4` — the same format as the demo GIF above.+4. **Iterate** with [docs/PIPELINE.md](docs/PIPELINE.md) and[docs/PITFALLS.md](docs/PITFALLS.md).diff --git a/docs/PIPELINE.md b/docs/PIPELINE.mdindex 2f937dd..bdeab5a 100644--- a/docs/PIPELINE.md+++ b/docs/PIPELINE.md@@ -129,19 +129,29 @@ positions. Sanity: rest frames print the exact Y Bot rest## 5. Apply (inside live Blender)Blender must be open on `ybot_rest.blend` with the MCP add-on server-running. Via MCP `execute_blender_code` or `pipeline\blender_exec.py`:--```python-import sys; sys.path.insert(0, r"<repo>\pipeline")-import apply_mixamo_fk-apply_mixamo_fk.run("action_specs/<motion>.json") # keys the action (~2-4 min / 300 frames; UI freezes — normal)-apply_mixamo_fk.dump_curves("action_specs/<motion>.json") # curves.json (every bone, every frame)-apply_mixamo_fk.run_stills_render("action_specs/<motion>.json", [1, 30, ...]) # front+side PNGs per beat+running. One command drives all three Blender-side stages:++```+python pipeline\run_in_blender.py all action_specs\<motion>.json```-Stills use a temporary camera + Workbench render (window-independent);-never use viewport screenshots — they capture black when the Blender-window is occluded.+(`apply` keys the action — ~2–4 min per 300 frames, Blender's UI+freezes, that's normal; `curves` dumps every bone every frame;+`stills` renders front+side PNGs at the spec's QA frames. Run stages+individually with `apply|curves|stills`.) Agents with MCP can instead+call `apply_mixamo_fk.run/dump_curves/run_stills_render` directly via+`execute_blender_code`.++Stills and previews use a temporary camera + Workbench render+(window-independent); never use viewport screenshots — they capture+black when the Blender window is occluded.++To produce the review videos (`preview.mp4` + the side-by-side+`showcase.mp4` against the source plate):++```+tools\GVHMR\.venv\Scripts\python.exe pipeline\render_preview.py action_specs\<motion>.json --showcase+```## 6. QAdiff --git a/pipeline/render_preview.py b/pipeline/render_preview.pynew file mode 100644index 0000000..11caa5f--- /dev/null+++ b/pipeline/render_preview.py@@ -0,0 +1,168 @@+"""Render a clip's preview video — and the side-by-side showcase+against its source plate — straight from the live Blender rig.++Usage (run with the GVHMR venv python — it has cv2/PIL/PyAV; Blender+open on your rig scene with the clip's action applied):++ tools\\GVHMR\\.venv\\Scripts\\python.exe pipeline\\render_preview.py action_specs\\<motion>.json+ tools\\GVHMR\\.venv\\Scripts\\python.exe pipeline\\render_preview.py action_specs\\<motion>.json --showcase++Outputs into the spec's clip_dir:+ preview.mp4 the retarget alone (front camera, Workbench, 30 fps)+ showcase.mp4 (--showcase) source plate left, retarget right,+ time-aligned, labeled — the proof-of-fidelity video++The source video for --showcase is auto-discovered as the first .mp4+next to the spec's landmarks file (override with --video). Frames are+rendered through a temporary camera that is removed afterwards; the+Blender window may be occluded or minimized (offscreen render).+"""++from __future__ import annotations++import argparse+import json+import sys+import tempfile+from pathlib import Path++import av+import cv2+import numpy as np+from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parent))+from blender_exec import execute_file # noqa: E402++REPO = Path(__file__).resolve().parents[1]++RENDER_SEQ = """import bpy, math+from mathutils import Vector+scene = bpy.context.scene+cam_data = bpy.data.cameras.new("QA_Camera")+cam = bpy.data.objects.new("QA_Camera", cam_data)+scene.collection.objects.link(cam)+old = (scene.camera, scene.render.engine, scene.render.filepath,+ scene.render.resolution_x, scene.render.resolution_y)+try:+ scene.camera = cam+ cam.location = Vector((0.0, -4.6, 1.05))+ cam.rotation_euler = (math.radians(90), 0.0, 0.0)+ scene.render.engine = "BLENDER_WORKBENCH"+ scene.render.resolution_x, scene.render.resolution_y = 960, 720+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = "PNG"+ scene.render.filepath = r"{outdir}" + "\\\\f####"+ bpy.ops.render.render(animation=True)+finally:+ (scene.camera, scene.render.engine, scene.render.filepath,+ scene.render.resolution_x, scene.render.resolution_y) = old+ bpy.data.objects.remove(cam)+ bpy.data.cameras.remove(cam_data)+result = {{"frames": scene.frame_end}}+"""+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def encode(files: list[Path], out: Path, fps: int, width: int, height: int, make_frame) -> None:+ container = av.open(str(out), "w")+ stream = container.add_stream("libx264", rate=fps)+ stream.width, stream.height = width, height+ stream.pix_fmt = "yuv420p"+ stream.options = {"crf": "19"}+ for i, f in enumerate(files):+ frame = av.VideoFrame.from_ndarray(make_frame(i, f), format="rgb24")+ for pkt in stream.encode(frame):+ container.mux(pkt)+ for pkt in stream.encode():+ container.mux(pkt)+ container.close()+++def label(img, text):+ cv2.putText(img, text, (22, 42), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 5, cv2.LINE_AA)+ cv2.putText(img, text, (22, 42), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA)+ return img+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("spec")+ ap.add_argument("--showcase", action="store_true", help="also build the side-by-side against the source plate")+ ap.add_argument("--video", help="source plate video (default: first .mp4 next to the spec's landmarks)")+ ap.add_argument("--keep-frames", action="store_true")+ args = ap.parse_args()++ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))+ clip_dir = rpath(spec["clip_dir"])+ clip_dir.mkdir(parents=True, exist_ok=True)+ frames_dir = clip_dir / "preview_frames"+ frames_dir.mkdir(exist_ok=True)++ # 1. PNG sequence from the live Blender.+ code = RENDER_SEQ.format(outdir=str(frames_dir))+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:+ f.write(code)+ tmp = f.name+ try:+ res = execute_file(tmp, 600.0)+ finally:+ Path(tmp).unlink(missing_ok=True)+ if res.get("status") != "ok":+ raise SystemExit(res.get("message", "render failed"))++ files = sorted(frames_dir.glob("f*.png"))+ if not files:+ raise SystemExit(f"no frames rendered in {frames_dir}")++ # 2. preview.mp4+ dst_fps = int(spec.get("dst_fps", 30))+ encode(files, clip_dir / "preview.mp4", dst_fps, 960, 720,+ lambda i, f: np.asarray(Image.open(f).convert("RGB")))+ print("wrote", clip_dir / "preview.mp4", f"({len(files)} frames)")++ # 3. showcase.mp4+ if args.showcase:+ video = Path(args.video) if args.video else None+ if video is None:+ plate_dir = rpath(spec["landmarks"]).parent+ mp4s = sorted(plate_dir.glob("*.mp4"))+ if not mp4s:+ raise SystemExit(f"no source .mp4 found in {plate_dir}; pass --video")+ video = mp4s[0]+ cap = cv2.VideoCapture(str(video))+ src_fps = cap.get(cv2.CAP_PROP_FPS) or float(spec.get("src_fps", 24))+ src = []+ while True:+ ok, img = cap.read()+ if not ok:+ break+ src.append(img)+ cap.release()+ sh, sw = src[0].shape[:2]+ scale = 720.0 / sh+ sw = int(sw * scale)+ W = sw + 4 + 960++ def make(i, f):+ si = min(len(src) - 1, int(round(i / dst_fps * src_fps)))+ left = label(cv2.resize(src[si], (sw, 720)), "SOURCE")+ right = label(cv2.imread(str(f)), "MIXAMO RETARGET")+ canvas = np.hstack([left, np.full((720, 4, 3), 40, np.uint8), right])+ return cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)++ encode(files, clip_dir / "showcase.mp4", dst_fps, W, 720, make)+ print("wrote", clip_dir / "showcase.mp4", f"(source: {video.name})")++ if not args.keep_frames:+ for f in files:+ f.unlink()+ frames_dir.rmdir()+++if __name__ == "__main__":+ main()diff --git a/pipeline/run_in_blender.py b/pipeline/run_in_blender.pynew file mode 100644index 0000000..a72bc33--- /dev/null+++ b/pipeline/run_in_blender.py@@ -0,0 +1,88 @@+"""One-command driver for the Blender-side stages — no hand-written+snippets. Talks to the live Blender through the MCP add-on socket.++Usage (any Python, Blender open on your rig scene):++ python pipeline\\run_in_blender.py apply action_specs\\<motion>.json+ python pipeline\\run_in_blender.py curves action_specs\\<motion>.json+ python pipeline\\run_in_blender.py stills action_specs\\<motion>.json [--frames 1,30,60]+ python pipeline\\run_in_blender.py all action_specs\\<motion>.json++`apply` keys the action (Blender's UI freezes for a few minutes on a+300-frame clip — normal). `stills` defaults to the spec's+`qa_src_frames` converted to destination frames. `all` runs the three+in sequence. Exit code is nonzero on any in-Blender error.+"""++from __future__ import annotations++import argparse+import json+import sys+import tempfile+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from blender_exec import execute_file # noqa: E402++REPO = Path(__file__).resolve().parents[1]+PIPELINE = REPO / "pipeline"++TEMPLATE = """import importlib, sys+sys.path.insert(0, r"{pipeline}")+import apply_mixamo_fk+importlib.reload(apply_mixamo_fk)+{body}+"""++BODIES = {+ "apply": 'r = apply_mixamo_fk.run("{spec}")\n'+ 'result = {{"action": r["action"], "frames": r["frames"], "constraints": r["constraints"]}}',+ "curves": 'result = apply_mixamo_fk.dump_curves("{spec}")',+ "stills": 'result = apply_mixamo_fk.run_stills_render("{spec}", {frames})',+}++TIMEOUTS = {"apply": 600.0, "curves": 400.0, "stills": 400.0}+++def dest_frames_from_spec(spec: dict) -> list[int]:+ src_fps = float(spec.get("src_fps", 24))+ dst_fps = float(spec.get("dst_fps", 30))+ return sorted({max(1, int(round((sf - 1) * dst_fps / src_fps + 1)))+ for sf in spec.get("qa_src_frames", [1])})+++def run_stage(stage: str, spec_path: str, frames: list[int]) -> None:+ body = BODIES[stage].format(spec=spec_path.replace("\\", "/"), frames=frames)+ code = TEMPLATE.format(pipeline=PIPELINE, body=body)+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:+ f.write(code)+ tmp = f.name+ try:+ res = execute_file(tmp, TIMEOUTS[stage])+ finally:+ Path(tmp).unlink(missing_ok=True)+ print(f"[{stage}]", json.dumps(res.get("result", res), indent=1))+ if res.get("status") != "ok":+ print(res.get("message", ""), file=sys.stderr)+ sys.exit(1)+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("stage", choices=["apply", "curves", "stills", "all"])+ ap.add_argument("spec")+ ap.add_argument("--frames", help="comma-separated dest frames for stills (default: spec qa frames)")+ args = ap.parse_args()++ spec_path = args.spec+ spec = json.loads((Path(spec_path) if Path(spec_path).is_absolute() else REPO / spec_path).read_text(encoding="utf-8"))+ frames = ([int(x) for x in args.frames.split(",")] if args.frames else dest_frames_from_spec(spec))++ stages = ["apply", "curves", "stills"] if args.stage == "all" else [args.stage]+ for s in stages:+ run_stage(s, spec_path, frames)+++if __name__ == "__main__":+ main()