Skip to content

Retarget human motion from video to an Adobe Mixamo-rigged 3D character.

Python

Add Blender ext

MaxLiuf1a02f25142b
diff --git a/.gitignore b/.gitignore
index b126c58..c6fb329 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,5 +28,10 @@ dist/
.env
.env.*
+# ── Local tests and editor junk: not committed ───────────────
+tests/
+scripts/verify_blender_addon.py
+:memory:.ses
+
# ── OS junk ──────────────────────────────────────────────────
.DS_Store
diff --git a/AGENTS.md b/AGENTS.md
index 4c0d52f..03e56cb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,11 +35,46 @@ m2mr run # latest video in assets/video/ + assets/mixamo/Y_Bot.fbx
m2mr run --video assets/video/dance.mp4 --rig assets/mixamo/Vampire.fbx
m2mr run --image assets/image/pose.jpg --rig assets/mixamo/Y_Bot.fbx
m2mr run --skeleton outputs/<run>/skeleton_motion.npz --rig ... # reuse extraction, swap rig
+m2mr run --output-dir DIR --progress-jsonl FILE --no-preview # Blender Extension / automation
```
`--video` / `--image` and `--rig` combine freely (not `--video` with `--image`).
Extraction is the slow step; reuse it with `--skeleton` when only the rig changes.
+## Blender Extension
+
+The add-on is a thin UI. It must **not** import PyTorch / GVHMR / OpenCV in
+Blender’s Python. It launches the user’s venv:
+
+```text
+<external-python> -m motion2mixamorig.cli run ...
+```
+
+How to install and use it (for the user, or to walk them through it):
+[`blender_extension/README.md`](blender_extension/README.md).
+
+When helping a user:
+
+1. They need the same venv + SMPL-X + Mixamo FBX as the CLI (see Setup above).
+2. Build `dist/motion2mixamorig-0.1.0.zip` with
+ `python scripts/package_blender_extension.py`.
+3. In Blender 4.2+: **Edit → Preferences → Get Extensions**, then the **∨**
+ next to Repositories → **Install from Disk…** (no large button). Enable it.
+4. The panel is **3D Viewport → N sidebar → Motion2MixamoRig**, not Get
+ Extensions. Setup is the first box: UI Language, External Python
+ (`.venv/bin/python` or `Scripts\python.exe`, not Blender’s interpreter),
+ Project Directory, Device, then **Check Environment**.
+5. After add-on **code** changes they must rebuild the zip and reinstall.
+ The installed copy is not live from this repo. If
+ `already registered` / `EnumProperty could not register` appears: disable,
+ **quit Blender fully**, reopen, install again.
+6. Jobs write `<project>/outputs/blender_jobs/<job-id>/`. After import, hide
+ **Icosphere** and the **armature** in the Outliner; leave **skinned_mesh**
+ visible. FPS must match the source clip duration (a 60 fps video tagged as
+ 30 fps plays at half speed).
+
+Smoke-test checklist: [`docs/blender-extension.md`](docs/blender-extension.md).
+
## Outputs
Each run writes `outputs/<YYYYMMDD_HHMMSS>_<source>/`:
@@ -58,3 +93,7 @@ Each run writes `outputs/<YYYYMMDD_HHMMSS>_<source>/`:
- `motion2mixamorig/mixamo/` — FBX parsing, FK, retargeting, skinning, rendering
- `motion2mixamorig/pipeline.py` — one run end to end
- `motion2mixamorig/cli.py` — `m2mr doctor` / `m2mr run`
+- `blender_extension/motion2mixamorig_blender/` — Blender 4.2+ Extension (UI + external process)
+- `blender_extension/README.md` — install and use the add-on
+- `docs/blender-extension.md` — maintainer smoke-test checklist
+- `scripts/package_blender_extension.py` — build `dist/motion2mixamorig-0.1.0.zip`
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 855838a..0297489 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,9 +4,10 @@ All notable changes to this project will be documented in this file.
## [Unreleased]
-### Planned
+### Added
-- Blender Extension integration.
+- Blender 4.2+ Extension that launches `m2mr` in an external Python environment, streams progress, and imports the generated GLB.
+- `m2mr run --output-dir`, `--progress-jsonl`, and `--no-preview` for add-on job control (existing CLI flags unchanged).
## [0.1.0] - 2026-09-04
diff --git a/README.ar.md b/README.ar.md
index 49ebd5f..46d0253 100644
--- a/README.ar.md
+++ b/README.ar.md
@@ -10,6 +10,8 @@
للمطوّرين في مجال الألعاب: قدّم فيديو حركة لـ**شخص واحد** (أو صورة) وشخصية Mixamo؛ يكتب معاينات وملف شخصية مكسوّة (`.glb`) يمكن وضعه في Blender أو Unity.
+> Motion2MixamoRig لا يزال تجريبيًا. الإصدار 0.1.0 هو مسار سطر الأوامر. يضم هذا المستودع أيضًا امتداد Blender 4.2+ يشغّل المسار نفسه في Python خارجي. تثبيت الإضافة واستخدامها: [`blender_extension/README.md`](blender_extension/README.md).
+
ينبغي للوكلاء البرمجيين (Agents) البدء من [`AGENTS.md`](AGENTS.md).
https://github.com/user-attachments/assets/37c67642-f36c-4815-bcf3-028ed9546a2f
@@ -152,7 +154,7 @@ images/
# اليمين: مدار 10° حول الهيكل (دورة كاملة)
```
-افتح `mixamo_character.glb` في Blender: File → Import → glTF 2.0 (.glb/.gltf). إن وُجّهت الكاميرا إلى فراغ، حدّد الشخصية ثم View → Frame Selected. مجموعة الكرات على الرأس واليدين هي عرض للعظام وليست الشبكة: حدّد الهيكل (Armature) وأوقف Shapes تحت Armature → Viewport Display. في تشغيل الفيديو اضبط إطار نهاية الخط الزمني على طول المقطع وقارن مع `videos/mixamo_character.mp4`. في تشغيل الصورة قارن مع `images/mixamo_character.png` أو مقطع المدار.
+افتح `mixamo_character.glb` في Blender: File → Import → glTF 2.0 (.glb/.gltf). إن وُجّهت الكاميرا إلى فراغ، حدّد شبكة الشخصية ثم View → Frame Selected. مجموعة الكرات على الرأس واليدين هي عرض للعظام وليست الشبكة: في Outliner أخفِ **Icosphere** و**armature** واترك الشبكة المكسوّة ظاهرة. اضبط FPS المشهد وإطار نهاية الخط الزمني من `run.json` (`fps` و`n_frames`) حتى تطابق مدة المصدر. في تشغيل الفيديو قارن مع `videos/mixamo_character.mp4`، وفي تشغيل الصورة مع `images/mixamo_character.png` أو مقطع المدار.
## الرخصة
diff --git a/README.de.md b/README.de.md
index 7923f32..3baacc6 100644
--- a/README.de.md
+++ b/README.de.md
@@ -10,6 +10,8 @@
Für Spieleentwickler: ein Video mit **genau einer Person** (oder ein Still) und ein Mixamo-Charakter; Ausgabe sind Vorschauen plus eine Charakterdatei mit Skinning (`.glb`) für Blender oder Unity.
+> Motion2MixamoRig ist noch experimentell. Version 0.1.0 ist die Kommandozeilen-Pipeline. In diesem Repository liegt außerdem eine Blender-4.2+-Extension, die dieselbe Pipeline in einem externen Python ausführt. Installation und Bedienung des Add-ons: [`blender_extension/README.md`](blender_extension/README.md).
+
Agents beginnen mit [`AGENTS.md`](AGENTS.md).
https://github.com/user-attachments/assets/37c67642-f36c-4815-bcf3-028ed9546a2f
@@ -152,7 +154,7 @@ images/
# rechts: 10°-Orbit um den Rig (eine volle Umdrehung)
```
-`mixamo_character.glb` in Blender öffnen: File → Import → glTF 2.0 (.glb/.gltf). Zeigt die Kamera ins Leere, den Charakter wählen und View → Frame Selected. Die Kugeln an Kopf und Händen sind die Knochenanzeige, nicht das Mesh: Armature wählen und unter Armature → Viewport Display die Shapes ausschalten. Beim Videolauf das letzte Timeline-Frame auf die Cliplänge setzen und mit `videos/mixamo_character.mp4` vergleichen. Beim Fotolauf mit `images/mixamo_character.png` oder dem Orbit-Clip vergleichen.
+`mixamo_character.glb` in Blender öffnen: File → Import → glTF 2.0 (.glb/.gltf). Zeigt die Kamera ins Leere, das Charakter-Mesh wählen und View → Frame Selected. Die Kugeln an Kopf und Händen sind die Knochenanzeige, nicht das Mesh: im Outliner **Icosphere** und die **Armature** ausblenden, das Mesh mit Skinning sichtbar lassen. Szene-FPS und letztes Timeline-Frame aus `run.json` (`fps`, `n_frames`) setzen, damit die Wiedergabe zur Quelle passt. Videolauf mit `videos/mixamo_character.mp4` vergleichen, Fotolauf mit `images/mixamo_character.png` oder dem Orbit-Clip.
## Lizenz
diff --git a/README.ja.md b/README.ja.md
index efebc1c..a9e6bbf 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -10,6 +10,8 @@
ゲーム開発者向け:入力は**一人**の動作動画(または写真)と Mixamo キャラクター。プレビューと、Blender / Unity にそのまま入れられるスキン付きキャラクターファイル(`.glb`)を書き出します。
+> Motion2MixamoRig はまだ実験段階です。v0.1.0 はコマンドラインのパイプラインです。このリポジトリの Blender 4.2+ Extension は、同じパイプラインを外部 Python で実行します。アドオンの導入と使い方は [`blender_extension/README.md`](blender_extension/README.md)。
+
Agent は先に [`AGENTS.md`](AGENTS.md) を読んでください。
https://github.com/user-attachments/assets/37c67642-f36c-4815-bcf3-028ed9546a2f
@@ -152,7 +154,7 @@ images/
# 右:10° で一周する周回
```
-`mixamo_character.glb` は Blender で File → Import → glTF 2.0 (.glb/.gltf) で開きます。カメラが空を向いているときはキャラクターを選び、View → Frame Selected。頭と手の球の塊はメッシュではなくボーン表示です:アーマチュアを選び、Armature → Viewport Display で Shapes をオフにします。動画実行はタイムラインの終了フレームをクリップ長に合わせ、`videos/mixamo_character.mp4` と見比べてください。写真実行は `images/mixamo_character.png` または周回クリップと見比べてください。
+`mixamo_character.glb` は Blender で File → Import → glTF 2.0 (.glb/.gltf) で開きます。カメラが空を向いているときはキャラクターのメッシュを選び、View → Frame Selected。頭と手の球の塊はメッシュではなくボーン表示です。Outliner で **Icosphere** と **armature** を非表示にし、スキン付きメッシュは残してください。再生を原寸に合わせるには、`run.json` の `fps` / `n_frames` でシーンの FPS とタイムライン終了フレームを設定します。動画実行は `videos/mixamo_character.mp4`、写真実行は `images/mixamo_character.png` または周回クリップと見比べてください。
## ライセンス
diff --git a/README.ko.md b/README.ko.md
index b2bf4ea..31813a6 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -10,6 +10,8 @@
게임 개발자를 위한 도구입니다. **한 사람만** 나오는 동작 영상(또는 사진)과 Mixamo 캐릭터를 넣으면 미리보기와, Blender / Unity에 바로 넣을 수 있는 스키닝된 캐릭터 파일(`.glb`)을 생성합니다.
+> Motion2MixamoRig는 아직 실험 단계입니다. v0.1.0은 명령줄 파이프라인입니다. 이 저장소의 Blender 4.2+ Extension은 같은 파이프라인을 외부 Python에서 실행합니다. 애드온 설치와 사용법: [`blender_extension/README.md`](blender_extension/README.md).
+
Agent는 먼저 [`AGENTS.md`](AGENTS.md)를 읽어 주세요.
https://github.com/user-attachments/assets/37c67642-f36c-4815-bcf3-028ed9546a2f
@@ -152,7 +154,7 @@ images/
# 오른쪽: 10° 궤도(한 바퀴)
```
-`mixamo_character.glb`는 Blender에서 File → Import → glTF 2.0 (.glb/.gltf)로 엽니다. 카메라가 빈 곳을 보고 있으면 캐릭터를 선택한 뒤 View → Frame Selected. 머리와 손의 구체들은 메시가 아니라 본 표시입니다. Armature를 선택하고 Armature → Viewport Display에서 Shapes를 끄세요. 영상 실행은 타임라인 끝 프레임을 클립 길이에 맞추고 `videos/mixamo_character.mp4`와 비교하세요. 사진 실행은 `images/mixamo_character.png` 또는 궤도 클립과 비교하세요.
+`mixamo_character.glb`는 Blender에서 File → Import → glTF 2.0 (.glb/.gltf)로 엽니다. 카메라가 빈 곳을 보고 있으면 캐릭터 메시를 선택한 뒤 View → Frame Selected. 머리와 손의 구체들은 메시가 아니라 본 표시입니다. Outliner에서 **Icosphere**와 **armature**를 숨기고, 스키닝된 메시는 그대로 두세요. 재생이 원본과 같아지려면 `run.json`의 `fps` / `n_frames`로 장면 FPS와 타임라인 끝 프레임을 맞추세요. 영상 실행은 `videos/mixamo_character.mp4`와, 사진 실행은 `images/mixamo_character.png` 또는 궤도 클립과 비교하세요.
## 라이선스
diff --git a/README.md b/README.md
index 9410129..5017eb1 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ Transfer the motion of a person in a video — or the pose in a still photo —
For game developers: give it a **single-person** action video (or a still) and a Mixamo character; it writes preview videos plus a skinned character file (`.glb`) you can drop into Blender or Unity.
-> Motion2MixamoRig is currently experimental. Version 0.1.0 provides the command-line pipeline; a Blender Extension is planned for v0.2.0.
+> Motion2MixamoRig is currently experimental. Version 0.1.0 is the command-line pipeline. This repository also includes a Blender 4.2+ Extension that runs that same pipeline in an external Python environment. How to install and use the add-on: [`blender_extension/README.md`](blender_extension/README.md).
Agents should start with [`AGENTS.md`](AGENTS.md).
@@ -154,7 +154,7 @@ images/
# right: 10° orbit of the rig (one full turn)
```
-Open `mixamo_character.glb` in Blender: File → Import → glTF 2.0 (.glb/.gltf). If the camera is framed on empty space, select the character and use View → Frame Selected. The cluster of spheres on the head and hands is the bone display, not the mesh: select the armature and turn off Shapes under Armature → Viewport Display. For a video run, set the timeline end frame to the clip length and compare against `videos/mixamo_character.mp4`. For a still run, compare against `images/mixamo_character.png` or the orbit clip.
+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
diff --git a/README.ru.md b/README.ru.md
index b9662cd..1ac679b 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -10,6 +10,8 @@
Для разработчиков игр: видео с **одним человеком** (или фото) и персонаж Mixamo; на выходе превью и файл персонажа со скином (`.glb`) для Blender или Unity.
+> Motion2MixamoRig пока экспериментален. Версия 0.1.0 — конвейер командной строки. В этом репозитории также есть расширение Blender 4.2+, которое запускает тот же конвейер во внешнем Python. Установка и использование аддона: [`blender_extension/README.md`](blender_extension/README.md).
+
Агентам следует начать с [`AGENTS.md`](AGENTS.md).
https://github.com/user-attachments/assets/37c67642-f36c-4815-bcf3-028ed9546a2f
@@ -152,7 +154,7 @@ images/
# справа: орбита 10° вокруг рига (полный оборот)
```
-`mixamo_character.glb` в Blender: File → Import → glTF 2.0 (.glb/.gltf). Если камера смотрит в пустоту, выберите персонажа и View → Frame Selected. Скопление сфер на голове и руках — отображение костей, не меш: выберите арматуру и отключите Shapes в Armature → Viewport Display. Для видео-запуска поставьте конечный кадр таймлайна по длине клипа и сверяйте с `videos/mixamo_character.mp4`. Для фото-запуска сверяйте с `images/mixamo_character.png` или клипом орбиты.
+`mixamo_character.glb` в Blender: File → Import → glTF 2.0 (.glb/.gltf). Если камера смотрит в пустоту, выберите меш персонажа и View → Frame Selected. Скопление сфер на голове и руках — отображение костей, не меш: в Outliner спрячьте **Icosphere** и **armature**, оставьте видимым меш со скином. FPS сцены и конечный кадр таймлайна возьмите из `run.json` (`fps`, `n_frames`), чтобы длительность совпала с исходником. Видео-запуск сверяйте с `videos/mixamo_character.mp4`, фото-запуск — с `images/mixamo_character.png` или клипом орбиты.
## Лицензия
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3af5562..cf985c0 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -10,7 +10,7 @@
面向游戏开发者:输入一段**单人**动作视频(或一张人物照片)和一个 Mixamo 角色,输出预览视频,以及可直接丢进 Blender / Unity 的带皮角色文件(`.glb`)。
-> Motion2MixamoRig 目前仍处于实验阶段。v0.1.0 提供命令行工作流;Blender Extension 计划在 v0.2.0 中加入。
+> Motion2MixamoRig 目前仍处于实验阶段。v0.1.0 是命令行工作流。本仓库另有一个 Blender 4.2+ Extension,在外部 Python 里跑同一条 pipeline。插件的安装和用法见 [`blender_extension/README.md`](blender_extension/README.md)。
Agent 请先读 [`AGENTS.md`](AGENTS.md)。
@@ -154,7 +154,7 @@ images/
# 右:10° 俯视绕角色转一圈
```
-`mixamo_character.glb` 用 Blender 打开:File → Import → glTF 2.0 (.glb/.gltf)。导入后若镜头对不准,先选中角色,再 View → Frame Selected。头和手上那堆球是骨头的显示形状,不是模型:选中骨架,在 Armature → Viewport Display 里去掉 Shapes。视频 run 把时间轴结束帧改成和片段一样长,对照 `videos/mixamo_character.mp4`。照片 run 对照 `images/mixamo_character.png` 或那条绕转视频。
+`mixamo_character.glb` 用 Blender 打开:File → Import → glTF 2.0 (.glb/.gltf)。导入后若镜头对不准,选中角色网格,再 View → Frame Selected。头和手上那堆球是骨头的显示形状,不是模型:在 Outliner 里隐藏 **Icosphere** 和骨架(armature),留下带皮网格。时间轴 FPS 和结束帧按 `run.json` 里的 `fps` / `n_frames` 设置,播放才会和原片一样长。视频 run 对照 `videos/mixamo_character.mp4`,照片 run 对照 `images/mixamo_character.png` 或那条绕转视频。
## 许可证
diff --git a/blender_extension/README.md b/blender_extension/README.md
new file mode 100644
index 0000000..cb0e416
--- /dev/null
+++ b/blender_extension/README.md
@@ -0,0 +1,183 @@
+# Motion2MixamoRig Blender Extension
+
+A Blender **4.2+** add-on that runs Motion2MixamoRig in a **separate Python**,
+then imports the generated Mixamo character (`.glb`) into the scene.
+
+Blender’s own interpreter never loads PyTorch, GVHMR, or OpenCV. The panel
+launches:
+
+```text
+<external-python> -m motion2mixamorig.cli run ...
+```
+
+This folder is the add-on source. It does **not** install Python, download
+SMPL-X, or bundle inference weights.
+
+## What you need first
+
+Do this in a terminal, not inside Blender. Details (venv, `chumpy`, SMPL-X,
+Mixamo FBX) are in the [repository README](../README.md).
+
+1. Clone this repo and install Motion2MixamoRig into a Python 3.10+ venv.
+2. Put `SMPLX_NEUTRAL.npz` at `assets/body_models/smplx/`.
+3. Download a Mixamo character as **FBX Binary, T-pose**.
+4. Confirm `python -m motion2mixamorig.cli doctor` in that venv.
+
+The first successful extraction downloads **about 5 GB** of weights into
+`<project>/weights/`. That happens in External Python, not in this add-on.
+
+## Install the add-on
+
+From the repository root:
+
+```bash
+python scripts/package_blender_extension.py
+```
+
+That writes `dist/motion2mixamorig-0.1.0.zip`. The zip root is
+`blender_manifest.toml` + `__init__.py` (no wrapping folder).
+
+In Blender 4.2+:
+
+1. **Edit → Preferences → Get Extensions**
+2. Next to **Repositories**, open the small **∨** menu → **Install from Disk…**
+ (there is no large “Install from Disk” button)
+3. Choose the zip and enable **Motion2MixamoRig**
+
+Command line:
+
+```bash
+blender --command extension install-file --repo user_default --enable dist/motion2mixamorig-0.1.0.zip
+```
+
+After you change the add-on code, rebuild the zip and install it again. The
+copy Blender loaded is not live from this folder.
+
+An offline alert for `extensions.blender.org` is unrelated and can be ignored.
+
+## Open the panel
+
+Get Extensions only lists whether the add-on is installed. The working UI is
+the 3D Viewport sidebar:
+
+1. Go to the **3D Viewport**
+2. Press **N** (or open the sidebar on the right)
+3. Click the **Motion2MixamoRig** tab
+
+That sidebar has **Setup**, **Input**, and **Progress / Result**.
+
+## Setup
+
+Set these in the Setup box, or under **Edit → Preferences → Add-ons → Motion2MixamoRig**:
+
+| Field | What to put |
+| --- | --- |
+| **UI Language** | Auto follows Blender / the system, or pick a language (same set as the repo README) |
+| **External Python** | The venv interpreter, **not** Blender’s Python |
+| **Project Directory** | This repository (or the install that has `assets/` and `weights/`) |
+| **Device** | CPU, CUDA, or MPS |
+
+| Platform | External Python |
+| --- | --- |
+| macOS / Linux | `<project>/.venv/bin/python` |
+| Windows | `<project>\.venv\Scripts\python.exe` |
+
+Do not `source` or activate the venv from Blender. The add-on calls that
+binary directly. External Python, Project Directory, and UI Language persist
+across `.blend` files.
+
+Click **Check Environment**. Missing default clips under `assets/video/` is
+fine: you pick files in the panel.
+
+## Generate
+
+In **Input**:
+
+1. Source Type: Video or Image
+2. Source File: **one** clearly visible person, head to toe
+3. Mixamo Rig FBX
+4. Leave **Generate Preview Videos** off unless you want extra renders
+5. **Generate Motion**
+
+Blender stays interactive. **Progress / Result** shows stage, a bar, recent
+log lines, and **Cancel** (only the process this add-on started).
+
+On success the add-on imports `mixamo_character.glb` into a collection
+`M2MR_<source-name>`, hides the joint-bubble objects, frames the visible mesh,
+and sets timeline FPS / start / end from the clip.
+
+If import fails, generation still succeeded: use **Import Generated Character**.
+**Open Output Folder** and **View Full Log** are always available after a job.
+
+Jobs write to:
+
+```text
+<project>/outputs/blender_jobs/<job-id>/
+```
+
+(`run.json`, `job.log`, `progress.jsonl`, NPZ files, and the GLB.)
+
+## After import
+
+- If the camera looks at empty space: select the character → **View → Frame Selected**.
+- The cluster of spheres on joints is bone display, not the mesh. In the
+ Outliner, hide **Icosphere** and the **armature** (the row with pose /
+ armature / mesh icons). Leave **skinned_mesh** visible; it still deforms.
+- Playback speed follows the source clip’s duration (`fps` in `run.json`). If a
+ 60 fps video is stored as 30 fps, it will play at half speed.
+
+## Devices
+
+| Device | When |
+| --- | --- |
+| **CPU** | Works everywhere. Slowest. Safest first try. |
+| **MPS** | Apple Silicon, if PyTorch MPS works in External Python. |
+| **CUDA** | Windows/Linux NVIDIA GPU; drivers must match the PyTorch CUDA build. |
+
+The add-on does not install GPU drivers. If CUDA or MPS is unavailable, the
+external process fails; open the full log.
+
+## Common errors
+
+| Message | What to do |
+| --- | --- |
+| External Python not found | Point Setup at `.venv/bin/python` or `Scripts\python.exe` |
+| Motion2MixamoRig package not installed | In that interpreter: `pip install -e .` |
+| SMPL-X model missing | Put `SMPLX_NEUTRAL.npz` in `assets/body_models/smplx/` |
+| Mixamo FBX invalid | Re-download as **FBX Binary**, T-pose |
+| Input contains multiple people | Use a single-person shot |
+| CUDA / MPS unavailable | Switch Device to CPU, or install a matching PyTorch |
+| Pipeline process exited unexpectedly | **View Full Log**; an empty log means the CLI did not start |
+| Result GLB not found | Re-run; check `run.json` in the job folder |
+| Generation succeeded, but automatic import failed | **Import Generated Character** |
+
+The panel shows one short line. Full stdout/stderr is in `job.log`.
+
+`register_class(...): already registered` after installing over an enabled
+add-on: disable it, **quit Blender fully**, reopen, then install the zip again.
+
+## Uninstall
+
+**Edit → Preferences → Get Extensions** → remove **Motion2MixamoRig**.
+
+That does **not** delete `<project>/weights/`, `assets/`, or `outputs/`
+(including `outputs/blender_jobs/`). Remove those folders yourself if you want
+them gone.
+
+## Layout
+
+```text
+blender_extension/
+├── README.md # this file
+└── motion2mixamorig_blender/ # packed into the zip
+ ├── blender_manifest.toml
+ ├── __init__.py
+ ├── i18n.py
+ ├── preferences.py
+ ├── panels/
+ ├── operators/
+ └── services/
+```
+
+Packaging: `scripts/package_blender_extension.py`.
+Maintainer smoke-tests: [`docs/blender-extension.md`](../docs/blender-extension.md).
diff --git a/blender_extension/motion2mixamorig_blender/__init__.py b/blender_extension/motion2mixamorig_blender/__init__.py
new file mode 100644
index 0000000..52cb59e
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/__init__.py
@@ -0,0 +1,45 @@
+"""Motion2MixamoRig Blender Extension: UI + external `m2mr` process control."""
+
+from __future__ import annotations
+
+bl_info = {
+ "name": "Motion2MixamoRig",
+ "author": "Max Liu",
+ "version": (0, 1, 0),
+ "blender": (4, 2, 0),
+ "location": "View3D > Sidebar > Motion2MixamoRig",
+ "description": "Transfer human motion from video to Mixamo characters",
+ "category": "Animation",
+}
+
+from . import operators, panels, preferences, properties
+
+
+def register() -> None:
+ try:
+ unregister()
+ except Exception:
+ pass
+ preferences.register()
+ properties.register()
+ operators.register()
+ panels.register()
+
+
+def unregister() -> None:
+ try:
+ panels.unregister()
+ except Exception:
+ pass
+ try:
+ operators.unregister()
+ except Exception:
+ pass
+ try:
+ properties.unregister()
+ except Exception:
+ pass
+ try:
+ preferences.unregister()
+ except Exception:
+ pass
diff --git a/blender_extension/motion2mixamorig_blender/blender_manifest.toml b/blender_extension/motion2mixamorig_blender/blender_manifest.toml
new file mode 100644
index 0000000..a54b389
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/blender_manifest.toml
@@ -0,0 +1,18 @@
+schema_version = "1.0.0"
+
+id = "motion2mixamorig"
+version = "0.1.0"
+name = "Motion2MixamoRig"
+tagline = "Transfer human motion from video to Mixamo characters"
+maintainer = "Max Liu"
+type = "add-on"
+
+website = "https://github.com/MaxLiu22/Motion2MixamoRig"
+tags = ["Animation", "Import-Export"]
+blender_version_min = "4.2.0"
+
+license = ["SPDX:Apache-2.0"]
+copyright = ["2026 Max Liu"]
+
+[permissions]
+files = "Read inputs and write job logs and generated GLB files"
diff --git a/blender_extension/motion2mixamorig_blender/i18n.py b/blender_extension/motion2mixamorig_blender/i18n.py
new file mode 100644
index 0000000..025326f
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/i18n.py
@@ -0,0 +1,518 @@
+"""Plugin UI strings. Languages match the repository README set."""
+
+from __future__ import annotations
+
+from typing import Any
+
+LANGS = ("en", "zh-CN", "ko", "ja", "de", "ru", "ar")
+
+# Blender EnumProperty identifiers cannot contain "-".
+PREF_TO_LANG = {
+ "en": "en",
+ "zh_CN": "zh-CN",
+ "ko": "ko",
+ "ja": "ja",
+ "de": "de",
+ "ru": "ru",
+ "ar": "ar",
+}
+
+_BLENDER_PREFIX = (
+ ("zh", "zh-CN"),
+ ("ko", "ko"),
+ ("ja", "ja"),
+ ("de", "de"),
+ ("ru", "ru"),
+ ("ar", "ar"),
+)
+
+STRINGS: dict[str, dict[str, str]] = {}
+
+
+def _add(key: str, **langs: str) -> None:
+ for lang in LANGS:
+ STRINGS.setdefault(lang, {})[key] = langs.get(lang) or langs["en"]
+
+
+_add(
+ "section_setup",
+ en="Setup",
+ **{"zh-CN": "设置"},
+ ko="설정",
+ ja="セットアップ",
+ de="Einrichtung",
+ ru="Настройка",
+ ar="إعداد",
+)
+_add(
+ "section_input",
+ en="Input",
+ **{"zh-CN": "输入"},
+ ko="입력",
+ ja="入力",
+ de="Eingabe",
+ ru="Ввод",
+ ar="إدخال",
+)
+_add(
+ "section_progress",
+ en="Progress / Result",
+ **{"zh-CN": "进度 / 结果"},
+ ko="진행 / 결과",
+ ja="進行状況 / 結果",
+ de="Fortschritt / Ergebnis",
+ ru="Прогресс / результат",
+ ar="التقدم / النتيجة",
+)
+_add(
+ "external_python",
+ en="External Python",
+ **{"zh-CN": "外部 Python"},
+ ko="외부 Python",
+ ja="外部 Python",
+ de="Externes Python",
+ ru="Внешний Python",
+ ar="Python الخارجي",
+)
+_add(
+ "project_directory",
+ en="Project Directory",
+ **{"zh-CN": "项目目录"},
+ ko="프로젝트 디렉터리",
+ ja="プロジェクトディレクトリ",
+ de="Projektverzeichnis",
+ ru="Каталог проекта",
+ ar="مجلد المشروع",
+)
+_add(
+ "device",
+ en="Device",
+ **{"zh-CN": "设备"},
+ ko="장치",
+ ja="デバイス",
+ de="Gerät",
+ ru="Устройство",
+ ar="الجهاز",
+)
+_add(
+ "ui_language",
+ en="UI Language",
+ **{"zh-CN": "界面语言"},
+ ko="UI 언어",
+ ja="UI 言語",
+ de="UI-Sprache",
+ ru="Язык интерфейса",
+ ar="لغة الواجهة",
+)
+_add(
+ "lang_auto",
+ en="Auto (Blender / System)",
+ **{"zh-CN": "自动(跟随 Blender / 系统)"},
+ ko="자동 (Blender / 시스템)",
+ ja="自動(Blender / システム)",
+ de="Automatisch (Blender / System)",
+ ru="Авто (Blender / система)",
+ ar="تلقائي (Blender / النظام)",
+)
+_add(
+ "check_environment",
+ en="Check Environment",
+ **{"zh-CN": "检查环境"},
+ ko="환경 확인",
+ ja="環境を確認",
+ de="Umgebung prüfen",
+ ru="Проверить среду",
+ ar="فحص البيئة",
+)
+_add(
+ "environment_fmt",
+ en="Environment: {status}",
+ **{"zh-CN": "环境:{status}"},
+ ko="환경: {status}",
+ ja="環境: {status}",
+ de="Umgebung: {status}",
+ ru="Среда: {status}",
+ ar="البيئة: {status}",
+)
+_add("env_not_checked", en="Not checked", **{"zh-CN": "未检查"}, ko="미확인", ja="未確認", de="Nicht geprüft", ru="Не проверено", ar="لم يُفحص")
+_add("env_checking", en="Checking…", **{"zh-CN": "正在检查…"}, ko="확인 중…", ja="確認中…", de="Prüfung…", ru="Проверка…", ar="جاري الفحص…")
+_add("env_ready", en="Ready", **{"zh-CN": "就绪"}, ko="준비됨", ja="準備完了", de="Bereit", ru="Готово", ar="جاهز")
+_add("env_error", en="Error", **{"zh-CN": "错误"}, ko="오류", ja="エラー", de="Fehler", ru="Ошибка", ar="خطأ")
+_add(
+ "source_type",
+ en="Source Type",
+ **{"zh-CN": "来源类型"},
+ ko="소스 유형",
+ ja="ソースの種類",
+ de="Quelltyp",
+ ru="Тип источника",
+ ar="نوع المصدر",
+)
+_add("source_video", en="Video", **{"zh-CN": "视频"}, ko="비디오", ja="動画", de="Video", ru="Видео", ar="فيديو")
+_add("source_image", en="Image", **{"zh-CN": "图片"}, ko="이미지", ja="画像", de="Bild", ru="Изображение", ar="صورة")
+_add(
+ "source_video_desc",
+ en="Single-person motion video",
+ **{"zh-CN": "单人动作视频"},
+ ko="1인 동작 영상",
+ ja="一人のモーション動画",
+ de="Video mit einer Person",
+ ru="Видео с одним человеком",
+ ar="فيديو حركة لشخص واحد",
+)
+_add(
+ "source_image_desc",
+ en="Single-person still photo",
+ **{"zh-CN": "单人全身照片"},
+ ko="1인 사진",
+ ja="一人の静止画",
+ de="Foto mit einer Person",
+ ru="Фото одного человека",
+ ar="صورة لشخص واحد",
+)
+_add(
+ "source_file",
+ en="Source File",
+ **{"zh-CN": "来源文件"},
+ ko="소스 파일",
+ ja="ソースファイル",
+ de="Quelldatei",
+ ru="Файл источника",
+ ar="ملف المصدر",
+)
+_add(
+ "mixamo_rig",
+ en="Mixamo Rig FBX",
+ **{"zh-CN": "Mixamo 角色 FBX"},
+ ko="Mixamo 리그 FBX",
+ ja="Mixamo リグ FBX",
+ de="Mixamo-Rig FBX",
+ ru="Mixamo Rig FBX",
+ ar="هيكل Mixamo FBX",
+)
+_add(
+ "generate_preview",
+ en="Generate Preview Videos",
+ **{"zh-CN": "生成预览视频"},
+ ko="미리보기 영상 생성",
+ ja="プレビュー動画を生成",
+ de="Vorschauvideos erzeugen",
+ ru="Создавать превью-видео",
+ ar="إنشاء فيديوهات المعاينة",
+)
+_add(
+ "generate_motion",
+ en="Generate Motion",
+ **{"zh-CN": "生成动作"},
+ ko="모션 생성",
+ ja="モーションを生成",
+ de="Motion erzeugen",
+ ru="Сгенерировать движение",
+ ar="توليد الحركة",
+)
+_add("status_fmt", en="Status: {status}", **{"zh-CN": "状态:{status}"}, ko="상태: {status}", ja="状態: {status}", de="Status: {status}", ru="Статус: {status}", ar="الحالة: {status}")
+_add("stage_fmt", en="Stage: {stage}", **{"zh-CN": "阶段:{stage}"}, ko="단계: {stage}", ja="段階: {stage}", de="Phase: {stage}", ru="Этап: {stage}", ar="المرحلة: {stage}")
+_add("progress", en="Progress", **{"zh-CN": "进度"}, ko="진행률", ja="進捗", de="Fortschritt", ru="Прогресс", ar="التقدم")
+_add("recent_log", en="Recent log", **{"zh-CN": "最近日志"}, ko="최근 로그", ja="最近のログ", de="Aktuelles Protokoll", ru="Последний журнал", ar="السجل الأخير")
+_add("cancel", en="Cancel", **{"zh-CN": "取消"}, ko="취소", ja="キャンセル", de="Abbrechen", ru="Отмена", ar="إلغاء")
+_add(
+ "generation_succeeded",
+ en="Generation succeeded",
+ **{"zh-CN": "生成成功"},
+ ko="생성 성공",
+ ja="生成に成功しました",
+ de="Erzeugung erfolgreich",
+ ru="Генерация выполнена",
+ ar="تم التوليد بنجاح",
+)
+_add(
+ "generation_import_failed",
+ en="Generation succeeded, but automatic import failed",
+ **{"zh-CN": "生成成功,但自动导入失败"},
+ ko="생성은 성공했지만 자동 가져오기에 실패했습니다",
+ ja="生成は成功しましたが、自動インポートに失敗しました",
+ de="Erzeugung erfolgreich, automatischer Import fehlgeschlagen",
+ ru="Генерация успешна, но автоимпорт не удался",
+ ar="نجح التوليد، لكن الاستيراد التلقائي فشل",
+)
+_add("cancelled", en="Cancelled", **{"zh-CN": "已取消"}, ko="취소됨", ja="キャンセル済み", de="Abgebrochen", ru="Отменено", ar="أُلغي")
+_add(
+ "import_character",
+ en="Import Generated Character",
+ **{"zh-CN": "导入生成的角色"},
+ ko="생성된 캐릭터 가져오기",
+ ja="生成したキャラクターをインポート",
+ de="Erzeugten Charakter importieren",
+ ru="Импортировать персонажа",
+ ar="استيراد الشخصية المولَّدة",
+)
+_add(
+ "open_output",
+ en="Open Output Folder",
+ **{"zh-CN": "打开输出文件夹"},
+ ko="출력 폴더 열기",
+ ja="出力フォルダーを開く",
+ de="Ausgabeordner öffnen",
+ ru="Открыть папку результатов",
+ ar="فتح مجلد الناتج",
+)
+_add(
+ "view_log",
+ en="View Full Log",
+ **{"zh-CN": "查看完整日志"},
+ ko="전체 로그 보기",
+ ja="ログを表示",
+ de="Vollständiges Protokoll",
+ ru="Полный журнал",
+ ar="عرض السجل الكامل",
+)
+_add("no_job_yet", en="No job yet", **{"zh-CN": "还没有任务"}, ko="아직 작업 없음", ja="まだジョブがありません", de="Noch kein Auftrag", ru="Заданий пока нет", ar="لا توجد مهمة بعد")
+_add("glb_fmt", en="GLB: {name}", **{"zh-CN": "GLB:{name}"}, ko="GLB: {name}", ja="GLB: {name}", de="GLB: {name}", ru="GLB: {name}", ar="GLB: {name}")
+_add(
+ "prefs_venv_hint",
+ en="Use the venv Python, not Blender's bundled interpreter.",
+ **{"zh-CN": "请使用虚拟环境里的 Python,不要用 Blender 自带的解释器。"},
+ ko="Blender 내장 인터프리터가 아니라 venv Python을 사용하세요.",
+ ja="Blender 同梱の Python ではなく、venv の Python を指定してください。",
+ de="Verwende das venv-Python, nicht den mitgelieferten Blender-Interpreter.",
+ ru="Укажите Python из venv, не встроенный интерпретатор Blender.",
+ ar="استخدم Python الخاص بالبيئة الافتراضية، وليس مفسر Blender.",
+)
+_add(
+ "device_cpu_desc",
+ en="Run extraction on CPU",
+ **{"zh-CN": "使用 CPU 提取动作"},
+ ko="CPU에서 추출",
+ ja="CPU で抽出",
+ de="Extraktion auf der CPU",
+ ru="Извлечение на CPU",
+ ar="الاستخراج على المعالج",
+)
+_add(
+ "device_cuda_desc",
+ en="Run extraction on an NVIDIA GPU",
+ **{"zh-CN": "使用 NVIDIA GPU 提取动作"},
+ ko="NVIDIA GPU에서 추출",
+ ja="NVIDIA GPU で抽出",
+ de="Extraktion auf einer NVIDIA-GPU",
+ ru="Извлечение на GPU NVIDIA",
+ ar="الاستخراج على معالج NVIDIA",
+)
+_add(
+ "device_mps_desc",
+ en="Run extraction on Apple Silicon",
+ **{"zh-CN": "使用 Apple Silicon (MPS) 提取动作"},
+ ko="Apple Silicon에서 추출",
+ ja="Apple Silicon で抽出",
+ de="Extraktion auf Apple Silicon",
+ ru="Извлечение на Apple Silicon",
+ ar="الاستخراج على Apple Silicon",
+)
+_add("status_idle", en="idle", **{"zh-CN": "空闲"}, ko="대기", ja="待機", de="inaktiv", ru="ожидание", ar="خامل")
+_add("status_running", en="running", **{"zh-CN": "运行中"}, ko="실행 중", ja="実行中", de="läuft", ru="выполняется", ar="قيد التشغيل")
+_add("status_cancelling", en="cancelling", **{"zh-CN": "正在取消"}, ko="취소 중", ja="キャンセル中", de="wird abgebrochen", ru="отмена", ar="جارٍ الإلغاء")
+_add("status_completed", en="completed", **{"zh-CN": "已完成"}, ko="완료", ja="完了", de="abgeschlossen", ru="завершено", ar="مكتمل")
+_add("status_failed", en="failed", **{"zh-CN": "失败"}, ko="실패", ja="失敗", de="fehlgeschlagen", ru="ошибка", ar="فشل")
+_add("status_cancelled", en="cancelled", **{"zh-CN": "已取消"}, ko="취소됨", ja="キャンセル済み", de="abgebrochen", ru="отменено", ar="أُلغي")
+_add("status_import_failed", en="import_failed", **{"zh-CN": "导入失败"}, ko="가져오기 실패", ja="インポート失敗", de="Import fehlgeschlagen", ru="ошибка импорта", ar="فشل الاستيراد")
+_add("stage_preflight", en="preflight", **{"zh-CN": "预检查"}, ko="사전 검사", ja="事前チェック", de="Vorprüfung", ru="проверка", ar="فحص أولي")
+_add("stage_extract", en="extract", **{"zh-CN": "提取动作"}, ko="추출", ja="抽出", de="Extraktion", ru="извлечение", ar="استخراج")
+_add("stage_retarget", en="retarget", **{"zh-CN": "重定向"}, ko="리타깃", ja="リターゲット", de="Retargeting", ru="ретаргет", ar="إعادة توجيه")
+_add("stage_export", en="export", **{"zh-CN": "导出"}, ko="내보내기", ja="書き出し", de="Export", ru="экспорт", ar="تصدير")
+_add("stage_preview", en="preview", **{"zh-CN": "预览"}, ko="미리보기", ja="プレビュー", de="Vorschau", ru="превью", ar="معاينة")
+_add("stage_done", en="done", **{"zh-CN": "完成"}, ko="완료", ja="完了", de="fertig", ru="готово", ar="تم")
+_add("stage_failed", en="failed", **{"zh-CN": "失败"}, ko="실패", ja="失敗", de="fehlgeschlagen", ru="ошибка", ar="فشل")
+_add("stage_cancelled", en="cancelled", **{"zh-CN": "已取消"}, ko="취소됨", ja="キャンセル済み", de="abgebrochen", ru="отменено", ar="أُلغي")
+_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_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="لم يُكتشف أي شخص في المصدر")
+_add("err_cuda", en="CUDA unavailable", **{"zh-CN": "CUDA 不可用"}, ko="CUDA를 사용할 수 없습니다", ja="CUDA を利用できません", de="CUDA nicht verfügbar", ru="CUDA недоступна", ar="CUDA غير متاح")
+_add("err_mps", en="Apple MPS unavailable", **{"zh-CN": "Apple MPS 不可用"}, ko="Apple MPS를 사용할 수 없습니다", ja="Apple MPS を利用できません", de="Apple MPS nicht verfügbar", ru="Apple MPS недоступен", ar="Apple MPS غير متاح")
+_add("err_process_exited", en="Pipeline process exited unexpectedly", **{"zh-CN": "流水线进程意外退出"}, ko="파이프라인 프로세스가 예기치 않게 종료되었습니다", ja="パイプラインが予期せず終了しました", de="Pipeline-Prozess unerwartet beendet", ru="Процесс конвейера неожиданно завершился", ar="توقفت عملية المعالجة بشكل غير متوقع")
+_add(
+ "err_process_exited_code",
+ en="Pipeline process exited unexpectedly (exit {code}). Open View Full Log; if the file is empty the CLI did not start.",
+ **{"zh-CN": "流水线进程意外退出(退出码 {code})。请打开「查看完整日志」;若文件是空的,说明 CLI 没有启动。"},
+ ko="파이프라인 프로세스가 예기치 않게 종료되었습니다(종료 코드 {code}). 전체 로그를 확인하세요. 파일이 비어 있으면 CLI가 시작되지 않은 것입니다.",
+ ja="パイプラインが予期せず終了しました(終了コード {code})。完全なログを開いてください。空なら CLI は起動していません。",
+ de="Pipeline-Prozess unerwartet beendet (Exit {code}). Öffne das vollständige Protokoll; ist die Datei leer, startete die CLI nicht.",
+ ru="Процесс конвейера завершился (код {code}). Откройте полный журнал; пустой файл значит, что CLI не запустился.",
+ ar="توقفت عملية المعالجة فجأة (رمز {code}). افتح السجل الكامل؛ إذا كان الملف فارغًا فلم يبدأ CLI.",
+)
+_add("err_glb", en="Result GLB not found", **{"zh-CN": "找不到结果 GLB"}, ko="결과 GLB를 찾을 수 없습니다", ja="結果の GLB が見つかりません", de="Ergebnis-GLB nicht gefunden", ru="Результирующий GLB не найден", ar="لم يُعثر على ملف GLB الناتج")
+_add("err_json", en="Result JSON is invalid", **{"zh-CN": "结果 JSON 无效"}, ko="결과 JSON이 올바르지 않습니다", ja="結果 JSON が無効です", de="Ergebnis-JSON ungültig", ru="Некорректный JSON результата", ar="ملف JSON الناتج غير صالح")
+_add("err_preflight", en="Input check failed", **{"zh-CN": "输入检查未通过"}, ko="입력 검사에 실패했습니다", ja="入力チェックに失敗しました", de="Eingabeprüfung fehlgeschlagen", ru="Проверка входа не пройдена", ar="فشل فحص المدخلات")
+_add("err_pipeline", en="Motion2MixamoRig pipeline failed", **{"zh-CN": "Motion2MixamoRig 流水线失败"}, ko="Motion2MixamoRig 파이프라인이 실패했습니다", ja="Motion2MixamoRig パイプラインが失敗しました", de="Motion2MixamoRig-Pipeline fehlgeschlagen", ru="Конвейер Motion2MixamoRig не выполнен", ar="فشلت معالجة Motion2MixamoRig")
+_add("err_busy", en="A Motion2MixamoRig job is already running", **{"zh-CN": "已有 Motion2MixamoRig 任务在运行"}, ko="이미 Motion2MixamoRig 작업이 실행 중입니다", ja="すでに Motion2MixamoRig ジョブが実行中です", de="Es läuft bereits ein Motion2MixamoRig-Auftrag", ru="Задание Motion2MixamoRig уже выполняется", ar="توجد مهمة Motion2MixamoRig قيد التشغيل")
+_add("err_project", en="Project Directory does not exist", **{"zh-CN": "项目目录不存在"}, ko="프로젝트 디렉터리가 없습니다", ja="プロジェクトディレクトリが存在しません", de="Projektverzeichnis existiert nicht", ru="Каталог проекта не существует", ar="مجلد المشروع غير موجود")
+_add("err_source", en="Source file not found", **{"zh-CN": "找不到来源文件"}, ko="소스 파일을 찾을 수 없습니다", ja="ソースファイルが見つかりません", de="Quelldatei nicht gefunden", ru="Файл источника не найден", ar="لم يُعثر على ملف المصدر")
+_add("err_rig", en="Mixamo FBX not found", **{"zh-CN": "找不到 Mixamo FBX"}, ko="Mixamo FBX를 찾을 수 없습니다", ja="Mixamo FBX が見つかりません", de="Mixamo-FBX nicht gefunden", ru="Mixamo FBX не найден", ar="لم يُعثر على ملف Mixamo FBX")
+_add("err_output_missing", en="Output folder not found", **{"zh-CN": "找不到输出文件夹"}, ko="출력 폴더를 찾을 수 없습니다", ja="出力フォルダーが見つかりません", de="Ausgabeordner nicht gefunden", ru="Папка результатов не найдена", ar="لم يُعثر على مجلد الناتج")
+_add("err_log_missing", en="Log file not found", **{"zh-CN": "找不到日志文件"}, ko="로그 파일을 찾을 수 없습니다", ja="ログファイルが見つかりません", de="Protokolldatei nicht gefunden", ru="Файл журнала не найден", ar="لم يُعثر على ملف السجل")
+_add("err_no_job_folder", en="No output folder from a previous job", **{"zh-CN": "还没有上次任务的输出文件夹"}, ko="이전 작업의 출력 폴더가 없습니다", ja="前回ジョブの出力フォルダーがありません", de="Kein Ausgabeordner eines vorherigen Auftrags", ru="Нет папки предыдущего задания", ar="لا يوجد مجلد ناتج من مهمة سابقة")
+_add("err_no_cancel", en="No Motion2MixamoRig job to cancel", **{"zh-CN": "没有可取消的 Motion2MixamoRig 任务"}, ko="취소할 Motion2MixamoRig 작업이 없습니다", ja="キャンセルする Motion2MixamoRig ジョブがありません", de="Kein Motion2MixamoRig-Auftrag zum Abbrechen", ru="Нет задания Motion2MixamoRig для отмены", ar="لا توجد مهمة Motion2MixamoRig لإلغائها")
+_add("env_ready_choose", en="Ready — choose a video/image and Mixamo FBX in the panel", **{"zh-CN": "就绪 — 在面板里选择视频/图片和 Mixamo FBX"}, ko="준비됨 — 패널에서 비디오/이미지와 Mixamo FBX를 선택하세요", ja="準備完了 — パネルで動画/画像と Mixamo FBX を選んでください", de="Bereit — wähle Video/Bild und Mixamo-FBX im Panel", ru="Готово — выберите видео/фото и Mixamo FBX на панели", ar="جاهز — اختر فيديو/صورة وملف Mixamo FBX من اللوحة")
+_add("env_checking_fmt", en="Checking… {version}", **{"zh-CN": "正在检查… {version}"}, ko="확인 중… {version}", ja="確認中… {version}", de="Prüfung… {version}", ru="Проверка… {version}", ar="جاري الفحص… {version}")
+_add("env_running_doctor", en="Running m2mr doctor…", **{"zh-CN": "正在运行 m2mr doctor…"}, ko="m2mr doctor 실행 중…", ja="m2mr doctor を実行中…", de="m2mr doctor läuft…", ru="Запуск m2mr doctor…", ar="جارٍ تشغيل m2mr doctor…")
+_add("env_check_failed", en="Environment check failed", **{"zh-CN": "环境检查失败"}, ko="환경 확인에 실패했습니다", ja="環境確認に失敗しました", de="Umgebungsprüfung fehlgeschlagen", ru="Проверка среды не удалась", ar="فشل فحص البيئة")
+_add("env_cancelled", en="Environment check cancelled", **{"zh-CN": "已取消环境检查"}, ko="환경 확인이 취소되었습니다", ja="環境確認をキャンセルしました", de="Umgebungsprüfung abgebrochen", ru="Проверка среды отменена", ar="أُلغي فحص البيئة")
+_add("info_started_job", en="Started Motion2MixamoRig job {job}", **{"zh-CN": "已开始 Motion2MixamoRig 任务 {job}"}, ko="Motion2MixamoRig 작업 {job}을(를) 시작했습니다", ja="Motion2MixamoRig ジョブ {job} を開始しました", de="Motion2MixamoRig-Auftrag {job} gestartet", ru="Запущено задание Motion2MixamoRig {job}", ar="بدأت مهمة Motion2MixamoRig {job}")
+_add("info_started_env", en="Started environment check with {version}", **{"zh-CN": "已开始环境检查({version})"}, ko="{version}(으)로 환경 확인을 시작했습니다", ja="{version} で環境確認を開始しました", de="Umgebungsprüfung mit {version} gestartet", ru="Проверка среды запущена ({version})", ar="بدأ فحص البيئة باستخدام {version}")
+_add("info_cancelling", en="Cancelling Motion2MixamoRig job", **{"zh-CN": "正在取消 Motion2MixamoRig 任务"}, ko="Motion2MixamoRig 작업을 취소하는 중", ja="Motion2MixamoRig ジョブをキャンセルしています", de="Motion2MixamoRig-Auftrag wird abgebrochen", ru="Отмена задания Motion2MixamoRig", ar="جارٍ إلغاء مهمة Motion2MixamoRig")
+_add("info_imported", en="Imported {name}", **{"zh-CN": "已导入 {name}"}, ko="{name}을(를) 가져왔습니다", ja="{name} をインポートしました", de="{name} importiert", ru="Импортировано: {name}", ar="تم استيراد {name}")
+_add("cancelling_ellipsis", en="Cancelling…", **{"zh-CN": "正在取消…"}, ko="취소 중…", ja="キャンセル中…", de="Wird abgebrochen…", ru="Отмена…", ar="جارٍ الإلغاء…")
+
+_CODE_TO_KEY = {
+ "PYTHON_NOT_FOUND": "err_python",
+ "PACKAGE_MISSING": "err_package",
+ "SMPLX_MISSING": "err_smplx",
+ "INVALID_RIG": "err_invalid_rig",
+ "MULTIPLE_PEOPLE": "err_multiple_people",
+ "NO_PERSON": "err_no_person",
+ "CUDA_UNAVAILABLE": "err_cuda",
+ "MPS_UNAVAILABLE": "err_mps",
+ "PROCESS_EXITED": "err_process_exited",
+ "GLB_MISSING": "err_glb",
+ "JSON_INVALID": "err_json",
+ "PREFLIGHT_FAILED": "err_preflight",
+ "PIPELINE_FAILED": "err_pipeline",
+}
+
+_STATUS_KEYS = {
+ "idle": "status_idle",
+ "running": "status_running",
+ "cancelling": "status_cancelling",
+ "completed": "status_completed",
+ "failed": "status_failed",
+ "cancelled": "status_cancelled",
+ "import_failed": "status_import_failed",
+}
+
+_STAGE_KEYS = {
+ "preflight": "stage_preflight",
+ "extract": "stage_extract",
+ "retarget": "stage_retarget",
+ "export": "stage_export",
+ "preview": "stage_preview",
+ "done": "stage_done",
+ "failed": "stage_failed",
+ "cancelled": "stage_cancelled",
+}
+
+_ENV_KEYS = {
+ "NOT_CHECKED": "env_not_checked",
+ "CHECKING": "env_checking",
+ "READY": "env_ready",
+ "ERROR": "env_error",
+}
+
+_ENGLISH_TO_KEY = {STRINGS["en"][key]: key for key in STRINGS["en"]}
+
+
+def detect_system_language() -> str:
+ locale_name = ""
+ try:
+ import bpy
+
+ view = bpy.context.preferences.view
+ locale_name = getattr(view, "language", "") or ""
+ if not locale_name or locale_name in {"DEFAULT", "DEFAULT_SYSTEM"}:
+ locale_name = getattr(bpy.app.translations, "locale", "") or ""
+ except Exception:
+ locale_name = ""
+ if not locale_name:
+ try:
+ import locale
+
+ locale_name = locale.getdefaultlocale()[0] or ""
+ except Exception:
+ locale_name = ""
+ lowered = (locale_name or "en").replace("-", "_").lower()
+ for prefix, mapped in _BLENDER_PREFIX:
+ if lowered == prefix or lowered.startswith(prefix + "_"):
+ return mapped
+ return "en"
+
+
+def current_language() -> str:
+ try:
+ import bpy
+
+ addons = bpy.context.preferences.addons
+ for addon in addons.values():
+ prefs = getattr(addon, "preferences", None)
+ choice = getattr(prefs, "ui_language", None)
+ if choice:
+ if choice == "AUTO":
+ return detect_system_language()
+ mapped = PREF_TO_LANG.get(choice, choice)
+ if mapped in STRINGS:
+ return mapped
+ except Exception:
+ pass
+ return detect_system_language()
+
+
+def t(key: str, **kwargs: Any) -> str:
+ lang = current_language()
+ catalog = STRINGS.get(lang) or STRINGS["en"]
+ template = catalog.get(key) or STRINGS["en"].get(key) or key
+ if not kwargs:
+ return template
+ try:
+ return template.format(**kwargs)
+ except Exception:
+ return template
+
+
+def encode(key: str, **kwargs: Any) -> str:
+ """Store a translatable key plus format args so language can change later."""
+ if not kwargs:
+ return key
+ payload = ",".join(f"{name}={value}" for name, value in kwargs.items())
+ return f"{key}|{payload}"
+
+
+def localize(text: str) -> str:
+ """Translate a stored UI key, error code, or known English sentence."""
+ if not text:
+ return ""
+ if "|" in text:
+ key, payload = text.split("|", 1)
+ if key in STRINGS["en"]:
+ kwargs: dict[str, str] = {}
+ for part in payload.split(","):
+ if "=" in part:
+ name, value = part.split("=", 1)
+ kwargs[name] = value
+ return t(key, **kwargs) if kwargs else t(key)
+ if "+" in text and all(part in STRINGS["en"] for part in text.split("+")):
+ return "; ".join(t(part) for part in text.split("+"))
+ if text in STRINGS["en"]:
+ return t(text)
+ if text in _CODE_TO_KEY:
+ return t(_CODE_TO_KEY[text])
+ if text in _ENGLISH_TO_KEY:
+ return t(_ENGLISH_TO_KEY[text])
+ if ": " in text:
+ head, rest = text.split(": ", 1)
+ localized_head = localize(head)
+ if localized_head != head:
+ return f"{localized_head}: {rest}"
+ return text
+
+
+def status_label(status: str) -> str:
+ key = _STATUS_KEYS.get(status)
+ return t(key) if key else status
+
+
+def stage_label(stage: str) -> str:
+ return t(_STAGE_KEYS[stage]) if stage in _STAGE_KEYS else stage
+
+
+def env_status_label(status: str) -> str:
+ return t(_ENV_KEYS[status]) if status in _ENV_KEYS else status
diff --git a/blender_extension/motion2mixamorig_blender/operators/__init__.py b/blender_extension/motion2mixamorig_blender/operators/__init__.py
new file mode 100644
index 0000000..8120154
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/__init__.py
@@ -0,0 +1,17 @@
+from . import check_environment, import_result, open_output, run_pipeline, runtime
+
+
+def register() -> None:
+ runtime.register()
+ check_environment.register()
+ run_pipeline.register()
+ import_result.register()
+ open_output.register()
+
+
+def unregister() -> None:
+ runtime.unregister()
+ open_output.unregister()
+ import_result.unregister()
+ run_pipeline.unregister()
+ check_environment.unregister()
diff --git a/blender_extension/motion2mixamorig_blender/operators/check_environment.py b/blender_extension/motion2mixamorig_blender/operators/check_environment.py
new file mode 100644
index 0000000..d387edf
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/check_environment.py
@@ -0,0 +1,120 @@
+"""Check the configured External Python and Motion2MixamoRig install."""
+
+from __future__ import annotations
+
+import subprocess
+
+import bpy
+from bpy.types import Context, Operator
+
+from ..i18n import encode, t
+from ..preferences import get_preferences
+from ..registration import safe_register_class, safe_unregister_class
+from ..services.backend import (
+ build_doctor_argv,
+ build_version_argv,
+ directory_exists,
+ job_output_dir,
+ launch_process,
+ python_exists,
+ subprocess_env,
+)
+from .runtime import JobRuntime, attach, is_busy
+
+
+class M2MR_OT_check_environment(Operator):
+ bl_idname = "m2mr.check_environment"
+ bl_label = "Check Environment"
+ bl_description = "Verify External Python and that Motion2MixamoRig can run doctor"
+
+ def execute(self, context: Context):
+ if is_busy():
+ self.report({"ERROR"}, t("err_busy"))
+ return {"CANCELLED"}
+
+ prefs = get_preferences(context)
+ python = prefs.python_path
+ project = prefs.project_dir
+ props = context.scene.m2mr
+
+ if not python_exists(python):
+ props.env_status = "ERROR"
+ props.env_message = "err_python"
+ self.report({"ERROR"}, t("err_python"))
+ return {"CANCELLED"}
+ if not directory_exists(project):
+ props.env_status = "ERROR"
+ props.env_message = "err_project"
+ self.report({"ERROR"}, t("err_project"))
+ return {"CANCELLED"}
+
+ try:
+ version = subprocess.run(
+ build_version_argv(python),
+ capture_output=True,
+ text=True,
+ timeout=8,
+ shell=False,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ props.env_status = "ERROR"
+ props.env_message = "err_python"
+ self.report({"ERROR"}, f"{t('err_python')}: {exc}")
+ return {"CANCELLED"}
+
+ version_text = (version.stdout or version.stderr or "").strip()
+ if version.returncode != 0:
+ props.env_status = "ERROR"
+ props.env_message = "err_python"
+ self.report({"ERROR"}, t("err_python"))
+ return {"CANCELLED"}
+
+ output_dir = job_output_dir(project, "_env_check")
+ output_dir.mkdir(parents=True, exist_ok=True)
+ log_path = output_dir / "doctor.log"
+ header = f"{version_text}\n"
+ log_path.write_text(header, encoding="utf-8")
+
+ try:
+ process, log_file = launch_process(
+ build_doctor_argv(python),
+ cwd=project,
+ log_path=log_path,
+ env=subprocess_env(project),
+ )
+ except OSError as exc:
+ props.env_status = "ERROR"
+ props.env_message = f"err_python: {exc}"
+ self.report({"ERROR"}, f"{t('err_python')}: {exc}")
+ return {"CANCELLED"}
+
+ try:
+ log_file.close()
+ except OSError:
+ pass
+
+ props.env_status = "CHECKING"
+ props.env_message = encode("env_checking_fmt", version=version_text)
+ attach(
+ JobRuntime(
+ kind="doctor",
+ process=process,
+ owned_pid=process.pid,
+ output_dir=output_dir,
+ log_path=log_path,
+ progress_path=output_dir / "progress.jsonl",
+ log_file=None,
+ extra={"python_version": version_text},
+ )
+ )
+ self.report({"INFO"}, t("info_started_env", version=version_text))
+ return {"FINISHED"}
+
+
+def register() -> None:
+ safe_register_class(M2MR_OT_check_environment)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MR_OT_check_environment)
diff --git a/blender_extension/motion2mixamorig_blender/operators/import_result.py b/blender_extension/motion2mixamorig_blender/operators/import_result.py
new file mode 100644
index 0000000..b828439
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/import_result.py
@@ -0,0 +1,221 @@
+"""Import a generated mixamo_character.glb and set the scene timeline."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import bpy
+from bpy.types import Context, Operator
+
+from ..i18n import t
+from ..registration import safe_register_class, safe_unregister_class
+from ..services.backend import collection_name_for_source
+from ..services.result_reader import RunResult, blender_frame_settings, read_run_json
+
+
+def _import_gltf(filepath: str) -> None:
+ if hasattr(bpy.ops.import_scene, "gltf"):
+ bpy.ops.import_scene.gltf(filepath=filepath)
+ return
+ if hasattr(bpy.ops.wm, "gltf_import"):
+ bpy.ops.wm.gltf_import(filepath=filepath)
+ return
+ raise RuntimeError("Blender glTF importer is not available")
+
+
+def _view3d_region(area):
+ for region in area.regions:
+ if region.type == "WINDOW":
+ return region
+ return None
+
+
+def _frame_selected(context: Context) -> None:
+ wm = context.window_manager
+ if wm is None:
+ return
+ for window in wm.windows:
+ screen = window.screen
+ if screen is None:
+ continue
+ for area in screen.areas:
+ if area.type != "VIEW_3D":
+ continue
+ region = _view3d_region(area)
+ if region is None:
+ continue
+ try:
+ with context.temp_override(window=window, area=area, region=region):
+ bpy.ops.view3d.view_selected()
+ return
+ except Exception:
+ return
+
+
+def apply_scene_frames(scene, fps: float | None, n_frames: int | None) -> None:
+ if fps is None or n_frames is None:
+ return
+ settings = blender_frame_settings(fps, n_frames)
+ scene.render.fps = int(settings["fps"])
+ scene.render.fps_base = float(settings["fps_base"])
+ scene.frame_start = int(settings["frame_start"])
+ scene.frame_end = int(settings["frame_end"])
+
+
+_BUBBLE_VERTEX_LIMIT = 500
+
+
+def hide_joint_bubbles(armature, imported_objects) -> None:
+ """Turn off the outliner eye on Mixamo joint-bubble objects. Do not delete them.
+
+ Blender's glTF importer assigns a small Icosphere as every bone's custom
+ shape. Hiding that object (and disabling armature Shapes) removes the
+ cluster of spheres; the Icosphere and bone custom_shape links stay.
+ """
+ imported = set(imported_objects)
+ shape_objects = []
+ if armature is not None and getattr(armature, "pose", None) is not None:
+ seen: set = set()
+ for bone in armature.pose.bones:
+ shape = bone.custom_shape
+ if shape is None or shape in seen or shape not in imported:
+ continue
+ seen.add(shape)
+ shape_objects.append(shape)
+ data = armature.data
+ if hasattr(data, "show_bone_custom_shapes"):
+ data.show_bone_custom_shapes = False
+ if hasattr(data, "display_type"):
+ data.display_type = "STICK"
+ # Hide the armature object itself. The skinned mesh stays visible
+ # and still deforms; this is the Outliner eye that removes the
+ # floating joint spheres.
+ try:
+ armature.hide_set(True)
+ except Exception:
+ armature.hide_viewport = True
+
+ extra = [
+ obj
+ for obj in imported
+ if obj.type == "MESH"
+ and obj.name.rsplit(".", 1)[0] == "Icosphere"
+ and len(obj.data.vertices) <= _BUBBLE_VERTEX_LIMIT
+ and obj not in shape_objects
+ ]
+ shape_objects.extend(extra)
+
+ for obj in shape_objects:
+ if obj.type == "ARMATURE":
+ continue
+ if obj.type == "MESH" and len(obj.data.vertices) > _BUBBLE_VERTEX_LIMIT:
+ continue
+ try:
+ obj.hide_set(True)
+ except Exception:
+ pass
+ obj.hide_viewport = True
+
+
+def import_generated_character(
+ context: Context,
+ result: RunResult,
+ *,
+ source_name: str,
+) -> None:
+ if result.glb_path is None or not result.glb_path.is_file():
+ raise FileNotFoundError("Result GLB not found")
+
+ # glTF keys are in seconds; Blender converts them with the scene FPS at
+ # import time. Set that first or a 24 fps default will stretch the clip.
+ apply_scene_frames(context.scene, result.fps, result.n_frames)
+
+ existing = set(bpy.data.objects)
+ _import_gltf(str(result.glb_path))
+ new_objects = [obj for obj in bpy.data.objects if obj not in existing]
+ if not new_objects:
+ raise RuntimeError("glTF import produced no objects")
+
+ collection_name = collection_name_for_source(source_name)
+ collection = bpy.data.collections.get(collection_name)
+ if collection is None:
+ collection = bpy.data.collections.new(collection_name)
+ context.scene.collection.children.link(collection)
+
+ for obj in new_objects:
+ for user in list(obj.users_collection):
+ user.objects.unlink(obj)
+ if obj.name not in collection.objects:
+ collection.objects.link(obj)
+
+ armature = next((obj for obj in new_objects if obj.type == "ARMATURE"), None)
+ hide_joint_bubbles(armature, new_objects)
+ view_layer = context.view_layer
+ for obj in list(view_layer.objects):
+ obj.select_set(False)
+ visible_mesh = next(
+ (
+ obj
+ for obj in new_objects
+ if obj.type == "MESH" and not obj.hide_get() and obj.name.rsplit(".", 1)[0] != "Icosphere"
+ ),
+ None,
+ )
+ focus = visible_mesh or armature
+ if focus is not None:
+ focus.select_set(True)
+ view_layer.objects.active = focus
+ try:
+ _frame_selected(context)
+ except Exception:
+ pass
+ elif new_objects:
+ new_objects[0].select_set(True)
+ view_layer.objects.active = new_objects[0]
+
+
+class M2MR_OT_import_result(Operator):
+ bl_idname = "m2mr.import_result"
+ bl_label = "Import Generated Character"
+ bl_description = "Import mixamo_character.glb from the last Motion2MixamoRig job"
+
+ def execute(self, context: Context):
+ props = context.scene.m2mr
+ run_dir = Path(props.job_output_dir).expanduser() if props.job_output_dir else None
+ if run_dir is None or not run_dir.is_dir():
+ self.report({"ERROR"}, t("err_no_job_folder"))
+ return {"CANCELLED"}
+
+ result = read_run_json(run_dir)
+ if result.glb_path is None or not result.glb_path.is_file():
+ props.job_error = "err_glb"
+ self.report({"ERROR"}, t("err_glb"))
+ return {"CANCELLED"}
+
+ try:
+ import_generated_character(
+ context,
+ result,
+ source_name=props.job_source_name or run_dir.name,
+ )
+ except Exception as exc:
+ props.import_note = "generation_import_failed"
+ props.job_error = f"generation_import_failed: {exc}"
+ self.report({"ERROR"}, f"{t('generation_import_failed')}: {exc}")
+ return {"CANCELLED"}
+
+ props.job_glb_path = str(result.glb_path)
+ props.import_note = ""
+ if props.job_status in {"import_failed", "completed"}:
+ props.job_status = "completed"
+ props.job_error = ""
+ self.report({"INFO"}, t("info_imported", name=result.glb_path.name))
+ return {"FINISHED"}
+
+
+def register() -> None:
+ safe_register_class(M2MR_OT_import_result)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MR_OT_import_result)
diff --git a/blender_extension/motion2mixamorig_blender/operators/open_output.py b/blender_extension/motion2mixamorig_blender/operators/open_output.py
new file mode 100644
index 0000000..40629ac
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/open_output.py
@@ -0,0 +1,58 @@
+"""Open the job output folder or the full log in the system file manager."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import bpy
+from bpy.types import Context, Operator
+
+from ..i18n import t
+from ..registration import safe_register_class, safe_unregister_class
+from ..services.backend import open_path
+
+
+class M2MR_OT_open_output(Operator):
+ bl_idname = "m2mr.open_output"
+ bl_label = "Open Output Folder"
+ bl_description = "Open the Motion2MixamoRig job directory"
+
+ def execute(self, context: Context):
+ path = Path(context.scene.m2mr.job_output_dir).expanduser()
+ if not path.is_dir():
+ self.report({"ERROR"}, t("err_output_missing"))
+ return {"CANCELLED"}
+ try:
+ open_path(path)
+ except OSError as exc:
+ self.report({"ERROR"}, str(exc))
+ return {"CANCELLED"}
+ return {"FINISHED"}
+
+
+class M2MR_OT_view_log(Operator):
+ bl_idname = "m2mr.view_log"
+ bl_label = "View Full Log"
+ bl_description = "Open the job log in the default text editor"
+
+ def execute(self, context: Context):
+ path = Path(context.scene.m2mr.job_log_path).expanduser()
+ if not path.is_file():
+ self.report({"ERROR"}, t("err_log_missing"))
+ return {"CANCELLED"}
+ try:
+ open_path(path)
+ except OSError as exc:
+ self.report({"ERROR"}, str(exc))
+ return {"CANCELLED"}
+ return {"FINISHED"}
+
+
+def register() -> None:
+ safe_register_class(M2MR_OT_open_output)
+ safe_register_class(M2MR_OT_view_log)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MR_OT_view_log)
+ safe_unregister_class(M2MR_OT_open_output)
diff --git a/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py b/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py
new file mode 100644
index 0000000..05e9ca4
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/run_pipeline.py
@@ -0,0 +1,126 @@
+"""Start or cancel an external `m2mr run` without blocking the UI."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import bpy
+from bpy.types import Context, Operator
+
+from ..i18n import t
+from ..preferences import get_preferences
+from ..registration import safe_register_class, safe_unregister_class
+from ..services.backend import (
+ build_run_argv,
+ job_output_dir,
+ launch_process,
+ new_job_id,
+ subprocess_env,
+ validate_run_inputs,
+)
+from .runtime import JobRuntime, attach, is_busy, request_cancel
+
+
+class M2MR_OT_run_pipeline(Operator):
+ bl_idname = "m2mr.run_pipeline"
+ bl_label = "Generate Motion"
+ bl_description = "Run Motion2MixamoRig in the configured External Python"
+
+ def execute(self, context: Context):
+ prefs = get_preferences(context)
+ props = context.scene.m2mr
+ source_type = "image" if props.source_type == "IMAGE" else "video"
+ errors = validate_run_inputs(
+ python=prefs.python_path,
+ project_dir=prefs.project_dir,
+ source=props.source_path,
+ rig=props.rig_path,
+ busy=is_busy(),
+ )
+ if errors:
+ props.job_status = "failed"
+ props.job_error = errors[0]
+ self.report({"ERROR"}, t(errors[0]))
+ return {"CANCELLED"}
+
+ source = Path(props.source_path).expanduser()
+ job_id = new_job_id(source.stem)
+ output_dir = job_output_dir(prefs.project_dir, job_id)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ progress_path = output_dir / "progress.jsonl"
+ log_path = output_dir / "job.log"
+
+ argv = build_run_argv(
+ prefs.python_path,
+ source_type=source_type,
+ source=source,
+ rig=props.rig_path,
+ device=props.device,
+ output_dir=output_dir,
+ progress_jsonl=progress_path,
+ preview=bool(props.generate_preview),
+ )
+ try:
+ process, log_file = launch_process(
+ argv,
+ cwd=prefs.project_dir,
+ log_path=log_path,
+ env=subprocess_env(prefs.project_dir),
+ )
+ except OSError as exc:
+ props.job_status = "failed"
+ props.job_error = f"err_python: {exc}"
+ self.report({"ERROR"}, f"{t('err_python')}: {exc}")
+ return {"CANCELLED"}
+
+ props.job_status = "running"
+ props.job_stage = "preflight"
+ props.job_progress = 0.05
+ props.job_error = ""
+ props.import_note = ""
+ props.job_glb_path = ""
+ props.job_output_dir = str(output_dir)
+ props.job_log_path = str(log_path)
+ props.job_id = job_id
+ props.job_source_name = source.stem
+
+ attach(
+ JobRuntime(
+ kind="run",
+ process=process,
+ owned_pid=process.pid,
+ output_dir=output_dir,
+ log_path=log_path,
+ progress_path=progress_path,
+ log_file=log_file,
+ source_name=source.stem,
+ auto_import=True,
+ )
+ )
+ self.report({"INFO"}, t("info_started_job", job=job_id))
+ return {"FINISHED"}
+
+
+class M2MR_OT_cancel_job(Operator):
+ bl_idname = "m2mr.cancel_job"
+ bl_label = "Cancel"
+ bl_description = "Stop the Motion2MixamoRig job started by this add-on"
+
+ def execute(self, context: Context):
+ if not request_cancel():
+ self.report({"WARNING"}, t("err_no_cancel"))
+ return {"CANCELLED"}
+ context.scene.m2mr.job_status = "cancelling"
+ context.scene.m2mr.job_error = "cancelling_ellipsis"
+ self.report({"INFO"}, t("info_cancelling"))
+ return {"FINISHED"}
+
+
+def register() -> None:
+ safe_register_class(M2MR_OT_run_pipeline)
+ safe_register_class(M2MR_OT_cancel_job)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MR_OT_cancel_job)
+ safe_unregister_class(M2MR_OT_run_pipeline)
diff --git a/blender_extension/motion2mixamorig_blender/operators/runtime.py b/blender_extension/motion2mixamorig_blender/operators/runtime.py
new file mode 100644
index 0000000..d1fceb3
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/operators/runtime.py
@@ -0,0 +1,284 @@
+"""Single in-memory job plus a bpy.app.timers poller.
+
+Importing this module does not start a process or touch the filesystem.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import bpy
+
+from ..services.backend import kill_process, tail_text, terminate_process
+from ..services.errors import classify_log_text, key_for_code
+from ..services.job_monitor import latest_progress, read_progress_file
+from ..services.result_reader import read_run_json
+
+_TIMER_INTERVAL = 0.25
+_KILL_AFTER_S = 4.0
+
+
+@dataclass
+class JobRuntime:
+ kind: str
+ process: Any
+ owned_pid: int
+ output_dir: Path
+ log_path: Path
+ progress_path: Path
+ log_file: Any = None
+ cancelled: bool = False
+ finished: bool = False
+ cancel_started: float = 0.0
+ source_name: str = ""
+ auto_import: bool = True
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+_runtime: JobRuntime | None = None
+
+
+def get_runtime() -> JobRuntime | None:
+ return _runtime
+
+
+def is_busy() -> bool:
+ runtime = _runtime
+ if runtime is None or runtime.finished or runtime.process is None:
+ return False
+ return runtime.process.poll() is None
+
+
+def attach(runtime: JobRuntime) -> None:
+ global _runtime
+ _runtime = runtime
+ _start_timer()
+
+
+def _start_timer() -> None:
+ if not bpy.app.timers.is_registered(_poll):
+ bpy.app.timers.register(_poll, first_interval=_TIMER_INTERVAL, persistent=True)
+
+
+def stop_timer() -> None:
+ if bpy.app.timers.is_registered(_poll):
+ bpy.app.timers.unregister(_poll)
+
+
+def _close_log(runtime: JobRuntime) -> None:
+ log_file = runtime.log_file
+ runtime.log_file = None
+ if log_file is not None:
+ try:
+ log_file.close()
+ except OSError:
+ pass
+
+
+def shutdown() -> None:
+ """Called from addon unregister: drop the timer and stop our process."""
+ global _runtime
+ stop_timer()
+ runtime = _runtime
+ _runtime = None
+ if runtime is None:
+ return
+ if runtime.process is not None and runtime.process.poll() is None:
+ terminate_process(runtime.process)
+ try:
+ runtime.process.wait(timeout=1.0)
+ except Exception:
+ kill_process(runtime.process)
+ _close_log(runtime)
+
+
+def request_cancel() -> bool:
+ runtime = _runtime
+ if runtime is None or runtime.process is None:
+ return False
+ if runtime.process.pid != runtime.owned_pid:
+ return False
+ if runtime.process.poll() is not None:
+ return False
+ runtime.cancelled = True
+ import time
+
+ runtime.cancel_started = time.monotonic()
+ terminate_process(runtime.process)
+ return True
+
+
+def _tag_redraw() -> None:
+ wm = bpy.context.window_manager
+ if wm is None:
+ return
+ for window in wm.windows:
+ screen = window.screen
+ if screen is None:
+ continue
+ for area in screen.areas:
+ if area.type == "VIEW_3D":
+ area.tag_redraw()
+
+
+def _props():
+ scene = bpy.context.scene
+ return getattr(scene, "m2mr", None)
+
+
+def _poll() -> float | None:
+ runtime = _runtime
+ if runtime is None:
+ return None
+ props = _props()
+ if props is None:
+ return _TIMER_INTERVAL
+
+ if runtime.kind == "doctor":
+ _poll_doctor(runtime, props)
+ else:
+ _poll_run(runtime, props)
+
+ _tag_redraw()
+ if runtime.finished:
+ stop_timer()
+ return None
+ return _TIMER_INTERVAL
+
+
+def _poll_doctor(runtime: JobRuntime, props) -> None:
+ import time
+
+ code = runtime.process.poll()
+ log = tail_text(runtime.log_path, max_lines=80, max_chars=8000)
+ if runtime.cancelled and code is None:
+ if time.monotonic() - runtime.cancel_started > _KILL_AFTER_S:
+ kill_process(runtime.process)
+ return
+ if code is None:
+ props.env_status = "CHECKING"
+ props.env_message = "env_running_doctor"
+ return
+
+ _close_log(runtime)
+ runtime.finished = True
+ from ..services.backend import interpret_doctor_output
+
+ try:
+ full = Path(runtime.log_path).read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ full = log
+ status, message = interpret_doctor_output(code, full)
+ props.env_status = status
+ props.env_message = message
+ if runtime.cancelled:
+ props.env_status = "ERROR"
+ props.env_message = "env_cancelled"
+
+
+def _poll_run(runtime: JobRuntime, props) -> None:
+ import time
+
+ events = read_progress_file(runtime.progress_path)
+ latest = latest_progress(events)
+ if latest is not None:
+ props.job_stage = latest.stage
+ props.job_progress = latest.progress
+ if latest.stage == "failed" and latest.message:
+ props.job_error = latest.message
+
+ props.job_output_dir = str(runtime.output_dir)
+ props.job_log_path = str(runtime.log_path)
+
+ code = runtime.process.poll()
+ if runtime.cancelled and code is None:
+ props.job_status = "cancelling"
+ props.job_stage = "cancelled"
+ if time.monotonic() - runtime.cancel_started > _KILL_AFTER_S:
+ kill_process(runtime.process)
+ return
+ if code is None:
+ props.job_status = "running"
+ return
+
+ _close_log(runtime)
+ runtime.finished = True
+ _finish_run(runtime, props, code)
+
+
+def _finish_run(runtime: JobRuntime, props, code: int) -> None:
+ if runtime.cancelled:
+ props.job_status = "cancelled"
+ props.job_stage = "cancelled"
+ props.job_error = "cancelled"
+ return
+
+ result = read_run_json(runtime.output_dir)
+ if result.status == "completed" and result.glb_path is not None:
+ props.job_status = "completed"
+ props.job_stage = "done"
+ props.job_progress = 1.0
+ props.job_glb_path = str(result.glb_path)
+ props.job_error = ""
+ props.import_note = ""
+ if runtime.auto_import:
+ from .import_result import import_generated_character
+
+ try:
+ import_generated_character(
+ bpy.context,
+ result,
+ source_name=runtime.source_name or props.job_source_name,
+ )
+ except Exception as exc:
+ props.job_status = "import_failed"
+ props.import_note = "generation_import_failed"
+ props.job_error = f"generation_import_failed: {exc}"
+ return
+
+ if result.status == "failed":
+ props.job_status = "failed"
+ props.job_stage = result.stage or "failed"
+ props.job_error = key_for_code(result.error_code or "PIPELINE_FAILED")
+ if result.glb_path is not None:
+ props.job_glb_path = str(result.glb_path)
+ return
+
+ if result.status == "glb_missing":
+ props.job_status = "failed"
+ props.job_error = "err_glb"
+ return
+
+ if result.status == "invalid":
+ props.job_status = "failed"
+ props.job_error = "err_json"
+ return
+
+ try:
+ log = Path(runtime.log_path).read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ log = ""
+ error_code, _message = classify_log_text(log)
+ if not log.strip() or error_code == "PROCESS_EXITED":
+ from ..i18n import encode
+
+ message = encode("err_process_exited_code", code=code)
+ elif code not in (0, None) and error_code == "PIPELINE_FAILED":
+ from ..i18n import encode
+
+ message = encode("err_process_exited_code", code=code)
+ else:
+ message = key_for_code(error_code)
+ props.job_status = "failed"
+ props.job_stage = "failed"
+ props.job_error = message
+
+
+def register() -> None:
+ return
+
+
+def unregister() -> None:
+ shutdown()
diff --git a/blender_extension/motion2mixamorig_blender/panels/__init__.py b/blender_extension/motion2mixamorig_blender/panels/__init__.py
new file mode 100644
index 0000000..8f2973e
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/panels/__init__.py
@@ -0,0 +1,9 @@
+from . import main_panel
+
+
+def register() -> None:
+ main_panel.register()
+
+
+def unregister() -> None:
+ main_panel.unregister()
diff --git a/blender_extension/motion2mixamorig_blender/panels/main_panel.py b/blender_extension/motion2mixamorig_blender/panels/main_panel.py
new file mode 100644
index 0000000..01f8ee1
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/panels/main_panel.py
@@ -0,0 +1,112 @@
+"""3D Viewport → Sidebar (N Panel) → Motion2MixamoRig."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import bpy
+from bpy.types import Context, Panel
+
+from ..i18n import env_status_label, localize, stage_label, status_label, t
+from ..operators.runtime import get_runtime
+from ..preferences import get_preferences
+from ..registration import safe_register_class, safe_unregister_class
+from ..services.backend import tail_text
+
+
+class M2MR_PT_main(Panel):
+ bl_label = "Motion2MixamoRig"
+ bl_idname = "M2MR_PT_main"
+ bl_space_type = "VIEW_3D"
+ bl_region_type = "UI"
+ bl_category = "Motion2MixamoRig"
+
+ def draw(self, context: Context) -> None:
+ layout = self.layout
+ props = context.scene.m2mr
+ prefs = get_preferences(context)
+ runtime = get_runtime()
+ busy = runtime is not None and not runtime.finished
+
+ self._draw_setup(layout, prefs, props, busy)
+ self._draw_input(layout, props, busy)
+ self._draw_progress(layout, props, busy)
+
+ def _draw_setup(self, layout, prefs, props, busy: bool) -> None:
+ box = layout.box()
+ box.label(text=t("section_setup"))
+ box.prop(prefs, "ui_language", text=t("ui_language"))
+ box.prop(prefs, "python_path", text=t("external_python"))
+ box.prop(prefs, "project_dir", text=t("project_directory"))
+ box.prop(props, "device", text=t("device"))
+ row = box.row()
+ row.enabled = not busy
+ row.operator("m2mr.check_environment", text=t("check_environment"), icon="CHECKMARK")
+ box.label(text=t("environment_fmt", status=env_status_label(props.env_status)))
+ if props.env_message:
+ box.label(text=localize(props.env_message))
+
+ def _draw_input(self, layout, 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, "generate_preview", text=t("generate_preview"))
+ row = box.row()
+ row.enabled = not busy
+ row.scale_y = 1.4
+ row.operator("m2mr.run_pipeline", text=t("generate_motion"), icon="PLAY")
+
+ def _draw_progress(self, layout, props, busy: bool) -> None:
+ box = layout.box()
+ box.label(text=t("section_progress"))
+ status = props.job_status or "idle"
+ box.label(text=t("status_fmt", status=status_label(status)))
+
+ if busy or status in {"running", "cancelling"}:
+ if props.job_stage:
+ box.label(text=t("stage_fmt", stage=stage_label(props.job_stage)))
+ try:
+ box.progress(factor=float(props.job_progress), type="BAR")
+ except Exception:
+ box.prop(props, "job_progress", text=t("progress"), slider=True)
+ log_path = Path(props.job_log_path) if props.job_log_path else None
+ log = tail_text(log_path, max_lines=8) if log_path else ""
+ if log:
+ log_box = box.box()
+ log_box.label(text=t("recent_log"))
+ for line in log.splitlines()[-8:]:
+ log_box.label(text=line[:96])
+ box.operator("m2mr.cancel_job", text=t("cancel"), icon="X")
+ return
+
+ if status in {"completed", "import_failed", "failed", "cancelled"}:
+ if props.job_stage:
+ box.label(text=t("stage_fmt", stage=stage_label(props.job_stage)))
+ if status == "completed":
+ box.label(text=t("generation_succeeded"))
+ elif status == "import_failed":
+ box.label(text=t("generation_import_failed"))
+ elif status == "cancelled":
+ box.label(text=t("cancelled"))
+ if props.job_error:
+ box.label(text=localize(props.job_error))
+ if props.job_glb_path:
+ box.label(text=t("glb_fmt", name=Path(props.job_glb_path).name))
+ row = box.row()
+ row.operator("m2mr.import_result", text=t("import_character"), icon="IMPORT")
+ row = box.row()
+ row.operator("m2mr.open_output", text=t("open_output"), icon="FILE_FOLDER")
+ row.operator("m2mr.view_log", text=t("view_log"), icon="TEXT")
+ return
+
+ box.label(text=t("no_job_yet"))
+
+
+def register() -> None:
+ safe_register_class(M2MR_PT_main)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MR_PT_main)
diff --git a/blender_extension/motion2mixamorig_blender/preferences.py b/blender_extension/motion2mixamorig_blender/preferences.py
new file mode 100644
index 0000000..0fe7df8
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/preferences.py
@@ -0,0 +1,95 @@
+"""Add-on preferences that persist across .blend files."""
+
+from __future__ import annotations
+
+import bpy
+from bpy.props import EnumProperty, StringProperty
+from bpy.types import AddonPreferences, Context
+
+from .registration import safe_register_class, safe_unregister_class
+
+
+ADDON_ID = __package__
+
+
+def _on_language_update(self, context: Context) -> None:
+ wm = context.window_manager
+ if wm is None:
+ return
+ for window in wm.windows:
+ screen = window.screen
+ if screen is None:
+ continue
+ for area in screen.areas:
+ area.tag_redraw()
+
+
+# Static items: identifiers must be valid Python names (no "-").
+# A callback + default= is rejected by Blender during register_class.
+_UI_LANGUAGE_ITEMS = (
+ ("AUTO", "Auto (Blender / System)", ""),
+ ("en", "English", ""),
+ ("zh_CN", "中文", ""),
+ ("ko", "한국어", ""),
+ ("ja", "日本語", ""),
+ ("de", "Deutsch", ""),
+ ("ru", "Русский", ""),
+ ("ar", "العربية", ""),
+)
+
+
+class M2MRPreferences(AddonPreferences):
+ bl_idname = ADDON_ID
+
+ python_path: StringProperty(
+ name="External Python",
+ description="Python interpreter that has Motion2MixamoRig installed (not Blender's Python)",
+ subtype="FILE_PATH",
+ maxlen=2048,
+ default="",
+ )
+ project_dir: StringProperty(
+ name="Project Directory",
+ description="Motion2MixamoRig repository or install directory",
+ subtype="DIR_PATH",
+ maxlen=2048,
+ default="",
+ )
+ ui_language: EnumProperty(
+ name="UI Language",
+ description="Plugin UI language. Auto follows Blender / the system language",
+ items=_UI_LANGUAGE_ITEMS,
+ default="AUTO",
+ update=_on_language_update,
+ )
+
+ def draw(self, context: Context) -> None:
+ from .i18n import t
+
+ layout = self.layout
+ layout.prop(self, "ui_language", text=t("ui_language"))
+ layout.prop(self, "python_path", text=t("external_python"))
+ layout.prop(self, "project_dir", text=t("project_directory"))
+ layout.label(text=t("prefs_venv_hint"))
+
+
+def get_preferences(context: Context | None = None) -> M2MRPreferences:
+ ctx = context or bpy.context
+ addons = ctx.preferences.addons
+ if ADDON_ID in addons:
+ return addons[ADDON_ID].preferences
+ for key in addons.keys():
+ if key.endswith(".motion2mixamorig") or key in {
+ "motion2mixamorig",
+ "motion2mixamorig_blender",
+ }:
+ return addons[key].preferences
+ raise KeyError(f"Motion2MixamoRig add-on preferences not found ({ADDON_ID})")
+
+
+def register() -> None:
+ safe_register_class(M2MRPreferences)
+
+
+def unregister() -> None:
+ safe_unregister_class(M2MRPreferences)
diff --git a/blender_extension/motion2mixamorig_blender/properties.py b/blender_extension/motion2mixamorig_blender/properties.py
new file mode 100644
index 0000000..7ee7560
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/properties.py
@@ -0,0 +1,98 @@
+"""Per-scene UI and job state."""
+
+from __future__ import annotations
+
+import bpy
+from bpy.props import BoolProperty, EnumProperty, FloatProperty, StringProperty
+from bpy.types import PropertyGroup, Scene
+
+from .registration import safe_register_class, safe_unregister_class
+
+
+_SOURCE_TYPE_ITEMS = ()
+_DEVICE_ITEMS = ()
+
+
+def _source_type_items(self, context):
+ from .i18n import t
+
+ global _SOURCE_TYPE_ITEMS
+ _SOURCE_TYPE_ITEMS = (
+ ("VIDEO", t("source_video"), t("source_video_desc")),
+ ("IMAGE", t("source_image"), t("source_image_desc")),
+ )
+ return _SOURCE_TYPE_ITEMS
+
+
+def _device_items(self, context):
+ from .i18n import t
+
+ global _DEVICE_ITEMS
+ _DEVICE_ITEMS = (
+ ("cpu", "CPU", t("device_cpu_desc")),
+ ("cuda", "CUDA", t("device_cuda_desc")),
+ ("mps", "MPS", t("device_mps_desc")),
+ )
+ return _DEVICE_ITEMS
+
+
+class M2MRProperties(PropertyGroup):
+ source_type: EnumProperty(
+ name="Source Type",
+ items=_source_type_items,
+ )
+ source_path: StringProperty(
+ name="Source File",
+ subtype="FILE_PATH",
+ maxlen=2048,
+ default="",
+ )
+ rig_path: StringProperty(
+ name="Mixamo Rig FBX",
+ subtype="FILE_PATH",
+ maxlen=2048,
+ default="",
+ )
+ device: EnumProperty(
+ name="Device",
+ items=_device_items,
+ )
+ generate_preview: BoolProperty(
+ name="Generate Preview Videos",
+ description="Also render preview videos/images (slower)",
+ default=False,
+ )
+
+ env_status: EnumProperty(
+ name="Environment",
+ items=(
+ ("NOT_CHECKED", "Not checked", ""),
+ ("CHECKING", "Checking", ""),
+ ("READY", "Ready", ""),
+ ("ERROR", "Error", ""),
+ ),
+ default="NOT_CHECKED",
+ )
+ env_message: StringProperty(name="Environment message", default="", maxlen=512)
+
+ job_status: StringProperty(name="Job status", default="idle", maxlen=64)
+ job_stage: StringProperty(name="Job stage", default="", maxlen=64)
+ job_progress: FloatProperty(name="Progress", default=0.0, min=0.0, max=1.0)
+ job_error: StringProperty(name="Job error", default="", maxlen=512)
+ job_glb_path: StringProperty(name="GLB path", default="", maxlen=2048, subtype="FILE_PATH")
+ job_output_dir: StringProperty(name="Output folder", default="", maxlen=2048, subtype="DIR_PATH")
+ job_log_path: StringProperty(name="Log path", default="", maxlen=2048, subtype="FILE_PATH")
+ job_id: StringProperty(name="Job id", default="", maxlen=128)
+ job_source_name: StringProperty(name="Source name", default="", maxlen=128)
+ import_note: StringProperty(name="Import note", default="", maxlen=512)
+
+
+def register() -> None:
+ safe_register_class(M2MRProperties)
+ Scene.m2mr = bpy.props.PointerProperty(type=M2MRProperties)
+
+
+def unregister() -> None:
+ if hasattr(Scene, "m2mr"):
+ del Scene.m2mr
+ safe_unregister_class(M2MRProperties)
diff --git a/blender_extension/motion2mixamorig_blender/registration.py b/blender_extension/motion2mixamorig_blender/registration.py
new file mode 100644
index 0000000..14f9767
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/registration.py
@@ -0,0 +1,33 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import bpy
+
+
+def registered_class(cls):
+ return getattr(bpy.types, cls.__name__, None)
+
+
+def safe_register_class(cls) -> None:
+ existing = registered_class(cls)
+ if existing is not None:
+ try:
+ 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
+ try:
+ bpy.utils.unregister_class(existing)
+ except Exception:
+ pass
diff --git a/blender_extension/motion2mixamorig_blender/services/__init__.py b/blender_extension/motion2mixamorig_blender/services/__init__.py
new file mode 100644
index 0000000..c62298c
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/services/__init__.py
@@ -0,0 +1 @@
+"""Blender-free helpers used by the extension and by unit tests."""
diff --git a/blender_extension/motion2mixamorig_blender/services/backend.py b/blender_extension/motion2mixamorig_blender/services/backend.py
new file mode 100644
index 0000000..3e4acec
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/services/backend.py
@@ -0,0 +1,305 @@
+"""Command construction, process launch, and filesystem helpers.
+
+No Blender imports. Paths are passed as list arguments with shell=False so
+spaces in Windows/macOS paths stay intact.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import subprocess
+import sys
+from datetime import datetime
+from pathlib import Path
+
+
+def as_user_path(value: str | Path) -> Path:
+ return Path(value).expanduser()
+
+
+def python_exists(python: str | Path) -> bool:
+ path = as_user_path(python)
+ return bool(str(python).strip()) and path.is_file()
+
+
+def directory_exists(path: str | Path) -> bool:
+ return bool(str(path).strip()) and as_user_path(path).is_dir()
+
+
+def file_exists(path: str | Path) -> bool:
+ return bool(str(path).strip()) and as_user_path(path).is_file()
+
+
+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"]
+
+
+def build_run_argv(
+ python: str | Path,
+ *,
+ source_type: str,
+ source: str | Path,
+ rig: str | Path,
+ device: str,
+ output_dir: str | Path,
+ progress_jsonl: str | Path,
+ preview: bool,
+) -> 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}")
+
+ cmd = [
+ os.fspath(as_user_path(python)),
+ "-m",
+ "motion2mixamorig.cli",
+ "run",
+ "--device",
+ device,
+ "--rig",
+ os.fspath(as_user_path(rig)),
+ "--output-dir",
+ os.fspath(as_user_path(output_dir)),
+ "--progress-jsonl",
+ os.fspath(as_user_path(progress_jsonl)),
+ ]
+ flag = "--image" if source_type == "image" else "--video"
+ cmd.extend([flag, os.fspath(as_user_path(source))])
+ if not preview:
+ cmd.append("--no-preview")
+ return cmd
+
+
+_BLENDER_ENV_DROP = (
+ "PYTHONHOME",
+ "PYTHONPATH",
+ "PYTHONEXECUTABLE",
+ "PYTHONUSERBASE",
+ "PYTHONSTARTUP",
+ "__PYVENV_LAUNCHER__",
+ "BLENDER_SYSTEM_PYTHON",
+ "DYLD_LIBRARY_PATH",
+ "DYLD_FRAMEWORK_PATH",
+ "DYLD_INSERT_LIBRARIES",
+ "DYLD_FALLBACK_LIBRARY_PATH",
+)
+
+
+def subprocess_env(project_dir: str | Path) -> dict[str, str]:
+ """Build an env for External Python that does not inherit Blender's interpreter."""
+ env = os.environ.copy()
+ for key in _BLENDER_ENV_DROP:
+ env.pop(key, None)
+ if "PATH" in env:
+ env["PATH"] = os.pathsep.join(
+ part
+ for part in env["PATH"].split(os.pathsep)
+ if "Blender.app" not in part and "Blender/" not in part
+ )
+ if "LD_LIBRARY_PATH" in env:
+ env["LD_LIBRARY_PATH"] = os.pathsep.join(
+ part
+ for part in env["LD_LIBRARY_PATH"].split(os.pathsep)
+ if "blender" not in part.lower()
+ )
+ if not env["LD_LIBRARY_PATH"]:
+ env.pop("LD_LIBRARY_PATH", None)
+ root = os.fspath(as_user_path(project_dir))
+ env["PYTHONPATH"] = root
+ env["PYTHONUNBUFFERED"] = "1"
+ return env
+
+
+def validate_run_inputs(
+ *,
+ python: str | Path,
+ project_dir: str | Path,
+ source: str | Path,
+ rig: str | Path,
+ busy: bool,
+) -> list[str]:
+ errors: list[str] = []
+ if busy:
+ errors.append("err_busy")
+ if not python_exists(python):
+ errors.append("err_python")
+ if not directory_exists(project_dir):
+ errors.append("err_project")
+ if not file_exists(source):
+ errors.append("err_source")
+ if not file_exists(rig):
+ errors.append("err_rig")
+ return errors
+
+
+def new_job_id(source_stem: str, now: datetime | None = None) -> str:
+ stamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S")
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in source_stem)
+ safe = safe.strip("_") or "job"
+ return f"{stamp}_{safe[:40]}"
+
+
+def job_output_dir(project_dir: str | Path, job_id: str) -> Path:
+ return as_user_path(project_dir) / "outputs" / "blender_jobs" / job_id
+
+
+def collection_name_for_source(source_stem: str) -> str:
+ safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in source_stem)
+ safe = safe.strip("_") or "character"
+ return f"M2MR_{safe[:80]}"
+
+
+def launch_process(
+ argv: list[str],
+ *,
+ cwd: str | Path,
+ log_path: str | Path,
+ env: dict[str, str] | None = None,
+) -> tuple[subprocess.Popen, object]:
+ """Start a child process; stdout/stderr go to `log_path`.
+
+ Returns `(process, log_file)` — the caller must keep the file open until
+ the process exits, then close it.
+ """
+ log = Path(log_path)
+ log.parent.mkdir(parents=True, exist_ok=True)
+ header = " ".join(os.fspath(part) for part in argv) + "\n"
+ log.write_text(header, encoding="utf-8")
+ log_file = open(log, "ab", buffering=0)
+ kwargs: dict = {
+ "args": list(argv),
+ "cwd": os.fspath(as_user_path(cwd)),
+ "stdout": log_file,
+ "stderr": subprocess.STDOUT,
+ "stdin": subprocess.DEVNULL,
+ "shell": False,
+ "env": env,
+ }
+ if sys.platform == "win32":
+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
+ else:
+ kwargs["start_new_session"] = True
+ process = subprocess.Popen(**kwargs)
+ return process, log_file
+
+
+def terminate_process(process: subprocess.Popen) -> None:
+ """Stop only this plugin-owned process (and its process group on POSIX)."""
+ if process.poll() is not None:
+ return
+ if sys.platform == "win32":
+ process.terminate()
+ return
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except (ProcessLookupError, PermissionError, OSError):
+ try:
+ process.terminate()
+ except OSError:
+ pass
+
+
+def kill_process(process: subprocess.Popen) -> None:
+ if process.poll() is not None:
+ return
+ if sys.platform == "win32":
+ process.kill()
+ return
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError, OSError):
+ try:
+ process.kill()
+ except OSError:
+ pass
+
+
+def open_path(path: str | Path) -> None:
+ target = os.fspath(as_user_path(path))
+ if sys.platform == "win32":
+ os.startfile(target) # type: ignore[attr-defined]
+ elif sys.platform == "darwin":
+ subprocess.Popen(["open", target], shell=False)
+ else:
+ subprocess.Popen(["xdg-open", target], shell=False)
+
+
+def tail_text(path: str | Path, max_lines: int = 12, max_chars: int = 2400) -> str:
+ file_path = Path(path)
+ if not file_path.is_file():
+ return ""
+ try:
+ data = file_path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return ""
+ lines = data.splitlines()
+ text = "\n".join(lines[-max_lines:])
+ if len(text) > max_chars:
+ text = text[-max_chars:]
+ return text
+
+
+def interpret_doctor_output(exit_code: int | None, stdout: str) -> tuple[str, str]:
+ """Return `('READY'|'ERROR', short message)` from `m2mr doctor` output.
+
+ Missing default videos/images in `assets/` is not an error for the add-on:
+ the user picks files in the panel.
+ """
+ text = stdout or ""
+ low = text.lower()
+ if "no module named 'motion2mixamorig'" in low or "no module named motion2mixamorig" in low:
+ return "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 _doctor_line_missing(text, "SMPL-X") or _doctor_line_bad(text, "SMPL-X"):
+ blocking.append("err_smplx")
+ if blocking:
+ seen: list[str] = []
+ for item in blocking:
+ if item not in seen:
+ seen.append(item)
+ return "ERROR", "+".join(seen)
+
+ if exit_code not in (0, None):
+ if _doctor_line_missing(text, "input source") or _doctor_line_missing(text, "Mixamo rig"):
+ return "READY", "env_ready_choose"
+ code, _message = classify_log_text_safe(text)
+ from .errors import key_for_code
+
+ if code != "PIPELINE_FAILED":
+ return "ERROR", key_for_code(code)
+ return "ERROR", "env_check_failed"
+
+ return "READY", "env_ready"
+
+
+def classify_log_text_safe(text: str) -> tuple[str, str]:
+ from .errors import classify_log_text
+
+ return classify_log_text(text)
+
+
+def _doctor_line_missing(text: str, label: str) -> bool:
+ needle = label.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():
+ if "[invalid]" in line.lower() and needle in line.lower():
+ return True
+ return False
diff --git a/blender_extension/motion2mixamorig_blender/services/errors.py b/blender_extension/motion2mixamorig_blender/services/errors.py
new file mode 100644
index 0000000..49d197c
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/services/errors.py
@@ -0,0 +1,84 @@
+"""Turn process logs and exceptions into short UI messages."""
+
+from __future__ import annotations
+
+
+ERROR_MESSAGES = {
+ "PYTHON_NOT_FOUND": "External Python not found",
+ "PACKAGE_MISSING": "Motion2MixamoRig package not installed",
+ "SMPLX_MISSING": "SMPL-X model missing",
+ "INVALID_RIG": "Mixamo FBX invalid",
+ "MULTIPLE_PEOPLE": "Input contains multiple people",
+ "NO_PERSON": "No person was detected in the input",
+ "CUDA_UNAVAILABLE": "CUDA unavailable",
+ "MPS_UNAVAILABLE": "Apple MPS unavailable",
+ "PROCESS_EXITED": "Pipeline process exited unexpectedly",
+ "GLB_MISSING": "Result GLB not found",
+ "JSON_INVALID": "Result JSON is invalid",
+ "PREFLIGHT_FAILED": "Input check failed",
+ "PIPELINE_FAILED": "Motion2MixamoRig pipeline failed",
+}
+
+_CODE_TO_KEY = {
+ "PYTHON_NOT_FOUND": "err_python",
+ "PACKAGE_MISSING": "err_package",
+ "SMPLX_MISSING": "err_smplx",
+ "INVALID_RIG": "err_invalid_rig",
+ "MULTIPLE_PEOPLE": "err_multiple_people",
+ "NO_PERSON": "err_no_person",
+ "CUDA_UNAVAILABLE": "err_cuda",
+ "MPS_UNAVAILABLE": "err_mps",
+ "PROCESS_EXITED": "err_process_exited",
+ "GLB_MISSING": "err_glb",
+ "JSON_INVALID": "err_json",
+ "PREFLIGHT_FAILED": "err_preflight",
+ "PIPELINE_FAILED": "err_pipeline",
+}
+
+
+def key_for_code(code: str) -> str:
+ return _CODE_TO_KEY.get(code, "err_pipeline")
+
+
+def message_for_code(code: str, fallback: str = "") -> str:
+ return ERROR_MESSAGES.get(code, fallback or ERROR_MESSAGES["PIPELINE_FAILED"])
+
+
+def classify_log_text(text: str) -> tuple[str, str]:
+ """Guess an error code from captured stdout/stderr."""
+ low = (text or "").lower()
+ if not low.strip():
+ return "PROCESS_EXITED", message_for_code("PROCESS_EXITED")
+
+ if "no module named 'motion2mixamorig'" in low or "no module named motion2mixamorig" in low:
+ 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 "smplx" in low and (
+ "missing" in low or "not found" in low or "[missing]" in low or "filenotfound" in low
+ ):
+ return "SMPLX_MISSING", message_for_code("SMPLX_MISSING")
+ if "people in frame" in low or ("shows about" in low and "people" in low):
+ return "MULTIPLE_PEOPLE", message_for_code("MULTIPLE_PEOPLE")
+ if "no person was detected" in low:
+ return "NO_PERSON", message_for_code("NO_PERSON")
+ if "cuda" in low and (
+ "not available" in low
+ or "not compiled" in low
+ or "no cuda gpus" in low
+ or "cudaerror" in low
+ ):
+ return "CUDA_UNAVAILABLE", message_for_code("CUDA_UNAVAILABLE")
+ if "mps" in low and ("not available" in low or "not built" in low):
+ return "MPS_UNAVAILABLE", message_for_code("MPS_UNAVAILABLE")
+ if "is not a *binary* fbx" in low or "has no mixamo skeleton" in low:
+ return "INVALID_RIG", message_for_code("INVALID_RIG")
+ if "could not be parsed as an fbx" in low:
+ return "INVALID_RIG", message_for_code("INVALID_RIG")
+ if "result json is invalid" in low or "jsondecodeerror" in low:
+ return "JSON_INVALID", message_for_code("JSON_INVALID")
+ if "mixamo_character.glb" in low and ("not found" in low or "missing" in low):
+ return "GLB_MISSING", message_for_code("GLB_MISSING")
+ if "input check failed" in low or "problem(s) — nothing was run" in low:
+ return "PREFLIGHT_FAILED", message_for_code("PREFLIGHT_FAILED")
+ return "PIPELINE_FAILED", message_for_code("PIPELINE_FAILED")
diff --git a/blender_extension/motion2mixamorig_blender/services/job_monitor.py b/blender_extension/motion2mixamorig_blender/services/job_monitor.py
new file mode 100644
index 0000000..1b3e0af
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/services/job_monitor.py
@@ -0,0 +1,69 @@
+"""Parse progress JSONL written by `m2mr run --progress-jsonl`."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+
+@dataclass
+class ProgressEvent:
+ stage: str
+ progress: float
+ message: str
+ raw: dict[str, Any] = field(default_factory=dict)
+
+
+def clamp_progress(value: object) -> float:
+ try:
+ progress = float(value)
+ except (TypeError, ValueError):
+ return 0.0
+ if progress < 0.0:
+ return 0.0
+ if progress > 1.0:
+ return 1.0
+ return progress
+
+
+def parse_progress_jsonl(text: str) -> list[ProgressEvent]:
+ """Parse complete JSON objects; skip a truncated final line."""
+ events: list[ProgressEvent] = []
+ if not text:
+ return events
+ for line in text.splitlines():
+ stripped = line.strip()
+ if not stripped:
+ continue
+ try:
+ data = json.loads(stripped)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(data, dict):
+ continue
+ events.append(
+ ProgressEvent(
+ stage=str(data.get("stage", "")),
+ progress=clamp_progress(data.get("progress", 0.0)),
+ message=str(data.get("message", "")),
+ raw=data,
+ )
+ )
+ return events
+
+
+def read_progress_file(path: str | Path) -> list[ProgressEvent]:
+ file_path = Path(path)
+ if not file_path.is_file():
+ return []
+ try:
+ text = file_path.read_text(encoding="utf-8")
+ except OSError:
+ return []
+ return parse_progress_jsonl(text)
+
+
+def latest_progress(events: list[ProgressEvent]) -> ProgressEvent | None:
+ return events[-1] if events else None
diff --git a/blender_extension/motion2mixamorig_blender/services/result_reader.py b/blender_extension/motion2mixamorig_blender/services/result_reader.py
new file mode 100644
index 0000000..b9d0f39
--- /dev/null
+++ b/blender_extension/motion2mixamorig_blender/services/result_reader.py
@@ -0,0 +1,149 @@
+"""Read `run.json` and turn fps / frame counts into Blender-friendly values."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+
+@dataclass
+class RunResult:
+ status: str
+ run_dir: Path
+ fps: float | None = None
+ n_frames: int | None = None
+ glb_path: Path | None = None
+ error_code: str | None = None
+ message: str | None = None
+ stage: str | None = None
+ raw: dict[str, Any] = field(default_factory=dict)
+
+
+def resolve_run_path(run_dir: Path, value: object) -> Path | None:
+ if not value:
+ return None
+ path = Path(str(value))
+ if path.is_absolute():
+ return path
+ return run_dir / path
+
+
+def blender_frame_settings(fps: float, n_frames: int) -> dict[str, float | int]:
+ """Map a fractional fps onto Blender's integer `fps` + `fps_base`."""
+ rate = float(fps)
+ frames = max(1, int(n_frames))
+ if abs(rate - round(rate)) < 1e-6:
+ fps_int = max(1, int(round(rate)))
+ fps_base = 1.0
+ else:
+ fps_int = max(1, int(round(rate)))
+ fps_base = fps_int / rate if rate > 0 else 1.0
+ return {
+ "fps": fps_int,
+ "fps_base": float(fps_base),
+ "frame_start": 1,
+ "frame_end": frames,
+ }
+
+
+def read_run_json(run_dir: str | Path) -> RunResult:
+ directory = Path(run_dir)
+ path = directory / "run.json"
+ if not path.is_file():
+ return RunResult(
+ status="missing",
+ run_dir=directory,
+ error_code="JSON_INVALID",
+ message="Result JSON is invalid",
+ )
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return RunResult(
+ status="invalid",
+ run_dir=directory,
+ error_code="JSON_INVALID",
+ message="Result JSON is invalid",
+ )
+ if not isinstance(raw, dict):
+ return RunResult(
+ status="invalid",
+ run_dir=directory,
+ error_code="JSON_INVALID",
+ message="Result JSON is invalid",
+ )
+
+ outputs = raw.get("outputs") if isinstance(raw.get("outputs"), dict) else {}
+ glb = resolve_run_path(directory, outputs.get("mixamo_character_glb"))
+ fps = _as_float(raw.get("fps"))
+ n_frames = _as_int(raw.get("n_frames"))
+ status = str(raw.get("status") or "")
+ error_code = raw.get("error_code")
+ message = raw.get("message")
+ stage = raw.get("stage")
+
+ if status == "failed":
+ return RunResult(
+ status="failed",
+ run_dir=directory,
+ fps=fps,
+ n_frames=n_frames,
+ glb_path=glb if glb is not None and glb.is_file() else None,
+ error_code=str(error_code) if error_code else "PIPELINE_FAILED",
+ message=str(message) if message else "Motion2MixamoRig pipeline failed",
+ stage=str(stage) if stage else None,
+ raw=raw,
+ )
+
+ if status == "completed" or (glb is not None and glb.is_file()):
+ if glb is None or not glb.is_file():
+ return RunResult(
+ status="glb_missing",
+ run_dir=directory,
+ fps=fps,
+ n_frames=n_frames,
+ glb_path=None,
+ error_code="GLB_MISSING",
+ message="Result GLB not found",
+ stage=str(stage) if stage else None,
+ raw=raw,
+ )
+ return RunResult(
+ status="completed",
+ run_dir=directory,
+ fps=fps,
+ n_frames=n_frames,
+ glb_path=glb,
+ error_code=None,
+ message=None,
+ stage="done",
+ raw=raw,
+ )
+
+ return RunResult(
+ status=status or "unknown",
+ run_dir=directory,
+ fps=fps,
+ n_frames=n_frames,
+ glb_path=glb if glb is not None and glb.is_file() else None,
+ error_code=str(error_code) if error_code else None,
+ message=str(message) if message else None,
+ stage=str(stage) if stage else None,
+ raw=raw,
+ )
+
+
+def _as_float(value: object) -> float | None:
+ try:
+ return float(value) if value is not None else None
+ except (TypeError, ValueError):
+ return None
+
+
+def _as_int(value: object) -> int | None:
+ try:
+ return int(value) if value is not None else None
+ except (TypeError, ValueError):
+ return None
diff --git a/docs/blender-extension.md b/docs/blender-extension.md
new file mode 100644
index 0000000..2f5633b
--- /dev/null
+++ b/docs/blender-extension.md
@@ -0,0 +1,51 @@
+# Blender Extension (maintainer notes)
+
+User install and usage: [`blender_extension/README.md`](../blender_extension/README.md).
+
+This page is the smoke-test checklist and the v0.1 out-of-scope list.
+
+## Manual smoke-test checklist
+
+### macOS (Apple Silicon)
+
+1. Create `.venv`, install Motion2MixamoRig, place SMPL-X.
+2. `python scripts/package_blender_extension.py`
+3. Install the zip in Blender 4.2+ and enable the add-on.
+4. Confirm the **Motion2MixamoRig** tab in the 3D Viewport N-panel.
+5. Set External Python to `.venv/bin/python` and Project Directory to the repo.
+6. Quit Blender, reopen a different `.blend`, and confirm the two paths remain.
+7. **Check Environment** → Ready (or a clear Error).
+8. Pick a single-person still, a Mixamo FBX, Device **MPS** (or CPU).
+9. Generate with preview off. The UI must stay usable (orbit the viewport).
+10. Confirm stage/progress/log update, then auto-import of the GLB.
+11. Timeline start is 1; end matches `n_frames` in `run.json`; FPS matches.
+12. **Open Output Folder** and **View Full Log** work.
+13. Start a second job and click **Cancel**. Only that job should stop.
+14. Disable and re-enable the add-on without a crash.
+
+### Windows 10/11
+
+1. Same venv install; External Python is `.venv\Scripts\python.exe`.
+2. Install the zip; confirm the N-panel tab.
+3. Paths with spaces (`C:\Users\Jane Doe\...`) must work for Python, video, and FBX.
+4. **Check Environment**.
+5. Run a short single-person video on **CPU** first; try **CUDA** only if that
+ PyTorch build is installed.
+6. Blender must not freeze during Generate.
+7. Confirm auto-import, FPS, and frame range.
+8. **Open Output Folder** uses Explorer; **View Full Log** opens the log.
+9. Cancel a running job; no other `python.exe` processes should be killed.
+10. Uninstall the add-on and confirm `weights/` and `outputs/` are still there.
+
+## Future work
+
+Not in v0.1:
+
+- Automatic Python / PyTorch / GVHMR install
+- Automatic SMPL-X download
+- Bundling weights inside the extension
+- Cloud inference
+- Multi-person video
+- Writing `mixamo_rotations.npz` onto the current Armature
+- Foot lock, root-motion editor, curve cleanup, NLA tools
+- Publishing to the Blender Extensions Platform
diff --git a/motion2mixamorig/__main__.py b/motion2mixamorig/__main__.py
new file mode 100644
index 0000000..d52b8c8
--- /dev/null
+++ b/motion2mixamorig/__main__.py
@@ -0,0 +1,6 @@
+"""`python -m motion2mixamorig` and `python -m motion2mixamorig.cli` entry."""
+
+from .cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/motion2mixamorig/cli.py b/motion2mixamorig/cli.py
index 72ccd06..6426c85 100644
--- a/motion2mixamorig/cli.py
+++ b/motion2mixamorig/cli.py
@@ -16,6 +16,8 @@ import sys
from pathlib import Path
from . import checks, paths
+from .progress import ProgressWriter
+from .run_report import write_failed_report
OK = "[ok] "
MISS = "[missing]"
@@ -256,20 +258,52 @@ def preflight(args: argparse.Namespace) -> tuple[Path | None, Path, Path | None,
def run(args: argparse.Namespace) -> int:
- video, rig, skeleton, image = preflight(args)
+ progress = ProgressWriter(getattr(args, "progress_jsonl", None))
+ output_dir = Path(args.output_dir).resolve() if getattr(args, "output_dir", None) else None
+ if output_dir is not None:
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ progress.emit("preflight", 0.05, "Checking inputs")
+ try:
+ video, rig, skeleton, image = preflight(args)
+ except SystemExit as exc:
+ code = exc.code if isinstance(exc.code, int) else (0 if exc.code in (0, None) else 1)
+ if code != 0:
+ progress.emit("failed", 0.05, "Input check failed")
+ write_failed_report(
+ output_dir,
+ stage="preflight",
+ error_code="PREFLIGHT_FAILED",
+ message="Input check failed",
+ )
+ raise
+
print()
from .pipeline import run_pipeline
- run_dir = run_pipeline(
- video, rig, image=image, device=args.device, skeleton_npz=skeleton
- )
+ try:
+ run_dir = run_pipeline(
+ video,
+ rig,
+ image=image,
+ device=args.device,
+ skeleton_npz=skeleton,
+ output_dir=output_dir,
+ progress=progress,
+ no_preview=bool(getattr(args, "no_preview", False)),
+ )
+ except Exception:
+ import traceback
+
+ traceback.print_exc()
+ return 1
preview = "images" if image is not None else "videos"
print(f"\nresults: {run_dir / preview}")
return 0
-def main() -> None:
+def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="m2mr",
description=(
@@ -310,8 +344,29 @@ def main() -> None:
choices=["cpu", "cuda", "mps"],
help="inference device for the extraction step (default: cpu)",
)
+ p_run.add_argument(
+ "--output-dir",
+ help="write this run's files into PATH instead of a timestamped outputs/ folder",
+ )
+ p_run.add_argument(
+ "--progress-jsonl",
+ help="append machine-readable JSONL progress events to PATH",
+ )
+ p_run.add_argument(
+ "--no-preview",
+ action="store_true",
+ help="skip preview videos/images; still write NPZ, GLB, and run.json",
+ )
+ return parser
+
+def main() -> None:
+ parser = build_parser()
args = parser.parse_args()
if args.command == "doctor":
sys.exit(doctor())
sys.exit(run(args))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/motion2mixamorig/errors.py b/motion2mixamorig/errors.py
new file mode 100644
index 0000000..a2527b8
--- /dev/null
+++ b/motion2mixamorig/errors.py
@@ -0,0 +1,69 @@
+"""Map pipeline exceptions to a short code + one-line message.
+
+Tracebacks stay on stderr / the job log. JSONL and `run.json` only get the
+short message.
+"""
+
+from __future__ import annotations
+
+
+def classify_error(exc: BaseException) -> tuple[str, str]:
+ """Return `(error_code, human_message)` for a caught pipeline exception."""
+ text = str(exc).strip()
+ low = text.lower()
+ name = type(exc).__name__
+
+ if isinstance(exc, ModuleNotFoundError) or "no module named" in low:
+ return "PACKAGE_MISSING", "Motion2MixamoRig package not installed"
+
+ if isinstance(exc, FileNotFoundError):
+ if "smplx" in low or "smpl" in low:
+ return "SMPLX_MISSING", "SMPL-X model missing"
+ return "FILE_NOT_FOUND", _short_message(text) or "A required file was not found"
+
+ if _looks_like_cuda(low):
+ return "CUDA_UNAVAILABLE", "CUDA unavailable"
+
+ if "mps" in low and ("not available" in low or "not built" in low or "not supported" in low):
+ return "MPS_UNAVAILABLE", "Apple MPS unavailable"
+
+ if "people" in low and ("in frame" in low or "shows about" in low or "group" in low):
+ return "MULTIPLE_PEOPLE", "Input contains multiple people"
+
+ if "no person" in low:
+ return "NO_PERSON", "No person was detected in the input"
+
+ if "mixamo" in low or "fbx" in low:
+ return "INVALID_RIG", "Mixamo FBX invalid"
+
+ if "smplx" in low or "smpl-x" in low or "smpl_x" in low:
+ return "SMPLX_MISSING", "SMPL-X model missing"
+
+ if name == "ValueError" and "video or an image" in low:
+ return "INVALID_INPUT", "A video or image is required"
+
+ return "PIPELINE_FAILED", _short_message(text) or "Pipeline failed"
+
+
+def _looks_like_cuda(low: str) -> bool:
+ if "cuda" not in low:
+ return False
+ hints = (
+ "not available",
+ "not compiled",
+ "no kernel image",
+ "cudaerror",
+ "invalid device",
+ "out of memory",
+ "no cuda gpus",
+ )
+ return any(hint in low for hint in hints)
+
+
+def _short_message(text: str, limit: int = 160) -> str:
+ if not text:
+ return ""
+ first = text.splitlines()[0].strip()
+ if len(first) > limit:
+ return first[: limit - 1] + "…"
+ return first
diff --git a/motion2mixamorig/extract.py b/motion2mixamorig/extract.py
index 3351fdf..841d9f2 100644
--- a/motion2mixamorig/extract.py
+++ b/motion2mixamorig/extract.py
@@ -55,6 +55,138 @@ HOLD_FPS = 30.0
HOLD_MAX_SIDE = 1920
+def video_duration_seconds(path: Path) -> float | None:
+ """Wall-clock length of a clip. Prefers ffprobe; OpenCV is the fallback."""
+ import os
+ import subprocess
+
+ try:
+ completed = subprocess.run(
+ [
+ "ffprobe",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=duration:format=duration",
+ "-of",
+ "json",
+ os.fspath(path),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=8,
+ )
+ if completed.returncode == 0 and completed.stdout.strip():
+ import json
+
+ payload = json.loads(completed.stdout)
+ streams = payload.get("streams") or []
+ candidates = []
+ if streams and streams[0].get("duration"):
+ candidates.append(streams[0]["duration"])
+ fmt = payload.get("format") or {}
+ if fmt.get("duration"):
+ candidates.append(fmt["duration"])
+ for raw in candidates:
+ duration = float(raw)
+ if duration > 0:
+ return duration
+ except (OSError, subprocess.TimeoutExpired, ValueError):
+ pass
+ try:
+ import cv2
+
+ cap = cv2.VideoCapture(os.fspath(path))
+ try:
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 0)
+ count = float(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
+ finally:
+ cap.release()
+ if fps > 1e-6 and count > 0:
+ return count / fps
+ except Exception:
+ pass
+ return None
+
+
+def video_native_fps(path: Path) -> float | None:
+ """Container frame rate (e.g. 60000/1001). None if it cannot be read."""
+ import os
+ import subprocess
+
+ try:
+ completed = subprocess.run(
+ [
+ "ffprobe",
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=avg_frame_rate,r_frame_rate",
+ "-of",
+ "json",
+ os.fspath(path),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=8,
+ )
+ if completed.returncode == 0 and completed.stdout.strip():
+ import json
+
+ streams = json.loads(completed.stdout).get("streams") or []
+ if streams:
+ rate = streams[0].get("avg_frame_rate") or streams[0].get("r_frame_rate") or "0/1"
+ num, _, den = str(rate).partition("/")
+ fps = float(num) / float(den or 1)
+ if fps > 0:
+ return fps
+ except (OSError, subprocess.TimeoutExpired, ValueError, KeyError):
+ pass
+ try:
+ import cv2
+
+ cap = cv2.VideoCapture(os.fspath(path))
+ try:
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 0)
+ finally:
+ cap.release()
+ if fps > 1e-6:
+ return fps
+ except Exception:
+ pass
+ return None
+
+
+def playback_fps(video: Path, n_motion_frames: int, fallback: float = 30.0) -> float:
+ """FPS that plays `n_motion_frames` in the source clip's real duration.
+
+ GVHMR always reports 30 fps (the model rate). If staging fails to resample a
+ 60 fps source, keeping that 30 would stretch the clip to ~2× length.
+ """
+ n = max(1, int(n_motion_frames))
+ duration = video_duration_seconds(video)
+ native = video_native_fps(video)
+ if duration and duration > 1e-6:
+ implied_source_frames = native * duration if native else None
+ if (
+ implied_source_frames is not None
+ and abs(implied_source_frames - n) <= 2
+ and native
+ and native > 0
+ ):
+ return float(native)
+ return n / duration
+ if native and native > 0:
+ return float(native)
+ return float(fallback) if fallback > 0 else 30.0
+
+
def _to_numpy(x):
if hasattr(x, "detach"):
return x.detach().cpu().numpy()
@@ -266,14 +398,21 @@ def extract_motion(
joints_3d = joints_world_from_smplx(world, device=device)
root_translation = _to_numpy(world["transl"]).astype(np.float32)
root_orientation = _to_numpy(world["global_orient"]).astype(np.float32)
- timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(result.fps)
+ reported = float(getattr(result, "fps", 0) or 0)
+ fps = playback_fps(video, len(joints_3d), fallback=reported or HOLD_FPS)
+ if verbose and reported > 0 and abs(fps - reported) > 1.5:
+ print(
+ f"source is {fps:.3g} fps ({len(joints_3d)} frames); "
+ f"GVHMR reported {reported:g} fps — using the source rate so playback matches the video"
+ )
+ timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(fps)
output_npz = Path(output_npz)
output_npz.parent.mkdir(parents=True, exist_ok=True)
payload = dict(
joints_3d=joints_3d,
joint_names=np.array(SMPL_JOINT_NAMES),
- fps=np.float32(result.fps),
+ fps=np.float32(fps),
timestamps=timestamps,
root_translation=root_translation,
root_orientation=root_orientation,
diff --git a/motion2mixamorig/pipeline.py b/motion2mixamorig/pipeline.py
index a5669a5..09a5a86 100644
--- a/motion2mixamorig/pipeline.py
+++ b/motion2mixamorig/pipeline.py
@@ -13,7 +13,6 @@ Everything a run produces lands in its own timestamped folder:
from __future__ import annotations
-import json
import sys
import time
from datetime import datetime
@@ -22,6 +21,7 @@ from pathlib import Path
import numpy as np
from . import paths
+from .errors import classify_error
from .human_motion import HumanMotion, load_human_motion
from .mixamo.animation import build_animation
from .mixamo.gltf import write_glb
@@ -30,6 +30,8 @@ from .mixamo.retarget import verify_rest_fk
from .mixamo.skinned_mesh import load_character_asset, rest_skin_error
from .mixamo.tpose_calibration import load_calibration
from .mixamo.ybot_retarget import build_mapping
+from .progress import ProgressWriter
+from .run_report import write_failed_report, write_run_json
from .videos import render_run_images, render_run_videos
ROTATION_CONVENTION = (
@@ -74,12 +76,20 @@ def run_pipeline(
device: str = "cpu",
skeleton_npz: Path | None = None,
verbose: bool = True,
+ output_dir: Path | None = None,
+ progress: ProgressWriter | None = None,
+ progress_jsonl: Path | None = None,
+ no_preview: bool = False,
) -> Path:
"""Full pipeline for one video or still + one rig. Returns the run directory.
`skeleton_npz` reuses a previous run's skeleton_motion.npz and skips the
(slow) extraction entirely. A still is turned into a short hold clip so
the same GVHMR path can recover a static 3D pose.
+
+ `output_dir` writes this run into a caller-chosen folder (used by the
+ Blender extension). When omitted, a timestamped directory is created.
+ `no_preview` still writes the NPZ/GLB products but skips rendered previews.
"""
if image is None and video is None:
raise ValueError("run_pipeline needs a video or an image")
@@ -92,109 +102,139 @@ def run_pipeline(
t0 = time.time()
source = image if image is not None else video
assert source is not None
- run_dir = paths.new_run_dir(source, started)
+ if output_dir is not None:
+ run_dir = Path(output_dir).resolve()
+ run_dir.mkdir(parents=True, exist_ok=True)
+ else:
+ run_dir = paths.new_run_dir(source, started)
print(f"run directory {run_dir}")
- extract_video = video
- motion_npz = run_dir / "skeleton_motion.npz"
- if skeleton_npz is not None:
- import shutil
-
- shutil.copy2(skeleton_npz, motion_npz)
- print(f"reusing skeleton from {skeleton_npz}")
- elif image is not None:
- from .extract import extract_motion, temp_hold_video
-
- print(f"extracting human pose from {image.name}")
- with temp_hold_video(image) as hold:
+ writer = progress if progress is not None else ProgressWriter(progress_jsonl)
+ stage = "extract"
+ try:
+ writer.emit("extract", 0.15, "Extracting human motion")
+ extract_video = video
+ motion_npz = run_dir / "skeleton_motion.npz"
+ if skeleton_npz is not None:
+ import shutil
+
+ shutil.copy2(skeleton_npz, motion_npz)
+ print(f"reusing skeleton from {skeleton_npz}")
+ elif image is not None:
+ from .extract import extract_motion, temp_hold_video
+
+ print(f"extracting human pose from {image.name}")
+ with temp_hold_video(image) as hold:
+ extract_motion(
+ hold,
+ motion_npz,
+ work_dir=run_dir / "cache",
+ device=device,
+ verbose=verbose,
+ source_image=image,
+ )
+ else:
+ from .extract import extract_motion
+
+ assert extract_video is not None
+ print(f"extracting human motion from {extract_video.name}")
extract_motion(
- hold,
+ extract_video,
motion_npz,
work_dir=run_dir / "cache",
device=device,
verbose=verbose,
- source_image=image,
)
- else:
- from .extract import extract_motion
-
- assert extract_video is not None
- print(f"extracting human motion from {extract_video.name}")
- extract_motion(
- extract_video,
- motion_npz,
- work_dir=run_dir / "cache",
- device=device,
- verbose=verbose,
- )
- motion: HumanMotion = load_human_motion(motion_npz)
- print(f"human motion {motion.n_frames} frames @ {motion.fps:g} fps")
-
- print(f"calibrating rig {rig.name}")
- calibration = load_calibration(rig)
- rest_err = verify_rest_fk(calibration.skeleton_rig)
- mapping = build_mapping(calibration, verbose=verbose)
- asset = load_character_asset(rig, textures=True)
- skin_err = rest_skin_error(asset)
- if verbose:
- print(f"rest FK error {rest_err:.3e} rest skin error {skin_err:.3e} cm")
-
- print("retargeting")
- frames = list(range(motion.n_frames))
- anim = build_animation(motion, mapping, frames, verbose=verbose)
-
- rotations_npz = run_dir / "mixamo_rotations.npz"
- save_mixamo_rotations(anim, mapping, rig, rotations_npz)
- print(f"saved {rotations_npz}")
-
- glb_path = run_dir / "mixamo_character.glb"
- write_glb(glb_path, asset, anim.r_anim_rig, anim.hips_cm_rig, anim.fps)
- print(f"saved {glb_path}")
-
- if image is not None:
- print("rendering result images")
- previews = render_run_images(
- anim, asset, calibration, image, run_dir / "images", verbose=verbose
- )
- preview_key = "images"
- preview_dir = "images"
- else:
- print("rendering result videos")
- assert extract_video is not None
- previews = render_run_videos(
- anim,
- asset,
- calibration,
- extract_video,
- run_dir / "videos",
- original_label="Original Video",
- verbose=verbose,
- )
- preview_key = "videos"
- preview_dir = "videos"
-
- report = {
- "started": started.isoformat(timespec="seconds"),
- "elapsed_s": round(time.time() - t0, 1),
- "command": sys.argv,
- "video": None if image is not None else str(video),
- "image": str(image) if image is not None else None,
- "rig": str(rig),
- "device": device,
- "fps": float(motion.fps),
- "n_frames": motion.n_frames,
- "skeleton_reused_from": str(skeleton_npz) if skeleton_npz else None,
- "rest_fk_error": rest_err,
- "rest_skin_error_cm": skin_err,
- "twist_events": len(anim.twist_events),
- "quat_sign_flips": len(anim.sign_events),
- "outputs": {
+ motion: HumanMotion = load_human_motion(motion_npz)
+ print(f"human motion {motion.n_frames} frames @ {motion.fps:g} fps")
+
+ stage = "retarget"
+ writer.emit("retarget", 0.70, "Retargeting animation")
+ print(f"calibrating rig {rig.name}")
+ calibration = load_calibration(rig)
+ rest_err = verify_rest_fk(calibration.skeleton_rig)
+ mapping = build_mapping(calibration, verbose=verbose)
+ asset = load_character_asset(rig, textures=True)
+ skin_err = rest_skin_error(asset)
+ if verbose:
+ print(f"rest FK error {rest_err:.3e} rest skin error {skin_err:.3e} cm")
+
+ print("retargeting")
+ frames = list(range(motion.n_frames))
+ anim = build_animation(motion, mapping, frames, verbose=verbose)
+
+ rotations_npz = run_dir / "mixamo_rotations.npz"
+ save_mixamo_rotations(anim, mapping, rig, rotations_npz)
+ print(f"saved {rotations_npz}")
+
+ stage = "export"
+ writer.emit("export", 0.85, "Writing GLB")
+ glb_path = run_dir / "mixamo_character.glb"
+ write_glb(glb_path, asset, anim.r_anim_rig, anim.hips_cm_rig, anim.fps)
+ print(f"saved {glb_path}")
+
+ outputs = {
"skeleton_motion": motion_npz.name,
"mixamo_rotations": rotations_npz.name,
"mixamo_character_glb": glb_path.name,
- preview_key: {k: f"{preview_dir}/{v.name}" for k, v in previews.items()},
- },
- }
- (run_dir / "run.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
- print(f"done in {report['elapsed_s']}s -> {run_dir}")
- return run_dir
+ }
+ if not no_preview:
+ stage = "preview"
+ writer.emit("preview", 0.90, "Rendering previews")
+ if image is not None:
+ print("rendering result images")
+ previews = render_run_images(
+ anim, asset, calibration, image, run_dir / "images", verbose=verbose
+ )
+ outputs["images"] = {k: f"images/{v.name}" for k, v in previews.items()}
+ else:
+ print("rendering result videos")
+ assert extract_video is not None
+ previews = render_run_videos(
+ anim,
+ asset,
+ calibration,
+ extract_video,
+ run_dir / "videos",
+ original_label="Original Video",
+ verbose=verbose,
+ )
+ outputs["videos"] = {k: f"videos/{v.name}" for k, v in previews.items()}
+
+ report = {
+ "status": "completed",
+ "started": started.isoformat(timespec="seconds"),
+ "elapsed_s": round(time.time() - t0, 1),
+ "command": sys.argv,
+ "video": None if image is not None else str(video),
+ "image": str(image) if image is not None else None,
+ "rig": str(rig),
+ "device": device,
+ "fps": float(motion.fps),
+ "n_frames": motion.n_frames,
+ "skeleton_reused_from": str(skeleton_npz) if skeleton_npz else None,
+ "rest_fk_error": rest_err,
+ "rest_skin_error_cm": skin_err,
+ "twist_events": len(anim.twist_events),
+ "quat_sign_flips": len(anim.sign_events),
+ "outputs": outputs,
+ }
+ write_run_json(run_dir, report)
+ writer.emit("done", 1.0, "Completed")
+ print(f"done in {report['elapsed_s']}s -> {run_dir}")
+ return run_dir
+ except Exception as exc:
+ error_code, message = classify_error(exc)
+ write_failed_report(run_dir, stage=stage, error_code=error_code, message=message)
+ writer.emit("failed", _failed_progress(stage), message)
+ raise
+
+
+def _failed_progress(stage: str) -> float:
+ return {
+ "preflight": 0.05,
+ "extract": 0.15,
+ "retarget": 0.70,
+ "export": 0.85,
+ "preview": 0.90,
+ }.get(stage, 0.0)
diff --git a/motion2mixamorig/progress.py b/motion2mixamorig/progress.py
new file mode 100644
index 0000000..365bd03
--- /dev/null
+++ b/motion2mixamorig/progress.py
@@ -0,0 +1,52 @@
+"""Machine-readable progress events for `m2mr run` and the Blender extension."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+
+class ProgressWriter:
+ """Append one JSON object per line and flush immediately.
+
+ `path=None` is a no-op so the CLI stays quiet when `--progress-jsonl` is
+ omitted. Creating a writer truncates an existing file so each run starts
+ clean.
+ """
+
+ def __init__(self, path: str | Path | None = None) -> None:
+ self.path = Path(path) if path else None
+ if self.path is not None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.write_text("", encoding="utf-8")
+
+ def emit(self, stage: str, progress: float, message: str) -> dict:
+ event = {
+ "stage": str(stage),
+ "progress": _clamp_progress(progress),
+ "message": str(message),
+ }
+ if self.path is None:
+ return event
+ line = json.dumps(event, ensure_ascii=False)
+ with self.path.open("a", encoding="utf-8") as fh:
+ fh.write(line + "\n")
+ fh.flush()
+ try:
+ os.fsync(fh.fileno())
+ except OSError:
+ pass
+ return event
+
+
+def _clamp_progress(value: object) -> float:
+ try:
+ progress = float(value)
+ except (TypeError, ValueError):
+ return 0.0
+ if progress < 0.0:
+ return 0.0
+ if progress > 1.0:
+ return 1.0
+ return progress
diff --git a/motion2mixamorig/run_report.py b/motion2mixamorig/run_report.py
new file mode 100644
index 0000000..cf50366
--- /dev/null
+++ b/motion2mixamorig/run_report.py
@@ -0,0 +1,52 @@
+"""Write and merge `run.json` for a single pipeline run."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+
+def write_run_json(run_dir: Path, report: dict[str, Any]) -> Path:
+ run_dir = Path(run_dir)
+ run_dir.mkdir(parents=True, exist_ok=True)
+ path = run_dir / "run.json"
+ path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ return path
+
+
+def write_failed_report(
+ run_dir: Path | None,
+ *,
+ stage: str,
+ error_code: str,
+ message: str,
+ extra: dict[str, Any] | None = None,
+) -> Path | None:
+ """Write a failed `run.json`. Keeps any earlier fields already on disk."""
+ if run_dir is None:
+ return None
+ run_dir = Path(run_dir)
+ run_dir.mkdir(parents=True, exist_ok=True)
+ report: dict[str, Any] = {}
+ existing = run_dir / "run.json"
+ if existing.is_file():
+ try:
+ loaded = json.loads(existing.read_text(encoding="utf-8"))
+ if isinstance(loaded, dict):
+ report.update(loaded)
+ except (OSError, json.JSONDecodeError):
+ pass
+ report.update(
+ {
+ "status": "failed",
+ "stage": stage,
+ "error_code": error_code,
+ "message": message,
+ }
+ )
+ if extra:
+ for key, value in extra.items():
+ if key not in {"status", "stage", "error_code", "message"}:
+ report[key] = value
+ return write_run_json(run_dir, report)
diff --git a/scripts/package_blender_extension.py b/scripts/package_blender_extension.py
new file mode 100644
index 0000000..da423bc
--- /dev/null
+++ b/scripts/package_blender_extension.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Build dist/motion2mixamorig-0.1.0.zip for Blender 4.2+.
+
+The zip root contains blender_manifest.toml and __init__.py directly — no
+extra wrapping folder.
+"""
+
+from __future__ import annotations
+
+import argparse
+import shutil
+import sys
+import zipfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SRC = ROOT / "blender_extension" / "motion2mixamorig_blender"
+DIST = ROOT / "dist"
+REQUIRED_MANIFEST_FIELDS = (
+ "schema_version",
+ "id",
+ "version",
+ "name",
+ "tagline",
+ "maintainer",
+ "type",
+ "blender_version_min",
+ "license",
+)
+SKIP_NAMES = {".DS_Store", ".gitkeep"}
+
+
+def read_manifest(path: Path) -> dict[str, str]:
+ values: dict[str, str] = {}
+ for raw in path.read_text(encoding="utf-8").splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or line.startswith("["):
+ continue
+ if "=" not in line:
+ continue
+ key, value = line.split("=", 1)
+ values[key.strip()] = value.strip().strip('"')
+ return values
+
+
+def extension_version(src: Path = SRC) -> str:
+ manifest = read_manifest(src / "blender_manifest.toml")
+ return manifest.get("version", "0.1.0")
+
+
+def should_include(path: Path) -> bool:
+ if path.name in SKIP_NAMES or path.suffix == ".pyc":
+ return False
+ return not any(part == "__pycache__" for part in path.parts)
+
+
+def iter_source_files(src: Path) -> list[Path]:
+ return sorted(p for p in src.rglob("*") if p.is_file() and should_include(p))
+
+
+def build_zip(src: Path = SRC, dest: Path | None = None) -> Path:
+ if not (src / "blender_manifest.toml").is_file() or not (src / "__init__.py").is_file():
+ raise FileNotFoundError(f"extension sources are incomplete: {src}")
+ version = extension_version(src)
+ dest = dest or (DIST / f"motion2mixamorig-{version}.zip")
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if dest.exists():
+ dest.unlink()
+ with zipfile.ZipFile(dest, "w", compression=zipfile.ZIP_DEFLATED) as archive:
+ for path in iter_source_files(src):
+ archive.write(path, path.relative_to(src).as_posix())
+ errors = validate_zip(dest)
+ if errors:
+ raise RuntimeError("invalid extension zip:\n" + "\n".join(errors))
+ return dest
+
+
+def validate_zip(zip_path: Path) -> list[str]:
+ errors: list[str] = []
+ if not zip_path.is_file():
+ return [f"zip does not exist: {zip_path}"]
+ with zipfile.ZipFile(zip_path) as archive:
+ names = archive.namelist()
+ if "blender_manifest.toml" not in names:
+ errors.append("zip root is missing blender_manifest.toml")
+ if "__init__.py" not in names:
+ errors.append("zip root is missing __init__.py")
+ if any(name.startswith("motion2mixamorig_blender/") for name in names):
+ errors.append("zip has an extra wrapping directory")
+ if any(name.startswith("blender_extension/") for name in names):
+ errors.append("zip includes the repository blender_extension/ prefix")
+ top_dirs = {name.split("/", 1)[0] for name in names if "/" in name}
+ if "blender_manifest.toml" in names and "motion2mixamorig_blender" in top_dirs:
+ errors.append("zip root is nested under motion2mixamorig_blender/")
+ try:
+ with zipfile.ZipFile(zip_path) as archive:
+ manifest_text = archive.read("blender_manifest.toml").decode("utf-8")
+ except KeyError:
+ return errors
+ for field in REQUIRED_MANIFEST_FIELDS:
+ if f"{field} =" not in manifest_text and f"{field}=" not in manifest_text:
+ errors.append(f"manifest is missing {field}")
+ if 'id = "motion2mixamorig"' not in manifest_text:
+ errors.append("manifest id must be motion2mixamorig")
+ return errors
+
+
+def maybe_blender_validate(zip_path: Path) -> str | None:
+ blender = shutil.which("blender")
+ candidates = [
+ Path(blender) if blender else None,
+ Path("/Applications/Blender.app/Contents/MacOS/Blender"),
+ Path(r"C:\Program Files\Blender Foundation\Blender 4.2\blender.exe"),
+ Path(r"C:\Program Files\Blender Foundation\Blender 5.2\blender.exe"),
+ ]
+ binary = next((path for path in candidates if path is not None and path.is_file()), None)
+ if binary is None:
+ return None
+ import subprocess
+
+ completed = subprocess.run(
+ [str(binary), "--command", "extension", "validate", str(zip_path)],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ output = (completed.stdout or "") + (completed.stderr or "")
+ if completed.returncode != 0:
+ raise RuntimeError(f"blender extension validate failed:\n{output}")
+ return output.strip() or "blender extension validate: ok"
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, default=None, help="zip path")
+ args = parser.parse_args(argv)
+ dest = build_zip(dest=args.output)
+ print(f"wrote {dest}")
+ try:
+ message = maybe_blender_validate(dest)
+ except RuntimeError as exc:
+ print(exc, file=sys.stderr)
+ return 1
+ if message:
+ print(message)
+ else:
+ print("Blender CLI not found; zip structure and manifest were checked locally.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())