Retarget human motion from video to an Adobe Mixamo-rigged 3D character.
Python
Update Body detect selector & detect hands selector in Blender
MaxLiud276894fb524
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2661317..f5605ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ All notable changes to this project will be documented in this file.- 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.+- Blender add-on: the Input section has a **Body Model** menu (`--set-extractor`, currently GVHMR) and **Detect Hands** (`--detect-hands`, off by default). Turning hands on shows the about-twice runtime, finger smoothing, and **Choose MANO Hand Model…**. **Check Environment** runs `m2mr doctor` with the same two choices.### Fixeddiff --git a/blender_extension/motion2mixamorig_blender/i18n.py b/blender_extension/motion2mixamorig_blender/i18n.pyindex c20f9fa..c4d6be0 100644--- a/blender_extension/motion2mixamorig_blender/i18n.py+++ b/blender_extension/motion2mixamorig_blender/i18n.py@@ -375,6 +375,17 @@ _add("stage_cancelled", en="cancelled", **{"zh-CN": "已取消"}, ko="취소됨"_add("err_python", en="External Python not found", **{"zh-CN": "找不到外部 Python"}, ko="외부 Python을 찾을 수 없습니다", ja="外部 Python が見つかりません", de="Externes Python nicht gefunden", ru="Внешний Python не найден", ar="لم يُعثر على Python الخارجي")_add("err_package", en="Motion2MixamoRig package not installed", **{"zh-CN": "未安装 Motion2MixamoRig 软件包"}, ko="Motion2MixamoRig 패키지가 설치되지 않았습니다", ja="Motion2MixamoRig パッケージがインストールされていません", de="Motion2MixamoRig-Paket ist nicht installiert", ru="Пакет Motion2MixamoRig не установлен", ar="حزمة Motion2MixamoRig غير مثبتة")_add("err_smplx", en="SMPL-X model missing", **{"zh-CN": "缺少 SMPL-X 模型"}, ko="SMPL-X 모델이 없습니다", ja="SMPL-X モデルがありません", de="SMPL-X-Modell fehlt", ru="Модель SMPL-X отсутствует", ar="نموذج SMPL-X مفقود")+_add("err_mano", en="MANO hand model missing", **{"zh-CN": "缺少 MANO 手部模型"}, ko="MANO 손 모델이 없습니다", ja="MANO ハンドモデルがありません", de="MANO-Handmodell fehlt", ru="Модель кисти MANO отсутствует", ar="نموذج يد MANO مفقود")+_add(+ "err_hand_deps",+ en="Hand detection needs timm, smplx, and scikit-image. Use Update Runtime",+ **{"zh-CN": "手部检测需要 timm、smplx 和 scikit-image。请点「更新运行环境」"},+ ko="손 검출에는 timm, smplx, scikit-image가 필요합니다. 런타임을 업데이트하세요",+ ja="手の検出には timm、smplx、scikit-image が必要です。ランタイムを更新してください",+ de="Handerkennung braucht timm, smplx und scikit-image. Laufzeit aktualisieren",+ ru="Для кистей нужны timm, smplx и scikit-image. Обновите среду",+ ar="كشف اليد يحتاج timm وsmplx وscikit-image. حدّث بيئة التشغيل",+)_add("err_invalid_rig", en="Mixamo FBX invalid", **{"zh-CN": "Mixamo FBX 无效"}, ko="Mixamo FBX가 올바르지 않습니다", ja="Mixamo FBX が無効です", de="Mixamo-FBX ungültig", ru="Некорректный Mixamo FBX", ar="ملف Mixamo FBX غير صالح")_add("err_multiple_people", en="Input contains multiple people", **{"zh-CN": "输入里有多个人"}, ko="입력에 여러 사람이 있습니다", ja="入力に複数人が写っています", de="Die Quelle enthält mehrere Personen", ru="Во входе несколько людей", ar="المصدر يحتوي على أكثر من شخص")_add("err_no_person", en="No person was detected in the input", **{"zh-CN": "输入里没有检测到人"}, ko="입력에서 사람을 찾지 못했습니다", ja="入力から人物を検出できませんでした", de="Keine Person in der Quelle erkannt", ru="Человек во входе не обнаружен", ar="لم يُكتشف أي شخص في المصدر")@@ -418,6 +429,8 @@ _CODE_TO_KEY = {"PYTHON_NOT_FOUND": "err_python","PACKAGE_MISSING": "err_package","SMPLX_MISSING": "err_smplx",+ "MANO_MISSING": "err_mano",+ "HAND_DEPS_MISSING": "err_hand_deps","INVALID_RIG": "err_invalid_rig","MULTIPLE_PEOPLE": "err_multiple_people","NO_PERSON": "err_no_person",@@ -450,6 +463,27 @@ _add("setup_running", en="Installing runtime…", **{"zh-CN": "正在安装运_add("setup_done", en="Runtime installed", **{"zh-CN": "运行环境已安装"})_add("setup_failed", en="Runtime installation failed", **{"zh-CN": "运行环境安装失败"})_add("err_backend_missing", en="This add-on build does not include the Motion2MixamoRig code", **{"zh-CN": "这个插件包里缺少 Motion2MixamoRig 程序代码"})+_add("extractor", en="Body Model", **{"zh-CN": "身体模型"})+_add("extractor_gvhmr_desc", en="Recover the 3D skeleton with GVHMR", **{"zh-CN": "用 GVHMR 恢复 3D 骨架"})+_add(+ "detect_hands",+ en="Detect Hands",+ **{"zh-CN": "检测手部"},+)+_add(+ "detect_hands_slow",+ en="About twice as long. The first time also downloads ~2.7 GB of hand weights",+ **{"zh-CN": "整次运行大约要两倍时间。第一次还会再下载约 2.7 GB 手部权重"},+)+_add("hand_smooth", en="Finger Smoothing (seconds)", **{"zh-CN": "手指平滑(秒)"})+_add("choose_mano", en="Choose MANO Hand Model…", **{"zh-CN": "选择 MANO 手部模型…"})+_add("mano_found", en="MANO hand model: found", **{"zh-CN": "MANO 手部模型:已就绪"})+_add(+ "mano_missing",+ en="MANO hand model: missing — download MANO_RIGHT.pkl from mano.is.tue.mpg.de",+ **{"zh-CN": "MANO 手部模型:缺失 — 请从 mano.is.tue.mpg.de 下载 MANO_RIGHT.pkl"},+)+_add("mano_copied", en="MANO hand model copied to {path}", **{"zh-CN": "MANO 手部模型已复制到 {path}"})_add("choose_smplx", en="Choose SMPL-X Model…", **{"zh-CN": "选择 SMPL-X 模型文件…"})_add("smplx_found", en="SMPL-X model: found", **{"zh-CN": "SMPL-X 模型:已就绪"})_add("smplx_missing", en="SMPL-X model: missing — download SMPLX_NEUTRAL.npz from smpl-x.is.tue.mpg.de", **{"zh-CN": "SMPL-X 模型:缺失 — 请从 smpl-x.is.tue.mpg.de 下载 SMPLX_NEUTRAL.npz"})diff --git a/blender_extension/motion2mixamorig_blender/operators/check_environment.py b/blender_extension/motion2mixamorig_blender/operators/check_environment.pyindex d387edf..539be15 100644--- a/blender_extension/motion2mixamorig_blender/operators/check_environment.py+++ b/blender_extension/motion2mixamorig_blender/operators/check_environment.py@@ -78,7 +78,11 @@ class M2MR_OT_check_environment(Operator):try:process, log_file = launch_process(- build_doctor_argv(python),+ build_doctor_argv(+ python,+ extractor=props.extractor,+ detect_hands=bool(props.detect_hands),+ ),cwd=project,log_path=log_path,env=subprocess_env(project),diff --git a/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py b/blender_extension/motion2mixamorig_blender/operators/run_pipeline.pyindex 30f127d..280cc4d 100644--- a/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py+++ b/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py@@ -36,6 +36,7 @@ class M2MR_OT_run_pipeline(Operator):source=props.source_path,rig=props.rig_path,busy=is_busy(),+ detect_hands=bool(props.detect_hands),)if errors:props.job_status = "failed"@@ -59,6 +60,9 @@ class M2MR_OT_run_pipeline(Operator):output_dir=output_dir,progress_jsonl=progress_path,preview=bool(props.generate_preview),+ extractor=props.extractor,+ detect_hands=bool(props.detect_hands),+ hand_smooth_s=float(props.hand_smooth),)try:process, log_file = launch_process(diff --git a/blender_extension/motion2mixamorig_blender/operators/setup_runtime.py b/blender_extension/motion2mixamorig_blender/operators/setup_runtime.pyindex 2713248..c6c5607 100644--- a/blender_extension/motion2mixamorig_blender/operators/setup_runtime.py+++ b/blender_extension/motion2mixamorig_blender/operators/setup_runtime.py@@ -24,6 +24,7 @@ from ..services.runtime_setup import (from .runtime import JobRuntime, attach, is_busySMPLX_RELATIVE = Path("assets") / "body_models" / "smplx" / "SMPLX_NEUTRAL.npz"+MANO_DIR = Path("assets") / "body_models" / "mano"class M2MR_OT_setup_runtime(Operator):@@ -107,7 +108,34 @@ class M2MR_OT_set_smplx(Operator):return {"FINISHED"}-CLASSES = (M2MR_OT_setup_runtime, M2MR_OT_set_smplx)+class M2MR_OT_set_mano(Operator):+ bl_idname = "m2mr.set_mano"+ bl_label = "Choose MANO Hand Model"+ bl_description = "Pick the MANO_RIGHT.pkl you downloaded; it is copied into the runtime"++ filepath: StringProperty(subtype="FILE_PATH")+ filter_glob: StringProperty(default="*.pkl;*.npz", options={"HIDDEN"})++ def invoke(self, context: Context, event):+ context.window_manager.fileselect_add(self)+ return {"RUNNING_MODAL"}++ def execute(self, context: Context):+ src = Path(bpy.path.abspath(self.filepath))+ if not src.is_file() or src.suffix.lower() not in {".pkl", ".npz"}:+ self.report({"ERROR"}, t("err_mano"))+ return {"CANCELLED"}+ prefs = get_preferences(context)+ project = Path(prefs.project_dir) if directory_exists(prefs.project_dir) else app_dir(default_home())+ name = "MANO_RIGHT.npz" if src.suffix.lower() == ".npz" else "MANO_RIGHT.pkl"+ dest = project / MANO_DIR / name+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(src, dest)+ self.report({"INFO"}, t("mano_copied", path=str(dest)))+ return {"FINISHED"}+++CLASSES = (M2MR_OT_setup_runtime, M2MR_OT_set_smplx, M2MR_OT_set_mano)def register() -> None:diff --git a/blender_extension/motion2mixamorig_blender/panels/main_panel.py b/blender_extension/motion2mixamorig_blender/panels/main_panel.pyindex 027ee43..7fe9056 100644--- a/blender_extension/motion2mixamorig_blender/panels/main_panel.py+++ b/blender_extension/motion2mixamorig_blender/panels/main_panel.py@@ -110,12 +110,27 @@ class M2MR_PT_main(Panel):row.operator("m2mr.set_smplx", text=t("choose_smplx"), icon="CHECKMARK" if found else "FILE_BLANK")sub.label(text=t("smplx_found") if found else t("smplx_missing"))+ def _draw_mano(self, box, prefs, busy: bool) -> None:+ from ..services.backend import mano_model_present++ found = bool(prefs.project_dir) and mano_model_present(prefs.project_dir)+ row = box.row()+ row.enabled = not busy+ row.operator("m2mr.set_mano", text=t("choose_mano"), icon="CHECKMARK" if found else "FILE_BLANK")+ box.label(text=t("mano_found") if found else t("mano_missing"))+def _draw_input(self, layout, prefs, props, busy: bool) -> None:box = layout.box()box.label(text=t("section_input"))box.prop(props, "source_type", text=t("source_type"))box.prop(props, "source_path", text=t("source_file"))box.prop(props, "rig_path", text=t("mixamo_rig"))+ box.prop(props, "extractor", text=t("extractor"))+ box.prop(props, "detect_hands", text=t("detect_hands"))+ if props.detect_hands:+ box.label(text=t("detect_hands_slow"))+ box.prop(props, "hand_smooth", text=t("hand_smooth"))+ self._draw_mano(box, prefs, busy)box.prop(props, "generate_preview", text=t("generate_preview"))if not busy and _first_run(prefs):_draw_first_run_note(box)diff --git a/blender_extension/motion2mixamorig_blender/properties.py b/blender_extension/motion2mixamorig_blender/properties.pyindex f86460e..1dd7427 100644--- a/blender_extension/motion2mixamorig_blender/properties.py+++ b/blender_extension/motion2mixamorig_blender/properties.py@@ -11,6 +11,7 @@ from .registration import safe_register_class, safe_unregister_class_SOURCE_TYPE_ITEMS = ()_DEVICE_ITEMS = ()+_EXTRACTOR_ITEMS = ()def _source_type_items(self, context):@@ -24,6 +25,16 @@ def _source_type_items(self, context):return _SOURCE_TYPE_ITEMS+def _extractor_items(self, context):+ from .i18n import t++ global _EXTRACTOR_ITEMS+ _EXTRACTOR_ITEMS = (+ ("gvhmr", "GVHMR", t("extractor_gvhmr_desc")),+ )+ return _EXTRACTOR_ITEMS++def _device_items(self, context):from .i18n import t@@ -57,6 +68,29 @@ class M2MRProperties(PropertyGroup):name="Device",items=_device_items,)+ extractor: EnumProperty(+ name="Body Model",+ description="How the video or still becomes a 3D skeleton",+ items=_extractor_items,+ )+ detect_hands: BoolProperty(+ name="Detect Hands",+ description=(+ "Also run the hand model that belongs to the selected body model "+ "(GVHMR uses HaMeR). Off leaves the fingers at rest. "+ "The run takes about twice as long"+ ),+ default=False,+ )+ hand_smooth: FloatProperty(+ name="Finger Smoothing",+ description="Smooth detected finger rotations over this many seconds. 0 keeps the raw estimate",+ default=0.08,+ min=0.0,+ max=2.0,+ step=1,+ precision=2,+ )generate_preview: BoolProperty(name="Generate Preview Videos",description="Also render preview videos/images (slower)",diff --git a/blender_extension/motion2mixamorig_blender/registration.py b/blender_extension/motion2mixamorig_blender/registration.pyindex 14f9767..f349910 100644--- a/blender_extension/motion2mixamorig_blender/registration.py+++ b/blender_extension/motion2mixamorig_blender/registration.py@@ -1,33 +1,68 @@"""Reload-safe class registration.-Installing a zip over an enabled extension can import a new class object-while Blender still holds the previous one under the same type name.+Installing a zip over an enabled extension imports a new class object while+Blender still holds the previous one. Operators and panels stay on+``bpy.types``. Preferences and property groups do not: Blender 5.2 keeps+those only on the RNA subclass list, so a ``bpy.types`` lookup misses them+and the next ``register_class`` reports "already registered"."""from __future__ import annotationsimport bpy+# Bases whose subclasses Blender may keep off ``bpy.types``.+_SUBCLASS_ROOTS = (+ "AddonPreferences",+ "PropertyGroup",+ "Operator",+ "Panel",+ "Menu",+ "Header",+ "UIList",+)-def registered_class(cls):- return getattr(bpy.types, cls.__name__, None)+def _registered_classes(name: str) -> list[type]:+ found: list[type] = []+ seen: set[int] = set()-def safe_register_class(cls) -> None:- existing = registered_class(cls)- if existing is not None:+ def add(cls) -> None:+ if not isinstance(cls, type) or cls.__name__ != name or id(cls) in seen:+ return+ seen.add(id(cls))+ found.append(cls)++ add(getattr(bpy.types, name, None))+ for root_name in _SUBCLASS_ROOTS:+ root = getattr(bpy.types, root_name, None)+ if root is None:+ continue+ for subclass in root.__subclasses__():+ add(subclass)+ return found+++def _unregister_named(name: str) -> None:+ for existing in _registered_classes(name):+ if not getattr(existing, "is_registered", False):+ continuetry:bpy.utils.unregister_class(existing)except Exception:pass- bpy.utils.register_class(cls)-def safe_unregister_class(cls) -> None:- existing = registered_class(cls)- if existing is None:- return+def safe_register_class(cls) -> None:+ _unregister_named(cls.__name__)try:- bpy.utils.unregister_class(existing)- except Exception:- pass+ bpy.utils.register_class(cls)+ except ValueError as exc:+ if "already registered" not in str(exc):+ raise+ _unregister_named(cls.__name__)+ bpy.utils.register_class(cls)+++def safe_unregister_class(cls) -> None:+ _unregister_named(cls.__name__)diff --git a/blender_extension/motion2mixamorig_blender/services/backend.py b/blender_extension/motion2mixamorig_blender/services/backend.pyindex 3e4acec..80a9b83 100644--- a/blender_extension/motion2mixamorig_blender/services/backend.py+++ b/blender_extension/motion2mixamorig_blender/services/backend.py@@ -35,8 +35,37 @@ def build_version_argv(python: str | Path) -> list[str]:return [os.fspath(as_user_path(python)), "--version"]-def build_doctor_argv(python: str | Path) -> list[str]:- return [os.fspath(as_user_path(python)), "-m", "motion2mixamorig.cli", "doctor"]+# Names the add-on may pass to `--set-extractor`. Keep this in step with+# motion2mixamorig.extractors; the add-on must not import that package.+EXTRACTORS = ("gvhmr",)+DEFAULT_EXTRACTOR = "gvhmr"+++def mano_model_present(project_dir: str | Path) -> bool:+ """True when the project already has a MANO right-hand file for `--detect-hands`."""+ folder = as_user_path(project_dir) / "assets" / "body_models" / "mano"+ return (folder / "MANO_RIGHT.pkl").is_file() or (folder / "MANO_RIGHT.npz").is_file()+++def build_doctor_argv(+ python: str | Path,+ *,+ extractor: str = DEFAULT_EXTRACTOR,+ detect_hands: bool = False,+) -> list[str]:+ if extractor not in EXTRACTORS:+ raise ValueError(f"extractor must be one of {EXTRACTORS}, got {extractor!r}")+ cmd = [+ os.fspath(as_user_path(python)),+ "-m",+ "motion2mixamorig.cli",+ "doctor",+ "--set-extractor",+ extractor,+ ]+ if detect_hands:+ cmd.append("--detect-hands")+ return cmddef build_run_argv(@@ -49,18 +78,25 @@ def build_run_argv(output_dir: str | Path,progress_jsonl: str | Path,preview: bool,+ extractor: str = DEFAULT_EXTRACTOR,+ detect_hands: bool = False,+ hand_smooth_s: float = 0.08,) -> list[str]:"""Build `external-python -m motion2mixamorig.cli run ...` as a list."""if source_type not in {"video", "image"}:raise ValueError(f"source_type must be 'video' or 'image', got {source_type!r}")if device not in {"cpu", "cuda", "mps"}:raise ValueError(f"device must be cpu, cuda, or mps, got {device!r}")+ if extractor not in EXTRACTORS:+ raise ValueError(f"extractor must be one of {EXTRACTORS}, got {extractor!r}")cmd = [os.fspath(as_user_path(python)),"-m","motion2mixamorig.cli","run",+ "--set-extractor",+ extractor,"--device",device,"--rig",@@ -72,6 +108,9 @@ def build_run_argv(]flag = "--image" if source_type == "image" else "--video"cmd.extend([flag, os.fspath(as_user_path(source))])+ if detect_hands:+ cmd.append("--detect-hands")+ cmd.extend(["--hand-smooth", f"{float(hand_smooth_s):g}"])if not preview:cmd.append("--no-preview")return cmd@@ -124,6 +163,7 @@ def validate_run_inputs(source: str | Path,rig: str | Path,busy: bool,+ detect_hands: bool = False,) -> list[str]:errors: list[str] = []if busy:@@ -136,6 +176,8 @@ def validate_run_inputs(errors.append("err_source")if not file_exists(rig):errors.append("err_rig")+ if detect_hands and directory_exists(project_dir) and not mano_model_present(project_dir):+ errors.append("err_mano")return errors@@ -258,11 +300,14 @@ def interpret_doctor_output(exit_code: int | None, stdout: str) -> tuple[str, streturn "ERROR", "err_package"blocking: list[str] = []- if _doctor_line_missing(text, "python module") or "no module named" in low:- if "torch" in low or "gvhmr" in low or "cv2" in low or "numpy" in low:- blocking.append("err_package")+ if any(_doctor_module_missing(text, name) for name in ("torch", "gvhmr", "cv2", "numpy")) or "no module named" in low:+ blocking.append("err_package")if _doctor_line_missing(text, "SMPL-X") or _doctor_line_bad(text, "SMPL-X"):blocking.append("err_smplx")+ if _doctor_line_missing(text, "MANO") or _doctor_line_bad(text, "MANO"):+ blocking.append("err_mano")+ if _doctor_module_missing(text, "timm") or _doctor_module_missing(text, "skimage") or _doctor_module_missing(text, "smplx"):+ blocking.append("err_hand_deps")if blocking:seen: list[str] = []for item in blocking:@@ -297,6 +342,15 @@ def _doctor_line_missing(text: str, label: str) -> bool:return False+def _doctor_module_missing(text: str, module: str) -> bool:+ """A `[missing]` doctor line for one Python module, not a similarly named asset."""+ needle = f"python module {module}".lower()+ for line in text.splitlines():+ if "[missing]" in line.lower() and needle in line.lower():+ return True+ return False++def _doctor_line_bad(text: str, label: str) -> bool:needle = label.lower()for line in text.splitlines():diff --git a/blender_extension/motion2mixamorig_blender/services/errors.py b/blender_extension/motion2mixamorig_blender/services/errors.pyindex 49d197c..25fd212 100644--- a/blender_extension/motion2mixamorig_blender/services/errors.py+++ b/blender_extension/motion2mixamorig_blender/services/errors.py@@ -7,6 +7,8 @@ ERROR_MESSAGES = {"PYTHON_NOT_FOUND": "External Python not found","PACKAGE_MISSING": "Motion2MixamoRig package not installed","SMPLX_MISSING": "SMPL-X model missing",+ "MANO_MISSING": "MANO hand model missing",+ "HAND_DEPS_MISSING": "Hand-detection Python packages missing","INVALID_RIG": "Mixamo FBX invalid","MULTIPLE_PEOPLE": "Input contains multiple people","NO_PERSON": "No person was detected in the input",@@ -23,6 +25,8 @@ _CODE_TO_KEY = {"PYTHON_NOT_FOUND": "err_python","PACKAGE_MISSING": "err_package","SMPLX_MISSING": "err_smplx",+ "MANO_MISSING": "err_mano",+ "HAND_DEPS_MISSING": "err_hand_deps","INVALID_RIG": "err_invalid_rig","MULTIPLE_PEOPLE": "err_multiple_people","NO_PERSON": "err_no_person",@@ -54,6 +58,8 @@ def classify_log_text(text: str) -> tuple[str, str]:return "PACKAGE_MISSING", message_for_code("PACKAGE_MISSING")if "no module named 'torch'" in low or "no module named 'gvhmr'" in low:return "PACKAGE_MISSING", message_for_code("PACKAGE_MISSING")+ if any("mano" in line and ("[missing]" in line or "[invalid]" in line) for line in low.splitlines()):+ return "MANO_MISSING", message_for_code("MANO_MISSING")if "smplx" in low and ("missing" in low or "not found" in low or "[missing]" in low or "filenotfound" in low):