Retarget human motion from video to an Adobe Mixamo-rigged 3D character.
Python
Add --detect-hands to drive Mixamo fingers with HaMeR
MaxLiudf8dadf1ba49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6cc54e8..2661317 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file.## [Unreleased]+### Added++- `m2mr run --detect-hands` turns on the hand model that travels with the body extractor. With the default extractor, GVHMR, that model is HaMeR: it crops the wrists from the person and the frames GVHMR already chose, writes the finger rotations into `skeleton_motion.npz`, and drives the 30 Mixamo finger bones on the skinned character. Off by default; a plain `m2mr run` leaves those bones at rest. A wrist the body pass did not see clearly stays at rest for that hand.+- The flag needs `assets/body_models/mano/MANO_RIGHT.pkl` (register at https://mano.is.tue.mpg.de/ and download Models & Code). The first `m2mr run --detect-hands` downloads the HaMeR weights into `weights/hamer/` (~2.7 GB, once). `m2mr doctor --detect-hands` checks that file and the extra Python packages; `m2mr doctor` without the flag does not.+- A run with `--detect-hands` takes about twice as long as the same clip without it. The extra time is the hand pass on top of the body extraction.+- `--hand-smooth SECONDS` smooths the finger rotations (default `0.08`; `0` keeps the raw estimate). It applies whenever the skeleton file already contains hand motion, including a later `--skeleton` reuse. A reused skeleton that already has hand motion drives the fingers without `--detect-hands`. If it does not, `--detect-hands` can add them only while that run's body cache is still beside the file; otherwise run the video or still again with the flag.+- The README quick start documents `--detect-hands`, the MANO file, the extra runtime, and how reuse behaves.+### Fixed- A subject who turned away and back could stay facing away in the recovered 3D motion for the rest of the clip. The 2D left/right stabilizer decided "real turn or label flip" at the single transition frame (it required four consecutive side-view frames after the first turn) and never revisited the decision, so one mislabelled frame or one fast spin locked the wrong facing in. `motion2mixamorig/stabilize_kp2d.py` now cuts the clip into segments at side-view frames and takes the majority of RTMPose's labels inside each segment; only runs of the opposite sign shorter than ~0.33 s count as flips. No facial keypoints are used (hats and masks do not matter) and each person track is handled on its own. On a dance clip with a fast half-second turn, wrong-facing frames went from 320 of 642 to 3. Re-running on an existing cache re-stabilizes from the `vitpose_raw.pt` backup, not from the previous rule's output.diff --git a/README.md b/README.mdindex 62cdb56..f7633ca 100644--- a/README.md+++ b/README.md@@ -65,7 +65,7 @@ pip install --upgrade pip setuptools wheel \&& pip install -e .```-Inference weights (GVHMR and so on) are not downloaded here. The first `m2mr run` pulls them into `weights/` (~5 GB, once only).+Inference weights are not downloaded here. The first `m2mr run` pulls the GVHMR weights into `weights/` (~5 GB, once only). The first `m2mr run --detect-hands` also pulls the HaMeR hand weights into `weights/hamer/` (~2.7 GB, once only).ffmpeg is recommended (macOS: `brew install ffmpeg`, Ubuntu: `apt install ffmpeg`).The pipeline runs without it, but the output videos will be **silent** and will not play in a browser.@@ -80,6 +80,7 @@ This repository does not ship these files; you have to fetch them. The SMPL-X fi| Mixamo character FBX | `assets/mixamo/Y_Bot.fbx` | With an Adobe account, download Y Bot (or any other Mixamo-rigged character) from [Mixamo](https://www.mixamo.com) || Action video | `assets/video/<your_clip>.mp4` | A clip with **exactly one** clearly visible person, **head to toe in frame the whole time** (you may keep several files; each run uses the most recently added) || Pose still (optional) | `assets/image/<your_photo>.jpg` | A photo with **exactly one** clearly visible person, **head to toe in frame**. Use with `--image` |+| MANO right hand (only for `--detect-hands`) | `assets/body_models/mano/MANO_RIGHT.pkl` | Register at [MANO](https://mano.is.tue.mpg.de/) and download **Models & Code**. A body-only run does not need this file |Note: Mixamo's download is named `Y Bot.fbx` (**space**), one character off from `Y_Bot.fbx` (**underscore**) in the table.Rename it to the underscore form and it becomes the default rig (`m2mr run` without `--rig`). Leaving the space is fine too — if `Y_Bot.fbx` is missing, the first `.fbx` in `assets/mixamo/` is used.@@ -99,6 +100,12 @@ Anything missing is printed with where to download it and where to put it.m2mr doctor```+`m2mr doctor` checks the body run. It does not require the MANO hand model. To check the extra file and Python packages used by finger detection:++```bash+m2mr doctor --detect-hands+```+### 2. First run: get something on screenWith no flags, this uses the **latest file in `assets/video/`** and `assets/mixamo/Y_Bot.fbx`.@@ -139,6 +146,30 @@ m2mr run --image assets/image/pose.jpg --rig assets/mixamo/Vampire.fbx`--image` with no path uses the file most recently added to `assets/image/`.+### 6. Fingers (`--detect-hands`)++A plain `m2mr run` moves the body and leaves the Mixamo finger bones at rest. `--detect-hands` turns on the hand model that travels with the body extractor. With the default extractor, GVHMR, that model is [HaMeR](https://github.com/geopavlakos/hamer). HaMeR crops the wrists from the person and the frames GVHMR already chose. It does not search the clip for a second person.++**This about doubles the runtime.** A clip that finishes in a few minutes without the flag takes about twice that long with `--detect-hands`, because the hand pass runs on top of the body extraction. On a long video, plan for that extra time before you start.++Place `MANO_RIGHT.pkl` as in the table above, then:++```bash+m2mr doctor --detect-hands+m2mr run --detect-hands+m2mr run --video assets/video/dance.mp4 --detect-hands --hand-smooth 0.08+```++The first `--detect-hands` run downloads the HaMeR weights into `weights/hamer/` (~2.7 GB, once). Finger rotations are written into `skeleton_motion.npz` and drive the 30 Mixamo finger bones on the skinned character. A wrist the body pass did not see clearly stays at rest for that hand.++`--hand-smooth` is how many seconds of smoothing to apply to those rotations. The default is `0.08`. `0` keeps the raw estimate. Smoothing runs whenever the skeleton file already contains hand motion, including a later run that only reuses that file.++Reusing a previous skeleton:++- The file already contains hand motion: `--skeleton` drives the fingers by itself. `--detect-hands` is not required again.+- It does not, but that run's body cache is still beside it (`cache/<clip>/0_input_video.mp4`, plus `preprocess/vitpose.pt` and `preprocess/bbx.pt`): `--skeleton ... --detect-hands` adds the fingers without extracting the body again.+- That cache is gone: run the video or still again with `--detect-hands`.+## OutputsEach `m2mr run` creates a directory named by **the time the command started**. The four files at the root are the same for video and still; only the preview folder changes.@@ -176,6 +207,8 @@ images/# right: 10° orbit of the rig (one full turn)```+With `--detect-hands`, `skeleton_motion.npz` also stores the finger rotations, and `mixamo_rotations.npz` / `mixamo_character.glb` include the 30 finger bones. Without that flag, and without hand motion already stored in a reused skeleton, those bones stay at rest.+Open `mixamo_character.glb` in Blender: File → Import → glTF 2.0 (.glb/.gltf). If the camera is framed on empty space, select the character mesh and use View → Frame Selected. The cluster of spheres on the head and hands is bone display, not the mesh: in the Outliner, hide **Icosphere** and the **armature**; leave the skinned mesh visible. Set scene FPS and the timeline end frame from `run.json` (`fps`, `n_frames`) so playback matches the source. Compare a video run against `videos/mixamo_character.mp4`, a still run against `images/mixamo_character.png` or the orbit clip.## License@@ -183,8 +216,10 @@ Open `mixamo_character.glb` in Blender: File → Import → glTF 2.0 (.glb/.gltfThis repository's code is Apache-2.0. The assets you download have their own terms and must not be redistributed with this repo:- **SMPL-X**: MPI-gated; default non-commercial research / education / art; commercial use needs a separate deal+- **MANO** (only if you use `--detect-hands`): MPI-gated, same kind of download as SMPL-X; place `MANO_RIGHT.pkl` locally and do not redistribute it- **Mixamo FBX**: fine in a shipped product; do not redistribute the raw FBX as an asset pack-- **GVHMR and other inference weights**: auto-downloaded into `weights/` on the first `m2mr run`, under each upstream license+- **GVHMR weights**: auto-downloaded into `weights/` on the first `m2mr run`, under the upstream license+- **HaMeR**: the inference code in this repository is MIT; the weights download into `weights/hamer/` on the first `m2mr run --detect-hands`, under the upstream release## Contactdiff --git a/motion2mixamorig/cli.py b/motion2mixamorig/cli.pyindex 77626e7..1b8daaf 100644--- a/motion2mixamorig/cli.py+++ b/motion2mixamorig/cli.py@@ -5,6 +5,7 @@m2mr 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 pathm2mr run --set-extractor NAME choose how the skeleton is recovered (default: gvhmr)+ m2mr run --detect-hands also run that extractor's hand model (GVHMR: HaMeR)`m2mr run` performs the same asset checks as `m2mr doctor` before doing anywork, and reports everything that is missing in one pass.@@ -66,6 +67,22 @@ def _report_requirement(item) -> bool:return False+def _report_hand_model(extractor, name: str, requirements) -> bool:+ """The hand model paired with `extractor`. False when it cannot run."""+ hand_model = getattr(extractor, "hand_model", None)+ if not hand_model:+ return _check(+ "hand detection --detect-hands",+ False,+ f"{name} has no paired hand model",+ )+ ok = _check(f"hand detection {hand_model}", True, "")+ for item in requirements:+ if item.section == "hand":+ ok &= _report_requirement(item)+ return ok++def _module_available(name: str) -> bool:import importlib.util@@ -76,7 +93,7 @@ def _available_rigs() -> list[Path]:return sorted(paths.MIXAMO_DIR.glob("*.fbx")) if paths.MIXAMO_DIR.is_dir() else []-def doctor(extractor_name: str | None = None) -> int:+def doctor(extractor_name: str | None = None, *, detect_hands: bool = False) -> int:"""Check every user-supplied asset and dependency; say where to get what's missing."""print(f"project root: {paths.PROJECT_ROOT}\n")@@ -87,7 +104,7 @@ def doctor(extractor_name: str | None = None) -> int:print(f"{BAD} motion extractor {name}")print(f" -> {exc}")return 1- requirements = extractor.check()+ requirements = extractor.check(detect_hands=detect_hands)ok = _check(f"motion extractor {name}", True, "")for item in requirements:if item.section == "asset" and item.audience in ("doctor", "both"):@@ -118,6 +135,10 @@ def doctor(extractor_name: str | None = None) -> int:for image in images:ok &= _check_content(f" - {image.name}", image, checks.check_image)+ if detect_hands:+ print()+ ok &= _report_hand_model(extractor, name, requirements)+print()deps_ok = Truefor module, hint in (@@ -138,9 +159,14 @@ def doctor(extractor_name: str | None = None) -> int:if extractor.weights_note:print(f"\ninference weights: {extractor.weights_note}")+ if detect_hands:+ note = getattr(extractor, "hand_weights_note", "")+ if note:+ print(f"hand weights: {note}")if ok and deps_ok:- print("\neverything in place — try: m2mr run")+ suggestion = "m2mr run --detect-hands" if detect_hands else "m2mr run"+ print(f"\neverything in place — try: {suggestion}")return 0print("\nfix the [missing] items above, then re-run: m2mr doctor")return 1@@ -245,7 +271,17 @@ 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 the extractor's model check skipped.+ # Skeleton reuse skips the body-model check. Hand detection still needs+ # either fingers already stored in that file, or the body cache beside it.+ detect_hands = bool(getattr(args, "detect_hands", False))+ chosen_name = getattr(args, "set_extractor", None) or DEFAULT_EXTRACTOR+ try:+ chosen = get_extractor(chosen_name)+ extractor_error = ""+ except ValueError as exc:+ chosen = None+ extractor_error = str(exc)+skeleton = Path(args.skeleton) if args.skeleton else Noneif skeleton is not None:check(@@ -254,18 +290,32 @@ def preflight(args: argparse.Namespace) -> tuple[Path | None, Path, Path | None,"check the --skeleton path (a previous run's skeleton_motion.npz)",)check_content(f"skeleton loads {skeleton.name}", skeleton, checks.check_skeleton_npz)+ if detect_hands and skeleton.exists():+ from .extractors.hamer import find_body_cache, skeleton_has_hands++ if skeleton_has_hands(skeleton):+ check("hand motion already in the skeleton file", True, "")+ else:+ if chosen is None:+ check("motion extractor --set-extractor", False, extractor_error)+ else:+ problems += _hand_problem_count(chosen, chosen_name)+ cache = find_body_cache(skeleton.parent)+ check(+ "body cache next to the reused skeleton",+ cache is not None,+ "re-run without --skeleton; this skeleton has no saved wrist cache",+ )+ elif chosen is None:+ check("motion extractor --set-extractor", False, extractor_error)else:- 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 += 1+ 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 += 1+ if detect_hands:+ problems += _hand_problem_count(chosen, chosen_name)if problems:print(f"\n{problems} problem(s) — nothing was run. `m2mr doctor` checks everything.")@@ -273,6 +323,24 @@ def preflight(args: argparse.Namespace) -> tuple[Path | None, Path, Path | None,return video, rig, skeleton, image+def _hand_problem_count(extractor, name: str) -> int:+ """Print the paired hand model's requirements and return how many failed."""+ hand_model = getattr(extractor, "hand_model", None)+ if not hand_model:+ if not _check(+ "hand detection --detect-hands",+ False,+ f"{name} has no paired hand model",+ ):+ return 1+ return 0+ failed = 0 if _check(f"hand detection {hand_model}", True, "") else 1+ for item in extractor.check(detect_hands=True):+ if item.section == "hand" and not _report_requirement(item):+ failed += 1+ return failed++def run(args: argparse.Namespace) -> int:progress = ProgressWriter(getattr(args, "progress_jsonl", None))output_dir = Path(args.output_dir).resolve() if getattr(args, "output_dir", None) else None@@ -305,6 +373,8 @@ def run(args: argparse.Namespace) -> int:image=image,device=args.device,extractor=getattr(args, "set_extractor", None) or DEFAULT_EXTRACTOR,+ detect_hands=bool(getattr(args, "detect_hands", False)),+ hand_smooth_s=float(getattr(args, "hand_smooth", 0.08)),skeleton_npz=skeleton,output_dir=output_dir,progress=progress,@@ -332,6 +402,7 @@ def build_parser() -> argparse.ArgumentParser:p_doctor = sub.add_parser("doctor", help="check assets, weights and dependencies")_add_extractor_arg(p_doctor)+ _add_detect_hands_arg(p_doctor)p_run = sub.add_parser("run", help="video or still -> Mixamo rig, results in outputs/")p_run.add_argument(@@ -357,6 +428,17 @@ def build_parser() -> argparse.ArgumentParser:help="reuse a previous run's skeleton_motion.npz and skip extraction",)_add_extractor_arg(p_run)+ _add_detect_hands_arg(p_run)+ p_run.add_argument(+ "--hand-smooth",+ type=float,+ default=0.08,+ metavar="SECONDS",+ help=(+ "smooth detected finger rotations over this many seconds "+ "(0 keeps the raw estimate; default: 0.08)"+ ),+ )p_run.add_argument("--device",default="cpu",@@ -379,6 +461,17 @@ def build_parser() -> argparse.ArgumentParser:return parser+def _add_detect_hands_arg(parser: argparse.ArgumentParser) -> None:+ parser.add_argument(+ "--detect-hands",+ action="store_true",+ help=(+ "turn on the hand detection bundled with the selected body extractor "+ "(GVHMR uses HaMeR). Needs assets/body_models/mano/MANO_RIGHT.pkl. Off by default"+ ),+ )++def _add_extractor_arg(parser: argparse.ArgumentParser) -> None:parser.add_argument("--set-extractor",@@ -395,7 +488,12 @@ def main() -> None:parser = build_parser()args = parser.parse_args()if args.command == "doctor":- sys.exit(doctor(getattr(args, "set_extractor", None)))+ sys.exit(+ doctor(+ getattr(args, "set_extractor", None),+ detect_hands=bool(getattr(args, "detect_hands", False)),+ )+ )sys.exit(run(args))diff --git a/motion2mixamorig/extractors/base.py b/motion2mixamorig/extractors/base.pyindex c476959..5ba5211 100644--- a/motion2mixamorig/extractors/base.py+++ b/motion2mixamorig/extractors/base.py@@ -72,8 +72,11 @@ class MotionExtractor(Protocol):name: strweights_note: str- def check(self) -> list[CheckResult]:- """Assets and modules this extractor needs, for doctor and preflight."""+ def check(self, detect_hands: bool = False) -> list[CheckResult]:+ """Assets and modules this extractor needs, for doctor and preflight.++ ``detect_hands`` adds the hand model paired with this extractor.+ """def extract(self,@@ -83,8 +86,14 @@ class MotionExtractor(Protocol):work_dir: Path,device: str = "cpu",verbose: bool = True,+ detect_hands: bool = False,) -> Path:- """Write the shared skeleton file for `source` (a video or a still)."""+ """Write the shared skeleton file for `source` (a video or a still).++ ``detect_hands`` asks the extractor to append its paired hand model+ into the same file. Preflight rejects the flag when this extractor+ has no paired hand model.+ """def write_skeleton_npz(diff --git a/motion2mixamorig/extractors/gvhmr.py b/motion2mixamorig/extractors/gvhmr.pyindex c7f64d8..ef21895 100644--- a/motion2mixamorig/extractors/gvhmr.py+++ b/motion2mixamorig/extractors/gvhmr.py@@ -241,9 +241,16 @@ class GvhmrExtractor:"""Recover a world-grounded skeleton with GVHMR."""name = "gvhmr"+ hand_model = "hamer"weights_note = "downloaded automatically into weights/ on the first `m2mr run` (~5 GB)"+ hand_weights_note = (+ "HaMeR hand weights (~2.7 GB) download into weights/hamer/ on the first "+ "`m2mr run --detect-hands`"+ )++ def check(self, detect_hands: bool = False) -> list[CheckResult]:+ from .hamer import hand_requirements- def check(self) -> list[CheckResult]:results = _smplx_checks()for module in ("torch", "gvhmr"):results.append(@@ -255,6 +262,8 @@ class GvhmrExtractor:audience="doctor",))+ if detect_hands:+ results.extend(hand_requirements())return resultsdef extract(@@ -265,6 +274,7 @@ class GvhmrExtractor:work_dir: Path,device: str = "cpu",verbose: bool = True,+ detect_hands: bool = False,) -> Path:source = Path(source)if paths.is_image(source):@@ -276,6 +286,7 @@ class GvhmrExtractor:device=device,verbose=verbose,source_image=source,+ detect_hands=detect_hands,)return _extract_video(source,@@ -283,6 +294,7 @@ class GvhmrExtractor:work_dir=work_dir,device=device,verbose=verbose,+ detect_hands=detect_hands,)@@ -295,6 +307,7 @@ def _extract_video(static_camera: bool = True,verbose: bool = True,source_image: Path | None = None,+ detect_hands: bool = False,) -> Path:"""Run GVHMR on `video` and save skeleton_motion.npz to `output_npz`.@@ -347,8 +360,6 @@ def _extract_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,@@ -363,4 +374,19 @@ def _extract_video()if verbose:print(f"saved {written}")+ if detect_hands:+ from .hamer import detect_and_append++ if verbose:+ print("detecting hands")+ detect_and_append(+ output_dir,+ written,+ len(joints_3d),+ device=device,+ verbose=verbose,+ single_frame=source_image is not None,+ )+ if source_image is not None:+ _strip_cache_videos(output_dir)return writtendiff --git a/motion2mixamorig/extractors/hamer.py b/motion2mixamorig/extractors/hamer.pynew file mode 100644index 0000000..973f813--- /dev/null+++ b/motion2mixamorig/extractors/hamer.py@@ -0,0 +1,443 @@+"""HaMeR finger pass for a body extractor that already chose the person and the frames.++The body cache supplies COCO-17 wrists (GVHMR's ``vitpose.pt``) and the staged+video those coordinates were measured on (``0_input_video.mp4``). This module+crops each wrist and appends MANO finger rotations to ``skeleton_motion.npz``.+It does not run its own person detector.+"""++from __future__ import annotations++import importlib.util+import time+from pathlib import Path++import numpy as np++from .. import paths+from .base import CheckResult++# MANO's 15 articulated joints, parent-relative, in MANO kintree order.+HAND_JOINT_NAMES = (+ "index1", "index2", "index3",+ "middle1", "middle2", "middle3",+ "pinky1", "pinky2", "pinky3",+ "ring1", "ring2", "ring3",+ "thumb1", "thumb2", "thumb3",+)+HAND_POSE_CONVENTION = (+ "MANO parent-relative rotation matrices relative to the flat MANO template "+ "(no hand_mean added); index 0 = left hand (mirrored back from HaMeR's "+ "right-hand prediction), index 1 = right hand."+)+HAND_MODEL_NAME = "hamer"++# Released hamer.ckpt configuration.+IMAGE_SIZE = 256+BBOX_SHAPE = (192, 256)+IMAGE_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)+IMAGE_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)+FOCAL_LENGTH = 5000.0+RESCALE_FACTOR = 2.0+BATCH = 8++# COCO-17. GVHMR's vitpose cache is (frames, 17, 3) in the staged video's pixels.+LEFT_ELBOW, LEFT_WRIST = 7, 9+RIGHT_ELBOW, RIGHT_WRIST = 8, 10+WRIST_CONF = 0.3+STAGED_VIDEO_NAME = "0_input_video.mp4"++HAMER_URL = "https://www.cs.utexas.edu/~pavlakos/hamer/data/hamer_demo_data.tar.gz"+HAMER_MEMBERS = {+ "_DATA/hamer_ckpts/checkpoints/hamer.ckpt": "hamer.ckpt",+ "_DATA/data/mano_mean_params.npz": "mano_mean_params.npz",+}+MANO_HINT = (+ "register at https://mano.is.tue.mpg.de/ , download 'Models & Code' (mano_v1_2.zip), "+ "place models/MANO_RIGHT.pkl at assets/body_models/mano/MANO_RIGHT.pkl"+)+HAND_WEIGHTS_NOTE = (+ "HaMeR hand weights (~2.7 GB) download into weights/hamer/ on the first "+ "`m2mr run --detect-hands`"+)+_MIRROR = np.diag([-1.0, 1.0, 1.0]).astype(np.float32)+++def _module_available(name: str) -> bool:+ return importlib.util.find_spec(name) is not None+++def mano_present() -> bool:+ return paths.MANO_RIGHT_NPZ.exists() or paths.MANO_RIGHT_PKL.exists()+++def hand_requirements() -> list[CheckResult]:+ """MANO and the Python modules the finger pass imports."""+ label = f"MANO hand model {paths.MANO_DIR.relative_to(paths.PROJECT_ROOT)}/MANO_RIGHT.pkl"+ results = [+ CheckResult(+ label,+ mano_present(),+ MANO_HINT,+ section="hand",+ audience="both",+ )+ ]+ for module in ("smplx", "timm", "skimage"):+ results.append(+ CheckResult(+ f"python module {module}",+ _module_available(module),+ "pip install -e .",+ section="hand",+ audience="both",+ )+ )+ return results+++def skeleton_from_still(path: Path) -> bool:+ """True when the skeleton file was recovered from a photo, not a video."""+ with np.load(path, allow_pickle=True) as data:+ if "image" not in data.files:+ return False+ value = np.asarray(data["image"]).reshape(-1)+ if value.size == 0:+ return False+ text = str(value[0])+ return bool(text) and text.lower() != "none"+++def skeleton_has_hands(path: Path) -> bool:+ with np.load(path, allow_pickle=True) as data:+ return "hand_pose" in data.files and "hand_valid" in data.files+++def read_hands_name(path: Path) -> str | None:+ """``hands`` on new files; ``hands_extractor`` on files written by the earlier hand pass."""+ with np.load(path, allow_pickle=True) as data:+ for key in ("hands", "hands_extractor"):+ if key not in data.files:+ continue+ text = str(np.asarray(data[key]).reshape(-1)[0]) if np.asarray(data[key]).size else ""+ if text and text.lower() != "none":+ return text+ return None+++def find_body_cache(run_dir: Path) -> Path | None:+ """The GVHMR output folder that holds the staged video and vitpose cache."""+ cache = Path(run_dir) / "cache"+ if not cache.is_dir():+ return None+ found = []+ for pose in cache.glob(f"*/preprocess/vitpose.pt"):+ folder = pose.parent.parent+ if (folder / STAGED_VIDEO_NAME).is_file() and (folder / "preprocess" / "bbx.pt").is_file():+ found.append(folder)+ if len(found) == 1:+ return found[0]+ return None+++def convert_mano_pkl(pkl: Path, npz: Path) -> Path:+ """MANO_RIGHT.pkl (chumpy pickle) -> MANO_RIGHT.npz that smplx can load."""+ import inspect+ import pickle++ if not hasattr(inspect, "getargspec"):+ inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined]+ for name, typ in (+ ("bool", bool), ("int", int), ("float", float), ("complex", complex),+ ("object", object), ("unicode", str), ("str", str),+ ):+ if not hasattr(np, name):+ setattr(np, name, typ)+ with open(pkl, "rb") as fh:+ data = pickle.load(fh, encoding="latin1")+ out: dict[str, np.ndarray] = {}+ for key, value in data.items():+ if hasattr(value, "r"):+ value = np.asarray(value.r)+ elif hasattr(value, "toarray"):+ value = value.toarray()+ if isinstance(value, (int, float, str, list, tuple, np.ndarray)):+ out[key] = np.asarray(value)+ npz = Path(npz)+ npz.parent.mkdir(parents=True, exist_ok=True)+ np.savez(npz, **out)+ return npz+++def ensure_mano_npz() -> Path:+ if paths.MANO_RIGHT_NPZ.exists():+ return paths.MANO_RIGHT_NPZ+ if paths.MANO_RIGHT_PKL.exists():+ print(f"converting {paths.MANO_RIGHT_PKL.name} -> {paths.MANO_RIGHT_NPZ.name} (one time)")+ return convert_mano_pkl(paths.MANO_RIGHT_PKL, paths.MANO_RIGHT_NPZ)+ raise FileNotFoundError(f"MANO model missing: {MANO_HINT}")+++def ensure_hamer_weights(verbose: bool = True) -> None:+ """Stream the official bundle and keep only the checkpoint and mean params."""+ if paths.HAMER_CKPT.exists() and paths.HAMER_MEAN_PARAMS.exists():+ return+ import tarfile+ import urllib.request++ paths.HAMER_WEIGHTS.mkdir(parents=True, exist_ok=True)+ if verbose:+ print(f"downloading HaMeR weights (bundle ~6 GB, keeping ~2.7 GB) -> {paths.HAMER_WEIGHTS}")+ wanted = dict(HAMER_MEMBERS)+ with urllib.request.urlopen(HAMER_URL) as resp:+ with tarfile.open(fileobj=resp, mode="r|gz") as tar:+ for member in tar:+ target = wanted.pop(member.name, None)+ if target is None:+ continue+ src = tar.extractfile(member)+ assert src is not None+ tmp = paths.HAMER_WEIGHTS / (target + ".part")+ with open(tmp, "wb") as dst:+ while chunk := src.read(1 << 24):+ dst.write(chunk)+ tmp.replace(paths.HAMER_WEIGHTS / target)+ if verbose:+ print(f" saved {target}")+ if not wanted:+ break+ if wanted:+ raise RuntimeError(f"HaMeR bundle did not contain {sorted(wanted)}")+++def _as_numpy(value) -> np.ndarray:+ if hasattr(value, "detach"):+ value = value.detach().cpu().numpy()+ return np.asarray(value)+++def wrist_box(frame_kp: np.ndarray, body_xyxy: np.ndarray, *, left: bool) -> np.ndarray | None:+ """A square crop around one COCO wrist, in the staged video's pixels.++ The side length follows the elbow-to-wrist distance when the elbow is+ visible, otherwise a fraction of the body box. HaMeR then expands it.+ """+ elbow_i, wrist_i = (LEFT_ELBOW, LEFT_WRIST) if left else (RIGHT_ELBOW, RIGHT_WRIST)+ wrist = np.asarray(frame_kp[wrist_i], dtype=np.float64)+ if wrist.shape[0] < 3 or float(wrist[2]) < WRIST_CONF:+ return None+ elbow = np.asarray(frame_kp[elbow_i], dtype=np.float64)+ if elbow.shape[0] >= 3 and float(elbow[2]) >= WRIST_CONF:+ length = float(np.linalg.norm(wrist[:2] - elbow[:2]))+ side = max(length * 1.2, 20.0)+ else:+ box = np.asarray(body_xyxy, dtype=np.float64)+ side = max(0.18 * max(float(box[2] - box[0]), float(box[3] - box[1])), 20.0)+ half = side / 2.0+ center = wrist[:2]+ return np.array(+ [center[0] - half, center[1] - half, center[0] + half, center[1] + half],+ dtype=np.float32,+ )+++class HamerHandModel:+ """HaMeR ViT-H + MANO head, inference only."""++ def __init__(self, device: str = "cpu", verbose: bool = True) -> None:+ import torch++ from ..vendor.hamer.mano_head import MANOTransformerDecoderHead+ from ..vendor.hamer.vit import ViT++ ensure_hamer_weights(verbose=verbose)+ ensure_mano_npz()+ self.device = torch.device(device)+ t0 = time.time()+ self.backbone = ViT(+ img_size=(256, 192), patch_size=16, embed_dim=1280, depth=32, num_heads=16,+ ratio=1, use_checkpoint=False, mlp_ratio=4, qkv_bias=True, drop_path_rate=0.55,+ )+ self.head = MANOTransformerDecoderHead(str(paths.HAMER_MEAN_PARAMS))+ state = torch.load(paths.HAMER_CKPT, map_location="cpu", weights_only=False)+ state = state.get("state_dict", state)+ self.backbone.load_state_dict({k[9:]: v for k, v in state.items() if k.startswith("backbone.")})+ self.head.load_state_dict({k[10:]: v for k, v in state.items() if k.startswith("mano_head.")})+ for module in (self.backbone, self.head):+ module.to(self.device).eval()+ if verbose:+ print(f"HaMeR loaded in {time.time() - t0:.1f}s on {self.device}")++ def crop(self, img_bgr: np.ndarray, box_xyxy: np.ndarray, is_right: bool) -> tuple[np.ndarray, np.ndarray, float]:+ """One normalised (3, 256, 256) RGB patch. Left hands are mirrored."""+ from skimage.filters import gaussian++ from ..vendor.hamer.crop import expand_to_aspect_ratio, generate_image_patch_cv2+ import cv2++ box = np.asarray(box_xyxy, dtype=np.float32)+ center = (box[2:4] + box[0:2]) / 2.0+ scale = RESCALE_FACTOR * (box[2:4] - box[0:2]) / 200.0+ size = float(expand_to_aspect_ratio(scale * 200, target_aspect_ratio=BBOX_SHAPE).max())+ img = img_bgr+ down = size / IMAGE_SIZE / 2.0+ if down > 1.1:+ img = gaussian(img, sigma=(down - 1) / 2, channel_axis=2, preserve_range=True)+ patch, _ = generate_image_patch_cv2(+ img, float(center[0]), float(center[1]), size, size, IMAGE_SIZE, IMAGE_SIZE,+ not is_right, 1.0, 0, border_mode=cv2.BORDER_CONSTANT,+ )+ patch = patch[:, :, ::-1].astype(np.float32) / 255.0+ patch = (patch - IMAGE_MEAN) / IMAGE_STD+ return np.ascontiguousarray(patch.transpose(2, 0, 1)), center, size++ def predict(self, patches: np.ndarray, is_right: np.ndarray) -> np.ndarray:+ """MANO joint rotations for a batch. Left hands are mirrored back."""+ import torch++ x = torch.from_numpy(np.asarray(patches, dtype=np.float32)).to(self.device)+ with torch.no_grad():+ feats = self.backbone(x[:, :, :, 32:-32])+ params, _cam = self.head(feats)+ hp = params["hand_pose"].float().cpu().numpy()+ for i in np.flatnonzero(~np.asarray(is_right, dtype=bool)):+ hp[i] = _MIRROR @ hp[i] @ _MIRROR+ return hp.reshape(x.shape[0], 15, 3, 3).astype(np.float32)+++def _load_pose_and_boxes(cache_dir: Path, n_frames: int) -> tuple[np.ndarray, np.ndarray]:+ import torch++ pose_path = cache_dir / "preprocess" / "vitpose.pt"+ box_path = cache_dir / "preprocess" / "bbx.pt"+ video_path = cache_dir / STAGED_VIDEO_NAME+ if not pose_path.is_file() or not box_path.is_file() or not video_path.is_file():+ raise FileNotFoundError(+ f"hand detection needs {STAGED_VIDEO_NAME}, vitpose.pt and bbx.pt under {cache_dir}"+ )+ kp = _as_numpy(torch.load(pose_path, weights_only=False))+ bbx = torch.load(box_path, weights_only=False)["bbx_xyxy"]+ boxes = _as_numpy(bbx)+ if kp.ndim != 3 or kp.shape[1] < 17 or kp.shape[-1] < 3:+ raise ValueError(f"vitpose cache must be (frames, 17, 3), got {getattr(kp, 'shape', None)}")+ if len(kp) != n_frames or len(boxes) != n_frames:+ raise ValueError(+ f"body cache has {len(kp)} pose frames and {len(boxes)} boxes, "+ f"but the skeleton has {n_frames}"+ )+ return kp, boxes+++def _blank_pose(n: int) -> np.ndarray:+ return np.tile(np.eye(3, dtype=np.float32), (n, 2, 15, 1, 1))+++def detect_on_cache(+ cache_dir: Path,+ n_frames: int,+ *,+ device: str = "cpu",+ verbose: bool = True,+ single_frame: bool = False,+) -> dict[str, np.ndarray]:+ """Finger rotations aligned with the body skeleton's frames."""+ import cv2++ kp, boxes = _load_pose_and_boxes(cache_dir, n_frames)+ video_path = cache_dir / STAGED_VIDEO_NAME+ use_n = 1 if single_frame else n_frames+ pose = _blank_pose(use_n)+ valid = np.zeros((use_n, 2), dtype=bool)+ model: HamerHandModel | None = None+ pending: list[tuple[int, int, np.ndarray, bool]] = []++ def flush() -> None:+ if not pending:+ return+ assert model is not None+ rotations = model.predict(+ np.stack([item[2] for item in pending]),+ np.array([item[3] for item in pending]),+ )+ for i, (frame, side, *_rest) in enumerate(pending):+ pose[frame, side] = rotations[i]+ valid[frame, side] = True+ pending.clear()++ cap = cv2.VideoCapture(str(video_path))+ if not cap.isOpened():+ raise ValueError(f"cannot open staged video {video_path}")+ t0 = time.time()+ try:+ for frame_i in range(use_n):+ ok, frame = cap.read()+ if not ok:+ raise ValueError(+ f"{video_path.name} ended at frame {frame_i}, expected {use_n}"+ )+ for side, is_right in ((0, False), (1, True)):+ box = wrist_box(kp[frame_i], boxes[frame_i], left=not is_right)+ if box is None:+ continue+ if model is None:+ model = HamerHandModel(device=device, verbose=verbose)+ patch, _center, _size = model.crop(frame, box, is_right)+ pending.append((frame_i, side, patch, is_right))+ if len(pending) >= BATCH:+ flush()+ if verbose and use_n > 1 and (frame_i == 0 or (frame_i + 1) % 30 == 0 or frame_i == use_n - 1):+ seen = valid[: frame_i + 1].sum(axis=0)+ print(+ f" hands frame {frame_i + 1}/{use_n} "+ f"left {int(seen[0])} right {int(seen[1])} {time.time() - t0:.0f}s"+ )+ flush()+ finally:+ cap.release()+ if single_frame and n_frames != 1:+ pose = np.repeat(pose, n_frames, axis=0)+ valid = np.repeat(valid, n_frames, axis=0)+ if verbose:+ seen = valid.sum(axis=0)+ print(+ f"hands done {n_frames} frames, left seen {int(seen[0])}, "+ f"right seen {int(seen[1])}, {time.time() - t0:.0f}s"+ )+ with np.load(ensure_mano_npz()) as mano:+ template = np.asarray(mano["J"], dtype=np.float32)+ return {+ "hand_pose": pose,+ "hand_valid": valid,+ "hand_template_joints": template,+ "hands": np.array(HAND_MODEL_NAME),+ "hand_pose_convention": np.array(HAND_POSE_CONVENTION),+ }+++def append_hands(skeleton_npz: Path, arrays: dict[str, np.ndarray]) -> Path:+ """Add the finger arrays to an existing skeleton file."""+ skeleton_npz = Path(skeleton_npz)+ with np.load(skeleton_npz, allow_pickle=True) as data:+ payload = {key: data[key] for key in data.files}+ payload.update(arrays)+ np.savez_compressed(skeleton_npz, **payload)+ return skeleton_npz+++def detect_and_append(+ cache_dir: Path,+ skeleton_npz: Path,+ n_frames: int,+ *,+ device: str = "cpu",+ verbose: bool = True,+ single_frame: bool = False,+) -> Path:+ arrays = detect_on_cache(+ cache_dir,+ n_frames,+ device=device,+ verbose=verbose,+ single_frame=single_frame,+ )+ return append_hands(skeleton_npz, arrays)diff --git a/motion2mixamorig/mixamo/animation.py b/motion2mixamorig/mixamo/animation.pyindex 6ac158b..297e1a4 100644--- a/motion2mixamorig/mixamo/animation.py+++ b/motion2mixamorig/mixamo/animation.py@@ -13,6 +13,7 @@ from dataclasses import dataclass, fieldimport numpy as np+from .hand_retarget import HandMapping, HandMotionfrom .kinematics import forward_kinematics, world_positions_mfrom .retarget import joint_mixamo, retarget_one_framefrom .skinned_mesh import YBotAsset, bone_palette, skin_mesh@@ -39,7 +40,13 @@ class RetargetedAnimation:def build_animation(- motion, mapping: YBotMapping, frames: list[int], *, verbose: bool = True+ motion,+ mapping: YBotMapping,+ frames: list[int],+ *,+ verbose: bool = True,+ hands: HandMotion | None = None,+ hand_mapping: HandMapping | None = None,) -> RetargetedAnimation:"""Retarget Human -> Mixamo, then carry the rest-relative motion onto the rig."""skel = mapping.skeleton_rig@@ -63,6 +70,8 @@ def build_animation(skel, forward_kinematics(skel, result.r_anim, hips_translation_cm=hips_cm))r_rig = mapping.apply_rest_relative_rotations(result.r_anim)+ if hands is not None and hand_mapping is not None and frame < hands.n_frames:+ r_rig.update(hand_mapping.finger_rotations(hands.pose[frame], hands.valid[frame]))hips_rig = mapping.hips_translation_cm(hips_cm)rig_pos = mapping.ybot_positions_m(r_rig, hips_rig)diff --git a/motion2mixamorig/mixamo/hand_retarget.py b/motion2mixamorig/mixamo/hand_retarget.pynew file mode 100644index 0000000..098473a--- /dev/null+++ b/motion2mixamorig/mixamo/hand_retarget.py@@ -0,0 +1,240 @@+"""MANO finger rotations (HaMeR hand pass) -> Mixamo finger bones.++MANO joint rotations are parent-relative and expressed in the hand model's own+axes, because every MANO rest frame is the identity. A Mixamo finger bone's+animation channel is also parent-relative, but expressed in that bone's own+rest frame (`M_local = T_bind * R_bind * R_anim`). The transfer is therefore a+pure basis change, measured from the two rest poses and never authored:++ R_anim[b] = D_bᵀ · (C · R_mano[j] · Cᵀ) · D_b++ C : MANO hand axes -> the Mixamo Hand bone's rest frame, from the hand+ frames (wrist->middle1, index1-pinky1) of both rest poses+ D_b : finger bone b's rest world rotation relative to the Hand bone's++HaMeR is a single-image model, so the raw rotations jitter frame to frame;+`load_hand_motion` smooths them with a validity-weighted Gaussian over time+and fills short detection gaps from the neighbouring frames.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++import numpy as np++from ..extractors.hamer import HAND_JOINT_NAMES+from .kinematics import MixamoRig, forward_kinematics, normalize++SIDES = ("Left", "Right") # hand_pose[:, 0] is the left hand, [:, 1] the right+# MANO joint order: 0 wrist, 1-3 index, 4-6 middle, 7-9 pinky, 10-12 ring, 13-15 thumb.+MANO_WRIST, MANO_INDEX1, MANO_MIDDLE1, MANO_PINKY1 = 0, 1, 4, 7+_FINGER = {"index": "Index", "middle": "Middle", "pinky": "Pinky", "ring": "Ring", "thumb": "Thumb"}+DEFAULT_SMOOTH_S = 0.08+++def finger_bone(side: str, joint: str) -> str:+ """'index2' on the left -> 'mixamorig:LeftHandIndex2'."""+ return f"mixamorig:{side}Hand{_FINGER[joint[:-1]]}{joint[-1]}"+++def _hand_frame(wrist: np.ndarray, middle1: np.ndarray, index1: np.ndarray, pinky1: np.ndarray) -> np.ndarray:+ """Columns: along the fingers, pinky->index, and their cross product (palm normal)."""+ e1 = normalize(middle1 - wrist)+ lateral = index1 - pinky1+ e2 = normalize(lateral - e1 * float(lateral @ e1))+ return np.stack([e1, e2, np.cross(e1, e2)], axis=1)+++def _mano_frame(template_joints: np.ndarray, side: str) -> np.ndarray:+ j = np.asarray(template_joints, dtype=np.float64)+ if side == "Left":+ j = j * np.array([-1.0, 1.0, 1.0]) # the hand pass mirrors left hands the same way+ return _hand_frame(j[MANO_WRIST], j[MANO_MIDDLE1], j[MANO_INDEX1], j[MANO_PINKY1])+++@dataclass(frozen=True)+class HandMapping:+ rig: MixamoRig+ basis: dict[str, np.ndarray] # side -> C+ bone_rest: dict[str, np.ndarray] # finger bone -> D_b+ bones: tuple[str, ...]++ def finger_rotations(self, hand_pose: np.ndarray, valid: np.ndarray) -> dict[str, np.ndarray]:+ """R_anim per finger bone for one frame; undetected hands stay at rest."""+ out: dict[str, np.ndarray] = {}+ for s, side in enumerate(SIDES):+ if not bool(valid[s]) or side not in self.basis:+ continue+ c = self.basis[side]+ for k, joint in enumerate(HAND_JOINT_NAMES):+ bone = finger_bone(side, joint)+ d = self.bone_rest.get(bone)+ if d is None:+ continue+ r = c @ np.asarray(hand_pose[s, k], dtype=np.float64) @ c.T+ out[bone] = d.T @ r @ d+ return out+++def build_hand_mapping(rig: MixamoRig, mano_template_joints: np.ndarray, *, verbose: bool = True) -> HandMapping:+ """Measure C per side and D_b per finger bone from the rig's rest pose and MANO's template."""+ world = forward_kinematics(rig, {})+ rot = {n: np.asarray(m[:3, :3], dtype=np.float64) for n, m in world.items()}+ pos = {n: np.asarray(m[:3, 3], dtype=np.float64) for n, m in world.items()}+ basis: dict[str, np.ndarray] = {}+ bone_rest: dict[str, np.ndarray] = {}+ bones: list[str] = []+ for side in SIDES:+ hand = f"mixamorig:{side}Hand"+ needed = [hand] + [finger_bone(side, j) for j in HAND_JOINT_NAMES]+ if any(b not in rig.bones for b in needed):+ if verbose:+ missing = [b for b in needed if b not in rig.bones]+ print(f" {side.lower()} hand: rig has no finger chain ({missing[0]} ...), fingers stay at rest")+ continue+ h = rot[hand]+ mix = _hand_frame(+ h.T @ pos[hand], h.T @ pos[finger_bone(side, "middle1")],+ h.T @ pos[finger_bone(side, "index1")], h.T @ pos[finger_bone(side, "pinky1")],+ )+ basis[side] = mix @ _mano_frame(mano_template_joints, side).T+ for joint in HAND_JOINT_NAMES:+ bone = finger_bone(side, joint)+ bone_rest[bone] = h.T @ rot[bone]+ bones.append(bone)+ if verbose and basis:+ angles = {s: float(np.degrees(np.arccos(np.clip((np.trace(c) - 1) / 2, -1, 1)))) for s, c in basis.items()}+ print(f" finger bones {len(bones)} (MANO -> Mixamo basis change "+ + ", ".join(f"{s.lower()} {a:.1f} deg" for s, a in angles.items()) + ")")+ return HandMapping(rig=rig, basis=basis, bone_rest=bone_rest, bones=tuple(bones))+++# ---------------------------------------------------------------- hand motion + smoothing+++@dataclass+class HandMotion:+ pose: np.ndarray # (F, 2, 15, 3, 3)+ valid: np.ndarray # (F, 2)+ template_joints: np.ndarray # (16, 3) MANO right-hand rest joints+ fps: float+ smoothed_s: float++ @property+ def n_frames(self) -> int:+ return int(self.pose.shape[0])+++def _quat_from_rotmat(r: np.ndarray) -> np.ndarray:+ """(..., 3, 3) -> (..., 4) wxyz, batch-safe."""+ r = np.asarray(r, dtype=np.float64)+ shape = r.shape[:-2]+ r = r.reshape(-1, 3, 3)+ m00, m11, m22 = r[..., 0, 0], r[..., 1, 1], r[..., 2, 2]+ t = m00 + m11 + m22+ q = np.empty(r.shape[:-2] + (4,))+ # branch on the largest diagonal term for stability+ s = np.sqrt(np.maximum(t + 1.0, 0.0)) * 2+ q[..., 0] = 0.25 * s+ q[..., 1] = (r[..., 2, 1] - r[..., 1, 2]) / np.where(s > 1e-9, s, 1)+ q[..., 2] = (r[..., 0, 2] - r[..., 2, 0]) / np.where(s > 1e-9, s, 1)+ q[..., 3] = (r[..., 1, 0] - r[..., 0, 1]) / np.where(s > 1e-9, s, 1)+ bad = t <= -0.5 # near 180 deg: fall back to the per-element formula+ if np.any(bad):+ for idx in zip(*np.nonzero(bad)):+ q[idx] = _quat_from_rotmat_single(r[idx])+ q /= np.linalg.norm(q, axis=-1, keepdims=True)+ return q.reshape(shape + (4,))+++def _quat_from_rotmat_single(r: np.ndarray) -> np.ndarray:+ diag = np.array([r[0, 0], r[1, 1], r[2, 2]])+ i = int(np.argmax(diag))+ j, k = (i + 1) % 3, (i + 2) % 3+ s = np.sqrt(max(diag[i] - diag[j] - diag[k] + 1.0, 1e-12)) * 2+ q = np.empty(4)+ q[0] = (r[k, j] - r[j, k]) / s+ q[1 + i] = 0.25 * s+ q[1 + j] = (r[j, i] + r[i, j]) / s+ q[1 + k] = (r[k, i] + r[i, k]) / s+ return q+++def _rotmat_from_quat(q: np.ndarray) -> np.ndarray:+ w, x, y, z = (q[..., i] for i in range(4))+ r = np.empty(q.shape[:-1] + (3, 3))+ r[..., 0, 0] = 1 - 2 * (y * y + z * z)+ r[..., 0, 1] = 2 * (x * y - z * w)+ r[..., 0, 2] = 2 * (x * z + y * w)+ r[..., 1, 0] = 2 * (x * y + z * w)+ r[..., 1, 1] = 1 - 2 * (x * x + z * z)+ r[..., 1, 2] = 2 * (y * z - x * w)+ r[..., 2, 0] = 2 * (x * z - y * w)+ r[..., 2, 1] = 2 * (y * z + x * w)+ r[..., 2, 2] = 1 - 2 * (x * x + y * y)+ return r+++def smooth_hand_pose(pose: np.ndarray, valid: np.ndarray, fps: float, sigma_s: float = DEFAULT_SMOOTH_S) -> tuple[np.ndarray, np.ndarray]:+ """Validity-weighted Gaussian smoothing of each joint rotation over time.++ Frames without a detection take the weighted mean of their valid+ neighbours inside the window; frames with no valid neighbour at all stay at+ rest and are reported invalid. Returns (pose, valid) with the same shapes.+ """+ pose = np.asarray(pose, dtype=np.float64)+ valid = np.asarray(valid, dtype=bool)+ n = pose.shape[0]+ if sigma_s <= 0 or n < 2:+ return pose.copy(), valid.copy()+ sigma = max(float(sigma_s) * float(fps), 1e-6)+ radius = int(np.ceil(3 * sigma))+ offsets = np.arange(-radius, radius + 1)+ kernel = np.exp(-0.5 * (offsets / sigma) ** 2)+ out = np.tile(np.eye(3), pose.shape[:-2] + (1, 1))+ out_valid = np.zeros_like(valid)+ for s in range(pose.shape[1]):+ if not valid[:, s].any():+ continue+ q = _quat_from_rotmat(pose[:, s]) # (F, 15, 4)+ # hemisphere continuity along time so averaging does not cancel out+ for f in range(1, n):+ flip = np.sum(q[f] * q[f - 1], axis=-1) < 0+ q[f, flip] *= -1+ w_valid = valid[:, s].astype(np.float64)+ acc = np.zeros_like(q)+ wsum = np.zeros(n)+ for off, k in zip(offsets, kernel):+ src = np.arange(n) + off+ ok = (src >= 0) & (src < n)+ w = np.zeros(n)+ w[ok] = k * w_valid[src[ok]]+ acc[ok] += w[ok, None, None] * q[src[ok]]+ wsum += w+ has = wsum > 1e-9+ mean = acc[has] / wsum[has, None, None]+ mean /= np.linalg.norm(mean, axis=-1, keepdims=True)+ out[has, s] = _rotmat_from_quat(mean)+ out_valid[:, s] = has+ return out, out_valid+++def load_hand_motion(skeleton_npz: Path, *, smooth_s: float = DEFAULT_SMOOTH_S) -> HandMotion | None:+ """Finger rotations from a skeleton file, smoothed. None when the file has no hands."""+ with np.load(Path(skeleton_npz), allow_pickle=True) as data:+ if "hand_pose" not in data.files or "hand_valid" not in data.files:+ return None+ pose = np.asarray(data["hand_pose"], dtype=np.float64)+ valid = np.asarray(data["hand_valid"], dtype=bool)+ fps = float(data["fps"]) if "fps" in data.files else 30.0+ if "hand_template_joints" in data.files:+ template = np.asarray(data["hand_template_joints"], dtype=np.float64)+ else:+ from ..extractors.hamer import ensure_mano_npz++ with np.load(ensure_mano_npz()) as mano:+ template = np.asarray(mano["J"], dtype=np.float64)+ pose, valid = smooth_hand_pose(pose, valid, fps, smooth_s)+ return HandMotion(pose=pose, valid=valid, template_joints=template, fps=fps, smoothed_s=float(smooth_s))diff --git a/motion2mixamorig/paths.py b/motion2mixamorig/paths.pyindex 45f2aba..5a3133e 100644--- a/motion2mixamorig/paths.py+++ b/motion2mixamorig/paths.py@@ -11,12 +11,18 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1]ASSETS = PROJECT_ROOT / "assets"BODY_MODELS = ASSETS / "body_models"SMPLX_NEUTRAL = BODY_MODELS / "smplx" / "SMPLX_NEUTRAL.npz"+MANO_DIR = BODY_MODELS / "mano"+MANO_RIGHT_PKL = MANO_DIR / "MANO_RIGHT.pkl"+MANO_RIGHT_NPZ = MANO_DIR / "MANO_RIGHT.npz"MIXAMO_DIR = ASSETS / "mixamo"DEFAULT_RIG = MIXAMO_DIR / "Y_Bot.fbx"VIDEO_DIR = ASSETS / "video"IMAGE_DIR = ASSETS / "image"WEIGHTS = PROJECT_ROOT / "weights"+HAMER_WEIGHTS = WEIGHTS / "hamer"+HAMER_CKPT = HAMER_WEIGHTS / "hamer.ckpt"+HAMER_MEAN_PARAMS = HAMER_WEIGHTS / "mano_mean_params.npz"OUTPUTS = PROJECT_ROOT / "outputs"VIDEO_SUFFIXES = (".mp4", ".mov", ".avi", ".mkv", ".webm")diff --git a/motion2mixamorig/pipeline.py b/motion2mixamorig/pipeline.pyindex c730b73..83e23f0 100644--- a/motion2mixamorig/pipeline.py+++ b/motion2mixamorig/pipeline.py@@ -24,6 +24,14 @@ from . import pathsfrom .errors import classify_errorfrom .extractors import DEFAULT_EXTRACTOR, get_extractorfrom .extractors.base import read_extractor_name+from .extractors.hamer import (+ detect_and_append,+ find_body_cache,+ read_hands_name,+ skeleton_from_still,+ skeleton_has_hands,+)+from .mixamo.hand_retarget import build_hand_mapping, load_hand_motionfrom .human_motion import HumanMotion, load_human_motionfrom .mixamo.animation import build_animationfrom .mixamo.gltf import write_glb@@ -43,10 +51,15 @@ ROTATION_CONVENTION = ()-def save_mixamo_rotations(anim, mapping, rig_path: Path, out_npz: Path) -> Path:+def save_mixamo_rotations(+ anim, mapping, rig_path: Path, out_npz: Path, *, extra_bones: list[str] | None = None+) -> Path:"""Per-bone animation rotations, both the portable Mixamo Skeleton channeland the channel already converted for this rig file."""bones = list(mapping.controlled)+ for name in extra_bones or []:+ if name not in bones:+ bones.append(name)n = anim.nq_skel = np.zeros((n, len(bones), 4), dtype=np.float64)q_rig = np.zeros((n, len(bones), 4), dtype=np.float64)@@ -78,6 +91,8 @@ def run_pipeline(image: Path | None = None,device: str = "cpu",extractor: str = DEFAULT_EXTRACTOR,+ detect_hands: bool = False,+ hand_smooth_s: float = 0.08,skeleton_npz: Path | None = None,verbose: bool = True,output_dir: Path | None = None,@@ -136,6 +151,23 @@ def run_pipeline(work_dir=run_dir / "cache",device=device,verbose=verbose,+ detect_hands=detect_hands,+ )+ if detect_hands and skeleton_npz is not None and not skeleton_has_hands(motion_npz):+ cache_dir = find_body_cache(Path(skeleton_npz).parent)+ if cache_dir is None:+ raise FileNotFoundError(+ "hand detection needs the body cache next to the reused skeleton "+ "(cache/*/0_input_video.mp4, vitpose.pt, bbx.pt)"+ )+ print("detecting hands on the reused skeleton")+ detect_and_append(+ cache_dir,+ motion_npz,+ load_human_motion(motion_npz).n_frames,+ device=device,+ verbose=verbose,+ single_frame=image is not None or skeleton_from_still(motion_npz),)motion: HumanMotion = load_human_motion(motion_npz)print(f"human motion {motion.n_frames} frames @ {motion.fps:g} fps")@@ -153,10 +185,27 @@ def run_pipeline(print("retargeting")frames = list(range(motion.n_frames))- anim = build_animation(motion, mapping, frames, verbose=verbose)+ hands = load_hand_motion(motion_npz, smooth_s=hand_smooth_s)+ hand_mapping = None+ if hands is not None:+ hand_mapping = build_hand_mapping(asset.rig, hands.template_joints, verbose=verbose)+ anim = build_animation(+ motion,+ mapping,+ frames,+ verbose=verbose,+ hands=hands,+ hand_mapping=hand_mapping,+ )rotations_npz = run_dir / "mixamo_rotations.npz"- save_mixamo_rotations(anim, mapping, rig, rotations_npz)+ save_mixamo_rotations(+ anim,+ mapping,+ rig,+ rotations_npz,+ extra_bones=list(hand_mapping.bones) if hand_mapping is not None else None,+ )print(f"saved {rotations_npz}")stage = "export"@@ -205,6 +254,9 @@ def run_pipeline("extractor": (read_extractor_name(motion_npz) if skeleton_npz is not None else extractor),+ "hands": read_hands_name(motion_npz),+ "hand_smooth_s": hand_smooth_s if hands is not None else None,+ "finger_bones": 0 if hand_mapping is None else len(hand_mapping.bones),"fps": float(motion.fps),"n_frames": motion.n_frames,"skeleton_reused_from": str(skeleton_npz) if skeleton_npz else None,diff --git a/motion2mixamorig/vendor/__init__.py b/motion2mixamorig/vendor/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/motion2mixamorig/vendor/hamer/LICENSE.md b/motion2mixamorig/vendor/hamer/LICENSE.mdnew file mode 100644index 0000000..209a6f5--- /dev/null+++ b/motion2mixamorig/vendor/hamer/LICENSE.md@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2023 UC Regents, Georgios Pavlakos++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/motion2mixamorig/vendor/hamer/__init__.py b/motion2mixamorig/vendor/hamer/__init__.pynew file mode 100644index 0000000..b326a54--- /dev/null+++ b/motion2mixamorig/vendor/hamer/__init__.py@@ -0,0 +1,7 @@+"""Minimal HaMeR (Pavlakos et al., CVPR 2024) inference code, vendored.++Copied from https://github.com/geopavlakos/hamer (MIT, see LICENSE.md):+the ViT-H backbone, the MANO transformer head, the MANO joint wrapper and+the hand-crop helpers. Training, datasets, renderers, detectron2 and mmpose+are left out; hand boxes come from the body extractor's wrist keypoints.+"""diff --git a/motion2mixamorig/vendor/hamer/crop.py b/motion2mixamorig/vendor/hamer/crop.pynew file mode 100644index 0000000..32936e8--- /dev/null+++ b/motion2mixamorig/vendor/hamer/crop.py@@ -0,0 +1,144 @@+"""Hand-crop helpers from HaMeR (hamer/datasets/utils.py), unchanged. MIT, see LICENSE.md."""++from __future__ import annotations++import cv2+import numpy as np+++def expand_to_aspect_ratio(input_shape, target_aspect_ratio=None):+ """Increase the size of the bounding box to match the target shape."""+ if target_aspect_ratio is None:+ return input_shape++ try:+ w , h = input_shape+ except (ValueError, TypeError):+ return input_shape++ w_t, h_t = target_aspect_ratio+ if h / w < h_t / w_t:+ h_new = max(w * h_t / w_t, h)+ w_new = w+ else:+ h_new = h+ w_new = max(h * w_t / h_t, w)+ if h_new < h or w_new < w:+ breakpoint()+ return np.array([w_new, h_new])+++def rotate_2d(pt_2d: np.array, rot_rad: float) -> np.array:+ """+ Rotate a 2D point on the x-y plane.+ Args:+ pt_2d (np.array): Input 2D point with shape (2,).+ rot_rad (float): Rotation angle+ Returns:+ np.array: Rotated 2D point.+ """+ x = pt_2d[0]+ y = pt_2d[1]+ sn, cs = np.sin(rot_rad), np.cos(rot_rad)+ xx = x * cs - y * sn+ yy = x * sn + y * cs+ return np.array([xx, yy], dtype=np.float32)+++def gen_trans_from_patch_cv(c_x: float, c_y: float,+ src_width: float, src_height: float,+ dst_width: float, dst_height: float,+ scale: float, rot: float) -> np.array:+ """+ Create transformation matrix for the bounding box crop.+ Args:+ c_x (float): Bounding box center x coordinate in the original image.+ c_y (float): Bounding box center y coordinate in the original image.+ src_width (float): Bounding box width.+ src_height (float): Bounding box height.+ dst_width (float): Output box width.+ dst_height (float): Output box height.+ scale (float): Rescaling factor for the bounding box (augmentation).+ rot (float): Random rotation applied to the box.+ Returns:+ trans (np.array): Target geometric transformation.+ """+ # augment size with scale+ src_w = src_width * scale+ src_h = src_height * scale+ src_center = np.zeros(2)+ src_center[0] = c_x+ src_center[1] = c_y+ # augment rotation+ rot_rad = np.pi * rot / 180+ src_downdir = rotate_2d(np.array([0, src_h * 0.5], dtype=np.float32), rot_rad)+ src_rightdir = rotate_2d(np.array([src_w * 0.5, 0], dtype=np.float32), rot_rad)++ dst_w = dst_width+ dst_h = dst_height+ dst_center = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32)+ dst_downdir = np.array([0, dst_h * 0.5], dtype=np.float32)+ dst_rightdir = np.array([dst_w * 0.5, 0], dtype=np.float32)++ src = np.zeros((3, 2), dtype=np.float32)+ src[0, :] = src_center+ src[1, :] = src_center + src_downdir+ src[2, :] = src_center + src_rightdir++ dst = np.zeros((3, 2), dtype=np.float32)+ dst[0, :] = dst_center+ dst[1, :] = dst_center + dst_downdir+ dst[2, :] = dst_center + dst_rightdir++ trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))++ return trans+++++def generate_image_patch_cv2(img: np.array, c_x: float, c_y: float,+ bb_width: float, bb_height: float,+ patch_width: float, patch_height: float,+ do_flip: bool, scale: float, rot: float,+ border_mode=cv2.BORDER_CONSTANT, border_value=0) -> Tuple[np.array, np.array]:+ """+ Crop the input image and return the crop and the corresponding transformation matrix.+ Args:+ img (np.array): Input image of shape (H, W, 3)+ c_x (float): Bounding box center x coordinate in the original image.+ c_y (float): Bounding box center y coordinate in the original image.+ bb_width (float): Bounding box width.+ bb_height (float): Bounding box height.+ patch_width (float): Output box width.+ patch_height (float): Output box height.+ do_flip (bool): Whether to flip image or not.+ scale (float): Rescaling factor for the bounding box (augmentation).+ rot (float): Random rotation applied to the box.+ Returns:+ img_patch (np.array): Cropped image patch of shape (patch_height, patch_height, 3)+ trans (np.array): Transformation matrix.+ """++ img_height, img_width, img_channels = img.shape+ if do_flip:+ img = img[:, ::-1, :]+ c_x = img_width - c_x - 1+++ trans = gen_trans_from_patch_cv(c_x, c_y, bb_width, bb_height, patch_width, patch_height, scale, rot)++ img_patch = cv2.warpAffine(img, trans, (int(patch_width), int(patch_height)),+ flags=cv2.INTER_LINEAR,+ borderMode=border_mode,+ borderValue=border_value,+ )+ # Force borderValue=cv2.BORDER_CONSTANT for alpha channel+ if (img.shape[2] == 4) and (border_mode != cv2.BORDER_CONSTANT):+ img_patch[:,:,3] = cv2.warpAffine(img[:,:,3], trans, (int(patch_width), int(patch_height)),+ flags=cv2.INTER_LINEAR,+ borderMode=cv2.BORDER_CONSTANT,+ )++ return img_patch, trans+diff --git a/motion2mixamorig/vendor/hamer/geometry.py b/motion2mixamorig/vendor/hamer/geometry.pynew file mode 100644index 0000000..c48d633--- /dev/null+++ b/motion2mixamorig/vendor/hamer/geometry.py@@ -0,0 +1,102 @@+from typing import Optional+import torch+from torch.nn import functional as F++def aa_to_rotmat(theta: torch.Tensor):+ """+ Convert axis-angle representation to rotation matrix.+ Works by first converting it to a quaternion.+ Args:+ theta (torch.Tensor): Tensor of shape (B, 3) containing axis-angle representations.+ Returns:+ torch.Tensor: Corresponding rotation matrices with shape (B, 3, 3).+ """+ norm = torch.norm(theta + 1e-8, p = 2, dim = 1)+ angle = torch.unsqueeze(norm, -1)+ normalized = torch.div(theta, angle)+ angle = angle * 0.5+ v_cos = torch.cos(angle)+ v_sin = torch.sin(angle)+ quat = torch.cat([v_cos, v_sin * normalized], dim = 1)+ return quat_to_rotmat(quat)++def quat_to_rotmat(quat: torch.Tensor) -> torch.Tensor:+ """+ Convert quaternion representation to rotation matrix.+ Args:+ quat (torch.Tensor) of shape (B, 4); 4 <===> (w, x, y, z).+ Returns:+ torch.Tensor: Corresponding rotation matrices with shape (B, 3, 3).+ """+ norm_quat = quat+ norm_quat = norm_quat/norm_quat.norm(p=2, dim=1, keepdim=True)+ w, x, y, z = norm_quat[:,0], norm_quat[:,1], norm_quat[:,2], norm_quat[:,3]++ B = quat.size(0)++ w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)+ wx, wy, wz = w*x, w*y, w*z+ xy, xz, yz = x*y, x*z, y*z++ rotMat = torch.stack([w2 + x2 - y2 - z2, 2*xy - 2*wz, 2*wy + 2*xz,+ 2*wz + 2*xy, w2 - x2 + y2 - z2, 2*yz - 2*wx,+ 2*xz - 2*wy, 2*wx + 2*yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)+ return rotMat+++def rot6d_to_rotmat(x: torch.Tensor) -> torch.Tensor:+ """+ Convert 6D rotation representation to 3x3 rotation matrix.+ Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019+ Args:+ x (torch.Tensor): (B,6) Batch of 6-D rotation representations.+ Returns:+ torch.Tensor: Batch of corresponding rotation matrices with shape (B,3,3).+ """+ x = x.reshape(-1,2,3).permute(0, 2, 1).contiguous()+ a1 = x[:, :, 0]+ a2 = x[:, :, 1]+ b1 = F.normalize(a1)+ b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)+ b3 = torch.cross(b1, b2, dim=-1)+ return torch.stack((b1, b2, b3), dim=-1)++def perspective_projection(points: torch.Tensor,+ translation: torch.Tensor,+ focal_length: torch.Tensor,+ camera_center: Optional[torch.Tensor] = None,+ rotation: Optional[torch.Tensor] = None) -> torch.Tensor:+ """+ Computes the perspective projection of a set of 3D points.+ Args:+ points (torch.Tensor): Tensor of shape (B, N, 3) containing the input 3D points.+ translation (torch.Tensor): Tensor of shape (B, 3) containing the 3D camera translation.+ focal_length (torch.Tensor): Tensor of shape (B, 2) containing the focal length in pixels.+ camera_center (torch.Tensor): Tensor of shape (B, 2) containing the camera center in pixels.+ rotation (torch.Tensor): Tensor of shape (B, 3, 3) containing the camera rotation.+ Returns:+ torch.Tensor: Tensor of shape (B, N, 2) containing the projection of the input points.+ """+ batch_size = points.shape[0]+ if rotation is None:+ rotation = torch.eye(3, device=points.device, dtype=points.dtype).unsqueeze(0).expand(batch_size, -1, -1)+ if camera_center is None:+ camera_center = torch.zeros(batch_size, 2, device=points.device, dtype=points.dtype)+ # Populate intrinsic camera matrix K.+ K = torch.zeros([batch_size, 3, 3], device=points.device, dtype=points.dtype)+ K[:,0,0] = focal_length[:,0]+ K[:,1,1] = focal_length[:,1]+ K[:,2,2] = 1.+ K[:,:-1, -1] = camera_center++ # Transform points+ points = torch.einsum('bij,bkj->bki', rotation, points)+ points = points + translation.unsqueeze(1)++ # Apply perspective distortion+ projected_points = points / points[:,:,-1].unsqueeze(-1)++ # Apply camera intrinsics+ projected_points = torch.einsum('bij,bkj->bki', K, projected_points)++ return projected_points[:, :, :-1]\ No newline at end of filediff --git a/motion2mixamorig/vendor/hamer/mano_head.py b/motion2mixamorig/vendor/hamer/mano_head.pynew file mode 100644index 0000000..63249fe--- /dev/null+++ b/motion2mixamorig/vendor/hamer/mano_head.py@@ -0,0 +1,60 @@+"""HaMeR MANO transformer-decoder head (hamer/models/heads/mano_head.py), without yacs.++The constants are the released hamer.ckpt configuration (model_config.yaml):+6d joint representation, 15 hand joints + global orient, zero input token,+one IEF iteration, decoder depth 6 / heads 8 / mlp 1024 / context 1280.+"""++from __future__ import annotations++import einops+import numpy as np+import torch+import torch.nn as nn++from .geometry import rot6d_to_rotmat+from .pose_transformer import TransformerDecoder++NUM_HAND_JOINTS = 15+++class MANOTransformerDecoderHead(nn.Module):+ """Cross-attention based MANO Transformer decoder."""++ def __init__(self, mean_params_npz: str):+ super().__init__()+ self.joint_rep_dim = 6+ self.npose = self.joint_rep_dim * (NUM_HAND_JOINTS + 1)+ self.transformer = TransformerDecoder(+ num_tokens=1,+ token_dim=1,+ dim=1024,+ depth=6,+ heads=8,+ mlp_dim=1024,+ dim_head=64,+ dropout=0.0,+ emb_dropout=0.0,+ norm="layer",+ context_dim=1280,+ )+ dim = 1024+ self.decpose = nn.Linear(dim, self.npose)+ self.decshape = nn.Linear(dim, 10)+ self.deccam = nn.Linear(dim, 3)++ mean_params = np.load(mean_params_npz)+ self.register_buffer("init_hand_pose", torch.from_numpy(mean_params["pose"].astype(np.float32)).unsqueeze(0))+ self.register_buffer("init_betas", torch.from_numpy(mean_params["shape"].astype(np.float32)).unsqueeze(0))+ self.register_buffer("init_cam", torch.from_numpy(mean_params["cam"].astype(np.float32)).unsqueeze(0))++ def forward(self, x: torch.Tensor):+ batch_size = x.shape[0]+ x = einops.rearrange(x, "b c h w -> b (h w) c") # channel-first -> token-first+ token = torch.zeros(batch_size, 1, 1, device=x.device, dtype=x.dtype)+ token_out = self.transformer(token, context=x).squeeze(1)+ pred_hand_pose = self.decpose(token_out) + self.init_hand_pose.expand(batch_size, -1)+ pred_betas = self.decshape(token_out) + self.init_betas.expand(batch_size, -1)+ pred_cam = self.deccam(token_out) + self.init_cam.expand(batch_size, -1)+ rotmats = rot6d_to_rotmat(pred_hand_pose).view(batch_size, NUM_HAND_JOINTS + 1, 3, 3)+ return {"global_orient": rotmats[:, 0], "hand_pose": rotmats[:, 1:], "betas": pred_betas}, pred_camdiff --git a/motion2mixamorig/vendor/hamer/mano_wrapper.py b/motion2mixamorig/vendor/hamer/mano_wrapper.pynew file mode 100644index 0000000..f6f0cc3--- /dev/null+++ b/motion2mixamorig/vendor/hamer/mano_wrapper.py@@ -0,0 +1,40 @@+import torch+import numpy as np+import pickle+from typing import Optional+import smplx+from smplx.lbs import vertices2joints+from smplx.utils import MANOOutput, to_tensor+from smplx.vertex_ids import vertex_ids+++class MANO(smplx.MANOLayer):+ def __init__(self, *args, joint_regressor_extra: Optional[str] = None, **kwargs):+ """+ Extension of the official MANO implementation to support more joints.+ Args:+ Same as MANOLayer.+ joint_regressor_extra (str): Path to extra joint regressor.+ """+ super(MANO, self).__init__(*args, **kwargs)+ mano_to_openpose = [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20]++ #2, 3, 5, 4, 1+ if joint_regressor_extra is not None:+ self.register_buffer('joint_regressor_extra', torch.tensor(pickle.load(open(joint_regressor_extra, 'rb'), encoding='latin1'), dtype=torch.float32))+ self.register_buffer('extra_joints_idxs', to_tensor(list(vertex_ids['mano'].values()), dtype=torch.long))+ self.register_buffer('joint_map', torch.tensor(mano_to_openpose, dtype=torch.long))++ def forward(self, *args, **kwargs) -> MANOOutput:+ """+ Run forward pass. Same as MANO and also append an extra set of joints if joint_regressor_extra is specified.+ """+ mano_output = super(MANO, self).forward(*args, **kwargs)+ extra_joints = torch.index_select(mano_output.vertices, 1, self.extra_joints_idxs)+ joints = torch.cat([mano_output.joints, extra_joints], dim=1)+ joints = joints[:, self.joint_map, :]+ if hasattr(self, 'joint_regressor_extra'):+ extra_joints = vertices2joints(self.joint_regressor_extra, mano_output.vertices)+ joints = torch.cat([joints, extra_joints], dim=1)+ mano_output.joints = joints+ return mano_outputdiff --git a/motion2mixamorig/vendor/hamer/pose_transformer.py b/motion2mixamorig/vendor/hamer/pose_transformer.pynew file mode 100644index 0000000..ac04971--- /dev/null+++ b/motion2mixamorig/vendor/hamer/pose_transformer.py@@ -0,0 +1,358 @@+from inspect import isfunction+from typing import Callable, Optional++import torch+from einops import rearrange+from einops.layers.torch import Rearrange+from torch import nn++from .t_cond_mlp import (+ AdaptiveLayerNorm1D,+ FrequencyEmbedder,+ normalization_layer,+)+# from .vit import Attention, FeedForward+++def exists(val):+ return val is not None+++def default(val, d):+ if exists(val):+ return val+ return d() if isfunction(d) else d+++class PreNorm(nn.Module):+ def __init__(self, dim: int, fn: Callable, norm: str = "layer", norm_cond_dim: int = -1):+ super().__init__()+ self.norm = normalization_layer(norm, dim, norm_cond_dim)+ self.fn = fn++ def forward(self, x: torch.Tensor, *args, **kwargs):+ if isinstance(self.norm, AdaptiveLayerNorm1D):+ return self.fn(self.norm(x, *args), **kwargs)+ else:+ return self.fn(self.norm(x), **kwargs)+++class FeedForward(nn.Module):+ def __init__(self, dim, hidden_dim, dropout=0.0):+ super().__init__()+ self.net = nn.Sequential(+ nn.Linear(dim, hidden_dim),+ nn.GELU(),+ nn.Dropout(dropout),+ nn.Linear(hidden_dim, dim),+ nn.Dropout(dropout),+ )++ def forward(self, x):+ return self.net(x)+++class Attention(nn.Module):+ def __init__(self, dim, heads=8, dim_head=64, dropout=0.0):+ super().__init__()+ inner_dim = dim_head * heads+ project_out = not (heads == 1 and dim_head == dim)++ self.heads = heads+ self.scale = dim_head**-0.5++ self.attend = nn.Softmax(dim=-1)+ self.dropout = nn.Dropout(dropout)++ self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)++ self.to_out = (+ nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout))+ if project_out+ else nn.Identity()+ )++ def forward(self, x):+ qkv = self.to_qkv(x).chunk(3, dim=-1)+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=self.heads), qkv)++ dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale++ attn = self.attend(dots)+ attn = self.dropout(attn)++ out = torch.matmul(attn, v)+ out = rearrange(out, "b h n d -> b n (h d)")+ return self.to_out(out)+++class CrossAttention(nn.Module):+ def __init__(self, dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):+ super().__init__()+ inner_dim = dim_head * heads+ project_out = not (heads == 1 and dim_head == dim)++ self.heads = heads+ self.scale = dim_head**-0.5++ self.attend = nn.Softmax(dim=-1)+ self.dropout = nn.Dropout(dropout)++ context_dim = default(context_dim, dim)+ self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias=False)+ self.to_q = nn.Linear(dim, inner_dim, bias=False)++ self.to_out = (+ nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout))+ if project_out+ else nn.Identity()+ )++ def forward(self, x, context=None):+ context = default(context, x)+ k, v = self.to_kv(context).chunk(2, dim=-1)+ q = self.to_q(x)+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=self.heads), [q, k, v])++ dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale++ attn = self.attend(dots)+ attn = self.dropout(attn)++ out = torch.matmul(attn, v)+ out = rearrange(out, "b h n d -> b n (h d)")+ return self.to_out(out)+++class Transformer(nn.Module):+ def __init__(+ self,+ dim: int,+ depth: int,+ heads: int,+ dim_head: int,+ mlp_dim: int,+ dropout: float = 0.0,+ norm: str = "layer",+ norm_cond_dim: int = -1,+ ):+ super().__init__()+ self.layers = nn.ModuleList([])+ for _ in range(depth):+ sa = Attention(dim, heads=heads, dim_head=dim_head, dropout=dropout)+ ff = FeedForward(dim, mlp_dim, dropout=dropout)+ self.layers.append(+ nn.ModuleList(+ [+ PreNorm(dim, sa, norm=norm, norm_cond_dim=norm_cond_dim),+ PreNorm(dim, ff, norm=norm, norm_cond_dim=norm_cond_dim),+ ]+ )+ )++ def forward(self, x: torch.Tensor, *args):+ for attn, ff in self.layers:+ x = attn(x, *args) + x+ x = ff(x, *args) + x+ return x+++class TransformerCrossAttn(nn.Module):+ def __init__(+ self,+ dim: int,+ depth: int,+ heads: int,+ dim_head: int,+ mlp_dim: int,+ dropout: float = 0.0,+ norm: str = "layer",+ norm_cond_dim: int = -1,+ context_dim: Optional[int] = None,+ ):+ super().__init__()+ self.layers = nn.ModuleList([])+ for _ in range(depth):+ sa = Attention(dim, heads=heads, dim_head=dim_head, dropout=dropout)+ ca = CrossAttention(+ dim, context_dim=context_dim, heads=heads, dim_head=dim_head, dropout=dropout+ )+ ff = FeedForward(dim, mlp_dim, dropout=dropout)+ self.layers.append(+ nn.ModuleList(+ [+ PreNorm(dim, sa, norm=norm, norm_cond_dim=norm_cond_dim),+ PreNorm(dim, ca, norm=norm, norm_cond_dim=norm_cond_dim),+ PreNorm(dim, ff, norm=norm, norm_cond_dim=norm_cond_dim),+ ]+ )+ )++ def forward(self, x: torch.Tensor, *args, context=None, context_list=None):+ if context_list is None:+ context_list = [context] * len(self.layers)+ if len(context_list) != len(self.layers):+ raise ValueError(f"len(context_list) != len(self.layers) ({len(context_list)} != {len(self.layers)})")++ for i, (self_attn, cross_attn, ff) in enumerate(self.layers):+ x = self_attn(x, *args) + x+ x = cross_attn(x, *args, context=context_list[i]) + x+ x = ff(x, *args) + x+ return x+++class DropTokenDropout(nn.Module):+ def __init__(self, p: float = 0.1):+ super().__init__()+ if p < 0 or p > 1:+ raise ValueError(+ "dropout probability has to be between 0 and 1, " "but got {}".format(p)+ )+ self.p = p++ def forward(self, x: torch.Tensor):+ # x: (batch_size, seq_len, dim)+ if self.training and self.p > 0:+ zero_mask = torch.full_like(x[0, :, 0], self.p).bernoulli().bool()+ # TODO: permutation idx for each batch using torch.argsort+ if zero_mask.any():+ x = x[:, ~zero_mask, :]+ return x+++class ZeroTokenDropout(nn.Module):+ def __init__(self, p: float = 0.1):+ super().__init__()+ if p < 0 or p > 1:+ raise ValueError(+ "dropout probability has to be between 0 and 1, " "but got {}".format(p)+ )+ self.p = p++ def forward(self, x: torch.Tensor):+ # x: (batch_size, seq_len, dim)+ if self.training and self.p > 0:+ zero_mask = torch.full_like(x[:, :, 0], self.p).bernoulli().bool()+ # Zero-out the masked tokens+ x[zero_mask, :] = 0+ return x+++class TransformerEncoder(nn.Module):+ def __init__(+ self,+ num_tokens: int,+ token_dim: int,+ dim: int,+ depth: int,+ heads: int,+ mlp_dim: int,+ dim_head: int = 64,+ dropout: float = 0.0,+ emb_dropout: float = 0.0,+ emb_dropout_type: str = "drop",+ emb_dropout_loc: str = "token",+ norm: str = "layer",+ norm_cond_dim: int = -1,+ token_pe_numfreq: int = -1,+ ):+ super().__init__()+ if token_pe_numfreq > 0:+ token_dim_new = token_dim * (2 * token_pe_numfreq + 1)+ self.to_token_embedding = nn.Sequential(+ Rearrange("b n d -> (b n) d", n=num_tokens, d=token_dim),+ FrequencyEmbedder(token_pe_numfreq, token_pe_numfreq - 1),+ Rearrange("(b n) d -> b n d", n=num_tokens, d=token_dim_new),+ nn.Linear(token_dim_new, dim),+ )+ else:+ self.to_token_embedding = nn.Linear(token_dim, dim)+ self.pos_embedding = nn.Parameter(torch.randn(1, num_tokens, dim))+ if emb_dropout_type == "drop":+ self.dropout = DropTokenDropout(emb_dropout)+ elif emb_dropout_type == "zero":+ self.dropout = ZeroTokenDropout(emb_dropout)+ else:+ raise ValueError(f"Unknown emb_dropout_type: {emb_dropout_type}")+ self.emb_dropout_loc = emb_dropout_loc++ self.transformer = Transformer(+ dim, depth, heads, dim_head, mlp_dim, dropout, norm=norm, norm_cond_dim=norm_cond_dim+ )++ def forward(self, inp: torch.Tensor, *args, **kwargs):+ x = inp++ if self.emb_dropout_loc == "input":+ x = self.dropout(x)+ x = self.to_token_embedding(x)++ if self.emb_dropout_loc == "token":+ x = self.dropout(x)+ b, n, _ = x.shape+ x += self.pos_embedding[:, :n]++ if self.emb_dropout_loc == "token_afterpos":+ x = self.dropout(x)+ x = self.transformer(x, *args)+ return x+++class TransformerDecoder(nn.Module):+ def __init__(+ self,+ num_tokens: int,+ token_dim: int,+ dim: int,+ depth: int,+ heads: int,+ mlp_dim: int,+ dim_head: int = 64,+ dropout: float = 0.0,+ emb_dropout: float = 0.0,+ emb_dropout_type: str = 'drop',+ norm: str = "layer",+ norm_cond_dim: int = -1,+ context_dim: Optional[int] = None,+ skip_token_embedding: bool = False,+ ):+ super().__init__()+ if not skip_token_embedding:+ self.to_token_embedding = nn.Linear(token_dim, dim)+ else:+ self.to_token_embedding = nn.Identity()+ if token_dim != dim:+ raise ValueError(+ f"token_dim ({token_dim}) != dim ({dim}) when skip_token_embedding is True"+ )++ self.pos_embedding = nn.Parameter(torch.randn(1, num_tokens, dim))+ if emb_dropout_type == "drop":+ self.dropout = DropTokenDropout(emb_dropout)+ elif emb_dropout_type == "zero":+ self.dropout = ZeroTokenDropout(emb_dropout)+ elif emb_dropout_type == "normal":+ self.dropout = nn.Dropout(emb_dropout)++ self.transformer = TransformerCrossAttn(+ dim,+ depth,+ heads,+ dim_head,+ mlp_dim,+ dropout,+ norm=norm,+ norm_cond_dim=norm_cond_dim,+ context_dim=context_dim,+ )++ def forward(self, inp: torch.Tensor, *args, context=None, context_list=None):+ x = self.to_token_embedding(inp)+ b, n, _ = x.shape++ x = self.dropout(x)+ x += self.pos_embedding[:, :n]++ x = self.transformer(x, *args, context=context, context_list=context_list)+ return x+diff --git a/motion2mixamorig/vendor/hamer/t_cond_mlp.py b/motion2mixamorig/vendor/hamer/t_cond_mlp.pynew file mode 100644index 0000000..44d5a09--- /dev/null+++ b/motion2mixamorig/vendor/hamer/t_cond_mlp.py@@ -0,0 +1,199 @@+import copy+from typing import List, Optional++import torch+++class AdaptiveLayerNorm1D(torch.nn.Module):+ def __init__(self, data_dim: int, norm_cond_dim: int):+ super().__init__()+ if data_dim <= 0:+ raise ValueError(f"data_dim must be positive, but got {data_dim}")+ if norm_cond_dim <= 0:+ raise ValueError(f"norm_cond_dim must be positive, but got {norm_cond_dim}")+ self.norm = torch.nn.LayerNorm(+ data_dim+ ) # TODO: Check if elementwise_affine=True is correct+ self.linear = torch.nn.Linear(norm_cond_dim, 2 * data_dim)+ torch.nn.init.zeros_(self.linear.weight)+ torch.nn.init.zeros_(self.linear.bias)++ def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:+ # x: (batch, ..., data_dim)+ # t: (batch, norm_cond_dim)+ # return: (batch, data_dim)+ x = self.norm(x)+ alpha, beta = self.linear(t).chunk(2, dim=-1)++ # Add singleton dimensions to alpha and beta+ if x.dim() > 2:+ alpha = alpha.view(alpha.shape[0], *([1] * (x.dim() - 2)), alpha.shape[1])+ beta = beta.view(beta.shape[0], *([1] * (x.dim() - 2)), beta.shape[1])++ return x * (1 + alpha) + beta+++class SequentialCond(torch.nn.Sequential):+ def forward(self, input, *args, **kwargs):+ for module in self:+ if isinstance(module, (AdaptiveLayerNorm1D, SequentialCond, ResidualMLPBlock)):+ # print(f'Passing on args to {module}', [a.shape for a in args])+ input = module(input, *args, **kwargs)+ else:+ # print(f'Skipping passing args to {module}', [a.shape for a in args])+ input = module(input)+ return input+++def normalization_layer(norm: Optional[str], dim: int, norm_cond_dim: int = -1):+ if norm == "batch":+ return torch.nn.BatchNorm1d(dim)+ elif norm == "layer":+ return torch.nn.LayerNorm(dim)+ elif norm == "ada":+ assert norm_cond_dim > 0, f"norm_cond_dim must be positive, got {norm_cond_dim}"+ return AdaptiveLayerNorm1D(dim, norm_cond_dim)+ elif norm is None:+ return torch.nn.Identity()+ else:+ raise ValueError(f"Unknown norm: {norm}")+++def linear_norm_activ_dropout(+ input_dim: int,+ output_dim: int,+ activation: torch.nn.Module = torch.nn.ReLU(),+ bias: bool = True,+ norm: Optional[str] = "layer", # Options: ada/batch/layer+ dropout: float = 0.0,+ norm_cond_dim: int = -1,+) -> SequentialCond:+ layers = []+ layers.append(torch.nn.Linear(input_dim, output_dim, bias=bias))+ if norm is not None:+ layers.append(normalization_layer(norm, output_dim, norm_cond_dim))+ layers.append(copy.deepcopy(activation))+ if dropout > 0.0:+ layers.append(torch.nn.Dropout(dropout))+ return SequentialCond(*layers)+++def create_simple_mlp(+ input_dim: int,+ hidden_dims: List[int],+ output_dim: int,+ activation: torch.nn.Module = torch.nn.ReLU(),+ bias: bool = True,+ norm: Optional[str] = "layer", # Options: ada/batch/layer+ dropout: float = 0.0,+ norm_cond_dim: int = -1,+) -> SequentialCond:+ layers = []+ prev_dim = input_dim+ for hidden_dim in hidden_dims:+ layers.extend(+ linear_norm_activ_dropout(+ prev_dim, hidden_dim, activation, bias, norm, dropout, norm_cond_dim+ )+ )+ prev_dim = hidden_dim+ layers.append(torch.nn.Linear(prev_dim, output_dim, bias=bias))+ return SequentialCond(*layers)+++class ResidualMLPBlock(torch.nn.Module):+ def __init__(+ self,+ input_dim: int,+ hidden_dim: int,+ num_hidden_layers: int,+ output_dim: int,+ activation: torch.nn.Module = torch.nn.ReLU(),+ bias: bool = True,+ norm: Optional[str] = "layer", # Options: ada/batch/layer+ dropout: float = 0.0,+ norm_cond_dim: int = -1,+ ):+ super().__init__()+ if not (input_dim == output_dim == hidden_dim):+ raise NotImplementedError(+ f"input_dim {input_dim} != output_dim {output_dim} is not implemented"+ )++ layers = []+ prev_dim = input_dim+ for i in range(num_hidden_layers):+ layers.append(+ linear_norm_activ_dropout(+ prev_dim, hidden_dim, activation, bias, norm, dropout, norm_cond_dim+ )+ )+ prev_dim = hidden_dim+ self.model = SequentialCond(*layers)+ self.skip = torch.nn.Identity()++ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:+ return x + self.model(x, *args, **kwargs)+++class ResidualMLP(torch.nn.Module):+ def __init__(+ self,+ input_dim: int,+ hidden_dim: int,+ num_hidden_layers: int,+ output_dim: int,+ activation: torch.nn.Module = torch.nn.ReLU(),+ bias: bool = True,+ norm: Optional[str] = "layer", # Options: ada/batch/layer+ dropout: float = 0.0,+ num_blocks: int = 1,+ norm_cond_dim: int = -1,+ ):+ super().__init__()+ self.input_dim = input_dim+ self.model = SequentialCond(+ linear_norm_activ_dropout(+ input_dim, hidden_dim, activation, bias, norm, dropout, norm_cond_dim+ ),+ *[+ ResidualMLPBlock(+ hidden_dim,+ hidden_dim,+ num_hidden_layers,+ hidden_dim,+ activation,+ bias,+ norm,+ dropout,+ norm_cond_dim,+ )+ for _ in range(num_blocks)+ ],+ torch.nn.Linear(hidden_dim, output_dim, bias=bias),+ )++ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:+ return self.model(x, *args, **kwargs)+++class FrequencyEmbedder(torch.nn.Module):+ def __init__(self, num_frequencies, max_freq_log2):+ super().__init__()+ frequencies = 2 ** torch.linspace(0, max_freq_log2, steps=num_frequencies)+ self.register_buffer("frequencies", frequencies)++ def forward(self, x):+ # x should be of size (N,) or (N, D)+ N = x.size(0)+ if x.dim() == 1: # (N,)+ x = x.unsqueeze(1) # (N, D) where D=1+ x_unsqueezed = x.unsqueeze(-1) # (N, D, 1)+ scaled = self.frequencies.view(1, 1, -1) * x_unsqueezed # (N, D, num_frequencies)+ s = torch.sin(scaled)+ c = torch.cos(scaled)+ embedded = torch.cat([s, c, x_unsqueezed], dim=-1).view(+ N, -1+ ) # (N, D * 2 * num_frequencies + D)+ return embedded+diff --git a/motion2mixamorig/vendor/hamer/vit.py b/motion2mixamorig/vendor/hamer/vit.pynew file mode 100644index 0000000..21c8cd6--- /dev/null+++ b/motion2mixamorig/vendor/hamer/vit.py@@ -0,0 +1,338 @@+# Copyright (c) OpenMMLab. All rights reserved.+import math++import torch+from functools import partial+import torch.nn as nn+import torch.nn.functional as F+import torch.utils.checkpoint as checkpoint++try:+ from timm.layers import drop_path, to_2tuple, trunc_normal_+except ImportError: # timm < 0.9+ from timm.models.layers import drop_path, to_2tuple, trunc_normal_+++def get_abs_pos(abs_pos, h, w, ori_h, ori_w, has_cls_token=True):+ """+ Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token+ dimension for the original embeddings.+ Args:+ abs_pos (Tensor): absolute positional embeddings with (1, num_position, C).+ has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token.+ hw (Tuple): size of input image tokens.++ Returns:+ Absolute positional embeddings after processing with shape (1, H, W, C)+ """+ cls_token = None+ B, L, C = abs_pos.shape+ if has_cls_token:+ cls_token = abs_pos[:, 0:1]+ abs_pos = abs_pos[:, 1:]++ if ori_h != h or ori_w != w:+ new_abs_pos = F.interpolate(+ abs_pos.reshape(1, ori_h, ori_w, -1).permute(0, 3, 1, 2),+ size=(h, w),+ mode="bicubic",+ align_corners=False,+ ).permute(0, 2, 3, 1).reshape(B, -1, C)++ else:+ new_abs_pos = abs_pos++ if cls_token is not None:+ new_abs_pos = torch.cat([cls_token, new_abs_pos], dim=1)+ return new_abs_pos++class DropPath(nn.Module):+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).+ """+ def __init__(self, drop_prob=None):+ super(DropPath, self).__init__()+ self.drop_prob = drop_prob++ def forward(self, x):+ return drop_path(x, self.drop_prob, self.training)++ def extra_repr(self):+ return 'p={}'.format(self.drop_prob)++class Mlp(nn.Module):+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):+ super().__init__()+ out_features = out_features or in_features+ hidden_features = hidden_features or in_features+ self.fc1 = nn.Linear(in_features, hidden_features)+ self.act = act_layer()+ self.fc2 = nn.Linear(hidden_features, out_features)+ self.drop = nn.Dropout(drop)++ def forward(self, x):+ x = self.fc1(x)+ x = self.act(x)+ x = self.fc2(x)+ x = self.drop(x)+ return x++class Attention(nn.Module):+ def __init__(+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,+ proj_drop=0., attn_head_dim=None,):+ super().__init__()+ self.num_heads = num_heads+ head_dim = dim // num_heads+ self.dim = dim++ if attn_head_dim is not None:+ head_dim = attn_head_dim+ all_head_dim = head_dim * self.num_heads++ self.scale = qk_scale or head_dim ** -0.5++ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=qkv_bias)++ self.attn_drop = nn.Dropout(attn_drop)+ self.proj = nn.Linear(all_head_dim, dim)+ self.proj_drop = nn.Dropout(proj_drop)++ def forward(self, x):+ B, N, C = x.shape+ qkv = self.qkv(x)+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)++ q = q * self.scale+ attn = (q @ k.transpose(-2, -1))++ attn = attn.softmax(dim=-1)+ attn = self.attn_drop(attn)++ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)+ x = self.proj(x)+ x = self.proj_drop(x)++ return x++class Block(nn.Module):++ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None,+ drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU,+ norm_layer=nn.LayerNorm, attn_head_dim=None+ ):+ super().__init__()++ self.norm1 = norm_layer(dim)+ self.attn = Attention(+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,+ attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim+ )++ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()+ self.norm2 = norm_layer(dim)+ mlp_hidden_dim = int(dim * mlp_ratio)+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)++ def forward(self, x):+ x = x + self.drop_path(self.attn(self.norm1(x)))+ x = x + self.drop_path(self.mlp(self.norm2(x)))+ return x+++class PatchEmbed(nn.Module):+ """ Image to Patch Embedding+ """+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, ratio=1):+ super().__init__()+ img_size = to_2tuple(img_size)+ patch_size = to_2tuple(patch_size)+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (ratio ** 2)+ self.patch_shape = (int(img_size[0] // patch_size[0] * ratio), int(img_size[1] // patch_size[1] * ratio))+ self.origin_patch_shape = (int(img_size[0] // patch_size[0]), int(img_size[1] // patch_size[1]))+ self.img_size = img_size+ self.patch_size = patch_size+ self.num_patches = num_patches++ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=(patch_size[0] // ratio), padding=4 + 2 * (ratio//2-1))++ def forward(self, x, **kwargs):+ B, C, H, W = x.shape+ x = self.proj(x)+ Hp, Wp = x.shape[2], x.shape[3]++ x = x.flatten(2).transpose(1, 2)+ return x, (Hp, Wp)+++class HybridEmbed(nn.Module):+ """ CNN Feature Map Embedding+ Extract feature map from CNN, flatten, project to embedding dim.+ """+ def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768):+ super().__init__()+ assert isinstance(backbone, nn.Module)+ img_size = to_2tuple(img_size)+ self.img_size = img_size+ self.backbone = backbone+ if feature_size is None:+ with torch.no_grad():+ training = backbone.training+ if training:+ backbone.eval()+ o = self.backbone(torch.zeros(1, in_chans, img_size[0], img_size[1]))[-1]+ feature_size = o.shape[-2:]+ feature_dim = o.shape[1]+ backbone.train(training)+ else:+ feature_size = to_2tuple(feature_size)+ feature_dim = self.backbone.feature_info.channels()[-1]+ self.num_patches = feature_size[0] * feature_size[1]+ self.proj = nn.Linear(feature_dim, embed_dim)++ def forward(self, x):+ x = self.backbone(x)[-1]+ x = x.flatten(2).transpose(1, 2)+ x = self.proj(x)+ return x+++class ViT(nn.Module):++ def __init__(self,+ img_size=224, patch_size=16, in_chans=3, num_classes=80, embed_dim=768, depth=12,+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,+ drop_path_rate=0., hybrid_backbone=None, norm_layer=None, use_checkpoint=False,+ frozen_stages=-1, ratio=1, last_norm=True,+ patch_padding='pad', freeze_attn=False, freeze_ffn=False,+ ):+ # Protect mutable default arguments+ super(ViT, self).__init__()+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)+ self.num_classes = num_classes+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models+ self.frozen_stages = frozen_stages+ self.use_checkpoint = use_checkpoint+ self.patch_padding = patch_padding+ self.freeze_attn = freeze_attn+ self.freeze_ffn = freeze_ffn+ self.depth = depth++ if hybrid_backbone is not None:+ self.patch_embed = HybridEmbed(+ hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim)+ else:+ self.patch_embed = PatchEmbed(+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, ratio=ratio)+ num_patches = self.patch_embed.num_patches++ # since the pretraining model has class token+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))++ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule++ self.blocks = nn.ModuleList([+ Block(+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,+ )+ for i in range(depth)])++ self.last_norm = norm_layer(embed_dim) if last_norm else nn.Identity()++ if self.pos_embed is not None:+ trunc_normal_(self.pos_embed, std=.02)++ self._freeze_stages()++ def _freeze_stages(self):+ """Freeze parameters."""+ if self.frozen_stages >= 0:+ self.patch_embed.eval()+ for param in self.patch_embed.parameters():+ param.requires_grad = False++ for i in range(1, self.frozen_stages + 1):+ m = self.blocks[i]+ m.eval()+ for param in m.parameters():+ param.requires_grad = False++ if self.freeze_attn:+ for i in range(0, self.depth):+ m = self.blocks[i]+ m.attn.eval()+ m.norm1.eval()+ for param in m.attn.parameters():+ param.requires_grad = False+ for param in m.norm1.parameters():+ param.requires_grad = False++ if self.freeze_ffn:+ self.pos_embed.requires_grad = False+ self.patch_embed.eval()+ for param in self.patch_embed.parameters():+ param.requires_grad = False+ for i in range(0, self.depth):+ m = self.blocks[i]+ m.mlp.eval()+ m.norm2.eval()+ for param in m.mlp.parameters():+ param.requires_grad = False+ for param in m.norm2.parameters():+ param.requires_grad = False++ def init_weights(self):+ """Initialize the weights in backbone.+ Args:+ pretrained (str, optional): Path to pre-trained weights.+ Defaults to None.+ """+ def _init_weights(m):+ if isinstance(m, nn.Linear):+ trunc_normal_(m.weight, std=.02)+ if isinstance(m, nn.Linear) and m.bias is not None:+ nn.init.constant_(m.bias, 0)+ elif isinstance(m, nn.LayerNorm):+ nn.init.constant_(m.bias, 0)+ nn.init.constant_(m.weight, 1.0)++ self.apply(_init_weights)++ def get_num_layers(self):+ return len(self.blocks)++ @torch.jit.ignore+ def no_weight_decay(self):+ return {'pos_embed', 'cls_token'}++ def forward_features(self, x):+ B, C, H, W = x.shape+ x, (Hp, Wp) = self.patch_embed(x)++ if self.pos_embed is not None:+ # fit for multiple GPU training+ # since the first element for pos embed (sin-cos manner) is zero, it will cause no difference+ x = x + self.pos_embed[:, 1:] + self.pos_embed[:, :1]++ for blk in self.blocks:+ if self.use_checkpoint:+ x = checkpoint.checkpoint(blk, x)+ else:+ x = blk(x)++ x = self.last_norm(x)++ xp = x.permute(0, 2, 1).reshape(B, -1, Hp, Wp).contiguous()++ return xp++ def forward(self, x):+ x = self.forward_features(x)+ return x++ def train(self, mode=True):+ """Convert the model into training mode."""+ super().train(mode)+ self._freeze_stages()diff --git a/pyproject.toml b/pyproject.tomlindex 8359a53..c01722e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -7,6 +7,11 @@ dependencies = ["numpy","opencv-python","einops",+ # Optional finger pass (`--detect-hands`): HaMeR + MANO. Not imported+ # unless that flag is on.+ "timm",+ "smplx",+ "scikit-image",# Video -> 3D human skeleton. `preproc` = person detection/tracking,# `rtmpose` = the ungated 2D-pose backend the pipeline uses."gvhmr[preproc,rtmpose]>=1.6",