Retarget human motion from video to an Adobe Mixamo-rigged 3D character.
Python
Add --set-extractor in cli
MaxLiubf79f515373d
diff --git a/motion2mixamorig/checks.py b/motion2mixamorig/checks.pyindex 11335ab..ba2cbd1 100644--- a/motion2mixamorig/checks.py+++ b/motion2mixamorig/checks.py@@ -188,11 +188,22 @@ def check_skeleton_npz(path: Path) -> str | None:try:with np.load(path, allow_pickle=True) as data:missing = {"joints_3d", "joint_names", "fps"} - set(data.keys())+ if missing:+ return (+ f"is missing {sorted(missing)} — pass the skeleton_motion.npz "+ "found inside a previous run's output directory"+ )+ joints = np.asarray(data["joints_3d"])+ names = [str(x) for x in data["joint_names"]]except Exception:return "is not a valid .npz file"- if missing:+ from .extractors.base import SMPL_JOINT_NAMES++ if names != list(SMPL_JOINT_NAMES):return (- f"is missing {sorted(missing)} — pass the skeleton_motion.npz "- "found inside a previous run's output directory"+ "joint_names are not the 24 SMPL joints this pipeline retargets "+ "— pass the skeleton_motion.npz from a previous run")+ if joints.ndim != 3 or tuple(joints.shape[1:]) != (len(SMPL_JOINT_NAMES), 3):+ return f"joints_3d must be (frames, 24, 3), got {getattr(joints, 'shape', None)}"return Nonediff --git a/motion2mixamorig/cli.py b/motion2mixamorig/cli.pyindex 6426c85..77626e7 100644--- a/motion2mixamorig/cli.py+++ b/motion2mixamorig/cli.py@@ -4,6 +4,7 @@m2mr run latest video in assets/video/ + default Y Botm2mr run --video V --rig R pick the inputs explicitly (flags combine freely)m2mr run --image I --rig R still photo -> 3D pose on the same Mixamo path+ m2mr run --set-extractor NAME choose how the skeleton is recovered (default: gvhmr)`m2mr run` performs the same asset checks as `m2mr doctor` before doing anywork, and reports everything that is missing in one pass.@@ -16,6 +17,7 @@ import sysfrom pathlib import Pathfrom . import checks, paths+from .extractors import DEFAULT_EXTRACTOR, extractor_names, get_extractorfrom .progress import ProgressWriterfrom .run_report import write_failed_report@@ -23,10 +25,6 @@ OK = "[ok] "MISS = "[missing]"BAD = "[invalid]"-SMPLX_HINT = (- "register at https://smpl-x.is.tue.mpg.de/ , download SMPLX_NEUTRAL.npz, "- "place it at assets/body_models/smplx/SMPLX_NEUTRAL.npz"-)RIG_HINT = ("download a character from https://www.mixamo.com/ (FBX Binary, T-pose) ""into assets/mixamo/ , e.g. Y_Bot.fbx"@@ -58,6 +56,16 @@ def _check_content(label: str, path: Path, checker) -> bool:return problem is None+def _report_requirement(item) -> bool:+ if item.ok:+ print(f"{OK} {item.label}")+ return True+ print(f"{BAD if item.invalid else MISS} {item.label}")+ if item.hint:+ print(f" -> {item.hint}")+ return False++def _module_available(name: str) -> bool:import importlib.util@@ -68,16 +76,22 @@ def _available_rigs() -> list[Path]:return sorted(paths.MIXAMO_DIR.glob("*.fbx")) if paths.MIXAMO_DIR.is_dir() else []-def doctor() -> int:+def doctor(extractor_name: str | None = None) -> int:"""Check every user-supplied asset and dependency; say where to get what's missing."""print(f"project root: {paths.PROJECT_ROOT}\n")- ok = True- smplx_label = f"SMPL-X body model {paths.SMPLX_NEUTRAL.relative_to(paths.PROJECT_ROOT)}"- if paths.SMPLX_NEUTRAL.exists():- ok &= _check_content(smplx_label, paths.SMPLX_NEUTRAL, checks.check_smplx)- else:- ok &= _check(smplx_label, False, SMPLX_HINT)+ name = extractor_name or DEFAULT_EXTRACTOR+ try:+ extractor = get_extractor(name)+ except ValueError as exc:+ print(f"{BAD} motion extractor {name}")+ print(f" -> {exc}")+ return 1+ requirements = extractor.check()+ ok = _check(f"motion extractor {name}", True, "")+ for item in requirements:+ if item.section == "asset" and item.audience in ("doctor", "both"):+ ok &= _report_requirement(item)rigs = _available_rigs()ok &= _check(f"Mixamo rig .fbx assets/mixamo/ ({len(rigs)} found"@@ -109,10 +123,11 @@ def doctor() -> int:for module, hint in (("numpy", "pip install -e ."),("cv2", "pip install -e ."),- ("torch", "pip install -e ."),- ("gvhmr", "pip install -e ."),):deps_ok &= _check(f"python module {module}", _module_available(module), hint)+ for item in requirements:+ if item.section == "module" and item.audience in ("doctor", "both"):+ deps_ok &= _report_requirement(item)import shutil as _shutil_check(@@ -121,10 +136,8 @@ def doctor() -> int:"brew install ffmpeg / apt install ffmpeg — runs fine without, but videos are silent mp4v",)- weights_note = (- "downloaded automatically into weights/ on the first `m2mr run` (~5 GB)"- )- print(f"\ninference weights: {weights_note}")+ if extractor.weights_note:+ print(f"\ninference weights: {extractor.weights_note}")if ok and deps_ok:print("\neverything in place — try: m2mr run")@@ -232,7 +245,7 @@ def preflight(args: argparse.Namespace) -> tuple[Path | None, Path, Path | None,)check_content(f"rig is Mixamo {rig.name if rig else ''}", rig, checks.check_rig)- # Skeleton reuse skips extraction; only then is SMPL-X not needed.+ # Skeleton reuse skips extraction; only then is the extractor's model check skipped.skeleton = Path(args.skeleton) if args.skeleton else Noneif skeleton is not None:check(@@ -242,14 +255,17 @@ def preflight(args: argparse.Namespace) -> tuple[Path | None, Path, Path | None,)check_content(f"skeleton loads {skeleton.name}", skeleton, checks.check_skeleton_npz)else:- check(- f"SMPL-X body model {paths.SMPLX_NEUTRAL.relative_to(paths.PROJECT_ROOT)}",- paths.SMPLX_NEUTRAL.exists(),- SMPLX_HINT,- )- check_content(- "SMPL-X loads SMPLX_NEUTRAL.npz", paths.SMPLX_NEUTRAL, checks.check_smplx- )+ chosen_name = getattr(args, "set_extractor", None) or DEFAULT_EXTRACTOR+ try:+ chosen = get_extractor(chosen_name)+ except ValueError as exc:+ check("motion extractor --set-extractor", False, str(exc))+ else:+ check(f"motion extractor {chosen_name}", True, "")+ for item in chosen.check():+ if item.section == "asset" and item.audience in ("preflight", "both"):+ if not _report_requirement(item):+ problems += 1if problems:print(f"\n{problems} problem(s) — nothing was run. `m2mr doctor` checks everything.")@@ -288,6 +304,7 @@ def run(args: argparse.Namespace) -> int:rig,image=image,device=args.device,+ extractor=getattr(args, "set_extractor", None) or DEFAULT_EXTRACTOR,skeleton_npz=skeleton,output_dir=output_dir,progress=progress,@@ -313,7 +330,8 @@ def build_parser() -> argparse.ArgumentParser:)sub = parser.add_subparsers(dest="command", required=True)- sub.add_parser("doctor", help="check assets, weights and dependencies")+ p_doctor = sub.add_parser("doctor", help="check assets, weights and dependencies")+ _add_extractor_arg(p_doctor)p_run = sub.add_parser("run", help="video or still -> Mixamo rig, results in outputs/")p_run.add_argument(@@ -338,6 +356,7 @@ def build_parser() -> argparse.ArgumentParser:"--skeleton",help="reuse a previous run's skeleton_motion.npz and skip extraction",)+ _add_extractor_arg(p_run)p_run.add_argument("--device",default="cpu",@@ -360,11 +379,23 @@ def build_parser() -> argparse.ArgumentParser:return parser+def _add_extractor_arg(parser: argparse.ArgumentParser) -> None:+ parser.add_argument(+ "--set-extractor",+ default=DEFAULT_EXTRACTOR,+ choices=list(extractor_names()),+ help=(+ "how to turn the video or still into skeleton_motion.npz "+ f"(default: {DEFAULT_EXTRACTOR})"+ ),+ )++def main() -> None:parser = build_parser()args = parser.parse_args()if args.command == "doctor":- sys.exit(doctor())+ sys.exit(doctor(getattr(args, "set_extractor", None)))sys.exit(run(args))diff --git a/motion2mixamorig/extract.py b/motion2mixamorig/extract.pyindex dd2e564..3b82155 100644--- a/motion2mixamorig/extract.py+++ b/motion2mixamorig/extract.py@@ -1,58 +1,13 @@-"""Video or still -> 3D human skeleton (GVHMR world-grounded motion recovery).+"""Clip timing helpers shared by extraction and preview rendering.-Produces skeleton_motion.npz with 24 SMPL joints per frame in a Y-up,-meter-scaled world, plus the root translation/orientation and fps.--A still photo is repeated into a short hold clip first: GVHMR is a temporal-model and a one-frame "video" is too short to recover a stable pose.+Motion recovery lives in ``motion2mixamorig.extractors``. Preview rendering+reads the container frame rate from here so a 60 fps source is not played+back at the model's own rate."""from __future__ import annotations-from contextlib import contextmanagerfrom pathlib import Path-from typing import Iterator--import numpy as np--from .paths import VIDEO_SUFFIXES, export_gvhmr_env--# SMPL 24-joint order used by GVHMR (J_regressor).-SMPL_JOINT_NAMES = [- "pelvis",- "left_hip",- "right_hip",- "spine1",- "left_knee",- "right_knee",- "spine2",- "left_ankle",- "right_ankle",- "spine3",- "left_foot",- "right_foot",- "neck",- "left_collar",- "right_collar",- "head",- "left_shoulder",- "right_shoulder",- "left_elbow",- "right_elbow",- "left_wrist",- "right_wrist",- "left_hand",- "right_hand",-]--# GVHMR is a temporal model: a one-frame "video" is too short and often-# unstable. Repeating the still for about a second gives it a static clip-# without inventing motion, and the preview / .glb then hold the pose.-HOLD_FRAMES = 32-HOLD_FPS = 30.0-# Phone photos are often 4000px+; YOLO / RTMPose do not need that, and a-# huge still makes the hold-video encode the slow part of an image run.-HOLD_MAX_SIDE = 1920def video_duration_seconds(path: Path) -> float | None:@@ -185,248 +140,3 @@ def playback_fps(video: Path, n_motion_frames: int, fallback: float = 30.0) -> fif native and native > 0:return float(native)return float(fallback) if fallback > 0 else 30.0---def _to_numpy(x):- if hasattr(x, "detach"):- return x.detach().cpu().numpy()- return np.asarray(x)---def joints_world_from_smplx(params, device: str = "cpu") -> np.ndarray:- """Convert GVHMR SMPL-X params to 24 SMPL joints without the gated SMPL .pkl.-- Official ``result.joints_world`` also loads SMPL faces from- ``SMPL_NEUTRAL.pkl``. The joint math itself only needs SMPL-X plus the- shipped ``smplx2smpl`` / ``J_regressor`` maps.- """- import torch- from einops import einsum- from gvhmr import PROJ_ROOT- from gvhmr.utils.device import to_device- from gvhmr.utils.smplx_utils import make_smplx-- if device == "mps":- device = "cpu"- torch_device = torch.device(device)- smplx = make_smplx("supermotion").to(torch_device)- smplx2smpl = torch.load(- PROJ_ROOT / "gvhmr/utils/body_model/smplx2smpl_sparse.pt",- weights_only=False,- ).to(torch_device)- j_regressor = torch.load(- PROJ_ROOT / "gvhmr/utils/body_model/smpl_neutral_J_regressor.pt",- weights_only=False,- ).to(torch_device)- with torch.no_grad():- out = smplx(**to_device(dict(params), torch_device))- verts = torch.stack([torch.matmul(smplx2smpl, v) for v in out.vertices])- joints = einsum(j_regressor, verts, "j v, l v i -> l j i")- return joints.cpu().numpy().astype(np.float32)---def _stabilize_pose_cache(pose_cache: Path) -> bool:- """Stabilize GVHMR's 2D-pose cache in place. True if the file changed.-- Idempotent: a cache that was already stabilized comes back unchanged. The- pre-stabilization data is kept next to it (*_raw) so estimator-vs-- stabilizer questions stay answerable after the fact.- """- import shutil-- import torch-- from .stabilize_kp2d import stabilize_coco17-- current = torch.load(pose_cache, weights_only=False)- # Always stabilize the estimator's own output: a cache written by an older- # rule must not be stabilized a second time on top of its earlier swaps.- raw_backup = pose_cache.with_name(pose_cache.stem + "_raw" + pose_cache.suffix)- source = torch.load(raw_backup, weights_only=False) if raw_backup.exists() else current- fixed, swaps = stabilize_coco17(source)- if np.allclose(fixed, _to_numpy(current).astype(np.float32)):- return False- if not raw_backup.exists():- shutil.copy2(pose_cache, raw_backup)- torch.save(torch.from_numpy(fixed), pose_cache)- print(f"stabilized {pose_cache.name}: corrected {int(swaps.sum())}/{len(swaps)} left/right flips")- return True---def still_to_hold_video(- image: Path,- out_mp4: Path,- *,- n_frames: int = HOLD_FRAMES,- fps: float = HOLD_FPS,-) -> Path:- """Repeat a still as a short silent mp4 so GVHMR can treat it as a clip."""- import shutil- import subprocess-- import cv2-- image = Path(image)- frame = cv2.imread(str(image), cv2.IMREAD_COLOR)- if frame is None:- raise ValueError(f"cannot decode image: {image}")-- h, w = frame.shape[:2]- longest = max(h, w)- if longest > HOLD_MAX_SIDE:- scale = HOLD_MAX_SIDE / longest- w = int(round(w * scale))- h = int(round(h * scale))- frame = cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)- h, w = frame.shape[:2]- w -= w % 2- h -= h % 2- if w < 2 or h < 2:- raise ValueError(f"image is too small: {image}")- frame = frame[:h, :w]-- out_mp4 = Path(out_mp4)- out_mp4.parent.mkdir(parents=True, exist_ok=True)-- ffmpeg = shutil.which("ffmpeg")- if ffmpeg is not None:- cmd = [- ffmpeg, "-y", "-loglevel", "error",- "-f", "rawvideo", "-pix_fmt", "bgr24",- "-s", f"{w}x{h}", "-r", f"{fps:g}",- "-i", "-",- "-frames:v", str(n_frames),- "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",- "-preset", "veryfast", "-movflags", "+faststart",- str(out_mp4),- ]- proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)- assert proc.stdin is not None- for _ in range(n_frames):- proc.stdin.write(frame.tobytes())- proc.stdin.close()- if proc.wait() != 0:- raise RuntimeError(f"ffmpeg failed writing {out_mp4}")- return out_mp4-- writer = cv2.VideoWriter(- str(out_mp4), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)- )- if not writer.isOpened():- raise RuntimeError(f"Cannot open VideoWriter for {out_mp4}")- for _ in range(n_frames):- writer.write(frame)- writer.release()- return out_mp4---@contextmanager-def temp_hold_video(image: Path) -> Iterator[Path]:- """Write the hold clip under the system temp dir; delete it afterwards.-- GVHMR needs a real video file, but that file is not a run artifact and- must not land in cache/.- """- import shutil- import tempfile-- tmp = Path(tempfile.mkdtemp(prefix="m2mr-hold-"))- try:- yield still_to_hold_video(image, tmp / f"{Path(image).stem}.mp4")- finally:- shutil.rmtree(tmp, ignore_errors=True)---def _strip_cache_videos(root: Path) -> None:- """Drop staged / overlay mp4s from a still-image extract.-- GVHMR always stages ``0_input_video.mp4`` (and may write overlay clips- under preprocess/). Those are only useful for a video run.- """- if not root.is_dir():- return- for path in root.rglob("*"):- if path.suffix.lower() in VIDEO_SUFFIXES and (path.is_file() or path.is_symlink()):- path.unlink(missing_ok=True)---def extract_motion(- video: Path,- output_npz: Path,- *,- work_dir: Path,- device: str = "cpu",- static_camera: bool = True,- verbose: bool = True,- source_image: Path | None = None,-) -> Path:- """Run GVHMR on `video` and save skeleton_motion.npz to `output_npz`.-- `work_dir` holds GVHMR's per-video intermediates (2D pose cache, 3D lift).- Re-running with the same work_dir reuses the expensive passes.- `source_image` is recorded when the clip was built from a still.- """- export_gvhmr_env()- import gvhmr-- video = Path(video).resolve()- if not video.exists():- raise FileNotFoundError(video)-- output_dir = Path(work_dir) / video.stem-- def recover():- return gvhmr.recover(- str(video),- static_camera=static_camera,- device=device,- pose2d="rtmpose",- output_dir=str(output_dir),- output_root=str(work_dir),- progress=verbose,- )-- result = recover()-- # RTMPose labels left/right per frame and mislabels isolated frames, which- # spins the recovered 3D heading for those frames. Stabilize the 2D cache- # (segment majority, see stabilize_kp2d.py) and redo the 3D lift once if- # anything was corrected.- pose_cache = output_dir / "preprocess" / "vitpose.pt"- if pose_cache.exists() and _stabilize_pose_cache(pose_cache):- motion_cache = output_dir / "hmr4d_results.pt"- motion_cache.unlink(missing_ok=True)- result = recover()-- world = result.smpl_params_world- joints_3d = joints_world_from_smplx(world, device=device)- root_translation = _to_numpy(world["transl"]).astype(np.float32)- root_orientation = _to_numpy(world["global_orient"]).astype(np.float32)- reported = float(getattr(result, "fps", 0) or 0)- fps = playback_fps(video, len(joints_3d), fallback=reported or HOLD_FPS)- if verbose and reported > 0 and abs(fps - reported) > 1.5:- print(- f"source is {fps:.3g} fps ({len(joints_3d)} frames); "- f"GVHMR reported {reported:g} fps — using the source rate so playback matches the video"- )- timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(fps)-- output_npz = Path(output_npz)- output_npz.parent.mkdir(parents=True, exist_ok=True)- payload = dict(- joints_3d=joints_3d,- joint_names=np.array(SMPL_JOINT_NAMES),- fps=np.float32(fps),- timestamps=timestamps,- root_translation=root_translation,- root_orientation=root_orientation,- camera=np.array(result.camera),- video=np.array(str(video)),- )- if source_image is not None:- payload["image"] = np.array(str(source_image))- _strip_cache_videos(output_dir)- np.savez_compressed(output_npz, **payload)- if verbose:- print(f"saved {output_npz}")- return output_npzdiff --git a/motion2mixamorig/extractors/__init__.py b/motion2mixamorig/extractors/__init__.pynew file mode 100644index 0000000..6a1b391--- /dev/null+++ b/motion2mixamorig/extractors/__init__.py@@ -0,0 +1,24 @@+"""Motion extractors. Each one reads a video or a still and writes skeleton_motion.npz."""++from __future__ import annotations++from .base import MotionExtractor+from .gvhmr import GvhmrExtractor++DEFAULT_EXTRACTOR = "gvhmr"++_EXTRACTORS: dict[str, MotionExtractor] = {+ GvhmrExtractor.name: GvhmrExtractor(),+}+++def extractor_names() -> tuple[str, ...]:+ return tuple(_EXTRACTORS)+++def get_extractor(name: str) -> MotionExtractor:+ try:+ return _EXTRACTORS[name]+ except KeyError as exc:+ choices = ", ".join(extractor_names())+ raise ValueError(f"unknown extractor {name!r}; choose from {choices}") from excdiff --git a/motion2mixamorig/extractors/base.py b/motion2mixamorig/extractors/base.pynew file mode 100644index 0000000..c476959--- /dev/null+++ b/motion2mixamorig/extractors/base.py@@ -0,0 +1,144 @@+"""The skeleton file every extractor must write.++Input is a video or a still. Output is ``skeleton_motion.npz``: 24 SMPL joints,+Y-up metres, one continuous world frame for the whole clip, the order in+``SMPL_JOINT_NAMES``. Retargeting reads that file and does not care which+extractor produced it.++A new extractor maps its own joints into these 24 names, in metres, before+writing. ``root_orientation`` is optional metadata; retargeting uses joint+positions, not that rotation.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Protocol++import numpy as np++# SMPL 24-joint order. Retargeting looks joints up by these names.+SMPL_JOINT_NAMES = (+ "pelvis",+ "left_hip",+ "right_hip",+ "spine1",+ "left_knee",+ "right_knee",+ "spine2",+ "left_ankle",+ "right_ankle",+ "spine3",+ "left_foot",+ "right_foot",+ "neck",+ "left_collar",+ "right_collar",+ "head",+ "left_shoulder",+ "right_shoulder",+ "left_elbow",+ "right_elbow",+ "left_wrist",+ "right_wrist",+ "left_hand",+ "right_hand",+)+++@dataclass(frozen=True)+class CheckResult:+ """One doctor / preflight line owned by an extractor.++ ``section="asset"`` is a file the run needs. ``section="module"`` is a+ Python dependency, reported by ``m2mr doctor``. ``audience`` picks which+ command prints the line: doctor and preflight lay the same fact out+ differently, and ``both`` prints it in each.+ ``invalid`` prints ``[invalid]`` rather than ``[missing]``.+ """++ label: str+ ok: bool+ hint: str = ""+ section: str = "asset"+ audience: str = "both"+ invalid: bool = False+++class MotionExtractor(Protocol):+ """Turn a video or a still into ``skeleton_motion.npz``."""++ name: str+ weights_note: str++ def check(self) -> list[CheckResult]:+ """Assets and modules this extractor needs, for doctor and preflight."""++ def extract(+ self,+ source: Path,+ output_npz: Path,+ *,+ work_dir: Path,+ device: str = "cpu",+ verbose: bool = True,+ ) -> Path:+ """Write the shared skeleton file for `source` (a video or a still)."""+++def write_skeleton_npz(+ path: Path,+ *,+ extractor: str,+ joints_3d: np.ndarray,+ fps: float,+ timestamps: np.ndarray | None = None,+ root_translation: np.ndarray | None = None,+ root_orientation: np.ndarray | None = None,+ **extra,+) -> Path:+ """Write the shared skeleton file. Joint names are always ``SMPL_JOINT_NAMES``."""+ joints = np.asarray(joints_3d)+ expected = (len(SMPL_JOINT_NAMES), 3)+ if joints.ndim != 3 or tuple(joints.shape[1:]) != expected:+ raise ValueError(+ f"joints_3d must be (frames, {expected[0]}, 3), got {joints.shape}"+ )+ fps_value = float(fps)+ if not fps_value > 0:+ raise ValueError(f"fps must be positive, got {fps}")+ if timestamps is None:+ stamps = np.arange(len(joints), dtype=np.float64) / fps_value+ else:+ stamps = np.asarray(timestamps, dtype=np.float64)+ if len(stamps) != len(joints):+ raise ValueError(+ f"timestamps length {len(stamps)} does not match {len(joints)} frames"+ )+ payload: dict = {+ "joints_3d": joints,+ "joint_names": np.array(SMPL_JOINT_NAMES),+ "fps": np.float32(fps_value),+ "timestamps": stamps,+ "extractor": np.array(extractor),+ }+ if root_translation is not None:+ payload["root_translation"] = np.asarray(root_translation)+ if root_orientation is not None:+ payload["root_orientation"] = np.asarray(root_orientation)+ for key, value in extra.items():+ if value is not None:+ payload[key] = value+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ np.savez_compressed(path, **payload)+ return path+++def read_extractor_name(path: Path) -> str | None:+ """The extractor recorded in a skeleton file, if this pipeline wrote it."""+ with np.load(path, allow_pickle=True) as data:+ if "extractor" not in data.files:+ return None+ return str(data["extractor"])diff --git a/motion2mixamorig/extractors/gvhmr.py b/motion2mixamorig/extractors/gvhmr.pynew file mode 100644index 0000000..c7f64d8--- /dev/null+++ b/motion2mixamorig/extractors/gvhmr.py@@ -0,0 +1,366 @@+"""GVHMR extractor: a video or still -> skeleton_motion.npz.++A still is repeated into a short hold clip first. GVHMR is a temporal model+and a one-frame "video" is too short to recover a stable pose. Torch and+``gvhmr`` are imported only when a check or an extract actually needs them.+"""++from __future__ import annotations++import importlib.util+from contextlib import contextmanager+from pathlib import Path+from typing import Iterator++import numpy as np++from .. import paths+from ..extract import playback_fps+from .base import CheckResult, write_skeleton_npz++# GVHMR is a temporal model: a one-frame "video" is too short and often+# unstable. Repeating the still for about a second gives it a static clip+# without inventing motion, and the preview / .glb then hold the pose.+HOLD_FRAMES = 32+HOLD_FPS = 30.0+# Phone photos are often 4000px+; YOLO / RTMPose do not need that, and a+# huge still makes the hold-video encode the slow part of an image run.+HOLD_MAX_SIDE = 1920++SMPLX_HINT = (+ "register at https://smpl-x.is.tue.mpg.de/ , download SMPLX_NEUTRAL.npz, "+ "place it at assets/body_models/smplx/SMPLX_NEUTRAL.npz"+)+++def _module_available(name: str) -> bool:+ return importlib.util.find_spec(name) is not None+++def _to_numpy(x):+ if hasattr(x, "detach"):+ return x.detach().cpu().numpy()+ return np.asarray(x)+++def joints_world_from_smplx(params, device: str = "cpu") -> np.ndarray:+ """Convert GVHMR SMPL-X params to 24 SMPL joints without the gated SMPL .pkl.++ Official ``result.joints_world`` also loads SMPL faces from+ ``SMPL_NEUTRAL.pkl``. The joint math itself only needs SMPL-X plus the+ shipped ``smplx2smpl`` / ``J_regressor`` maps.+ """+ import torch+ from einops import einsum+ from gvhmr import PROJ_ROOT+ from gvhmr.utils.device import to_device+ from gvhmr.utils.smplx_utils import make_smplx++ if device == "mps":+ device = "cpu"+ torch_device = torch.device(device)+ smplx = make_smplx("supermotion").to(torch_device)+ smplx2smpl = torch.load(+ PROJ_ROOT / "gvhmr/utils/body_model/smplx2smpl_sparse.pt",+ weights_only=False,+ ).to(torch_device)+ j_regressor = torch.load(+ PROJ_ROOT / "gvhmr/utils/body_model/smpl_neutral_J_regressor.pt",+ weights_only=False,+ ).to(torch_device)+ with torch.no_grad():+ out = smplx(**to_device(dict(params), torch_device))+ verts = torch.stack([torch.matmul(smplx2smpl, v) for v in out.vertices])+ joints = einsum(j_regressor, verts, "j v, l v i -> l j i")+ return joints.cpu().numpy().astype(np.float32)+++def _stabilize_pose_cache(pose_cache: Path) -> bool:+ """Stabilize GVHMR's 2D-pose cache in place. True if the file changed.++ Idempotent: a cache that was already stabilized comes back unchanged. The+ pre-stabilization data is kept next to it (*_raw) so estimator-vs-+ stabilizer questions stay answerable after the fact.+ """+ import shutil++ import torch++ from ..stabilize_kp2d import stabilize_coco17++ current = torch.load(pose_cache, weights_only=False)+ # Always stabilize the estimator's own output: a cache written by an older+ # rule must not be stabilized a second time on top of its earlier swaps.+ raw_backup = pose_cache.with_name(pose_cache.stem + "_raw" + pose_cache.suffix)+ source = torch.load(raw_backup, weights_only=False) if raw_backup.exists() else current+ fixed, swaps = stabilize_coco17(source)+ if np.allclose(fixed, _to_numpy(current).astype(np.float32)):+ return False+ if not raw_backup.exists():+ shutil.copy2(pose_cache, raw_backup)+ torch.save(torch.from_numpy(fixed), pose_cache)+ print(f"stabilized {pose_cache.name}: corrected {int(swaps.sum())}/{len(swaps)} left/right flips")+ return True+++def still_to_hold_video(+ image: Path,+ out_mp4: Path,+ *,+ n_frames: int = HOLD_FRAMES,+ fps: float = HOLD_FPS,+) -> Path:+ """Repeat a still as a short silent mp4 so GVHMR can treat it as a clip."""+ import shutil+ import subprocess++ import cv2++ image = Path(image)+ frame = cv2.imread(str(image), cv2.IMREAD_COLOR)+ if frame is None:+ raise ValueError(f"cannot decode image: {image}")++ h, w = frame.shape[:2]+ longest = max(h, w)+ if longest > HOLD_MAX_SIDE:+ scale = HOLD_MAX_SIDE / longest+ w = int(round(w * scale))+ h = int(round(h * scale))+ frame = cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)+ h, w = frame.shape[:2]+ w -= w % 2+ h -= h % 2+ if w < 2 or h < 2:+ raise ValueError(f"image is too small: {image}")+ frame = frame[:h, :w]++ out_mp4 = Path(out_mp4)+ out_mp4.parent.mkdir(parents=True, exist_ok=True)++ ffmpeg = shutil.which("ffmpeg")+ if ffmpeg is not None:+ cmd = [+ ffmpeg, "-y", "-loglevel", "error",+ "-f", "rawvideo", "-pix_fmt", "bgr24",+ "-s", f"{w}x{h}", "-r", f"{fps:g}",+ "-i", "-",+ "-frames:v", str(n_frames),+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",+ "-preset", "veryfast", "-movflags", "+faststart",+ str(out_mp4),+ ]+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)+ assert proc.stdin is not None+ for _ in range(n_frames):+ proc.stdin.write(frame.tobytes())+ proc.stdin.close()+ if proc.wait() != 0:+ raise RuntimeError(f"ffmpeg failed writing {out_mp4}")+ return out_mp4++ writer = cv2.VideoWriter(+ str(out_mp4), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)+ )+ if not writer.isOpened():+ raise RuntimeError(f"Cannot open VideoWriter for {out_mp4}")+ for _ in range(n_frames):+ writer.write(frame)+ writer.release()+ return out_mp4+++@contextmanager+def temp_hold_video(image: Path) -> Iterator[Path]:+ """Write the hold clip under the system temp dir; delete it afterwards.++ GVHMR needs a real video file, but that file is not a run artifact and+ must not land in cache/.+ """+ import shutil+ import tempfile++ tmp = Path(tempfile.mkdtemp(prefix="m2mr-hold-"))+ try:+ yield still_to_hold_video(image, tmp / f"{Path(image).stem}.mp4")+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+++def _strip_cache_videos(root: Path) -> None:+ """Drop staged / overlay mp4s from a still-image extract.++ GVHMR always stages ``0_input_video.mp4`` (and may write overlay clips+ under preprocess/). Those are only useful for a video run.+ """+ if not root.is_dir():+ return+ for path in root.rglob("*"):+ if path.suffix.lower() in paths.VIDEO_SUFFIXES and (path.is_file() or path.is_symlink()):+ path.unlink(missing_ok=True)+++def _smplx_checks() -> list[CheckResult]:+ """SMPL-X lines in the shape doctor and preflight already print."""+ from .. import checks++ label = f"SMPL-X body model {paths.SMPLX_NEUTRAL.relative_to(paths.PROJECT_ROOT)}"+ if not paths.SMPLX_NEUTRAL.exists():+ return [+ CheckResult(label, False, SMPLX_HINT, section="asset", audience="doctor"),+ CheckResult(label, False, SMPLX_HINT, section="asset", audience="preflight"),+ ]+ problem = checks.check_smplx(paths.SMPLX_NEUTRAL)+ if problem is None:+ return [+ CheckResult(label, True, section="asset", audience="doctor"),+ CheckResult(label, True, section="asset", audience="preflight"),+ CheckResult(+ "SMPL-X loads SMPLX_NEUTRAL.npz",+ True,+ section="asset",+ audience="preflight",+ ),+ ]+ hint = f"{paths.SMPLX_NEUTRAL.name} {problem}"+ return [+ CheckResult(label, False, hint, section="asset", audience="doctor", invalid=True),+ CheckResult(label, True, section="asset", audience="preflight"),+ CheckResult(+ "SMPL-X loads SMPLX_NEUTRAL.npz",+ False,+ hint,+ section="asset",+ audience="preflight",+ invalid=True,+ ),+ ]+++class GvhmrExtractor:+ """Recover a world-grounded skeleton with GVHMR."""++ name = "gvhmr"+ weights_note = "downloaded automatically into weights/ on the first `m2mr run` (~5 GB)"++ def check(self) -> list[CheckResult]:+ results = _smplx_checks()+ for module in ("torch", "gvhmr"):+ results.append(+ CheckResult(+ f"python module {module}",+ _module_available(module),+ "pip install -e .",+ section="module",+ audience="doctor",+ )+ )+ return results++ def extract(+ self,+ source: Path,+ output_npz: Path,+ *,+ work_dir: Path,+ device: str = "cpu",+ verbose: bool = True,+ ) -> Path:+ source = Path(source)+ if paths.is_image(source):+ with temp_hold_video(source) as hold:+ return _extract_video(+ hold,+ output_npz,+ work_dir=work_dir,+ device=device,+ verbose=verbose,+ source_image=source,+ )+ return _extract_video(+ source,+ output_npz,+ work_dir=work_dir,+ device=device,+ verbose=verbose,+ )+++def _extract_video(+ video: Path,+ output_npz: Path,+ *,+ work_dir: Path,+ device: str = "cpu",+ static_camera: bool = True,+ verbose: bool = True,+ source_image: Path | None = None,+) -> Path:+ """Run GVHMR on `video` and save skeleton_motion.npz to `output_npz`.++ `work_dir` holds GVHMR's per-video intermediates (2D pose cache, 3D lift).+ Re-running with the same work_dir reuses the expensive passes.+ `source_image` is recorded when the clip was built from a still.+ """+ paths.export_gvhmr_env()+ import gvhmr++ video = Path(video).resolve()+ if not video.exists():+ raise FileNotFoundError(video)++ output_dir = Path(work_dir) / video.stem++ def recover():+ return gvhmr.recover(+ str(video),+ static_camera=static_camera,+ device=device,+ pose2d="rtmpose",+ output_dir=str(output_dir),+ output_root=str(work_dir),+ progress=verbose,+ )++ result = recover()++ # RTMPose labels left/right per frame and mislabels isolated frames, which+ # spins the recovered 3D heading for those frames. Stabilize the 2D cache+ # (segment majority, see stabilize_kp2d.py) and redo the 3D lift once if+ # anything was corrected.+ pose_cache = output_dir / "preprocess" / "vitpose.pt"+ if pose_cache.exists() and _stabilize_pose_cache(pose_cache):+ motion_cache = output_dir / "hmr4d_results.pt"+ motion_cache.unlink(missing_ok=True)+ result = recover()++ world = result.smpl_params_world+ joints_3d = joints_world_from_smplx(world, device=device)+ root_translation = _to_numpy(world["transl"]).astype(np.float32)+ root_orientation = _to_numpy(world["global_orient"]).astype(np.float32)+ reported = float(getattr(result, "fps", 0) or 0)+ fps = playback_fps(video, len(joints_3d), fallback=reported or HOLD_FPS)+ if verbose and reported > 0 and abs(fps - reported) > 1.5:+ print(+ f"source is {fps:.3g} fps ({len(joints_3d)} frames); "+ f"GVHMR reported {reported:g} fps — using the source rate so playback matches the video"+ )+ timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(fps)+ image = None if source_image is None else np.array(str(source_image))+ if source_image is not None:+ _strip_cache_videos(output_dir)+ written = write_skeleton_npz(+ output_npz,+ extractor=GvhmrExtractor.name,+ joints_3d=joints_3d,+ fps=fps,+ timestamps=timestamps,+ root_translation=root_translation,+ root_orientation=root_orientation,+ camera=np.array(result.camera),+ video=np.array(str(video)),+ image=image,+ )+ if verbose:+ print(f"saved {written}")+ return writtendiff --git a/motion2mixamorig/human_motion.py b/motion2mixamorig/human_motion.pyindex 2e3a389..6877b0b 100644--- a/motion2mixamorig/human_motion.py+++ b/motion2mixamorig/human_motion.py@@ -1,6 +1,6 @@-"""Load the skeleton_motion.npz produced by extract.py.+"""Load the skeleton_motion.npz produced by an extractor.-Human world (GVHMR gravity frame):+Human world (the frame every extractor must write; GVHMR's gravity frame):+Y up, +X right, +Z forward (right-handed), units = meters."""diff --git a/motion2mixamorig/pipeline.py b/motion2mixamorig/pipeline.pyindex eecd82a..c730b73 100644--- a/motion2mixamorig/pipeline.py+++ b/motion2mixamorig/pipeline.py@@ -7,7 +7,7 @@ Everything a run produces lands in its own timestamped folder:├── skeleton_motion.npz 3D human skeleton (24 SMPL joints per frame)├── mixamo_rotations.npz per-bone animation rotations for the rig├── mixamo_character.glb skinned character + animation (Blender / Unity)- ├── cache/ GVHMR intermediates (2D pose, 3D lift)+ ├── cache/ extractor intermediates (GVHMR: 2D pose, 3D lift)└── videos/ or images/ four result clips (video in) or four stills (photo in)"""@@ -22,6 +22,8 @@ import numpy as npfrom . import pathsfrom .errors import classify_error+from .extractors import DEFAULT_EXTRACTOR, get_extractor+from .extractors.base import read_extractor_namefrom .human_motion import HumanMotion, load_human_motionfrom .mixamo.animation import build_animationfrom .mixamo.gltf import write_glb@@ -75,6 +77,7 @@ def run_pipeline(*,image: Path | None = None,device: str = "cpu",+ extractor: str = DEFAULT_EXTRACTOR,skeleton_npz: Path | None = None,verbose: bool = True,output_dir: Path | None = None,@@ -84,9 +87,9 @@ def run_pipeline() -> Path:"""Full pipeline for one video or still + one rig. Returns the run directory.- `skeleton_npz` reuses a previous run's skeleton_motion.npz and skips the- (slow) extraction entirely. A still is turned into a short hold clip so- the same GVHMR path can recover a static 3D pose.+ `extractor` chooses which method writes skeleton_motion.npz. `skeleton_npz`+ reuses a previous run's file and skips extraction entirely. A still is+ handed to the extractor as-is; GVHMR turns it into a short hold clip.`output_dir` writes this run into a caller-chosen folder (used by theBlender extension). When omitted, a timestamped directory is created.@@ -121,26 +124,14 @@ def run_pipeline(shutil.copy2(skeleton_npz, motion_npz)print(f"reusing skeleton from {skeleton_npz}")- elif image is not None:- from .extract import extract_motion, temp_hold_video-- print(f"extracting human pose from {image.name}")- with temp_hold_video(image) as hold:- extract_motion(- hold,- motion_npz,- work_dir=run_dir / "cache",- device=device,- verbose=verbose,- source_image=image,- )else:- from .extract import extract_motion-- assert extract_video is not None- print(f"extracting human motion from {extract_video.name}")- extract_motion(- extract_video,+ if image is not None:+ print(f"extracting human pose from {image.name}")+ else:+ assert video is not None+ print(f"extracting human motion from {video.name}")+ get_extractor(extractor).extract(+ source,motion_npz,work_dir=run_dir / "cache",device=device,@@ -211,6 +202,9 @@ def run_pipeline("image": str(image) if image is not None else None,"rig": str(rig),"device": device,+ "extractor": (+ read_extractor_name(motion_npz) if skeleton_npz is not None else extractor+ ),"fps": float(motion.fps),"n_frames": motion.n_frames,"skeleton_reused_from": str(skeleton_npz) if skeleton_npz else None,