[SIGGRAPH Asia 2026] UniMate: One Unified Model to Animate Diverse Skeletons
Python
Add annotation QA tooling and dataset statistics; rewrite pipeline README
Friedrich-Mb2869acb7171
diff --git a/data_process/README.md b/data_process/README.mdindex 8341d55..bd7c996 100644--- a/data_process/README.md+++ b/data_process/README.md@@ -2,7 +2,7 @@The pipeline that turns raw rigged assets (Truebones FBX, Mixamo FBX, Objaverse GLB) into **UniML3D** — the text-paired, topology-annotated motion clips used to train UniMate.-All commands are run **from the repository root**.+**How to read this document.** All commands are run **from the repository root**. Each stage lists the commands you need first; the collapsible **Details / Advanced / Reference** blocks hold the knobs, mechanics, and field tables. Every wrapper also prints its own usage with `-h`.## Table of Contents@@ -12,7 +12,15 @@ All commands are run **from the repository root**.- [Getting the Raw Data](#getting-the-raw-data)- [Quick Start](#quick-start)- [Pipeline Stages](#pipeline-stages)+ - [Stage 1 — Export](#stage-1--export-raw-assets--npz)+ - [Stage 2a — Render](#stage-2a--render-multi-view-frames--t-pose-grids)+ - [Stage 2b — Caption](#stage-2b--caption-renders--text)+ - [Stage 3 — Joint annotation](#stage-3--joint-annotation-name-cleanup--facing-direction)+ - [Stage 4 — Extract](#stage-4--extract-npz--metadata--training-clips)+ - [Stage 5 — Animate](#stage-5--animate-drive-a-mesh-with-a-motion)+- [Custom Assets](#custom-assets)- [Data Formats](#data-formats)+- [Tools](#tools)- [Conventions](#conventions)- [Troubleshooting](#troubleshooting)@@ -68,17 +76,17 @@ flowchart LR| Stage | Wrapper(s) | Input | Output ||-------|-----------|-------|--------|| 0. Download | `run_download.sh` | Hugging Face Hub | `dataset/raw/<dataset>/` |-| 1. Export | `run_export.sh`, `run_export_general.sh` | raw FBX / GLB | `export/<dataset>/{motions/*.npz, videos/*.mp4, tpose/*.png, joint_names.json}` |-| 2a. Render | `run_render_motion.sh`, `run_render_tpose.sh` | raw FBX / GLB (mixamo: animated characters) | `render/<dataset>/<clip>/v00{0..3}/*.png`, `render/<dataset>_tpose/<name>.png` |+| 1. Export | `run_export.sh`, `run_export_general.sh` | raw FBX / GLB | `export/<dataset>/{motions/*.npz, videos/*.mp4, tpose/*.png}` + summary JSONs |+| 2a. Render | `run_render_motion.sh`, `run_render_tpose.sh` | raw FBX / GLB (mixamo: animated characters) | `render/<dataset>/<clip>/v00{0..3}/`, `render/<dataset>_tpose/<name>.png` || 2b. Caption | `run_caption_motion.sh`, `run_caption_category.sh` | multi-view renders | `motion_captions.json`, `category_groups.json` || 3. Joints | `run_joints_*.sh` | `joint_names.json` | `clean_joint_names.json`, `face_joint_names.json` || 4. Extract | `run_extract_features.sh` | export NPZs + stage-2/3 JSONs | per-clip NPZs, `cond.npy`, `captions.json` || 5. Animate | `run_animate_{motion,npz,fbx,mixamo,lbs}.sh`, `run_preprocess_char.sh` | motion clip + rigged mesh | animated `.glb` / `.fbx` |-Stage 4 reads the caption and joint-annotation JSONs from the export directory, so stages 2 and 3 must run first.+Stages 1 and 2a both read the raw assets and can run in either order or in parallel. Stage 3 needs stage 1's `joint_names.json`, stage 2b needs stage 2a's renders, and stage 4 needs all three.> [!NOTE]-> **Mixamo runs stage 5 in the middle of the pipeline.** Raw Mixamo FBXs are animation-only (armature without mesh), so the render/caption input is produced by `run_animate_mixamo.sh`: export → animate a character → render → caption. The result also ships in the mixamo repo as `animation_motion_ybot/`, so this step can be skipped by downloading it.+> **Mixamo runs stage 5 in the middle of the pipeline.** Raw Mixamo FBXs are animation-only (armature without mesh), so the render/caption input has to be produced first by `run_animate_mixamo.sh`: export → animate a character → render → caption. The result also ships in the Mixamo repo as `animation_motion_ybot/`, so this step can be skipped by downloading it.## Requirements@@ -88,14 +96,16 @@ The pipeline uses the shared `unimate` conda environment — see [Environment Se|------|---------|| [Blender](https://www.blender.org/) on `PATH` | stages 1 & 5 (headless `blender -b -P`) || pip [`bpy`](https://pypi.org/project/bpy/) module (in the conda env) | stage 2a (EEVEE needs the module's GPU context) |-| `ffmpeg` on `PATH` | video visualizations |-| [`hf` CLI](https://hf.co/cli) | stage 0 |-| CUDA GPU | stages 2a & 2b |-| `OPENAI_API_KEY` / `GOOGLE_API_KEY` / `DEEPSEEK_API_KEY` | stage 2b (OpenAI / Gemini captioning) and stage 3 (OpenAI / DeepSeek joint annotation) API backends |+| `ffmpeg` | video previews — bundled by `imageio-ffmpeg` from `requirements.txt`; no system install needed |+| [`hf` CLI](https://hf.co/cli) | stage 0 — installed with the env's `huggingface_hub` |+| CUDA GPU | stages 2a & 2b (and stage 3 when a local LLM is used) |+| `OPENAI_API_KEY` / `GOOGLE_API_KEY` / `DEEPSEEK_API_KEY` | stage 2b (OpenAI / Gemini captioning) and stage 3 (DeepSeek / OpenAI joint annotation) API backends |++The two Blender surfaces are independent. Stages 1 and 5 run under a standalone Blender's bundled interpreter (`blender -b -P script.py -- args`) — developed against Blender 3.2. Stage 2a runs under the `bpy` wheel installed into the conda env, pinned to `bpy==4.0.0` in `requirements.txt`: it is the last release built for Python 3.10, and 4.2+ changes the EEVEE API the render helpers use.## Directory Layout-Code — one directory per stage, bash wrappers in `scripts/`, shared code in `utils/`:+Code — one directory per stage, bash wrappers in `scripts/`, shared library code in `utils/`:```data_process/@@ -107,7 +117,7 @@ data_process/├── feature_extraction/ Stage 4 NPZ + metadata → canonical training clips + cond.npy├── mesh_animation/ Stage 5 motion clip + rigged mesh → animated GLB/FBX (Blender);│ single-asset preprocessing + manual NumPy FK/LBS-├── tools/ Standalone utilities (summary merging, FBX→GLB, QA visualizers)+├── tools/ Standalone utilities (summary merging, QA patch/visualizers, FBX→GLB)└── utils/ Shared library code (no entry points)```@@ -121,18 +131,18 @@ dataset/render/<dataset>_tpose/ T-pose 2x2 grids (category input)dataset/features/<dataset>/ stage-4 training clips + cond.npy```-`<dataset>` is one of `truebones`, `mixamo`, `objaverse`.+`<dataset>` is one of `truebones`, `mixamo`, `objaverse`. For the full file-by-file contents of an export directory, see [Reference — files in `dataset/export/<dataset>/`](#data-formats).++<details>+<summary><b>Details —</b> why <code>dataset/render/</code> is a set of symlinks</summary>-Both `dataset/render/` paths are symlinks into the dataset's own Hub mirror, so renders sit-beside the assets they came from and upload with them — `truebones` →-`raw/truebones/{animation_render,species_tpose}`, `mixamo` →-`raw/mixamo/{animation_motion_render,character_tpose}`, `objaverse` →-`raw/objaverse_renders/{glb_render,tpose}`. Objaverse keeps its renders in a separate repo-because there are 10,355 clip folders.+Both `dataset/render/` paths are symlinks into the dataset's own Hub mirror, so renders sit beside the assets they came from and upload with them — `truebones` → `raw/truebones/{animation_render,species_tpose}`, `mixamo` → `raw/mixamo/{animation_motion_render,character_tpose}`, `objaverse` → `raw/objaverse_renders/{glb_render,tpose}`. Objaverse keeps its renders in a separate repo because there are 10,355 clip folders.++</details>## Getting the Raw Data-The source assets are hosted on the Hugging Face Hub and download straight into the layout above:+The source assets are hosted on the Hugging Face Hub (collected under [UniMate](https://huggingface.co/collections/Linzhan/unimate)) and download straight into the layout above:```bashbash data_process/scripts/run_download.sh mixamo # → dataset/raw/mixamo/{animation_motion,character_refined,...}@@ -146,26 +156,33 @@ bash data_process/scripts/run_download.sh objaverse_renders # → dataset/raw/| `mixamo` | [Linzhan/Mixamo-Animations-Characters](https://huggingface.co/datasets/Linzhan/Mixamo-Animations-Characters) || `objaverse` | [Linzhan/Objaverse-XL-Rigged-Animated](https://huggingface.co/datasets/Linzhan/Objaverse-XL-Rigged-Animated) || `truebones` | [Linzhan/Truebones-ZOO-Annotations](https://huggingface.co/datasets/Linzhan/Truebones-ZOO-Annotations) (prompts, metadata, renders, build scripts — no motion files) |-| `objaverse_renders` | [Linzhan/Objaverse-XL-Rigged-Animated-Renders](https://huggingface.co/datasets/Linzhan/Objaverse-XL-Rigged-Animated-Renders) (four-view clip MP4s + T-pose grids; download-only companion, not needed to run the pipeline) |+| `objaverse_renders` | [Linzhan/Objaverse-XL-Rigged-Animated-Renders](https://huggingface.co/datasets/Linzhan/Objaverse-XL-Rigged-Animated-Renders) (four-view clip MP4s + T-pose grids; download-only companion, not a pipeline dataset name) |-The mixamo and truebones repos also carry the stage-2a multi-view renders as per-view MP4 previews plus camera JSONs (`animation_motion_render/`, `animation_render/` — see each repo's README). The per-frame PNGs the caption stage reads are not hosted; stage 2a regenerates them (or extract stills from the MP4s).+The Mixamo and Truebones repos also carry the stage-2a multi-view renders as per-view MP4 previews plus camera JSONs (`animation_motion_render/`, `animation_render/` — see each repo's README). The per-frame PNGs the caption stage reads are not hosted; stage 2a regenerates them (or extract stills from the MP4s).> [!IMPORTANT]-> **The Truebones motion files are not downloadable from us.** The Truebones ZOO animal pack is a commercial product whose license does not allow redistribution, so its repo above ships annotations only. To reproduce the truebones part of the pipeline, purchase the pack from [Truebones](https://truebones.com), unpack it to `dataset/raw/truebones/Truebone_Z-OO/{Animal}/`, and run the downloaded `scripts/pipeline/` (see the repo's README) to rebuild the per-clip layout — one binary FBX per clip, flat in a single directory:->-> ```-> dataset/raw/truebones/animation/{Species}-{Action}.fbx # e.g. Alligator-Big_Mouth.fbx-> ```->-> (Species names must not contain `-` — the first dash separates species from action.)->-> Stage 5 additionally needs the **original per-animal layout** for the character meshes, since the flat per-clip files above are the animation source only:->-> ```-> dataset/raw/truebones/Truebone_Z-OO/{Animal}/*.fbx # e.g. Truebone_Z-OO/Dog-2/-> ```->-> Directory names are matched ignoring separators and case, so the clip-name object type `Dog2` resolves to the `Dog-2` directory.+> **The Truebones motion files are not downloadable from us.** The Truebones ZOO animal pack is a commercial product whose license does not allow redistribution, so its repo ships annotations only. Purchase the pack from [Truebones](https://truebones.com) and rebuild the per-clip layout as described below.++<details>+<summary><b>Details —</b> rebuilding the Truebones layout from a purchased copy</summary>++Unpack the pack to `dataset/raw/truebones/Truebone_Z-OO/{Animal}/` and run the downloaded `scripts/pipeline/` (see the repo's README) to rebuild the per-clip layout — one binary FBX per clip, flat in a single directory:++```+dataset/raw/truebones/animation/{Species}-{Action}.fbx # e.g. Alligator-Big_Mouth.fbx+```++Species names must not contain `-` — the first dash separates species from action.++Stage 5 additionally needs the **original per-animal layout** for the character meshes, since the flat per-clip files above are the animation source only:++```+dataset/raw/truebones/Truebone_Z-OO/{Animal}/*.fbx # e.g. Truebone_Z-OO/Dog-2/+```++Directory names are matched ignoring separators and case, so the clip-name object type `Dog2` resolves to the `Dog-2` directory.++</details>## Quick Start@@ -182,7 +199,7 @@ bash data_process/scripts/run_export.sh objaverse --multi-worker 8bash data_process/scripts/run_render_motion.sh objaverse --multi-worker 8bash data_process/scripts/run_render_tpose.sh objaverse-# 2b. Caption motions + classify body plans (local Qwen3-VL by default)+# 2b. Caption motions + classify body plans (local Qwen3.5-9B by default)bash data_process/scripts/run_caption_motion.sh objaverse --multi-gpubash data_process/scripts/run_caption_category.sh objaverse@@ -194,7 +211,7 @@ bash data_process/scripts/run_joints_face_select_llm.sh objaversebash data_process/scripts/run_extract_features.sh objaverse```-Every stage is resumable — rerunning a wrapper skips already-complete outputs.+Every stage is resumable — rerunning a wrapper skips already-complete outputs and retries only what failed.## Pipeline Stages@@ -206,19 +223,34 @@ bash data_process/scripts/run_export.sh mixamo # animationbash data_process/scripts/run_export.sh objaverse # GLB/GLTFbash data_process/scripts/run_export.sh objaverse --multi-worker 8 # parallel workers (mixamo too)bash data_process/scripts/run_export.sh mixamo --no-vis # skip per-clip MP4 previews (much faster)-DATA_DIR=my_assets bash data_process/scripts/run_export.sh # auto mode: .glb/.gltf and .fbx side by side```-Skeletons are pruned of control/helper bones that carry no skin weight and converted to Y-up. Mixamo needs its explicit preset: animation-only FBXs carry no mesh, so auto mode cannot detect them. For custom assets there is a general exporter (single file or a directory of mixed GLB/GLTF/FBX):+Skeletons are pruned of control/helper bones that carry no skin weight and converted to Y-up. Mixamo needs its explicit preset: animation-only FBXs carry no mesh, so auto mode cannot detect them. No joint-count filtering happens here — stage 4 decides which skeletons enter training, so the exports stay complete.-```bash-bash data_process/scripts/run_export_general.sh my_model.glb-bash data_process/scripts/run_export_general.sh my_assets/ --multi-worker 8-```+For assets outside the three datasets, use `run_export_general.sh` — see [Custom Assets](#custom-assets).++<details>+<summary><b>Details —</b> outputs, parallel workers, and resume markers</summary>++Each export directory receives:++| Path | Content |+|------|---------|+| `motions/{clip}.npz` | one NPZ per clip (see [Data Formats](#data-formats)) |+| `videos/{clip}.mp4`, `tpose/{name}.png` | skeleton preview per clip and rest-pose still per asset (skip with `--no-vis`) |+| `joint_names.json` | `{asset: [pruned bone names]}` — the input of stage 3 |+| `joint_count.json`, `clip_frames.json`, `summary.json` | joints per skeleton, frames per clip, dataset-level summary (plotted by `tools/vis_joint_count.py` / `tools/vis_clip_frames.py`) |+| `.completed/{asset}.json` | per-asset completion markers; delete one to force a re-export |++`--multi-worker N` shards a *directory* input over N Blender processes (objaverse, mixamo, auto mode). Each worker writes its own `*_worker{i}.json` summary shards, and the wrapper merges them into the canonical files afterwards with `tools/merge_summaries.py`. Truebones is exported by a single-process exporter and ignores `--multi-worker` (with a warning).++Skeleton pruning is joint across all of an asset's clips, so an asset only completes atomically — the marker is written once every clip of that asset is on disk (including assets that legitimately yield no clips, recorded as `status="skipped"`). Markers also carry the pruned joint names, which is what makes `joint_names.json` rebuildable from disk after an interrupted run.++</details>### Stage 2a — Render: multi-view frames & T-pose grids-Renders each motion from four fixed views (front / back / left / right) with EEVEE, plus a T-pose 2x2 grid per asset for body-plan classification:+Renders each motion with EEVEE from four cameras 90° apart at a fixed elevation (`v000`–`v003`, nominally front / back / left / right in the asset's own frame), plus a T-pose 2x2 grid per asset for body-plan classification. The captioner treats the four as unlabeled azimuths — the real front is only established by the stage-3 facing annotation.```bashbash data_process/scripts/run_render_motion.sh truebones@@ -228,47 +260,175 @@ bash data_process/scripts/run_render_tpose.sh objaverseDATA_DIR=outputs/mixamo_characters bash data_process/scripts/run_render_motion.sh mixamo```-Render folders use the same clip naming as stage 1, so they line up with the exported NPZs. Rendering is capped at the first 200 frames per clip (~6.7 s at 30 fps) — enough context for captioning without paying for full-length renders.+Each clip becomes `<clip>/v00{0..3}/*.png` (the per-frame PNGs the caption stage reads) plus a composed `<clip>/v00{0..3}.mp4` per view (`--no-video` to skip). Render folders use the same clip naming as stage 1, so they line up with the exported NPZs. Stage 2a runs with plain `python` and the pip `bpy` module rather than `blender -b`, because EEVEE needs the module's GPU context.++<details>+<summary><b>Details —</b> frame cap, fps consistency, render settings, multi-GPU</summary>++- **Frame cap.** Rendering stops at the first 200 frames per clip (`MAX_RENDER_FRAMES`, ~6.7 s at 30 fps) — enough context for captioning without paying for full-length renders. Clips shorter than `MIN_ACTION_FRAMES` (default 5) are skipped.+- **`--fps` must match stage 1.** glTF stores keyframe times in seconds, so the importer resamples them at the scene frame rate; a mismatch makes the renders cover a different time window than the NPZs. Default 30 in both stages.+- **Quality knobs.** `RESOLUTION` (512), `SAMPLES` (64), `CAMERA_DIST` (1.5) are environment overrides on both wrappers.+- **Resume.** Rerunning re-renders only what is missing. `--missing-only` (objaverse renderer only) additionally skips whole GLBs whose every action is already complete, which avoids re-importing them.+- **Multi-GPU.** `--multi-worker N` shards assets over N processes; with `NUM_GPUS>1` the workers are spread round-robin over the visible GPUs. The `CUDA_VISIBLE_DEVICES` pinning does **not** bind EEVEE's EGL context, so on a shared multi-GPU machine every worker still renders on the first GPU — give each render job a cgroup / scheduler allocation that exposes exactly one GPU instead.-`--fps` (default 30) must match the export stage's `--fps`: glTF stores keyframe times in seconds, so the importer resamples them at the scene frame rate, and a mismatch makes the renders cover a different time window than the NPZs.+</details>### Stage 2b — Caption: renders → text-One wrapper; the backend is picked from `MODEL`:+Two independent passes over the stage-2a output: per-clip motion captions, and one body-plan category per skeleton.```bash-bash data_process/scripts/run_caption_motion.sh truebones # local Qwen3-VL (default)+# motion captions — the backend is picked from MODEL+bash data_process/scripts/run_caption_motion.sh truebones # local Qwen3.5-9B (default)bash data_process/scripts/run_caption_motion.sh objaverse --multi-gpu # shard across all visible GPUs-MODEL=gemini-3-flash-preview bash data_process/scripts/run_caption_motion.sh objaverse # Gemini (GOOGLE_API_KEY)-MODEL=gpt-5-mini bash data_process/scripts/run_caption_motion.sh mixamo # OpenAI (OPENAI_API_KEY)-bash data_process/scripts/run_caption_category.sh objaverse # body-plan classification+MODEL=Qwen/Qwen3.8-27B bash data_process/scripts/run_caption_motion.sh objaverse # local 27B (one 80 GB GPU)+MODEL=gemini-3-flash-preview bash data_process/scripts/run_caption_motion.sh objaverse # Gemini (GOOGLE_API_KEY)+MODEL=gpt-5-mini bash data_process/scripts/run_caption_motion.sh mixamo # OpenAI (OPENAI_API_KEY)++# body-plan categories (single GPU, local model)+bash data_process/scripts/run_caption_category.sh objaverse+```++Both write into the export directory next to the stage-1 output:++| File | Content |+|------|---------|+| `motion_captions.json` | `{clip: caption}` — one short caption per clip |+| `motion_captions_failed.txt` | clips that failed or whose renders were incomplete; retried on the next run |+| `category_groups.json` | `{category: [assets]}` over `bipedal`, `quadrupedal`, `insectoid`, `avian`, `marine`, `serpentine`, `articulated_rigid`, plus an `uncertain` bucket |+| `category_groups_review.json` | per asset: votes, confidence and the evidence the model cited |+| `category_groups_errors.json` | assets whose retries were exhausted; retried on the next run |++Clips whose renders are incomplete are recorded as failures rather than captioned from a partial set. Mixamo is a single shared humanoid rig, so its wrapper writes `category_groups.json` directly instead of classifying.++<details>+<summary><b>Details —</b> caption backends, parallelism, and model inputs</summary>++- **Backend selection.** A `MODEL` containing `qwen` runs locally through HuggingFace transformers; `gemini*` uses the Gemini API; anything else is treated as an OpenAI-compatible model (`BASE_URL` points it at a proxy). The local default is `Qwen/Qwen3.5-9B`; `MODEL=Qwen/Qwen3.8-27B` selects the 27B model (same architecture and settings, about 56 GB in bf16, so one 80 GB GPU) and `MODEL=Qwen/Qwen3-VL-8B-Instruct` the older Qwen3-VL.+- **Parallelism.** `--multi-gpu` applies to the local backend only: one process per visible GPU writes a shard file, and the wrapper merges the shards into `motion_captions.json` when all of them succeed. API backends scale with `NUM_WORKERS` concurrent requests instead.+- **What the model sees.** The local backend receives each clip's four camera views as native video at the render frame rate (`--vision_input video`, the default). API backends receive frame sequences, uniformly sampled down to `--max_frames_per_view` with the first and last frame always kept.+- **Reference hints.** For mixamo and truebones the official catalogue prompts (`animation_motion_prompts.json` / `animation_prompts.json`) are attached as frame-grounded hints automatically; `HINTS_JSON` overrides the file, `HINTS_JSON=""` disables hints.++</details>++<details>+<summary><b>Details —</b> body-plan classification</summary>++Per asset, `vlm_caption/classify_category.py` shows the model four kinds of evidence: the four T-pose views from `dataset/render/<dataset>_tpose/`; the first frame of one clip from the same four cameras (a rest pose can lie flat on the ground, so the natural stance matters); skeleton facts derived from the export directory (joint count, grounded limb chains, cleaned-label histogram, body extents); and up to `--max_captions` of the asset's motion captions.++It answers with a small JSON object carrying evidence fields, a category and a confidence. `VOTES` (default 3) sampled answers are majority-voted; a tie, a low-confidence majority or the model's own `uncertain` verdict lands in the `uncertain` bucket for review instead of being silently mis-filed. Unparseable answers (`unknown`) are always re-attempted on the next run; `--retry_uncertain` also re-attempts the uncertain bucket.++Hand corrections belong in the patch directory as `<dataset>_categories.json` (applied by `tools/patch_annotations.py`). `tools/eval_category_groups.py` scores a run against `vlm_caption/eval/truebones_category_truth.json`, or diffs two runs against each other.++</details>++<details>+<summary><b>Advanced —</b> rewriting captions that name props</summary>++Nothing but the body is rendered, yet a catalogue hint such as *Rifle Run Left* can leak a prop or scenery word into a caption. `caption_rewrite_llm.py` finds those captions with a word list, asks a text LLM to rewrite each into body-only wording (`aims a rifle` → `extends one arm forward as if aiming`), validates the answer (no prop word, subject preserved, one short sentence) and writes a patch JSON that `tools/patch_annotations.py` applies after review — nothing is modified in place:++```bash+python data_process/vlm_caption/caption_rewrite_llm.py \+ --captions dataset/export/<dataset>/motion_captions.json \+ --output <patch_dir>/<dataset>_captions.json```-`--multi-gpu` applies to the local Qwen backend only; API backends scale via `NUM_WORKERS`. The local backend feeds each clip's four camera views as **native video** at the render frame rate (all frames, `--vision_input video`, the default); API backends receive frame sequences instead, capped by `--max_frames_per_view` (default 64, uniformly sampled including the first and last frame). For mixamo and truebones the official catalogue prompts (`animation_motion_prompts.json` / `animation_prompts.json`) are attached as reference hints automatically (`HINTS_JSON` overrides, `HINTS_JSON=""` disables). Clips whose renders are incomplete are recorded as failures and retried later rather than captioned from a partial set.+</details>### Stage 3 — Joint annotation: name cleanup & facing direction-Two `<task>_<step>` trios — joint-name cleaning (`names_*`) and facing-direction pair selection (`face_*`) — each with a rule-based and an LLM variant. The LLM variants default to `deepseek-v4-flash` (also `gpt-*` or a local HF model id via `MODEL=`) and fall back to the rules on failure.+Two tasks, each with a rule-based and an LLM variant: joint-name cleaning (`names_*`) maps raw bone names onto a canonical anatomical vocabulary, and facing-direction selection (`face_*`) picks the bilateral joint pair — or head/tail body axis, for serpentine rigs — that defines each rig's heading. The LLM variants default to `deepseek-v4-flash` (`MODEL=` switches to any `gpt-*` model or a local HF model id) and fall back to the rules on failure.-**Required** — these two produce the artifacts stage 4 consumes (`clean_joint_names.json`, `face_joint_names.json`):+**Required** — these two produce the artifacts stage 4 consumes:```bash-bash data_process/scripts/run_joints_names_clean_llm.sh objaverse # LLM names (falls back to rules)-bash data_process/scripts/run_joints_face_select_llm.sh objaverse # LLM facing pair+bash data_process/scripts/run_joints_names_clean_llm.sh objaverse # → clean_joint_names.json+bash data_process/scripts/run_joints_face_select_llm.sh objaverse # → face_joint_names.json```-**Optional** — refinement passes over the files above. Skip them entirely on a clean LLM run; reach for them when the required passes recorded failures (`failed_*.txt`) or when spot checks reveal residual label / pairing errors:+Rigs that fell back to the rules are listed in `failed_clean_names.txt` / `failed_face_joints.txt` next to the outputs, so a refinement pass can be restricted to them.++<details>+<summary><b>Advanced —</b> optional refinement passes</summary>++Skip these on a clean LLM run; reach for them when the required passes recorded failures or when spot checks reveal residual label / pairing errors:```bashbash data_process/scripts/run_joints_names_correct_llm.sh objaverse # re-check every label, correct in placebash data_process/scripts/run_joints_face_correct_llm.sh objaverse # retry rigs whose facing pair came back "empty"```-`names_correct_llm` sends each `{raw, current}` label pair back to the LLM to keep or fix (most useful for rigs that fell back to the rules — restrict with `FAILED_LIST=.../failed_clean_names.txt`; long rigs are chunked with the full rig attached as read-only context). `face_correct_llm` re-attempts only `source == "empty"` entries by default; pass `--force_reattempt` to also retry the rule-fallback rigs recorded in `failed_face_joints.txt` — the correction pass re-derives from scratch (no rule hint, higher reasoning budget) and only a clean non-empty LLM win replaces an existing entry. Both edit in place and create a `.bak` sibling on first run.+`names_correct_llm` sends each `{raw, current}` label pair back to the LLM to keep or fix — most useful for rigs that fell back to the rules (restrict with `FAILED_LIST=.../failed_clean_names.txt`; long rigs are chunked with the full rig attached as read-only context). `face_correct_llm` re-attempts only `source == "empty"` entries by default, with a correction prompt, no rule hint, and a larger reasoning budget; pass `--force_reattempt` to also retry the rule-fallback rigs in `failed_face_joints.txt`. Only a clean non-empty LLM answer replaces an existing entry. Both edit in place, create a `.bak` sibling on first run, and list rigs they still could not fix in `still_*` text files.++Both cleaners write the same `clean_joint_names.json`, so the LLM pass skips rigs the rule-based pass already filled in; pass `--overwrite` to redo everything or `--redo_failed` to redo only the rigs listed in `failed_clean_names.txt`.++</details>++<details>+<summary><b>Advanced —</b> rule-based variants and QA visualizers</summary>++Pure rule-based variants exist as `run_joints_names_clean_rule.sh` / `run_joints_face_select_rule.sh` (no API needed — useful offline or as a fast first pass; the LLM variants use them as hint and fallback).++Three visualizers check a facing pair by eye:++```bash+bash data_process/scripts/run_joints_vis_tpose.sh <dataset> # annotated T-pose PNG per skeleton+bash data_process/scripts/run_joints_vis_facing.sh <dataset> # rest pose vs. canonicalized pose+python -m data_process.tools.vis_motion <motion.npz> --direction face --face-joints I J+```++- `run_joints_vis_tpose.sh` renders one PNG per unique skeleton with every joint labeled, into `<export_dir>/face_joints_vis/` (`LIMIT=N` to stop early).+- `run_joints_vis_facing.sh` runs the stage-4 canonicalization on every rest pose and saves a side-by-side `[original rest pose with the pair marked (r red, l blue) and its forward arrow | the same pose corrected by the pair, facing +Z]` per skeleton under `outputs/tpose_facing_vis/<dataset>/`, plus a `facing_summary.tsv` flagging `COINCIDENT` pairs (both joints on the midline in the rest pose and at frame 0 — pick another pair), `REST-DEGENERATE` rest poses (the pair is lateral at frame 0 but not in the rest pose: the exported rest pose lies on its side, so the stage-4 T-pose facing is unreliable) and `UNRESOLVED` names. `FACE_JSON=<patch_dir>/<ds>_face_pairs.json` previews a patch before applying it.+- `vis_motion.py` renders an MP4 of an exported clip with the heading arrow the pair implies.++</details>++<details>+<summary><b>Details —</b> QA patch (<code>tools/patch_annotations.py</code>, run last)</summary>++```bash+python data_process/tools/patch_annotations.py [--dry_run] [--datasets truebones mixamo] [--report_dir DIR]+```++Applies the corrections found in a manual audit of the stage-2/3 outputs, so they are reproducible on a fresh run and recorded in one place. Rerun it after regenerating any stage-2/3 output.++**Rule fixes**, built into the script:++| Fix | Effect |+|-----|--------|+| Pelvis unification | unsided `Pelvis` / `Hip` → `Hips` (one label for the root pelvis bone; `Left Hip` / `Right Hip` untouched) |+| Numeric labels | pass-through labels (`_2`, `_1045`) → `Bone` |+| Arthropod chains | numbered leg / claw-arm chains get anatomical positions (Thigh, Shin, Foot, Toe … / Upper Arm, Forearm, Hand, Claw) instead of `Leg` repeated along the chain |+| Duplicate sides | rigs whose second side is a Blender/Maya duplicate (`LeftUpLeg.001`, `Leg_L1`, …) get side prefixes from the rest-pose X coordinate |+| Face resync | the `clean` fields of `face_joint_names.json` are re-synced against the labels |+| Captions | grammar and subject fixes, plus locomotion qualifiers grounded in the root trajectory (`walks forward` with no root travel → `walks in place`; `runs in place` with clear travel along the facing axis → `runs forward\|backward`) |++**Hand overrides** are read from `--patch_dir` (default `dataset/UniML3D/patches/`) as `<dataset>_{joint_labels,face_pairs,captions,categories}.json`. Missing files are skipped, so the rule fixes apply on their own.++**Skip lists** the patch writes into the export directory for stage 4:-Pure rule-based variants exist as `run_joints_names_clean_rule.sh` / `run_joints_face_select_rule.sh` (no API needed — useful offline or as a fast first pass). The QA visualizers behind this stage live in `data_process/tools/`: `run_joints_vis_tpose.sh` renders annotated T-pose PNGs (`tools/vis_tpose.py`), and to sanity-check a picked pair on an actual clip, `python -m data_process.tools.vis_motion <motion.npz> --direction face --face-joints I J` renders an MP4 with the implied heading arrow.+| Output | Scope | Source |+|--------|-------|--------|+| `export/<ds>/filtered_clips.txt` | individual clips, any dataset | `<ds>_filtered_clips.txt` in the patch dir |+| `export/objaverse/filtered_objects.txt` | whole rigs, objaverse only | the `tpose_wrong` entries of `objaverse_rig_flags.txt` |+| `export/objaverse/rig_flags.json` | informational | automatic facing checks + hand review |-Both cleaners default to the same `clean_joint_names.json`, so the LLM pass skips rigs the rule-based pass already filled in; pass `--overwrite` to redo everything or `--redo_failed` to redo only the rigs listed in `failed_clean_names.txt`.+Objaverse rig flags, and whether stage 4 acts on them:++| Flag | Meaning | Filtered out |+|------|---------|--------------|+| `tpose_wrong` | the exported rest pose lies flat / is rotated / upside-down | **yes** |+| `empty_pair` | no bilateral pair could be found | no |+| `bone_pair` | the pair is two unnamed `Bone` joints | no |+| `body_axis_unnamed` | the body axis runs through unnamed bones | no |+| `facing_wrong` | the pair does not give the real front | no |+| `object_no_front` | a prop with no meaningful front | no |++Everything except `tpose_wrong` is informational — those rigs are kept and trained with the facing they have. The per-rig evidence (rest-pose metrics, mesh T-pose grids and corrected-skeleton panels, all checked by eye) lives under `export/objaverse/tpose_abnormal_vis/`: one `[mesh rest-pose grid | rest pose with pair | corrected T-pose]` PNG per flagged rig, grouped by category, plus a TSV.++Truebones uses `filtered_clips.txt` for the three clips whose rig disagrees with their object's reference skeleton (`Monkey-B01_Die` has 79 joints against the object's 85; `KingCobra-Run` and `KingCobra-Walk_Fast` carry the hood joints `BN__Neck_{L,R}_01` mirrored across Z relative to the `KingCobra-Attack` T-pose); objaverse uses it for the motion-discontinuity review.++</details>### Stage 4 — Extract: NPZ + metadata → training clips@@ -282,13 +442,61 @@ APPLY_CLIP=1 bash data_process/scripts/run_extract_features.sh truebonesNUM_WORKERS=8 NO_VIS=1 bash data_process/scripts/run_extract_features.sh objaverse```-Mixamo is reduced to a built-in **22-joint humanoid core** (finger chains and End bones dropped) via `--mixamo_core_joints` (default on); pass `--no-mixamo_core_joints` to keep the full 65-joint rig. Truebones and objaverse always use the full skeleton.+Every object type is canonicalized against its T-pose (facing → XZ-centering → diameter scaling → grounding), static pre/post-roll is trimmed, low-activity and motion-discontinuous clips are filtered, and the per-object topology condition is written to `cond.npy`. Output goes to `dataset/features/<dataset>/`: `motions/{object}-{motion}-{clip_idx}.npz`, `videos/`, `tpose/`, plus `cond.npy`, `captions.json`, `category_groups.json`, `filtered_clips.json`, and a `metadata.txt` report.++<details>+<summary><b>Details —</b> filters and thresholds</summary>++| Setting | Default | Effect |+|---------|---------|--------|+| `--min_joints` / `--max_joints` | 8 / 150 (objaverse: 4 / 180 via the wrapper) | object types outside the range are skipped — this, not stage 1, decides which skeletons enter training |+| `--max_clip_len` | 200 | frames kept per motion; without `APPLY_CLIP` only the first 200 frames survive |+| `APPLY_CLIP=1` (`--apply_clip`) | off | crop long motions into overlapping windows of `max_clip_len` frames with stride `max_clip_len − diffusion_max_len` (200 − 90 = 110), so every training crop of up to `--diffusion_max_len` frames fits inside some saved clip |+| `--activity_threshold` | 0.02 | minimum joint activity (temporal spread at canonical scale) for a clip to be kept |+| `--jump_step_threshold` | 0.20 | discontinuity filter: a clip is dropped when one frame moves the skeleton at least this many body lengths **and** the step is at least `--jump_ratio_threshold` times the clip's median (a sequence stitched from several actions, or a teleporting root); `0` disables it |+| `--jump_ratio_threshold` | 8.0 | max/median per-frame joint displacement required alongside `--jump_step_threshold` |+| `--static_threshold` | 1e-5 | per-frame max-joint displacement below which a frame counts as static; leading / trailing static frames are trimmed |+| `--min_frames` | 8 | minimum frame count after trimming |+| `--target_diameter` | 2.0 | leaf-to-leaf skeleton diameter every object type is scaled to |+| `--max_freqs` / `--max_path_len` | 8 / 5 | Laplacian eigenvectors per joint and the clamp on topology distances in `cond.npy` |++Clips dropped at runtime and skipped object types are recorded in `filtered_clips.json`; `metadata.txt` reports the dataset totals (clips, frames, duration, max joints, captions), clips and joints per object type, filtered counts and the category breakdown.++</details>++<details>+<summary><b>Details —</b> optional skip lists and pass-through metadata</summary>++Two hand-reviewed skip lists are read from the export directory before any processing, both **optional** — when the file is absent the run simply proceeds on everything:++| List | Scope | Flag | Written by |+|------|-------|------|-----------|+| `filtered_clips.txt` | individual clips; every dataset (applied before clips are grouped into object types) | `--filtered_clips` | `tools/patch_annotations.py` |+| `filtered_objects.txt` | whole rigs; objaverse only | `--filtered_objects` | `tools/patch_annotations.py` |++Both flags take a path, `"auto"` (the default — look in the data dir) or an empty string to disable; a path that does not exist is warned about and skipped, so a stale override never aborts a run.++`--category_groups` follows the same convention for `category_groups.json`, which this stage only copies through to the feature dir. Pass an empty string while the stage-2 classifier is still running, so a partial file is not written out as if it were complete, then copy the finished file in by hand — nothing else in this stage reads it.-Every object type is canonicalized against its T-pose (facing → XZ-centering → diameter scaling → grounding), static pre/post-roll is trimmed, low-activity clips are filtered, and the per-object topology condition is written to `cond.npy`. Finished object types are cached under `cond_parts/`, so interrupted runs resume where they stopped; the cache is keyed on the clip/threshold settings **and** on digests of the caption / joint-annotation inputs, so changing any of them (including a stage-2/3 rerun) re-processes the affected object types instead of silently mixing old and new results.+</details>-Per-clip preview MP4s use a ground-plane view — checkerboard stage, smoothly following camera and root trajectory (`--vis_ground`, default on; `--no-vis_ground` renders the plain cubic view instead).+<details>+<summary><b>Details —</b> Mixamo core joints, grounding, and previews</summary>-Each motion is grounded on its own lowest joint by default; pass `--use_tpos_ground_height` to reuse the T-pose's ground height for every clip instead. Either way `cond['ground_height']` and `cond['ground_height_mode']` record what was actually applied. Object types that fail are logged to `extract_errors.log` and skipped rather than aborting the run, and are retried on the next run.+- **Mixamo** is reduced to a built-in **22-joint humanoid core** (finger chains and End bones dropped) via `--mixamo_core_joints` (default on); pass `--no-mixamo_core_joints` to keep the full 65-joint rig. Truebones and objaverse always use the full skeleton.+- **Grounding.** Each motion is grounded on its own lowest joint by default; `--use_tpos_ground_height` reuses the T-pose's ground height for every clip of the object type instead. Either way `cond['ground_height']` and `cond['ground_height_mode']` record what was applied.+- **Previews.** Per-clip MP4s use a ground-plane view — an unbounded checkerboard floor that fades out toward the horizon, a following camera, a contact shadow under the skeleton and a fading root trajectory (`--vis_ground`, default on; `--no-vis_ground` renders the plain cubic view). `NO_VIS=1` skips them entirely.++</details>++<details>+<summary><b>Details —</b> resume cache and error handling</summary>++Finished object types are cached under `cond_parts/`, so interrupted runs resume where they stopped. The cache is keyed on the clip / threshold / topology settings, on digests of the caption and joint-annotation inputs, **and** on the object's source clip list, so changing any of them (a stage-2/3 rerun, a new QA patch, a clip added to the export or newly listed in `filtered_clips.txt`) re-processes the affected object types instead of silently mixing old and new results. Re-processing an object first deletes the clip NPZs a previous run wrote for it — the training loader enumerates `motions/` rather than `captions.json`, so a dropped clip's file would otherwise still be trained on; previews are only pruned when the run regenerates them (`--vis`), so a later `--no-vis` run keeps the MP4s an earlier one made. Delete `cond_parts/` (or one entry) to force re-processing for any other reason.++Object types that fail are appended to `extract_errors.log`, recorded in `filtered_clips.json`, and skipped without a cache entry, so they are retried on the next run — one bad object never aborts the run.++</details>### Stage 5 — Animate: drive a mesh with a motion@@ -301,6 +509,13 @@ bash data_process/scripts/run_animate_fbx.sh #bash data_process/scripts/run_animate_mixamo.sh # batch over Mixamo export NPZs (Y Bot)```+`run_animate_motion.sh` accepts both the stage-4 feature NPZ and the `.npy` motion features written by the model's sampler. The character is auto-resolved for truebones / objaverse from the raw asset directories; mixamo needs `CHAR_PATH`.++<details>+<summary><b>Details —</b> character resolution and extra bones</summary>++For mixamo the character defaults to `character_refined/Y_Bot.fbx` — the rig the animation FBXs are authored on (identical 65-bone skeleton, so no bone reconciliation is needed); `CHAR_PATH` selects a different character. Armature bones absent from the motion are handled by `--extra_bones_strategy`: `merge` (default) transfers their vertex weights to the nearest kept ancestor and removes them, `remove` deletes the bones and their vertices, `keep` leaves them un-keyed.+`run_animate_fbx.sh` needs no export stage at all: it bakes a raw animation clip — or a whole directory of them — onto any character that shares the clips' bone names (the Mixamo convention), e.g. the full library on a different character:```bash@@ -308,11 +523,34 @@ CHAR_PATH=dataset/raw/mixamo/character_refined/Amy.fbx \bash data_process/scripts/run_animate_fbx.sh # → outputs/animated_Amy/*.fbx```-The character is auto-resolved for truebones / objaverse. For mixamo it defaults to `character_refined/Y_Bot.fbx` — the character whose skeleton the animation FBXs are authored on (identical 65-bone rig, so no bone reconciliation is needed); override with `CHAR_PATH` to use a different character. Armature bones absent from the motion are handled by `--extra_bones_strategy` (`merge` weights into the nearest kept ancestor, `remove` bones and their vertices, or `keep` them un-keyed).+</details>++## Custom Assets++Nothing in the pipeline is tied to the three datasets. There are three entry points for your own rigged assets, in increasing order of integration.++**1 · Export only** — turn assets into stage-1 NPZs. A single file or a directory of mixed GLB/GLTF/FBX; mesh optional (armature-only FBX works), every pose action becomes a clip. Directory runs support the same `--multi-worker` / marker / summary-shard machinery as the Objaverse exporter.++```bash+bash data_process/scripts/run_export_general.sh my_model.glb+bash data_process/scripts/run_export_general.sh my_assets/ --multi-worker 8 # → dataset/export/custom+DATA_DIR=my_assets bash data_process/scripts/run_export.sh # same thing via the dataset wrapper's auto mode+```++The general exporter uses the same `{asset}-{action}.npz` clip naming as the Objaverse layout, so the later stages run over a custom export by borrowing `objaverse` as the layout name and overriding the paths:-#### Standalone assets: preprocess once, animate cond-free+```bash+EXPORT=dataset/export/custom+INPUT=$EXPORT/joint_names.json OUTPUT=$EXPORT/clean_joint_names.json \+ bash data_process/scripts/run_joints_names_clean_llm.sh objaverse+INPUT_DIR=$EXPORT bash data_process/scripts/run_joints_face_select_llm.sh objaverse+DATA_DIR=$EXPORT SAVE_DIR=dataset/features/custom \+ bash data_process/scripts/run_extract_features.sh objaverse+```++The dataset argument selects the layout and the per-dataset defaults, not the data — every wrapper validates it against `truebones | mixamo | objaverse`, and each documents the environment variables that redirect its input and output.-For a single user-provided rigged asset, `run_preprocess_char.sh` runs the export + extraction stages in-process and bakes the result into a self-contained canonical asset:+**2 · Preprocess one asset for inference** — `run_preprocess_char.sh` runs the real export and extraction stages in-process on a single rigged, animated asset and bakes the result into a self-contained canonical asset:```bashCHAR_PATH=asset.glb OUTPUT_DIR=outputs/asset \@@ -320,20 +558,23 @@ CHAR_PATH=asset.glb OUTPUT_DIR=outputs/asset \bash data_process/scripts/run_preprocess_char.sh```-This leaves exactly three deliverables: `<name>_canonical.{glb,fbx}` (rest-pose asset rebuilt to the canonical T-pose — no animation, canonical joint order stored as a custom property), `cond.npy` (the model-side topology conditioning), and `motions/<clip>.npz` (one motion-feature NPZ per action). Assets **without** any action fall back to a rest-only cond (full skeleton — the export stage's motion-driven pruning needs animations — and no `motions/`).+It leaves exactly three deliverables: `<name>_canonical.{glb,fbx}` (the rest-pose asset rebuilt to the canonical T-pose — no animation, canonical joint order stored as a custom property), `cond.npy` (the model-side topology conditioning), and `motions/<clip>.npz` (one motion-feature NPZ per action). `FACE_R` / `FACE_L` name the asset's facing pair (`BODY_AXIS=1` for a head/tail axis on serpentine rigs). An asset **without** any action falls back to a rest-only cond — the export stage's motion-driven pruning needs animations — and writes no `motions/`.-A feature-format motion NPZ — generated by the model or extracted above — then drives the canonical asset directly, with no `cond.npy` or export NPZ at animate time:+**3 · Animate the canonical asset** — a feature-format motion NPZ (generated by the model, or extracted above) then drives it directly, with no `cond.npy` or export NPZ at animate time:```bashCHAR_PATH=outputs/asset/<name>_canonical.glb ANIM_PATH=<motion.npz-or-directory> \bash data_process/scripts/run_animate_lbs.sh # one animated GLB per action```-`animate_lbs` computes FK and Linear Blend Skinning manually in NumPy (Blender only parses the asset; the math is numerically identical to Blender's armature modifier) and exports the animated rigged GLB/FBX through the same path as `animate_npz`; `SAVE=npz,obj` additionally dumps raw deformed vertex sequences / per-frame OBJs. It also accepts stage-1 export NPZs and, with `DATASET_TYPE`/`COND_PATH`, cond-resolved feature NPZs on non-preprocessed assets.+`animate_lbs` computes FK and Linear Blend Skinning manually in NumPy (Blender only parses the asset; the math is numerically identical to Blender's armature modifier) and exports the animated rigged GLB/FBX through the same path as `animate_npz`; `SAVE=npz,obj` additionally dumps raw deformed vertex sequences / per-frame OBJs. It also accepts stage-1 export NPZs and, with `DATASET_TYPE` / `COND_PATH`, cond-resolved feature NPZs on non-preprocessed assets.## Data Formats-**Stage-1 export NPZ** (`dataset/export/<dataset>/motions/*.npz`) — one file per clip:+Three artifacts matter downstream: the **stage-1 export NPZ** (raw per-clip skeleton animation), the **stage-4 feature NPZ** (canonicalized per-clip arrays the training loader reads), and **`cond.npy`** (one topology-conditioning dict per object type).++<details>+<summary><b>Reference —</b> stage-1 export NPZ (<code>dataset/export/<dataset>/motions/*.npz</code>)</summary>| Field | Shape | Description ||-------|-------|-------------|@@ -345,31 +586,118 @@ CHAR_PATH=outputs/asset/<name>_canonical.glb ANIM_PATH=<motion.npz-or-directory>| `skin_matrix` | `(V, J)` | skinning weights (empty when no mesh) || `fps`, `action_name` | scalar | frame rate and source action |-**Stage-4 feature NPZ** (`dataset/features/<dataset>/motions/*.npz`) — canonicalized per-clip arrays, named `{object}-{motion}-{clip_idx}.npz`:+</details>++<details>+<summary><b>Reference —</b> stage-4 feature NPZ (<code>dataset/features/<dataset>/motions/{object}-{motion}-{clip_idx}.npz</code>)</summary>| Field | Shape | Description ||-------|-------|-------------|| `global_positions` | `(F, J, 3)` | global joint positions at canonical scale || `local_rotations` | `(F, J, 4)` | local joint rotations (quaternions) || `root_facing_quat` | `(F, 4)` | per-frame root quaternion aligning the skeleton to face Z+ |-| `fps` | scalar | frame rate of the clip (after any downsampling) |+| `fps` | scalar | frame rate of the clip, after halving anything ≥ 60 fps down below it (30 for every current source) |++The motion representation stores per-frame deltas without dividing by the frame rate, so the frame rate is part of the feature scale — the training loader rejects clips that are not 30 fps rather than mixing scales.++</details>++<details>+<summary><b>Reference —</b> <code>cond.npy</code> (one dict per object type)</summary>++| Key | Shape | Description |+|-----|-------|-------------|+| `object_type` | str | object-type name (clip-name prefix) |+| `parents` | `(J,)` | parent indices in canonical BFS joint order |+| `offsets`, `tpos_offsets` | `(J, 3)` | bind-pose and canonical T-pose bone offsets |+| `joint_names`, `clean_joint_names` | `(J,)` | raw and cleaned bone names (stage 3) |+| `tpos_first_frame` | `(J, 3)` | canonical T-pose global joint positions |+| `tpos_local_rotations`, `tpos_global_rotations` | `(J, 4)` | T-pose local / global rotations (quaternions) |+| `joint_relations`, `joint_graph_dists` | `(J, J)` | pairwise edge-relation types and clamped topology distances |+| `joint_depths` | `(J,)` | depth in the kinematic tree |+| `edge_indexs` | `(2, 2(J−1))` | undirected edge list |+| `spectral_feats` | `(J, K)` | Laplacian eigenvectors (`K = --max_freqs`) |+| `kinematic_chains` | list | root-to-leaf joint chains |+| `scale_factor`, `ground_height`, `ground_height_mode` | scalar | calibration applied to every clip of the type (`ground_height` is `None` in `per_motion` mode) |+| `face_joint_idxs` | dict | `{r_hip, l_hip, body_axis}` indices of the facing pair (when annotated) |+| `captions` | dict | `{clip_stem: caption}` for the type's clips (also flattened into `captions.json`) |++</details>++<details>+<summary><b>Reference —</b> files in <code>dataset/export/<dataset>/</code></summary>++The export directory is where every stage before feature extraction accumulates its output, and it is the single input directory stage 4 reads.++| Path | Stage | Content |+|------|-------|---------|+| `motions/{clip}.npz` | 1 | per-clip skeleton animation |+| `videos/{clip}.mp4` | 1 | per-clip skeleton preview |+| `tpose/{asset}.png` | 1 | rest-pose still per asset |+| `joint_names.json` | 1 | `{asset: [pruned bone names]}` |+| `joint_count.json` | 1 | `{asset: n_joints}` |+| `clip_frames.json` | 1 | `{clip: n_frames}` |+| `summary.json` | 1 | dataset totals (clips, frames, duration, fps) |+| `.completed/{asset}.json` | 1 | resume markers |+| `motion_captions.json` | 2b | `{clip: caption}` |+| `motion_captions_failed.txt` | 2b | clips to retry |+| `category_groups.json` | 2b | `{category: [assets]}` |+| `category_groups_review.json`, `category_groups_errors.json` | 2b | per-asset votes/evidence, exhausted retries |+| `clean_joint_names.json` | 3 | canonical anatomical labels per rig |+| `face_joint_names.json` | 3 | facing pair (or body axis) per rig |+| `failed_clean_names.txt`, `failed_face_joints.txt` | 3 | rigs that fell back to the rules |+| `filtered_clips.txt` | QA patch | clips stage 4 skips |+| `filtered_objects.txt`, `rig_flags.json` | QA patch | objaverse only: rigs stage 4 skips, and the full flag list |++</details>++## Tools++Standalone utilities in `data_process/tools/`. The QA visualizers have wrappers (listed under [Stage 3](#stage-3--joint-annotation-name-cleanup--facing-direction)); the rest are run directly.++| Tool | Purpose |+|------|---------|+| `merge_summaries.py` | Merge per-worker export summary shards into the canonical `joint_names` / `joint_count` / `clip_frames` / `summary` JSONs, self-healing from the `.completed/` markers. Additive and idempotent |+| `patch_annotations.py` | Post-stage-3 QA patch: rule fixes plus hand overrides for joint labels, face pairs, captions and categories; writes the stage-4 skip lists |+| `eval_category_groups.py` | Score a `category_groups.json` against a truth set, or diff two runs |+| `vis_tpose.py` | Annotated T-pose PNG with every joint labeled, per skeleton |+| `vis_tpose_facing.py` | Rest pose vs. facing-canonicalized pose per skeleton, plus `facing_summary.tsv` |+| `vis_motion.py` | MP4 of an export clip with a root-anchored heading arrow |+| `vis_clip_frames.py` | Frames-per-clip distribution figures from `clip_frames.json` (histogram + KDE + survival curve) |+| `vis_joint_count.py` | Joints-per-skeleton distribution figures from `joint_count.json` (histogram + KDE + cumulative curve; `--pooled` for the all-datasets figure) |+| `truebones_fbx2glb.py` | Per-clip Truebones FBX → GLB, preserving mesh, armature and the clip's take |+| `character_fbx2glb.py` | Rigged T-pose character FBX → GLB, animation stripped |++```bash+python -m data_process.tools.merge_summaries --output_dir dataset/export/<dataset>+python data_process/tools/patch_annotations.py --dry_run+python -m data_process.tools.vis_joint_count # defaults over every dataset/export/*+blender -b -P data_process/tools/truebones_fbx2glb.py -- --data_dir <in> --output_dir <out>+```-**`cond.npy`** — one dict per object type holding everything the training dataloader needs about the skeleton: topology (`parents`, `offsets`, joint names), T-pose positions/rotations, graph structure (relations, distances, depths, spectral features, kinematic chains), calibration (`scale_factor`, `ground_height`), face joints and per-clip captions.+Both distribution tools default over every `dataset/export/*`, write each dataset's figure next to its JSON, and put the comparison figure under `outputs/{clip_frames,joint_count}_vis/`.## Conventions-- **Run from the repo root.** Wrappers `cd` there themselves.+- **Run from the repo root.** Wrappers `cd` there themselves and activate the `unimate` conda env (`CONDA_ENV` overrides).+- **Self-documenting wrappers.** Every wrapper documents its overridable paths and knobs in its header comment; run any wrapper with `-h` to print it.- **Resumable by default.** Every batch stage skips outputs that already exist and records failures in sibling error logs, so failed items are retried on the next run without redoing finished work.-- **Env-var overrides.** Every wrapper documents its overridable paths/knobs in its header comment; run any wrapper with `-h` to print it.-- **Parallelism.** Blender stages shard with `--multi-worker N`; local-model captioning shards with `--multi-gpu`; API backends use concurrent workers via `NUM_WORKERS`.+- **Parallelism.** Blender stages shard with `--multi-worker N`; local-model captioning shards with `--multi-gpu`; API backends use concurrent workers via `NUM_WORKERS`; stage 4 parallelizes over object types with `NUM_WORKERS`.- **Naming.** Clips are named `{object_type}-{action}` (stage 1) and `{object_type}-{motion}-{clip_idx}` (stage 4). Mixamo is a single shared skeleton, so its files carry no object-type prefix.+- **Dependency direction.** `data_process/` is self-contained and never imports from the training package; kinematics come from the external [`Motion`](https://github.com/inbar-2344/Motion) library.## Troubleshooting- **EEVEE renders fail / produce black frames under `blender -b`** — stage 2a must run with plain `python` and the pip `bpy` module (the wrappers already do); headless `blender -b` has no GPU display surface for EEVEE.+- **All render workers land on one GPU** — `CUDA_VISIBLE_DEVICES` does not bind EEVEE's EGL context. Run one render job per GPU through a cgroup / scheduler allocation that exposes a single device.- **Offline compute nodes** — with a populated HuggingFace cache, export `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1` before the local Qwen caption/classify runs.-- **`joint_names.json` is missing object types that have clips** — an export killed mid-run (Slurm walltime, OOM) can leave the summary JSONs behind the completion markers. Rebuild them from the markers:+- **A multi-worker export exited non-zero** — the wrapper deliberately does **not** merge summary shards when any worker failed, since merging a truncated set would shrink the canonical JSONs and delete the shards. Rerun to finish the missing assets, then merge by hand (see below).+- **`joint_names.json` is missing object types that have clips** — an export killed mid-run (scheduler walltime, OOM) can leave the summary JSONs behind the completion markers. Rebuild them from the markers:```bashpython -m data_process.tools.merge_summaries --output_dir dataset/export/<dataset>```Additive and idempotent.+- **Stage 4 re-processes objects that look unchanged** — the `cond_parts/` cache key covers thresholds, topology settings, the caption/annotation digests and the object's clip list; any of those changing is enough. The run logs the exact diff per object (`cache invalidated (settings changed: ...)`).+- **`Object type mismatch between ...`** — stage 4 refuses to run when `joint_names.json`, `clean_joint_names.json` and `face_joint_names.json` cover different object types. Rerun the stage-3 wrappers on the current export directory.++If you run into a problem not covered here, please open an issue or email [[email protected]](mailto:[email protected]). Citation and license information is in the [top-level README](../README.md).diff --git a/data_process/feature_extraction/extract_features.py b/data_process/feature_extraction/extract_features.pyindex c77c419..39a6003 100644--- a/data_process/feature_extraction/extract_features.py+++ b/data_process/feature_extraction/extract_features.py@@ -11,6 +11,9 @@ Supports three dataset layouts via ``--dataset_type``:``data_dir/motions`` with no ``{object_type}-`` prefix; caption keys arebare motion stems.+An optional ``filtered_clips.txt`` listing individual clips to skip is read+for every layout.+Stage-2 (captions, category groups) and stage-3 (clean / face joint names)metadata JSONs are read from ``data_dir`` — see:mod:`data_process.feature_extraction.metadata`.@@ -53,6 +56,7 @@ from data_process.feature_extraction.metadata import (get_object_face_joints,get_object_metadata,load_all_metadata,+ load_json,print_summary,save_metadata_report,save_outputs,@@ -77,10 +81,15 @@ def parse_args():parser.add_argument("--save_dir", type=str, required=True,help="Output directory for processed clips and metadata")# Clip windowing- parser.add_argument("--max_clip_len", type=int, default=180,+ parser.add_argument("--max_clip_len", type=int, default=200,help="Max frames per saved clip")- parser.add_argument("--diffusion_max_len", type=int, default=60,- help="Model training max length (dataloader random-crops to this)")+ parser.add_argument("--diffusion_max_len", type=int, default=90,+ help="Longest model training max length (the dataloader "+ "random-crops to it). It sets the clip overlap: a "+ "training crop is only reachable when it fits inside "+ "one saved clip, so the stride is max_clip_len minus "+ "this value. Set it to the largest max_motion_length "+ "you train with.")parser.add_argument("--apply_clip", action="store_true", default=False,help="Crop long motions into overlapping fixed-length clips of ""max_clip_len frames (stride = max_clip_len - "@@ -107,6 +116,16 @@ def parse_args():parser.add_argument("--static_threshold", type=float, default=1e-5,help="Per-frame max-joint displacement below which a frame ""is static; leading/trailing static frames are trimmed")+ parser.add_argument("--jump_step_threshold", type=float, default=0.2,+ help="Discontinuity filter: a clip is dropped when one "+ "frame moves the skeleton at least this many body "+ "lengths AND that step is at least "+ "--jump_ratio_threshold times the clip median "+ "(concatenated actions / teleports). 0 disables.")+ parser.add_argument("--jump_ratio_threshold", type=float, default=8.0,+ help="Discontinuity filter: max/median per-frame joint "+ "displacement ratio required alongside "+ "--jump_step_threshold.")parser.add_argument("--min_frames", type=int, default=8,help="Minimum frame count for a motion to be kept ""(checked after downsampling and static trimming)")@@ -114,9 +133,8 @@ def parse_args():default=True,help="(mixamo only) Restrict the rig to the built-in ""22-joint humanoid core (drops finger chains and "- "End bones) — replaces the retired "- "corps_joint_names.json. Use --no-mixamo_core_joints "- "to keep the full 65-joint skeleton.")+ "End bones). Use --no-mixamo_core_joints to keep "+ "the full 65-joint skeleton.")parser.add_argument("--min_joints", type=int, default=8,help="Skip object types with fewer joints than this ""(counted after corps filtering)")@@ -124,12 +142,29 @@ def parse_args():help="Skip object types with more joints than this ""(counted after corps filtering)")# Objaverse-only filtering+ parser.add_argument("--filtered_clips", type=str, default="auto",+ help="Path to a txt file listing individual export "+ "clips (motion NPZ stems) to skip, one per line "+ "with optional '#' comments. Default 'auto' uses "+ "<data_dir>/filtered_clips.txt if present. Pass an "+ "empty string to disable. Complements the on-the-fly "+ "quality filters; entries land in filtered_clips.json.")parser.add_argument("--filtered_objects", type=str, default="auto",help="(objaverse only) Path to a txt file listing object ""types to skip (one per line; blanks and '#' comments ""ignored). Default 'auto' uses ""<data_dir>/filtered_objects.txt if present. Pass an ""empty string to disable.")+ parser.add_argument("--category_groups", type=str, default="auto",+ help="Path to the body-plan category JSON copied into "+ "the feature dir (the training loader reads it for "+ "objects_subset). Default 'auto' uses "+ "<data_dir>/category_groups.json if present. Pass "+ "an empty string to leave it out — the stage-2 "+ "classifier may still be running, and a partial "+ "file would land in the feature dir as if it were "+ "complete. Copy the finished file in afterwards; "+ "nothing else in this stage reads it.")# Executionparser.add_argument("--num_workers", type=int, default=1,help="Parallel worker processes (object types are independent)")@@ -138,27 +173,71 @@ def parse_args():parser.add_argument("--vis_ground", action=argparse.BooleanOptionalAction,default=True,help="Render previews with a checkerboard ground plane, "- "follow camera and root trajectory (default). "- "--no-vis_ground falls back to the legacy plain "- "cubic view.")+ "follow camera, contact shadow and root "+ "trajectory (default). --no-vis_ground renders "+ "the plain cubic view instead.")return parser.parse_args()-def resolve_filtered_objects_path(path, data_dir):+def _resolve_skip_list_path(path, data_dir, filename):+ """Both skip lists are optional: a missing file simply disables that step.++ ``"auto"`` looks for *filename* in *data_dir*; an empty string disables the+ list; any other value is used as given but is still skipped (with a warning)+ when it does not exist, so a stale path never aborts a run.+ """+ if not path:+ return Noneif path == "auto":- default = pjoin(data_dir, 'filtered_objects.txt')- return default if os.path.isfile(default) else None- return path or None+ default = pjoin(data_dir, filename)+ if os.path.isfile(default):+ return default+ logger.info(f'No {filename} in {data_dir}; skipping that filter step')+ return None+ if os.path.isfile(path):+ return path+ logger.warning(f'Skip list {path!r} not found; skipping that filter step')+ return None+++def resolve_filtered_objects_path(path, data_dir):+ return _resolve_skip_list_path(path, data_dir, 'filtered_objects.txt')+++def resolve_filtered_clips_path(path, data_dir):+ return _resolve_skip_list_path(path, data_dir, 'filtered_clips.txt')+++def resolve_category_groups(path, metadata):+ """Return the category groups to copy into the feature dir, or None.++ ``"auto"`` (the default) keeps whatever ``load_all_metadata`` found in+ the data dir; an empty string drops it; any other value is loaded as an+ explicit path. Nothing in this stage consumes the groups — they are+ passed through to the feature dir — so dropping them only means the+ copy is made later, by hand, once the classifier has finished.+ """+ if not path:+ if metadata.pop('category_groups', None) is not None:+ logger.info('Ignoring category_groups.json (--category_groups="")')+ return None+ if path != 'auto':+ groups = load_json(path)+ if groups is None:+ raise ValueError(f'--category_groups {path!r} not found')+ metadata['category_groups'] = groups+ return metadata.get('category_groups')def load_filtered_objects(path):+ """Read a skip list; a falsy path (no file) yields an empty set."""if not path:return set()with open(path, 'r') as f:- return {- line.strip() for line in f- if line.strip() and not line.startswith('#')- }+ # one entry per line; blank lines and '#' comments (whole-line or+ # trailing, e.g. "<uuid> # bone/bone pair") are ignored+ entries = (line.split('#', 1)[0].strip() for line in f)+ return {e for e in entries if e}def discover_object_types(motion_dir, dataset_type, args):@@ -173,6 +252,14 @@ def discover_object_types(motion_dir, dataset_type, args):logger.info(f'Ignoring {len(entries) - len(all_motions)} non-NPZ 'f'entries in {motion_dir}')+ clips_path = resolve_filtered_clips_path(args.filtered_clips, args.data_dir)+ skip_clips = load_filtered_objects(clips_path)+ if skip_clips:+ before = len(all_motions)+ all_motions = [m for m in all_motions if m[:-4] not in skip_clips]+ logger.info(f'Loaded {len(skip_clips)} entries from {clips_path}; '+ f'{before} -> {len(all_motions)} motion files after clip filtering')+if dataset_type == 'mixamo':# Single object type; no prefix-based grouping.return [MIXAMO_OBJECT_TYPE], all_motions@@ -229,7 +316,8 @@ CACHE_PARAM_KEYS = ('max_clip_len', 'clip_stride', 'apply_clip','max_path_len', 'max_freqs','target_diameter', 'activity_threshold', 'static_threshold',- 'min_frames', 'min_joints', 'max_joints',+ 'min_frames', 'jump_step_threshold', 'jump_ratio_threshold',+ 'min_joints', 'max_joints','use_tpos_ground_height','corps_names',)@@ -253,6 +341,14 @@ def _cache_params(task):params = {k: task[k] for k in CACHE_PARAM_KEYS}for k in CACHE_DATA_KEYS:params[f'{k}_digest'] = _digest(task[k])+ # The object's source clip list. A clip added to the export or newly+ # listed in filtered_clips.txt must re-process the object: a cached+ # result would otherwise keep the old clip set alive in the cond and+ # leave the dropped clip's NPZ in motions/, which the training loader+ # enumerates directly. Basenames only, so relocating data_dir (the+ # export dirs are symlinks) does not invalidate every entry.+ params['clips_digest'] = _digest(+ sorted(os.path.basename(p) for p in task['object_npzs']))return params@@ -290,6 +386,37 @@ def _load_cached_result(part_path, object_type, params, params_hash):return None+def _prune_object_clips(save_dir, clip_prefix, prune_vis):+ """Delete the clip files a previous run wrote for this object type.++ ``process_object`` only ever writes, and the training loader enumerates+ ``motions/`` rather than ``captions.json``, so a clip that disappears from+ an object (removed from the export, or newly listed in+ ``filtered_clips.txt``) would keep its stale+ ``motions/{object}-{motion}-{idx}.npz`` on disk and still be trained on.+ Called only on a cache miss, i.e. right before the object is rewritten in+ full. ``clip_prefix`` is ``"{object_type}-"`` (empty for mixamo, whose+ single object type owns every file in the directory).++ Previews are pruned only when the run regenerates them (``--vis``), so a+ later ``--no-vis`` run does not throw away the MP4s an earlier one made.+ """+ targets = [('motions', '.npz')] + ([('videos', '.mp4')] if prune_vis else [])+ removed = 0+ for sub, ext in targets:+ directory = pjoin(save_dir, sub)+ if not os.path.isdir(directory):+ continue+ for name in os.listdir(directory):+ if name.startswith(clip_prefix) and name.endswith(ext):+ try:+ os.remove(pjoin(directory, name))+ removed += 1+ except OSError as e: # noqa: PERF203 — one bad file must not abort+ logger.warning(f'Could not remove stale {sub}/{name}: {e}')+ return removed++def process_object_task(task):"""Process one object type, caching its result for resume.@@ -306,6 +433,7 @@ def process_object_task(task):"""object_type = task.pop('object_type')part_path = task.pop('part_path')+ clip_prefix = task.pop('clip_prefix')params = _cache_params(task)params_hash = _params_hash(params)@@ -313,6 +441,11 @@ def process_object_task(task):if cached is not None:return object_type, cached, True+ removed = _prune_object_clips(task['save_dir'], clip_prefix, task['save_vis'])+ if removed:+ logger.info(f'[{object_type}] removed {removed} clip files from a '+ f'previous run before re-processing')+try:obj_cond, n_clips, n_frames, n_joints, filtered = process_object(object_type, **task)@@ -363,6 +496,10 @@ def build_object_tasks(args, clip_stride, motion_dir, metadata):part_path=_object_part_path(args.save_dir, object_type),object_npzs=collect_object_npzs(object_type, args.dataset_type,motion_dir, all_motions),+ # Mixamo clip files carry no "{object_type}-" prefix; its single+ # object type owns the whole directory.+ clip_prefix=('' if args.dataset_type == 'mixamo'+ else f'{object_type}-'),save_dir=args.save_dir,max_clip_len=args.max_clip_len, clip_stride=clip_stride,apply_clip=args.apply_clip,@@ -380,6 +517,8 @@ def build_object_tasks(args, clip_stride, motion_dir, metadata):activity_threshold=args.activity_threshold,static_threshold=args.static_threshold,min_frames=args.min_frames,+ jump_step_threshold=args.jump_step_threshold,+ jump_ratio_threshold=args.jump_ratio_threshold,min_joints=args.min_joints, max_joints=args.max_joints,save_vis=args.vis, vis_ground=args.vis_ground,))@@ -407,7 +546,7 @@ def main(args):logger.info(f'Loaded metadata from {args.data_dir}: '+ ', '.join(f'{k}={len(v)}' for k, v in metadata.items()))check_metadata_object_types_consistent(metadata)- category_groups = metadata.get('category_groups')+ category_groups = resolve_category_groups(args.category_groups, metadata)tasks = build_object_tasks(args, clip_stride, motion_dir, metadata)diff --git a/data_process/feature_extraction/metadata.py b/data_process/feature_extraction/metadata.pyindex fc83854..7d5de44 100644--- a/data_process/feature_extraction/metadata.py+++ b/data_process/feature_extraction/metadata.py@@ -96,8 +96,7 @@ def load_face_joint_names(source_dir):# The 22-joint humanoid core the mixamo rig is reduced to at extraction time-# (drops the 40 finger bones plus the End bones). Replaces the retired-# corps_joint_names.json side file; toggled by --mixamo_core_joints.+# (drops the 40 finger bones plus the End bones); toggled by --mixamo_core_joints.MIXAMO_CORE_JOINTS = ["mixamorig:Hips","mixamorig:Spine", "mixamorig:Spine1", "mixamorig:Spine2",@@ -325,16 +324,19 @@ def compute_clip_windows(nframes, max_clip_len, clip_stride):frames. No returned window is ever longer than ``max_clip_len`` (the wholesequence is returned unsliced only when it already fits).- Leftover frames past the last strided window are handled by tail length:-- - at least half a clip: emitted as their own (shorter) trailing window;- - shorter than that, but still adding at least as many new frames as a- normal window's overlap (``max_clip_len - clip_stride``): covered by a- full-length window anchored at the final frame — replacing the last- window when the frames it gives up stay covered by the one before it,- otherwise appended;- - shorter than that: dropped, rather than glued onto the previous window- (which is what used to push clips past ``max_clip_len``).+ Leftover frames past the last strided window are handled by tail length,+ measured against the window overlap ``max_clip_len - clip_stride`` — the+ longest training crop the clips are cut to hold:++ - at least one full training crop: emitted as their own (shorter)+ trailing window, which is long enough to be croppable on its own;+ - shorter than that: covered by a full-length window anchored at the+ final frame, replacing the last window when the frames it gives up stay+ covered by the one before it (always true once there are two or more+ windows);+ - shorter than that and there is only one window to replace: dropped,+ rather than glued onto the previous window (which would push that clip+ past ``max_clip_len``) or duplicated as a near-copy of it."""if not max_clip_len or nframes <= max_clip_len:return [(0, nframes)]@@ -346,7 +348,10 @@ def compute_clip_windows(nframes, max_clip_len, clip_stride):last_end = clips[-1][1]if last_end < nframes:tail_len = nframes - last_end- if tail_len >= max_clip_len // 2:+ # A trailing window earns its place once it can hold one full+ # training crop, i.e. the overlap a normal window is given.+ min_tail = max(1, max_clip_len - clip_stride)+ if tail_len >= min_tail:clips.append((last_end, nframes))else:# Cover the tail with a full-length window anchored at the end.@@ -355,10 +360,6 @@ def compute_clip_windows(nframes, max_clip_len, clip_stride):if slid_start <= prev_end:# Free: the frames the last window gives up are still covered.clips[-1] = (slid_start, nframes)- elif tail_len >= max(1, max_clip_len - clip_stride):- # Worth an extra window: it adds at least as many new frames- # as a normal window's overlap.- clips.append((slid_start, nframes))# Otherwise the tail is too small to pay for a window of its own.return clipsdiff --git a/data_process/joint_annotation/face_select_llm.py b/data_process/joint_annotation/face_select_llm.pyindex 3eb3e60..ad1fe60 100644--- a/data_process/joint_annotation/face_select_llm.py+++ b/data_process/joint_annotation/face_select_llm.py@@ -6,8 +6,8 @@ defines the rig's lateral axis for heading-angle computation. For serpentinerigs with no bilateral symmetry, the LLM picks longitudinal body-axisendpoints (head-tip / tail-tip) and sets ``body_axis: true``.-Backends (see :mod:`llm`): local HF causal LM, OpenAI API (default:-gpt-5-mini), DeepSeek API.+Backends (see :mod:`llm`): DeepSeek API (default: ``deepseek-v4-flash``),+OpenAI API, or a local HF causal LM.Inputs :``joint_names.json`` — ``{rig_id: [raw_joint_name, ...]}``@@ -28,9 +28,9 @@ Pipeline per rig:Usage:python -m data_process.joint_annotation.face_select_llm \\- --input_dir <export_dir> # OpenAI gpt-5-mini+ --input_dir <export_dir> # DeepSeek v4-flash (default)python -m data_process.joint_annotation.face_select_llm \\- --input_dir <export_dir> --model deepseek-v4-flash+ --input_dir <export_dir> --model gpt-5-minipython -m data_process.joint_annotation.face_select_llm \\--input_dir <export_dir> --model Qwen/Qwen3-8B"""diff --git a/data_process/joint_annotation/llm.py b/data_process/joint_annotation/llm.pyindex fa44973..62a8bd9 100644--- a/data_process/joint_annotation/llm.py+++ b/data_process/joint_annotation/llm.py@@ -27,9 +27,9 @@ BACKEND_OPENAI = "openai"VALID_BACKENDS = [BACKEND_LOCAL, BACKEND_OPENAI]MAX_RETRIES = 4-# gpt-5-mini is the alternative once OPENAI credits are topped up; DeepSeek-# think-low reached quality parity (0 side errors, 99.6% format compliance,-# A/B 2026-08-30) at a fraction of the cost.+# Default model for every LLM-assisted joint-annotation pass. Any+# OpenAI-compatible model id (``gpt-*``) or a local HuggingFace causal LM works+# as well; see ``detect_backend``.DEFAULT_MODEL = "deepseek-v4-flash"# DeepSeek's API speaks the OpenAI protocol, so ``deepseek-*`` models ride thediff --git a/data_process/joint_annotation/names_clean_llm.py b/data_process/joint_annotation/names_clean_llm.pyindex 44ca613..389c3cd 100644--- a/data_process/joint_annotation/names_clean_llm.py+++ b/data_process/joint_annotation/names_clean_llm.py@@ -4,8 +4,8 @@ Complement to the rule-based :mod:`names_clean_rule`: sends raw joint names to aLLM and asks it to map each one to a canonical anatomical label from:mod:`vocab`. Pure text in / text out — no images needed.-Backends (see :mod:`llm`): local HF causal LM, OpenAI API (default:-gpt-5-mini), DeepSeek API.+Backends (see :mod:`llm`): DeepSeek API (default: ``deepseek-v4-flash``),+OpenAI API, or a local HF causal LM.Input : ``joint_names.json`` — ``{rig_id: [raw_joint_name, ...]}`` where``rig_id`` keys may be humans, animals, props, vehicles or any other@@ -28,9 +28,9 @@ rig or ``--redo_failed`` to redo just the recorded failures.Usage:python -m data_process.joint_annotation.names_clean_llm \\- --input <export_dir>/joint_names.json # OpenAI gpt-5-mini+ --input <export_dir>/joint_names.json # DeepSeek v4-flash (default)python -m data_process.joint_annotation.names_clean_llm \\- --input <export_dir>/joint_names.json --model deepseek-v4-flash+ --input <export_dir>/joint_names.json --model gpt-5-minipython -m data_process.joint_annotation.names_clean_llm \\--input <export_dir>/joint_names.json --model Qwen/Qwen3-8B"""diff --git a/data_process/mesh_animation/animate_motion.py b/data_process/mesh_animation/animate_motion.pyindex a149367..6613b03 100644--- a/data_process/mesh_animation/animate_motion.py+++ b/data_process/mesh_animation/animate_motion.py@@ -8,7 +8,7 @@ topology, joint names, scale) and drives the original rigged asset with it.Pipeline:1. Load the cond entry for the requested ``--dataset_type`` and the motion- file (NPZ; legacy ``.npy`` model features are also accepted, see below).+ file (NPZ, or the ``.npy`` motion features written by the model's sampler).2. Reconcile the character armature against the animation's bone list(see :func:`data_process.utils.blender_rig.sync_armature_bones`).3. Compute per-bone keyframes and bind them as a Blender Action.@@ -96,7 +96,7 @@ def build_anim_from_npz(anim_path, cond_data):def build_anim_from_npy(anim_path, cond_data, anim_mode):"""Build ``(anim, rest_anim, tpos_global_rot, raw_anim_data)`` from a- legacy ``.npy`` of model motion features.+ ``.npy`` of model motion features (the format ``unimate.inference.sample`` saves).Decoding model features back into an ``Animation`` requires thetraining/inference package (``unimate.utils.motion_utils``), which is@@ -109,7 +109,7 @@ def build_anim_from_npy(anim_path, cond_data, anim_mode):)except ImportError as exc: # pragma: no cover — depends on the model packageraise RuntimeError(- "Legacy .npy motion features need the training/inference package "+ ".npy model motion features need the training/inference package ""(unimate.utils.motion_utils); pass a feature-format .npz instead.") from exc@@ -243,12 +243,12 @@ def animate_character(char_path, anim_path, cond_path, output_dir,Args:char_path: Character FBX/GLB (provides mesh + armature).- anim_path: Feature-format motion NPZ (or legacy NPY).+ anim_path: Feature-format motion NPZ, or a ``.npy`` of model motion features.cond_path: ``cond.npy`` for the dataset.output_dir: Destination directory (created if missing).dataset_type: ``'truebones'`` | ``'objaverse'`` | ``'mixamo'``;controls how the cond-dict key is derived from ``anim_path``.- anim_mode: Recovery mode for legacy NPY input, ``'fk'`` or ``'ik'``.+ anim_mode: Recovery mode for ``.npy`` model-feature input, ``'fk'`` or ``'ik'``.extra_bones_strategy: How to handle armature bones not present inthe animation (see :func:`sync_armature_bones`)."""@@ -282,7 +282,7 @@ def parse_args():help="Dataset that produced the cond/anim files; controls ""how the cond-dict key is resolved.")parser.add_argument("--anim_path", type=str, required=True,- help="Feature-format motion NPZ (or legacy .npy).")+ help="Feature-format motion NPZ, or a .npy of model motion features.")parser.add_argument("--char_path", type=str, default=None,help="Character FBX/GLB. If omitted, auto-resolved from "f"--dataset_type and --anim_path (truebones -> "@@ -292,7 +292,7 @@ def parse_args():help=f"cond.npy for the dataset (default: {COND_PATH_TEMPLATE}).")parser.add_argument("--output_dir", type=str, default='outputs/animated')parser.add_argument("--anim_mode", type=str, default='fk', choices=['fk', 'ik'],- help="Recovery mode for legacy .npy input.")+ help="Recovery mode for .npy model-feature input.")parser.add_argument("--extra_bones_strategy", type=str, default='merge',choices=list(EXTRA_BONES_STRATEGIES),help="What to do with armature bones missing from the "diff --git a/data_process/mesh_animation/common.py b/data_process/mesh_animation/common.pyindex dd5ab70..be04087 100644--- a/data_process/mesh_animation/common.py+++ b/data_process/mesh_animation/common.py@@ -5,7 +5,7 @@ Every entry script in this package runs under Blender headlessdriving animation onto its armature, and exports GLB/FBX. They differ only inwhere the driving animation comes from:- animate_motion feature NPZ (or legacy model ``.npy``) + ``cond.npy``+ animate_motion feature NPZ (or model-feature ``.npy``) + ``cond.npy``animate_npz export-stage NPZ (bone names carried in the file)animate_fbx raw animation FBX/GLB clips (action transfer by name)animate_mixamo batch wrapper over ``animate_npz``@@ -58,7 +58,7 @@ def parse_blender_argv(parser):def npz_scalar(data, key, default):"""Read a scalar from an NpzFile / dict, falling back to *default*.- Mapping-free inputs (e.g. the legacy ``.npy`` ndarray in+ Mapping-free inputs (e.g. the model-feature ``.npy`` ndarray in``animate_motion``) have no keys and always yield *default*."""if hasattr(data, 'keys') and key in data:@@ -134,7 +134,7 @@ def drive_and_export(char_armature, anim, rest_anim, bone_names, fps,extra_bones_strategy: How to treat armature bones absent from*bone_names* (see :func:`sync_armature_bones`).tpos_global_rot: Optional ``(nbones, 4)`` T-pose global rotations to- conjugate keyframes by (legacy ``.npy`` path in animate_motion).+ conjugate keyframes by (``.npy`` model-feature path in animate_motion)."""anim_local_mat = transforms_local(anim) # (nframes, nbones, 4, 4)rest_local_mat = transforms_local(rest_anim)[0] # (nbones, 4, 4)diff --git a/data_process/motion_export/export_truebones.py b/data_process/motion_export/export_truebones.pyindex ecd6562..5edb21c 100644--- a/data_process/motion_export/export_truebones.py+++ b/data_process/motion_export/export_truebones.py@@ -15,7 +15,7 @@ Usage (Blender headless):--output_dir dataset/export/truebones"""-import bpy+import bpy # noqa: F401 — fail fast when the bpy module is unavailableimport sysimport osimport numpy as npdiff --git a/data_process/motion_rendering/render_mixamo.py b/data_process/motion_rendering/render_mixamo.pyindex b991a34..03e9085 100644--- a/data_process/motion_rendering/render_mixamo.py+++ b/data_process/motion_rendering/render_mixamo.py@@ -18,7 +18,7 @@ import sysimport argparsefrom pathlib import Path-import bpy+import bpy # noqa: F401 — fail fast when the bpy module is unavailablefrom loguru import loggerfrom data_process.utils.blender_export import discover_pose_actionsdiff --git a/data_process/motion_rendering/render_objaverse.py b/data_process/motion_rendering/render_objaverse.pyindex 8b7c9d7..6e9de91 100644--- a/data_process/motion_rendering/render_objaverse.py+++ b/data_process/motion_rendering/render_objaverse.py@@ -14,7 +14,7 @@ import sysimport argparsefrom pathlib import Path-import bpy+import bpy # noqa: F401 — fail fast when the bpy module is unavailablefrom loguru import loggerfrom data_process.utils.blender_export import (diff --git a/data_process/motion_rendering/render_tpose.py b/data_process/motion_rendering/render_tpose.pyindex eb2cd58..f4414a8 100644--- a/data_process/motion_rendering/render_tpose.py+++ b/data_process/motion_rendering/render_tpose.py@@ -15,7 +15,6 @@ Usage (plain python — EEVEE needs the pip ``bpy`` module's GPU context):"""import os-import sysimport argparsefrom pathlib import Pathdiff --git a/data_process/motion_rendering/render_truebones.py b/data_process/motion_rendering/render_truebones.pyindex 4570e99..e0fd988 100644--- a/data_process/motion_rendering/render_truebones.py+++ b/data_process/motion_rendering/render_truebones.py@@ -16,7 +16,7 @@ import sysimport argparsefrom pathlib import Path-import bpy+import bpy # noqa: F401 — fail fast when the bpy module is unavailablefrom loguru import loggerfrom data_process.utils.blender_export import (diff --git a/data_process/scripts/run_animate_motion.sh b/data_process/scripts/run_animate_motion.shindex 295de1d..d42f44d 100755--- a/data_process/scripts/run_animate_motion.sh+++ b/data_process/scripts/run_animate_motion.sh@@ -10,11 +10,11 @@# ANIM_PATH=clip.npz CHAR_PATH=char.fbx bash data_process/scripts/run_animate_motion.sh mixamo## Env overrides:-# ANIM_PATH (required) motion .npz (or legacy .npy)+# ANIM_PATH (required) motion .npz, or a .npy of model motion features# CHAR_PATH character mesh (auto-resolved for truebones/objaverse; required for mixamo)# COND_PATH cond.npy (default: dataset/features/<dataset>/cond.npy)# OUTPUT_DIR (default: outputs/animated)-# ANIM_MODE fk|ik, legacy .npy only (default: fk)+# ANIM_MODE fk|ik, .npy input only (default: fk)set -euo pipefailsource "$(dirname "${BASH_SOURCE[0]}")/_common.sh"diff --git a/data_process/scripts/run_caption_category.sh b/data_process/scripts/run_caption_category.shindex 1a8269b..742f38a 100755--- a/data_process/scripts/run_caption_category.sh+++ b/data_process/scripts/run_caption_category.sh@@ -1,5 +1,5 @@#!/bin/bash-# Stage 2 — classify assets into body-plan categories with a local Qwen3-VL model.+# Stage 2 — classify assets into body-plan categories with a local Qwen3.5 / Qwen3-VL model.# Single-GPU only — one classification per object, no sharding.## Usage:@@ -8,8 +8,10 @@## Env overrides:# MODEL, RENDER_ROOT (default: dataset/render/<dataset>_tpose),+# EXPORT_DIR (default: dataset/export/<dataset>; skeleton facts + captions shown to the model),+# MOTION_RENDER_ROOT (default: dataset/render/<dataset>; first frame of a clip, 4 cameras, as stance reference),# CATEGORY_GROUPS_JSON (default: dataset/export/<dataset>/category_groups.json),-# MAX_TOKENS+# VOTES (default 3 sampled answers, majority wins), MAX_TOKENS (default 96)# Extra arguments are passed through to classify_category.py.# On offline compute nodes with a populated HuggingFace cache, export# HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1.@@ -24,22 +26,38 @@ require_dataset "$DATASET"RENDER_ROOT=${RENDER_ROOT:-$(tpose_dir "$DATASET")}CATEGORY_GROUPS_JSON=${CATEGORY_GROUPS_JSON:-$(export_dir "$DATASET")/category_groups.json}+EXPORT_DIR=${EXPORT_DIR:-$(export_dir "$DATASET")}+MOTION_RENDER_ROOT=${MOTION_RENDER_ROOT:-$(render_dir "$DATASET")}+VOTES=${VOTES:-3}if [[ ! -d "$RENDER_ROOT" ]]; thenecho "RENDER_ROOT does not exist: $RENDER_ROOT" >&2exit 2fimkdir -p "$(dirname "$CATEGORY_GROUPS_JSON")"-# Local Qwen3-VL only. Sizes: Qwen/Qwen3-VL-{2B,8B,32B,72B}-Instruct.-MODEL=${MODEL:-Qwen/Qwen3-VL-8B-Instruct}-MAX_TOKENS=${MAX_TOKENS:-10}+# Local Qwen only: Qwen/Qwen3.5-9B (default, same as the captioner), Qwen/Qwen3.8-27B, or Qwen/Qwen3-VL-{2B,8B,32B,72B}-Instruct.+MODEL=${MODEL:-Qwen/Qwen3.5-9B}+MAX_TOKENS=${MAX_TOKENS:-96}echo "Dataset: $DATASET | Model: $MODEL"echo "Render root: $RENDER_ROOT"echo "Output JSON: $CATEGORY_GROUPS_JSON"+echo "Export dir (skeleton facts + captions): $EXPORT_DIR | motion renders: $MOTION_RENDER_ROOT | votes: $VOTES"++# Mixamo is one shared humanoid rig ("mixamo" in the export sidecars); its+# T-pose folder holds the 114 character renders, which are not what stage 4+# indexes, so the file is written directly instead of classified.+if [[ "$DATASET" == "mixamo" ]]; then+ printf '{\n "bipedal": [\n "mixamo"\n ]\n}\n' > "$CATEGORY_GROUPS_JSON"+ echo "mixamo: single humanoid rig -> wrote $CATEGORY_GROUPS_JSON"+ exit 0+fipython -m data_process.vlm_caption.classify_category \--render_root="$RENDER_ROOT" \--model="$MODEL" \--max_tokens="$MAX_TOKENS" \+ --votes="$VOTES" \+ --export_dir="$EXPORT_DIR" \+ --motion_render_root="$MOTION_RENDER_ROOT" \--category_groups_json="$CATEGORY_GROUPS_JSON" "$@"diff --git a/data_process/scripts/run_caption_motion.sh b/data_process/scripts/run_caption_motion.shindex f13221c..6e4b5ec 100755--- a/data_process/scripts/run_caption_motion.sh+++ b/data_process/scripts/run_caption_motion.sh@@ -2,14 +2,15 @@# Stage 2 — caption multi-view motion renders with a VLM.# The backend is picked from MODEL, with the same rules as detect_backend() in# vlm_caption/backends.py:-# *qwen* (default, any case) -> local Qwen3-VL / Qwen3.5 (GPU-bound; supports --multi-gpu)+# *qwen* (default, any case) -> local Qwen3.5 / Qwen3.8 / Qwen3-VL (GPU-bound; supports --multi-gpu)# gemini* -> Gemini API (needs GOOGLE_API_KEY)# anything else -> OpenAI-compatible API (needs OPENAI_API_KEY)## Usage:-# bash data_process/scripts/run_caption_motion.sh objaverse # local Qwen3-VL+# bash data_process/scripts/run_caption_motion.sh objaverse # local Qwen3.5-9B (default)# bash data_process/scripts/run_caption_motion.sh truebones --multi-gpu # all visible GPUs (local backend only)-# MODEL=Qwen/Qwen3.5-9B bash data_process/scripts/run_caption_motion.sh objaverse+# MODEL=Qwen/Qwen3.8-27B bash data_process/scripts/run_caption_motion.sh objaverse # 27B: one 80 GB GPU+# MODEL=Qwen/Qwen3-VL-8B-Instruct bash data_process/scripts/run_caption_motion.sh objaverse# MODEL=gemini-3-flash-preview bash data_process/scripts/run_caption_motion.sh objaverse# MODEL=gpt-5-mini NUM_WORKERS=16 bash data_process/scripts/run_caption_motion.sh mixamo#@@ -44,7 +45,7 @@ while [[ $# -gt 0 ]]; dodone# ── Backend from MODEL (mirrors vlm_caption/backends.py detect_backend) ─-MODEL=${MODEL:-Qwen/Qwen3-VL-8B-Instruct}+MODEL=${MODEL:-Qwen/Qwen3.5-9B}if [[ "${MODEL,,}" == *qwen* ]]; thenbackend=local # backends.py: BACKEND_QWENelif [[ "$MODEL" == gemini* ]]; thendiff --git a/data_process/scripts/run_extract_features.sh b/data_process/scripts/run_extract_features.shindex 021d783..d6abfd7 100755--- a/data_process/scripts/run_extract_features.sh+++ b/data_process/scripts/run_extract_features.sh@@ -32,7 +32,7 @@ SAVE_DIR=${SAVE_DIR:-$(features_dir "$DATASET")}EXTRA_ARGS=()# Per-dataset joint-count range (skeletons outside it are skipped here, not# at export — the exports stay complete). Defaults in extract_features.py-# are 8..150; objaverse keeps its wider historical range.+# are 8..150; objaverse uses a wider range.case "$DATASET" inobjaverse) EXTRA_ARGS+=(--min_joints 4 --max_joints 180) ;;esacdiff --git a/data_process/scripts/run_joints_vis_facing.sh b/data_process/scripts/run_joints_vis_facing.shnew file mode 100644index 0000000..7a8a849--- /dev/null+++ b/data_process/scripts/run_joints_vis_facing.sh@@ -0,0 +1,45 @@+#!/bin/bash+# Stage 3 QA — compare each exported rest pose with its stage-4 facing+# canonicalization: [original rest pose with the face pair marked | the same pose+# corrected by the pair, facing +Z], one PNG per skeleton plus facing_summary.tsv.+#+# Usage:+# bash data_process/scripts/run_joints_vis_facing.sh objaverse+# RIGS="RIG1 RIG2" bash data_process/scripts/run_joints_vis_facing.sh objaverse+# FACE_JSON=dataset/UniML3D/patches/objaverse_face_pairs.json OUTPUT_DIR=outputs/tmp \+# bash data_process/scripts/run_joints_vis_facing.sh objaverse # preview a patch+# LIMIT=50 bash data_process/scripts/run_joints_vis_facing.sh truebones+#+# Env overrides:+# FACE_JSON face pairs to draw (default: <export_dir>/face_joint_names.json)+# OUTPUT_DIR PNG output directory (default: outputs/tpose_facing_vis/<dataset>)+# RIGS space-separated skeleton keys (default: every non-empty pair)+# RIGS_FILE text file with one skeleton key per line+# SOURCE only pairs with this "source" (thigh, shoulder, body_axis, ...)+# LIMIT stop after N skeletons+# MARK_LABELS comma-separated clean labels to mark with extra symbols, e.g. "Head,Tail End,Toe"+# WORKERS parallel renderers (default: min(8, cpus/2))+# OVERWRITE=1 re-render existing PNGs++set -euo pipefail+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"++handle_help "$@"++DATASET=${1:?Usage: run_joints_vis_facing.sh <truebones|mixamo|objaverse>}+require_dataset "$DATASET"+EXPORT_DIR=$(export_dir "$DATASET")+[[ -d "$EXPORT_DIR/motions" ]] || { echo "export motions not found: $EXPORT_DIR/motions" >&2; exit 1; }++cmd=(python -m data_process.tools.vis_tpose_facing --export_dir "$EXPORT_DIR")+[[ -n "${FACE_JSON:-}" ]] && cmd+=(--face_json "$FACE_JSON")+[[ -n "${OUTPUT_DIR:-}" ]] && cmd+=(--output_dir "$OUTPUT_DIR")+[[ -n "${RIGS:-}" ]] && cmd+=(--rigs $RIGS)+[[ -n "${RIGS_FILE:-}" ]] && cmd+=(--rigs_file "$RIGS_FILE")+[[ -n "${SOURCE:-}" ]] && cmd+=(--source "$SOURCE")+[[ -n "${LIMIT:-}" ]] && cmd+=(--limit "$LIMIT")+[[ -n "${MARK_LABELS:-}" ]] && cmd+=(--mark_labels "$MARK_LABELS")+[[ -n "${WORKERS:-}" ]] && cmd+=(--workers "$WORKERS")+[[ "${OVERWRITE:-0}" == 1 ]] && cmd+=(--overwrite)++"${cmd[@]}"diff --git a/data_process/tools/character_fbx2glb.py b/data_process/tools/character_fbx2glb.pyindex e402d07..74958cb 100644--- a/data_process/tools/character_fbx2glb.py+++ b/data_process/tools/character_fbx2glb.py@@ -12,7 +12,6 @@ Usage (Blender headless):--output_dir dataset/raw/mixamo/character_refined_glb"""-import argparseimport osimport sys@@ -22,6 +21,7 @@ from loguru import loggersys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))from data_process.utils.blender_export import import_fbx, reset_scene+from data_process.utils.fbx2glb import parse_batch_args, run_batchdef convert_character_to_glb(fbx_path, glb_path):@@ -57,54 +57,6 @@ def convert_character_to_glb(fbx_path, glb_path):logger.info(f"Saved T-pose GLB: {glb_path}")-def parse_args():- parser = argparse.ArgumentParser(- description="Convert rigged T-pose character FBX files to GLB, one to one.")- parser.add_argument('--data_dir', type=str, required=True,- help='Flat directory of character FBX files.')- parser.add_argument('--output_dir', type=str, required=True,- help='Destination directory for the per-character GLB files.')- parser.add_argument('--worker_id', type=int, default=0,- help='Worker index for sharding across workers.')- parser.add_argument('--num_workers', type=int, default=1,- help='Total number of workers.')- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]- return parser.parse_args(argv)--if __name__ == "__main__":- args = parse_args()-- fbx_files = sorted(f for f in os.listdir(args.data_dir)- if f.lower().endswith('.fbx'))- logger.info(f"Found {len(fbx_files)} character FBXs in {args.data_dir}")-- if args.num_workers > 1:- fbx_files = fbx_files[args.worker_id::args.num_workers]- logger.info(f"Worker {args.worker_id}/{args.num_workers}: {len(fbx_files)} files")-- os.makedirs(args.output_dir, exist_ok=True)- error_log = os.path.join(args.output_dir,- f'fbx2glb_errors_worker{args.worker_id}.log')-- n_ok = n_skip = n_fail = 0- for fbx_file in fbx_files:- glb_path = os.path.join(args.output_dir,- os.path.splitext(fbx_file)[0] + '.glb')- if os.path.exists(glb_path):- n_skip += 1- continue- try:- convert_character_to_glb(os.path.join(args.data_dir, fbx_file), glb_path)- n_ok += 1- except Exception as e: # noqa: BLE001 — keep the batch going- logger.error(f"Failed to convert {fbx_file}: {e}")- with open(error_log, 'a') as f:- f.write(f"{fbx_file}\t{e}\n")- n_fail += 1-- logger.info(f"Done: {n_ok} converted, {n_skip} skipped, {n_fail} failed "- f"-> {args.output_dir}")-- if n_fail:- sys.exit(1)+ run_batch(parse_batch_args("Convert rigged T-pose character FBX files to GLB, one to one."),+ convert_character_to_glb, unit='character FBXs')diff --git a/data_process/tools/eval_category_groups.py b/data_process/tools/eval_category_groups.pynew file mode 100644index 0000000..32275f3--- /dev/null+++ b/data_process/tools/eval_category_groups.py@@ -0,0 +1,72 @@+#!/usr/bin/env python3+"""Score or diff body-plan classifications (``category_groups.json``).++ # accuracy against a hand truth set ({asset: [acceptable categories]})+ python data_process/tools/eval_category_groups.py \+ --groups dataset/export/truebones/category_groups.json \+ --truth data_process/vlm_caption/eval/truebones_category_truth.json++ # differences between two runs (e.g. two models / prompts)+ python data_process/tools/eval_category_groups.py --groups A.json --other B.json++With ``--review`` (the ``<stem>_review.json`` sibling written by+``classify_category.py``) every miss is printed with its votes and reasons.+"""++import argparse+import json+from collections import Counter++ALIASES = {'quadruped': 'quadrupedal', 'biped': 'bipedal'}+++def load_map(path):+ groups = json.load(open(path))+ return {a: ALIASES.get(c, c) for c, members in groups.items() for a in members}+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])+ ap.add_argument('--groups', required=True, help='category_groups.json to score')+ ap.add_argument('--truth', help='{asset: [acceptable categories]} JSON (keys starting with _ ignored)')+ ap.add_argument('--other', help='another category_groups.json to diff against')+ ap.add_argument('--review', help='<stem>_review.json of --groups (votes / reasons per asset)')+ args = ap.parse_args()++ pred = load_map(args.groups)+ review = json.load(open(args.review)) if args.review else {}+ print(f'{args.groups}: {len(pred)} assets, {dict(Counter(pred.values()))}')++ def detail(asset):+ rec = review.get(asset, {})+ if not rec:+ return ''+ reasons = [a.get('reason') for a in rec.get('answers', []) if a.get('reason')]+ return f" votes={rec.get('votes')} conf={rec.get('confidence')} reasons={reasons[:2]}"++ if args.truth:+ truth = {k: v for k, v in json.load(open(args.truth)).items() if not k.startswith('_')}+ ok = [a for a, t in truth.items() if pred.get(a) in t]+ unc = [a for a in truth if pred.get(a) == 'uncertain']+ miss = [a for a, t in truth.items() if pred.get(a) not in t and pred.get(a) != 'uncertain']+ print(f'truth: {len(truth)} assets | correct {len(ok)} | uncertain {len(unc)} | wrong {len(miss)} '+ f'| missing {sum(1 for a in truth if a not in pred)}')+ for a in miss:+ print(f' WRONG {a:36s} got={pred.get(a)!s:18s} truth={truth[a]}{detail(a)}')+ for a in unc:+ print(f' UNCERTAIN {a:36s} truth={truth[a]}{detail(a)}')++ if args.other:+ other = load_map(args.other)+ common = sorted(set(pred) & set(other))+ diff = [a for a in common if pred[a] != other[a]]+ print(f'vs {args.other}: {len(common)} common assets, {len(common) - len(diff)} agree, {len(diff)} differ')+ pairs = Counter((pred[a], other[a]) for a in diff)+ for (p, o), n in pairs.most_common():+ print(f' {p:18s} vs {o:18s} x{n}')+ for a in diff[:40]:+ print(f' {a:36s} {pred[a]:18s} vs {other[a]}{detail(a)}')+++if __name__ == '__main__':+ main()diff --git a/data_process/tools/merge_summaries.py b/data_process/tools/merge_summaries.pyindex 2223f24..1c65ce5 100644--- a/data_process/tools/merge_summaries.py+++ b/data_process/tools/merge_summaries.py@@ -85,7 +85,7 @@ def merge_summaries(output_dir, fps=30, keep_shards=False):af_path = os.path.join(output_dir, "clip_frames.json")frames = {}if os.path.isfile(af_path):- # Tolerate the legacy in-file summary block from older exports.+ # Ignore a "_summary" block embedded by older exporter versions.frames = {k: v for k, v in _load(af_path).items() if k != "_summary"}af_shards = sorted(glob.glob(os.path.join(output_dir, "clip_frames_worker*.json")))for shard in af_shards:diff --git a/data_process/tools/patch_annotations.py b/data_process/tools/patch_annotations.pynew file mode 100644index 0000000..fa7bab3--- /dev/null+++ b/data_process/tools/patch_annotations.py@@ -0,0 +1,744 @@+#!/usr/bin/env python3+"""Post-stage-3 QA patch for the export sidecars (joint labels, face pairs,+captions).++The stage-2/3 outputs are produced by rules plus LLM passes and were audited+by hand. This script applies the resulting corrections so that+they are reproducible on a fresh run of the pipeline and recorded in one+place. Two kinds of fixes:++ rules (in this file)+ - unsided ``Pelvis`` / ``Hip`` -> ``Hips`` (one label for the root pelvis+ bone across every rig; ``Left Hip`` / ``Right Hip`` are untouched);+ - numeric pass-through labels (``_2``, ``_1045``) -> ``Bone``;+ - numbered leg / claw-arm chains of the arthropod rigs get anatomical+ positions (Thigh, Shin, Foot, Toe ... / Upper Arm, Forearm, Hand, Claw)+ instead of ``Leg`` repeated along the chain;+ - rigs whose second side is a Blender/Maya duplicate (``LeftUpLeg.001``,+ ``Leg_L1``, ``UPLEG.001`` ...) get their side prefixes from the rest-pose+ X coordinate (+X = the character's left). About 6% of objaverse rigs face+ the other way, so this runs only on the hand-verified rigs listed below+ and, automatically, on rigs whose own side-carrying raw names confirm the+ orientation and where one sided label sits on both sides of the body+ (a duplicated chain) — there only that chain is relabelled;+ - the ``clean`` fields of face_joint_names.json are re-synced;+ - objaverse rigs are flagged in ``rig_flags.json``: automatically when the+ facing pair cannot be trusted (``source: empty``, a Bone/Bone pair, a body+ axis through unnamed bones), plus the hand-reviewed categories. Only+ ``tpose_wrong`` rigs are also written to ``filtered_objects.txt``, which+ stage 4 skips; every other flag is informational and the rig is kept;+ - caption grammar (``breaksdance`` -> ``breakdances``) and the per-dataset+ subject phrase;+ - locomotion qualifiers grounded in the root trajectory: ``<verb> forward``+ with no root travel -> ``<verb> in place``; ``<verb> in place`` with clear+ travel -> ``<verb> forward|backward`` when the travel is clearly along the+ facing axis (|cos| > 0.8 averaged over the clip), otherwise the qualifier+ is dropped (thresholds in body heights, see ``--still`` / ``--travel``).++ manual overrides (JSON files in ``--patch_dir``)+ <ds>_joint_labels.json {rig: {raw_joint_name: clean_label}}+ <ds>_face_pairs.json {rig: {"r_hip": raw, "l_hip": raw, "source": s,+ ["body_axis": true]}}+ <ds>_captions.json {clip: caption} (applied before the rules)+ <ds>_categories.json {rig: category} (moves the rig in category_groups.json)+ <ds>_filtered_clips.txt <clip> # <reason> (any dataset: individual clips ->+ export/<ds>/filtered_clips.txt, skipped by stage 4)+ <ds>_rig_flags.txt <rig> # <category>: <reason> (objaverse: hand-reviewed rig flags ->+ export/objaverse/rig_flags.json; only tpose_wrong also goes to+ export/objaverse/filtered_objects.txt, which stage 4 skips)++Usage (from the repo root; ``dataset/export/<ds>`` may be symlinks):+ python data_process/tools/patch_annotations.py [--dry_run] [--datasets truebones mixamo]+ python data_process/tools/patch_annotations.py --export_root dataset/export \\+ --patch_dir dataset/UniML3D/patches++Pure numpy; reads one NPZ per rig for the rest pose and every clip NPZ once+for the root trajectory (cached in ``<patch_dir>/.root_motion_cache.json``).+"""++import argparse+import glob+import json+import os+import re+from collections import Counter, OrderedDict++import numpy as np++DATASETS = ('truebones', 'mixamo', 'objaverse')+SUBJECT = {'truebones': 'An animal', 'mixamo': 'A person', 'objaverse': 'An object'}++# Rigs whose multi-segment legs / claw arms are labelled by chain position.+CHAIN_RIGS = {+ 'truebones': {+ 'Crab': {'Leg': ('Thigh', 'Shin', 'Foot', 'Toe'), 'Upper Arm': ('Upper Arm', 'Forearm', 'Hand', 'Claw')},+ 'HermitCrab': {'Leg': ('Thigh', 'Shin', 'Foot', 'Toe')},+ 'Isopetra': {'Leg': ('Thigh', 'Shin', 'Foot', 'Toe')},+ 'Spider': {'Leg': ('Thigh', 'Shin', 'Foot', 'Toe')},+ 'SpiderG': {'Leg': ('Thigh', 'Shin', 'Foot', 'Toe')},+ },+}+# Rigs whose second side was created by duplicating the first (same side word+# or no side word in the raw names): side prefixes come from rest-pose X.+# Every rig here was checked to face +Z (so +X is its left) — by a foot->toe+# cue, by its own side-carrying raw names, or by its T-pose render.+X_SIDE_RIGS = {+ 'objaverse': (+ '630247504c4b4f4b9b5c0371d89338c0', # mixamorig:Left*.001 duplicates+ 'b9d748ccc31344e2966d3f8176aed656', # *Links / *Links.001 (Dutch "left")+ '669a872557bbceb71e864bc9_fbx', # Leg_L / Leg_L1+ '669a6d9b57bbceb71e65252f_gltf', # UPLEG / UPLEG.001 (unsided)+ '669a6f7f57bbceb71e679870_fbx', # UPLEG / UPLEG.001 (unsided)+ '669a66c457bbceb71e5c8274_fbx', # HIP_1 / HIP_2 (unsided)+ '669a858957bbceb71e84351d_fbx', # shoulder_R / shoulder_R1+ '7f37f239817f41a2ad21b5f77cd0ff65', # thigh.L / thigh.L.001+ '669a72e657bbceb71e6bfe20_fbx', # Lhand / Rhand (unsided labels; names agree with X)+ ),+}+# Automatic candidates for side_from_x: a sided label that occurs on BOTH+# sides of the body (a duplicated appendage / whisker / finger chain labelled+# with one side) on a rig whose own raw names confirm the +X = left+# orientation (agreement >= X_SIDE_MIN_AGREE over >= X_SIDE_MIN_JOINTS sided+# joints). Rigs facing the other way are left alone.+X_SIDE_MIN_AGREE = 0.9+X_SIDE_MIN_JOINTS = 6+_RAW_SIDE_L = ('l', 'left', 'links', 'gauche', 'lewa', 'izq')+_RAW_SIDE_R = ('r', 'right', 'rechts', 'droit', 'prawa', 'der')++CENTER_LABELS = {'Root', 'Hips', 'Pelvis', 'Spine', 'Chest', 'Body', 'Neck', 'Head', 'Head End',+ 'Jaw', 'Tail', 'Bone', 'Center', 'Root End', 'Bone End', 'Abdomen', 'Ribcage'}++NUMERIC_RE = re.compile(r'^_?\d+$')+LOCO_VERBS = ('walks|runs|trots|jogs|sprints|marches|gallops|crawls|slithers|swims|flies|hops|'+ 'bounds|scurries|waddles|limps|sneaks|strides|paddles|glides|dashes|skips|struts|'+ 'creeps|prowls|stalks|shuffles|scampers|canters|flutters|soars|hovers|strolls|'+ 'wanders|races')+FACING_COS = 0.8 # |cos(travel, facing)| needed to call travel forward / backward+LOCO_RE = re.compile(r'\b(%s)((?: \w+ly)?) (forward|in place)\b' % LOCO_VERBS)+++# ---------------------------------------------------------------------------+# Kinematics (numpy only; quaternions are w,x,y,z as written by the exporter)+# ---------------------------------------------------------------------------++def qmul(a, b):+ w1, x1, y1, z1 = a[..., 0], a[..., 1], a[..., 2], a[..., 3]+ w2, x2, y2, z2 = b[..., 0], b[..., 1], b[..., 2], b[..., 3]+ return np.stack([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2], -1)+++def qrot(q, v):+ qv = np.concatenate([np.zeros(v.shape[:-1] + (1,)), v], -1)+ return qmul(qmul(q, qv), q * np.array([1, -1, -1, -1]))[..., 1:]+++def fk(local_pos, local_rot, parents):+ n = len(parents)+ g = np.zeros((n, 3))+ gr = np.zeros((n, 4))+ for i in range(n):+ p = parents[i]+ if p < 0:+ g[i], gr[i] = local_pos[i], local_rot[i]+ else:+ g[i] = g[p] + qrot(gr[p], local_pos[i])+ gr[i] = qmul(gr[p], local_rot[i])+ return g+++def rest_global(d):+ return fk(d['rest_local_pos'], d['rest_local_rot'], d['parents'])+++def frame_global(d, t=0):+ return fk(d['anim_local_pos'][t], d['anim_local_rot'][t], d['parents'])+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def load_json(path, default=None):+ if not os.path.isfile(path):+ return default+ with open(path) as f:+ return json.load(f, object_pairs_hook=OrderedDict)+++def load_overrides(path):+ """Override JSON; keys starting with '_' (``_comment``) are documentation."""+ data = load_json(path, OrderedDict())+ return OrderedDict((k, v) for k, v in data.items() if not k.startswith('_'))+++def save_json(path, obj, dry_run):+ if dry_run:+ return+ tmp = path + '.tmp'+ with open(tmp, 'w') as f:+ json.dump(obj, f, indent=2, ensure_ascii=False)+ os.replace(tmp, path)+++def object_type_of(ds, clip):+ return 'mixamo' if ds == 'mixamo' else clip.split('-', 1)[0]+++def rig_npz(root, ds, rig):+ if ds == 'mixamo':+ files = sorted(glob.glob(os.path.join(root, 'motions', '*.npz')))+ else:+ files = sorted(glob.glob(os.path.join(root, 'motions', rig + '-*.npz')))+ return files[0] if files else None+++def split_side(label):+ m = re.match(r'^(Left|Right) (.+)$', label)+ return (m.group(1), m.group(2)) if m else ('', label)+++# ---------------------------------------------------------------------------+# Joint labels+# ---------------------------------------------------------------------------++def unify_root_labels(clean, stats):+ for rig, labels in clean.items():+ # a lone unsided 'Hip' is the pelvis; several unsided 'Hip' labels are+ # lateral hip bones (HIP_1 / HIP_2) and keep their base for side_from_x+ lone_hip = labels.count('Hip') == 1+ for i, lab in enumerate(labels):+ if lab == 'Pelvis' or (lab == 'Hip' and lone_hip):+ labels[i] = 'Hips'+ stats['pelvis->hips'] += 1+ elif NUMERIC_RE.match(lab):+ labels[i] = 'Bone'+ stats['numeric->bone'] += 1+++def relabel_chains(names, labels, parents, spec, stats):+ """Chains of identical '<Side> <Base>' labels get positional labels."""+ children = {i: [] for i in range(len(names))}+ for i, p in enumerate(parents):+ if p >= 0:+ children[p].append(i)+ for i in range(len(names)):+ side, base = split_side(labels[i])+ if base not in spec:+ continue+ p = parents[i]+ if p >= 0 and labels[p] == labels[i]:+ continue # not the chain root+ seq = spec[base]+ j, k = i, 0+ while True:+ labels[j] = (side + ' ' + seq[min(k, len(seq) - 1)]).strip()+ stats['chain-relabel'] += 1+ nxt = [c for c in children[j] if split_side(labels[c]) == (side, base)]+ if len(nxt) != 1:+ break+ j, k = nxt[0], k + 1+++def raw_side(name):+ """'L' / 'R' when a raw joint name carries a side token, else None."""+ n = name.lower()+ for prefix in ('mixamorig:', 'bip01', 'bip001'):+ n = n.replace(prefix, '')+ toks = [t for t in re.split(r'[^a-z]+', n) if t]+ if any(t in _RAW_SIDE_L or t.startswith('left') for t in toks):+ return 'L'+ if any(t in _RAW_SIDE_R or t.startswith('right') for t in toks):+ return 'R'+ return None+++def needs_side_from_x(names, labels, d):+ """Base labels that sit on both sides of the body (a duplicated chain+ labelled with one side), or None — only for rigs whose raw names+ confirm the +X = left orientation."""+ g = rest_global(d)+ height = float(np.ptp(g, axis=0).max()) or 1.0+ x = (g[:, 0] - g[0, 0]) / height+ agree = total = 0+ seen = {}+ for i, (raw, lab) in enumerate(zip(names, labels)):+ if abs(x[i]) < 0.03:+ continue+ side, base = split_side(lab)+ if side:+ key = (side, base)+ seen.setdefault(key, set()).add(x[i] > 0)+ rs = raw_side(raw)+ if rs:+ total += 1+ agree += int((rs == 'L') == (x[i] > 0))+ both = {base for (_, base), v in seen.items() if len(v) == 2}+ if not both or total < X_SIDE_MIN_JOINTS:+ return None+ return both if agree / total >= X_SIDE_MIN_AGREE else None+++def side_from_x(labels, d, stats, only_bases=None, min_dx=0.03):+ """+X = left, -X = right (rest pose); joints near the midline keep their label.++ ``only_bases`` restricts the relabel to those base labels (the duplicated+ chains of an auto-detected rig); the explicit rigs relabel every+ off-centre joint.+ """+ g = rest_global(d)+ height = float(np.ptp(g, axis=0).max()) or 1.0+ x0 = g[0, 0]+ for i, lab in enumerate(labels):+ _, base = split_side(lab)+ if base in CENTER_LABELS or (only_bases is not None and base not in only_bases):+ continue+ dx = (g[i, 0] - x0) / height+ if abs(dx) < min_dx:+ continue+ new = ('Left ' if dx > 0 else 'Right ') + base+ if new != lab:+ labels[i] = new+ stats['side-from-x'] += 1+++def patch_joint_labels(ds, root, clean, names, overrides, stats, log):+ unify_root_labels(clean, stats)+ for rig, spec in CHAIN_RIGS.get(ds, {}).items():+ if rig not in clean:+ continue+ f = rig_npz(root, ds, rig)+ if not f:+ log.append(f'[{ds}] {rig}: no NPZ, chain relabel skipped')+ continue+ relabel_chains(names[rig], clean[rig], np.load(f, allow_pickle=True)['parents'], spec, stats)+ explicit = set(X_SIDE_RIGS.get(ds, ()))+ for rig in sorted(explicit):+ if rig not in clean:+ continue+ f = rig_npz(root, ds, rig)+ if not f:+ log.append(f'[{ds}] {rig}: no NPZ, side-from-x skipped')+ continue+ side_from_x(clean[rig], np.load(f, allow_pickle=True), stats)+ if ds == 'objaverse': # auto: duplicated-side chains on rigs that face +Z per their names+ for rig in clean:+ if rig in explicit:+ continue+ f = rig_npz(root, ds, rig)+ if not f:+ continue+ d = np.load(f, allow_pickle=True)+ bases = needs_side_from_x(names[rig], clean[rig], d)+ if bases:+ stats['side-from-x-auto-rig'] += 1+ side_from_x(clean[rig], d, stats, only_bases=bases, min_dx=0.05)+ for rig, mapping in (overrides or {}).items():+ if rig not in clean:+ log.append(f'[{ds}] override for unknown rig {rig!r} ignored')+ continue+ for raw, label in mapping.items():+ if raw not in names[rig]:+ log.append(f'[{ds}] {rig}: override for unknown joint {raw!r} ignored')+ continue+ idx = names[rig].index(raw)+ if clean[rig][idx] != label:+ clean[rig][idx] = label+ stats['manual-label'] += 1+++# ---------------------------------------------------------------------------+# Face pairs+# ---------------------------------------------------------------------------++def unreliable_facing(entry):+ if not entry or entry.get('source') == 'empty' or not entry['r_hip']['raw']:+ return 'empty'+ r, l = entry['r_hip']['clean'], entry['l_hip']['clean']+ if r == l == 'Bone':+ return 'bone/bone pair'+ if entry.get('body_axis') and ('Bone' in (r, l)):+ return 'body axis through unnamed bones'+ return ''+++def patch_face_pairs(ds, face, clean, names, overrides, stats, log):+ for rig, spec in (overrides or {}).items():+ if rig not in names:+ log.append(f'[{ds}] face override for unknown rig {rig!r} ignored')+ continue+ entry = OrderedDict()+ for key in ('r_hip', 'l_hip'):+ raw = spec[key]+ if raw not in names[rig]:+ raise SystemExit(f'[{ds}] {rig}: face override joint {raw!r} not in rig')+ entry[key] = {'raw': raw, 'clean': ''}+ entry['source'] = spec.get('source', 'manual')+ if spec.get('body_axis'):+ entry['body_axis'] = True+ face[rig] = entry+ stats['manual-face-pair'] += 1+ # re-sync clean labels+ for rig, entry in face.items():+ if rig not in names or not entry.get('r_hip', {}).get('raw'):+ continue+ for key in ('r_hip', 'l_hip'):+ raw = entry[key]['raw']+ if raw in names[rig]:+ new = clean[rig][names[rig].index(raw)]+ if entry[key].get('clean') != new:+ entry[key]['clean'] = new+ stats['face-clean-resync'] += 1+++# Rig flag categories. Only FILTER_CATEGORIES end up in filtered_objects.txt (stage 4 skips+# them); every other category is just recorded in rig_flags.json.+AUTO_FLAG = {'empty': 'empty_pair', 'bone/bone pair': 'bone_pair',+ 'body axis through unnamed bones': 'body_axis_unnamed'}+FILTER_CATEGORIES = ('tpose_wrong',)+++def load_rig_flags(path, names, log):+ """``patches/<ds>_rig_flags.txt``: one ``<rig> # <category>: <reason>`` per line — hand-reviewed+ rigs (``tpose_wrong`` = rest pose lying / rotated, ``facing_wrong`` = the facing pair does not give the+ real front, ``object_no_front`` = prop without a front, ``verified_ok`` = hand-checked, clears an automatic+ flag). Unknown rigs are reported and ignored."""+ out = OrderedDict()+ if not os.path.isfile(path):+ return out+ with open(path) as f:+ for line in f:+ body, _, comment = line.partition('#')+ rig = body.strip()+ if not rig:+ continue+ if rig not in names:+ log.append(f'[objaverse] rig flag for unknown rig {rig!r} ignored')+ continue+ cat, _, reason = comment.strip().partition(':')+ out[rig] = (cat.strip() or 'flagged', reason.strip())+ return out+++def write_filtered_clips(ds, root, patch_dir, frames, dry_run, log):+ """export/<ds>/filtered_clips.txt — hand-reviewed individual clips that stage 4 skips.++ Every dataset may have one: stage 4 applies the clip list before it groups+ clips into object types, so it is not objaverse-only the way+ filtered_objects.txt is. patches/<ds>_filtered_clips.txt holds+ ``<clip stem> # <reason>`` lines (motion discontinuity, skeletons that+ disagree with the object's reference rig, and anything else reviewed by hand).+ """+ src = os.path.join(patch_dir, f'{ds}_filtered_clips.txt')+ path = os.path.join(root, 'filtered_clips.txt')+ if not os.path.isfile(src):+ return {}+ clips = OrderedDict()+ with open(src) as f:+ for line in f:+ body, _, comment = line.partition('#')+ clip = body.strip()+ if not clip:+ continue+ if frames and clip not in frames:+ log.append(f'[{ds}] filtered clip {clip!r} is not in clip_frames.json; kept anyway')+ clips[clip] = comment.strip()+ lines = ['# Individual export clips skipped by stage 4 (extract_features.py reads this file',+ '# automatically; --filtered_clips auto). The clip-level twin of filtered_objects.txt.',+ f'# Generated by data_process/tools/patch_annotations.py from '+ f'patches/{ds}_filtered_clips.txt — {len(clips)} clips.',+ '# Delete this file to keep them (they then go through the stage-4 quality checks only).']+ for clip, why in clips.items():+ lines.append(f'{clip} # {why}' if why else clip)+ if not dry_run:+ with open(path, 'w') as f:+ f.write('\n'.join(lines) + '\n')+ kinds = Counter(w.split(':')[0] for w in clips.values())+ log.append(f'[{ds}] filtered_clips.txt: {len(clips)} clips ({kinds.most_common()})')+ return clips+++def write_rig_flags(root, face, frames, manual, dry_run, log):+ """rig_flags.json (every flagged rig with its category) + filtered_objects.txt (FILTER_CATEGORIES only)."""+ flags = OrderedDict()+ for rig, entry in face.items():+ why = unreliable_facing(entry)+ if why:+ flags[rig] = {'category': AUTO_FLAG.get(why, why), 'reason': why, 'origin': 'auto'}+ verified = OrderedDict()+ for rig, (cat, reason) in (manual or {}).items():+ if cat == 'verified_ok': # hand-checked: drop any automatic flag+ verified[rig] = reason+ flags.pop(rig, None)+ continue+ flags[rig] = {'category': cat, 'reason': reason, 'origin': 'manual'}+ cats = OrderedDict()+ for rig, fl in sorted(flags.items()):+ cats.setdefault(fl['category'], []).append(rig)+ bad = OrderedDict((rig, fl) for rig, fl in flags.items() if fl['category'] in FILTER_CATEGORIES)+ clips = [c for c in frames if object_type_of('objaverse', c) in bad]+ out = OrderedDict([+ ('_comment', 'Per-rig flags. Automatic facing checks (empty_pair: no bilateral joint pair; '+ 'bone_pair: the pair consists of unnamed Bone joints; body_axis_unnamed) plus the '+ 'hand-reviewed categories (tpose_wrong: the exported rest pose is unusable; facing_wrong: '+ 'the pair does not give the real front). Only ' + ', '.join(FILTER_CATEGORIES) ++ ' is written to filtered_objects.txt, which stage 4 skips; every other flag is '+ 'informational and those rigs are kept. verified_ok lists rigs whose automatic flag was '+ 'cleared after review.'),+ ('filtered', list(FILTER_CATEGORIES)),+ ('counts', OrderedDict((c, len(r)) for c, r in cats.items())),+ ('categories', cats),+ ('rigs', OrderedDict(sorted(flags.items()))),+ ('verified_ok', verified), # automatic flags cleared by hand review+ ])+ lines = ['# Object types skipped by stage 4 (extract_features.py reads this file automatically):',+ '# rigs flagged ' + ' / '.join(FILTER_CATEGORIES) + ' in patches/objaverse_rig_flags.txt — the exported',+ '# rest pose lies flat / is rotated / upside-down, so the stage-4 T-pose is unusable.',+ '# Other flags (empty_pair, bone_pair, facing_wrong, object_no_front, ...) are recorded in',+ '# rig_flags.json only and are NOT filtered.',+ f'# Generated by data_process/tools/patch_annotations.py — {len(bad)} rigs, {len(clips)} clips.',+ '# Delete this file to keep them (they then get the rest-pose facing as exported).']+ for rig, fl in bad.items():+ lines.append(f"{rig} # {fl['category']}: {fl['reason']}")+ if not dry_run:+ with open(os.path.join(root, 'rig_flags.json'), 'w') as f:+ json.dump(out, f, indent=1)+ with open(os.path.join(root, 'filtered_objects.txt'), 'w') as f:+ f.write('\n'.join(lines) + '\n')+ log.append(f'[objaverse] rig_flags.json: {dict(out["counts"])} (+{len(verified)} verified_ok); filtered_objects.txt: '+ f'{len(bad)} rigs / {len(clips)} clips ({", ".join(FILTER_CATEGORIES)})')+ return bad+++# ---------------------------------------------------------------------------+# Body-plan categories+# ---------------------------------------------------------------------------++def patch_categories(ds, groups, overrides, names, stats, log):+ """Move rigs between the {category: [rigs]} buckets of category_groups.json."""+ for rig, cat in (overrides or {}).items():+ if rig not in names:+ log.append(f'[{ds}] category override for unknown rig {rig!r} ignored')+ continue+ current = next((c for c, members in groups.items() if rig in members), None)+ if current == cat:+ continue+ if current is not None:+ groups[current].remove(rig)+ groups.setdefault(cat, []).append(rig)+ groups[cat].sort()+ stats['manual-category'] += 1+ for cat in [c for c, members in groups.items() if not members]:+ del groups[cat]+++# ---------------------------------------------------------------------------+# Captions+# ---------------------------------------------------------------------------++def root_motion(root, ds, clips, cache_path, face, log):+ """Per clip: net XZ root displacement in body heights and the travel+ direction relative to the facing pair at frame 0."""+ cache = load_json(cache_path, OrderedDict()) if cache_path else OrderedDict()+ key = lambda c: f'{ds}/{c}'+ todo = [c for c in clips if key(c) not in cache]+ if todo:+ log.append(f'[{ds}] computing root motion for {len(todo)} clips')+ for n, clip in enumerate(todo, 1):+ f = os.path.join(root, 'motions', clip + '.npz')+ if not os.path.isfile(f):+ continue+ d = np.load(f, allow_pickle=True)+ g0 = rest_global(d)+ height = float(np.ptp(g0, axis=0).max()) or 1.0+ r = d['anim_local_pos'][:, 0, :]+ disp = r[-1] - r[0]+ net = float(np.hypot(disp[0], disp[2]) / height)+ direction = ''+ rig = object_type_of(ds, clip)+ entry = face.get(rig)+ if net > 0 and entry and not unreliable_facing(entry):+ nm = list(d['names'])+ try:+ ri, li = nm.index(entry['r_hip']['raw']), nm.index(entry['l_hip']['raw'])+ dxz = np.array([disp[0], 0.0, disp[2]]) / (np.hypot(disp[0], disp[2]) or 1.0)+ cos = []+ nf = len(r)+ for t in range(0, nf, max(1, nf // 8)): # facing averaged over the clip+ gf = frame_global(d, t)+ if entry.get('body_axis'):+ fwd = gf[ri] - gf[li] # head - tail+ else:+ fwd = np.cross(gf[li] - gf[ri], [0.0, 1.0, 0.0]) # left x up+ fwd[1] = 0.0+ if np.linalg.norm(fwd) > 1e-6:+ cos.append(float(np.dot(dxz, fwd / np.linalg.norm(fwd))))+ if cos:+ c = float(np.mean(cos))+ # Strict: only a clear along-axis travel gets a word. Sideways or+ # twisted-pelvis gaits (strafes) are left unqualified.+ if c > FACING_COS:+ direction = 'forward'+ elif c < -FACING_COS:+ direction = 'backward'+ except ValueError:+ pass+ cache[key(clip)] = {'net': round(net, 3), 'dir': direction}+ if cache_path and (n % 500 == 0 or n == len(todo)): # derived data: cached even on --dry_run+ save_json(cache_path, cache, False)+ return {c: cache[key(c)] for c in clips if key(c) in cache}+++def normalize_locomotion(caption, motion, still, travel, stats):+ if not motion:+ return caption++ def repl(m):+ verb, adv, qual = m.group(1), m.group(2), m.group(3)+ net, direction = motion['net'], motion['dir']+ if qual == 'forward' and net < still:+ stats['forward->in place'] += 1+ return f'{verb}{adv} in place'+ if qual == 'in place' and net >= travel:+ if direction:+ stats[f'in place->{direction}'] += 1+ return f'{verb}{adv} {direction}'+ stats['in place->(dropped)'] += 1+ return f'{verb}{adv}'+ return m.group(0)++ return LOCO_RE.sub(repl, caption)+++def patch_captions(ds, caps, overrides, motion, args, stats, log):+ subject = SUBJECT[ds]+ for clip, text in (overrides or {}).items():+ if clip not in caps:+ log.append(f'[{ds}] caption override for unknown clip {clip!r} ignored')+ continue+ if caps[clip] != text:+ caps[clip] = text+ stats['manual-caption'] += 1+ for clip, text in caps.items():+ new = text.strip()+ new = re.sub(r'\bbreaksdance\b', 'breakdances', new)+ if not new.startswith(subject):+ fixed = re.sub(r'^(?:An?|The) [A-Za-z-]+\b', subject, new, count=1)+ if fixed.startswith(subject):+ new = fixed+ stats['subject-fixed'] += 1+ else:+ log.append(f'[{ds}] {clip}: caption does not start with {subject!r}: {new!r}')+ new = re.sub(r'\s+', ' ', new)+ if new and not new.endswith('.'):+ new += '.'+ new = normalize_locomotion(new, motion.get(clip), args.still, args.travel, stats)+ if new != text:+ caps[clip] = new+ stats['caption-changed'] += 1+++# ---------------------------------------------------------------------------++def write_report(ds, report_dir, before, clean, face, caps, names, motion):+ """TSV of every change: kind, key, joint/-, old, new, note."""+ os.makedirs(report_dir, exist_ok=True)+ rows = []+ for rig, labels in clean.items():+ old = before['clean'].get(rig, [])+ for i, lab in enumerate(labels):+ if i < len(old) and old[i] != lab:+ rows.append(('label', rig, names[rig][i], old[i], lab, ''))+ for rig, entry in face.items():+ o = before['face'].get(rig)+ if o != entry:+ fmt = lambda e: f"{e['r_hip']['raw']} ({e['r_hip']['clean']}) / {e['l_hip']['raw']} ({e['l_hip']['clean']}) src={e.get('source')}" if e and e.get('r_hip') else str(e)+ rows.append(('face', rig, '-', fmt(o), fmt(entry), ''))+ for clip, text in caps.items():+ o = before['caps'].get(clip)+ if o != text:+ m = motion.get(clip, {})+ note = f"net={m.get('net')} dir={m.get('dir')}" if m else ''+ rows.append(('caption', clip, '-', o, text, note))+ path = os.path.join(report_dir, f'{ds}_changes.tsv')+ with open(path, 'w') as f:+ f.write('kind\tkey\tjoint\told\tnew\tnote\n')+ for r in rows:+ f.write('\t'.join(str(x) for x in r) + '\n')+ return path+++def run_dataset(ds, args, log):+ root = os.path.join(args.export_root, ds)+ names = load_json(os.path.join(root, 'joint_names.json'))+ clean = load_json(os.path.join(root, 'clean_joint_names.json'))+ face = load_json(os.path.join(root, 'face_joint_names.json'))+ caps = load_json(os.path.join(root, 'motion_captions.json'))+ groups = load_json(os.path.join(root, 'category_groups.json'))+ frames = load_json(os.path.join(root, 'clip_frames.json'), {})+ if names is None or clean is None:+ log.append(f'[{ds}] no joint_names/clean_joint_names under {root}; skipped')+ return+ pd = args.patch_dir+ stats = Counter()+ before = {'clean': json.loads(json.dumps(clean)), 'face': json.loads(json.dumps(face)) if face else {},+ 'caps': dict(caps) if caps else {}}++ patch_joint_labels(ds, root, clean, names, load_overrides(os.path.join(pd, f'{ds}_joint_labels.json')), stats, log)+ if face is not None:+ patch_face_pairs(ds, face, clean, names, load_overrides(os.path.join(pd, f'{ds}_face_pairs.json')), stats, log)+ if ds == 'objaverse':+ manual = load_rig_flags(os.path.join(pd, f'{ds}_rig_flags.txt'), names, log)+ write_rig_flags(root, face, frames, manual, args.dry_run, log)+ stats['manual-rig-flag'] += len(manual)+ stats['manual-filtered-clip'] += len(+ write_filtered_clips(ds, root, pd, frames, args.dry_run, log))+ if groups is not None:+ patch_categories(ds, groups, load_overrides(os.path.join(pd, f'{ds}_categories.json')), names, stats, log)+ if caps is not None:+ motion = root_motion(root, ds, list(caps), os.path.join(pd, '.root_motion_cache.json'),+ face or {}, log) if not args.skip_locomotion else {}+ patch_captions(ds, caps, load_overrides(os.path.join(pd, f'{ds}_captions.json')), motion, args, stats, log)++ save_json(os.path.join(root, 'clean_joint_names.json'), clean, args.dry_run)+ if face is not None:+ save_json(os.path.join(root, 'face_joint_names.json'), face, args.dry_run)+ if caps is not None:+ save_json(os.path.join(root, 'motion_captions.json'), caps, args.dry_run)+ if groups is not None:+ save_json(os.path.join(root, 'category_groups.json'), groups, args.dry_run)+ if args.report_dir:+ write_report(ds, args.report_dir, before, clean, face or {}, caps or {}, names,+ motion if caps is not None and not args.skip_locomotion else {})+ log.append(f'[{ds}] ' + ', '.join(f'{k}={v}' for k, v in sorted(stats.items())))+++def main():+ here = os.path.dirname(os.path.abspath(__file__))+ repo = os.path.abspath(os.path.join(here, '..', '..'))+ ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])+ ap.add_argument('--export_root', default=os.path.join(repo, 'dataset', 'export'))+ ap.add_argument('--patch_dir', default=os.path.join(repo, 'dataset', 'UniML3D', 'patches'))+ ap.add_argument('--datasets', nargs='+', default=list(DATASETS))+ ap.add_argument('--still', type=float, default=0.15,+ help='net root XZ travel (body heights) below which locomotion is "in place"')+ ap.add_argument('--travel', type=float, default=0.5,+ help='net root XZ travel (body heights) above which "in place" is replaced')+ ap.add_argument('--skip_locomotion', action='store_true', help='do not touch forward/in place')+ ap.add_argument('--report_dir', default=None,+ help='write <ds>_changes.tsv (every label / face / caption change) here')+ ap.add_argument('--dry_run', action='store_true', help='report only, write nothing')+ args = ap.parse_args()+ os.makedirs(args.patch_dir, exist_ok=True)+ log = []+ for ds in args.datasets:+ run_dataset(ds, args, log)+ print('\n'.join(log))+ if args.dry_run:+ print('(dry run — nothing written)')+++if __name__ == '__main__':+ main()diff --git a/data_process/tools/truebones_fbx2glb.py b/data_process/tools/truebones_fbx2glb.pyindex b93386f..06214ae 100644--- a/data_process/tools/truebones_fbx2glb.py+++ b/data_process/tools/truebones_fbx2glb.py@@ -11,7 +11,6 @@ Usage (Blender headless):--output_dir dataset/raw/truebones/animation_glb"""-import argparseimport osimport sys@@ -21,6 +20,7 @@ from loguru import loggersys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))from data_process.utils.blender_export import import_fbx, reset_scene+from data_process.utils.fbx2glb import parse_batch_args, run_batchdef convert_fbx_to_glb(fbx_path, glb_path):@@ -74,54 +74,6 @@ def convert_fbx_to_glb(fbx_path, glb_path):logger.info(f"Saved animated GLB: {glb_path}")-def parse_args():- parser = argparse.ArgumentParser(- description="Convert curated Truebones per-clip FBX files to GLB, one to one.")- parser.add_argument('--data_dir', type=str, required=True,- help='Flat directory of per-clip {Species}-{Action}.fbx files.')- parser.add_argument('--output_dir', type=str, required=True,- help='Destination directory for the per-clip GLB files.')- parser.add_argument('--worker_id', type=int, default=0,- help='Worker index for sharding across workers.')- parser.add_argument('--num_workers', type=int, default=1,- help='Total number of workers.')- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]- return parser.parse_args(argv)--if __name__ == "__main__":- args = parse_args()-- fbx_files = sorted(f for f in os.listdir(args.data_dir)- if f.lower().endswith('.fbx'))- logger.info(f"Found {len(fbx_files)} FBX clips in {args.data_dir}")-- if args.num_workers > 1:- fbx_files = fbx_files[args.worker_id::args.num_workers]- logger.info(f"Worker {args.worker_id}/{args.num_workers}: {len(fbx_files)} files")-- os.makedirs(args.output_dir, exist_ok=True)- error_log = os.path.join(args.output_dir,- f'fbx2glb_errors_worker{args.worker_id}.log')-- n_ok = n_skip = n_fail = 0- for fbx_file in fbx_files:- glb_path = os.path.join(args.output_dir,- os.path.splitext(fbx_file)[0] + '.glb')- if os.path.exists(glb_path):- n_skip += 1- continue- try:- convert_fbx_to_glb(os.path.join(args.data_dir, fbx_file), glb_path)- n_ok += 1- except Exception as e: # noqa: BLE001 — keep the batch going- logger.error(f"Failed to convert {fbx_file}: {e}")- with open(error_log, 'a') as f:- f.write(f"{fbx_file}\t{e}\n")- n_fail += 1-- logger.info(f"Done: {n_ok} converted, {n_skip} skipped, {n_fail} failed "- f"-> {args.output_dir}")-- if n_fail:- sys.exit(1)+ run_batch(parse_batch_args("Convert curated Truebones per-clip FBX files to GLB, one to one."),+ convert_fbx_to_glb, unit='FBX clips')diff --git a/data_process/tools/vis_clip_frames.py b/data_process/tools/vis_clip_frames.pynew file mode 100644index 0000000..f8efd3c--- /dev/null+++ b/data_process/tools/vis_clip_frames.py@@ -0,0 +1,304 @@+"""Plot the per-clip frame-count distribution of ``clip_frames.json`` files.++Stage 1 writes ``<export_dir>/clip_frames.json`` — a flat ``{clip_name:+nframes}`` map (see :func:`data_process.utils.blender_export.write_clip_frames_json`).+This tool turns one or more of those files into paper-style distribution+figures plus a summary table, so clip-length settings — stage 4's+``--max_clip_len`` and the training ``max_motion_length`` of 60 / 90 / 120+frames — can be checked against the data instead of guessed.++Read-only: the JSON inputs are never modified. Styling follows the other+dataset-statistics figures (see :mod:`data_process.utils.dist_plot`).++Outputs:++ * ``<export_dir>/clip_frames_distribution.png`` — per file, written next+ to its JSON (PNG only) so every export directory carries its own+ clip-length figure; the name is the JSON stem plus ``_distribution``+ (``clip_frames_worker3.json`` → ``clip_frames_worker3_distribution.png``).+ Two panels:+ - histogram of frames per clip as a proportion of the file's clips+ (log-x by default — frame counts are heavy-tailed), with a kernel+ density estimate and mean / median guides;+ - the survival curve "share of clips with at least N frames", with+ the threshold frame counts marked and the share labeled at each.+ ``--per_dataset_dir DIR`` collects them in one directory instead, as+ ``DIR/<label>_clip_frames_distribution.{png,pdf}``.+ * ``<output_dir>/clip_frames_distribution_comparison.{png,pdf}`` — when+ several files are given: the kernel densities and survival curves of+ every dataset overlaid, each normalized to its own clip count so a+ 10k-clip set doesn't swamp a 1k-clip one.+ * ``<output_dir>/clip_frames_summary.json`` — the numbers behind the plots+ (percentiles, totals, per-threshold counts and shares), also printed as+ a table.++``<label>`` is the export directory name for a canonical ``clip_frames.json``+(``dataset/export/truebones/clip_frames.json`` → ``truebones``) and the file+stem otherwise (``clip_frames_worker3.json`` → ``clip_frames_worker3``). The+frame rate used to express thresholds in seconds is read from the sibling+``summary.json`` when present, else ``--fps``.++Usage:+ python -m data_process.tools.vis_clip_frames # every dataset/export/*/clip_frames.json+ python -m data_process.tools.vis_clip_frames dataset/export/truebones+ python -m data_process.tools.vis_clip_frames a/clip_frames.json b/clip_frames.json \\+ --thresholds 60,120 --per_dataset_dir outputs/clip_frames_vis --no-pdf+"""++import argparse+import json+import os++import numpy as np++from data_process.utils import dist_plot as dp+++DEFAULT_GLOB = 'dataset/export/*/clip_frames.json'+DEFAULT_OUTPUT_DIR = 'outputs/clip_frames_vis'+FILENAME = 'clip_frames.json'+SUFFIX = 'distribution'+DEFAULT_THRESHOLDS = '60,90,120,200' # training max_motion_length options + stage-4 max_clip_len+DEFAULT_FPS = 30+++# ---------------------------------------------------------------------------+# Statistics+# ---------------------------------------------------------------------------++def summarize(frames, fps, thresholds):+ total = int(frames.sum())+ stats = {'n_clips': int(frames.size)}+ stats.update(dp.percentile_stats(frames))+ stats.update({+ 'total_frames': total,+ 'fps': fps,+ 'duration_min': total / fps / 60.0,+ # Share of clips at least N frames long: the fraction usable at a+ # given max_motion_length without padding.+ 'at_least': {+ str(t): {'count': int((frames >= t).sum()),+ 'share': float((frames >= t).mean())}+ for t in thresholds+ },+ })+ return stats+++def print_table(stats_by_label, thresholds):+ cols = ['clips', 'min', 'p10', 'median', 'mean', 'p90', 'max', 'minutes']+ cols += [f'>={t}f' for t in thresholds]+ width = max(len(lab) for lab in stats_by_label)+ print(f'{"dataset":<{width}} ' + ' '.join(f'{c:>8}' for c in cols))+ for lab, s in stats_by_label.items():+ row = [f'{s["n_clips"]:,}', f'{s["min"]}', f'{s["p10"]:.0f}',+ f'{s["median"]:.0f}', f'{s["mean"]:.1f}', f'{s["p90"]:.0f}',+ f'{s["max"]:,}', f'{s["duration_min"]:.1f}']+ row += [f'{s["at_least"][str(t)]["share"]:.1%}' for t in thresholds]+ print(f'{lab:<{width}} ' + ' '.join(f'{c:>8}' for c in row))+++# ---------------------------------------------------------------------------+# Figures+# ---------------------------------------------------------------------------++def _xlabel(fps, log_x):+ return f'Frames per clip ({fps} fps' + (', log scale)' if log_x else ')')+++def _threshold_label(fps):+ return lambda t: f'{t} f · {t / fps:g} s'+++def plot_dataset(label, frames, fps, stats, thresholds, bins, log_x, out_base, pdf):+ """Histogram + KDE + mean/median guides, and the survival curve with+ threshold guides, for one clip_frames.json."""+ fig, (ax_h, ax_s) = dp.two_panel_figure()+ lo, hi = dp.value_range(frames, log_x)+ edges = dp.even_bins(lo, hi, bins, log_x)+ shown = [t for t in thresholds if lo <= t <= hi]++ # ---- Histogram (proportion of clips) + kernel density ----+ counts, _ = np.histogram(frames, bins=edges)+ props = counts / frames.size+ widths = np.diff(edges)+ ax_h.bar(edges[:-1] + 0.04 * widths, props, width=0.92 * widths, align='edge',+ color=dp.ACCENT, edgecolor='white', linewidth=0.6, alpha=0.92,+ label='Histogram', zorder=2)+ grid = dp.kde_grid(lo, hi, log_x)+ bin_width = float(np.diff(dp.to_axis(edges[:2], log_x))[0])+ kde = dp.kde_proportion(frames, grid, bin_width, log_x)+ y_top = props.max()+ if kde is not None:+ ax_h.fill_between(grid, kde, color=dp.ACCENT_FL, alpha=0.30, linewidth=0, zorder=1)+ ax_h.plot(grid, kde, color=dp.ACCENT_DK, linewidth=1.8, solid_capstyle='round',+ label='Kernel density', zorder=3)+ y_top = max(y_top, float(kde.max()))+ ax_h.set_ylim(0, y_top * dp.HEADROOM)+ dp.style_axes(ax_h)+ dp.value_axis(ax_h, lo, hi, log_x, _xlabel(fps, log_x))+ dp.pct_axis(ax_h)+ ax_h.set_ylabel('Proportion of clips')+ dp.mean_median_guides(ax_h, stats['mean'], stats['median'])+ ax_h.legend(loc=dp.legend_loc_clear_of(ax_h, (stats['mean'], stats['median'])),+ borderaxespad=0.6, handlelength=1.8)++ # ---- Survival: share of clips with at least N frames ----+ xs, ys, where = dp.survival_curve(frames, span=(lo, hi))+ ax_s.fill_between(xs, ys, step=where, color=dp.ACCENT_FL, alpha=0.30,+ linewidth=0, zorder=1)+ ax_s.step(xs, ys, where=where, color=dp.ACCENT_DK, linewidth=1.8,+ solid_capstyle='round', solid_joinstyle='round', zorder=3)+ ax_s.set_ylim(0, 1.06)+ dp.style_axes(ax_s)+ dp.value_axis(ax_s, lo, hi, log_x, _xlabel(fps, log_x))+ dp.pct_axis(ax_s)+ ax_s.set_ylabel('Share of clips with ≥ N frames')+ shares = {t: stats['at_least'][str(t)]['share'] for t in shown}+ dp.threshold_guides(ax_s, shown, _threshold_label(fps),+ at_bottom=dp.crowded_top(shares.get, shown))+ dp.mark_points(ax_s, [(t, shares[t]) for t in shown])++ subtitle = (f'{stats["n_clips"]:,} clips · median {stats["median"]:.0f} frames'+ f' · range {stats["min"]}–{stats["max"]:,}'+ f' · {stats["duration_min"]:.1f} min at {fps} fps')+ return dp.finish_figure(fig, f'Distribution of Clip Lengths — {dp.display_name(label)}',+ subtitle, out_base, pdf)+++def plot_comparison(datasets, thresholds, bins, log_x, out_base, pdf):+ """Overlay several datasets: kernel densities (proportion per bin) and+ survival curves, each normalized to its own clip count.++ ``datasets`` is ``[(label, frames, fps), ...]``; one categorical hue per+ dataset, in input order.+ """+ fig, (ax_k, ax_s) = dp.two_panel_figure()+ all_frames = np.concatenate([f for _, f, _ in datasets])+ lo, hi = dp.value_range(all_frames, log_x)+ edges = dp.even_bins(lo, hi, bins, log_x)+ shown = [t for t in thresholds if lo <= t <= hi]+ fps_set = sorted({fps for _, _, fps in datasets})+ fps_label = fps_set[0] if len(fps_set) == 1 else '/'.join(map(str, fps_set))++ grid = dp.kde_grid(lo, hi, log_x)+ bin_width = float(np.diff(dp.to_axis(edges[:2], log_x))[0])+ y_top = 0.0+ for i, (label, frames, _) in enumerate(datasets):+ color = dp.SERIES[i]+ name = dp.display_name(label)+ kde = dp.kde_proportion(frames, grid, bin_width, log_x)+ if kde is not None:+ ax_k.fill_between(grid, kde, color=color, alpha=0.12, linewidth=0, zorder=1)+ ax_k.plot(grid, kde, color=color, linewidth=1.8, solid_capstyle='round',+ label=name, zorder=3)+ y_top = max(y_top, float(kde.max()))+ xs, ys, where = dp.survival_curve(frames, span=(lo, hi))+ ax_s.step(xs, ys, where=where, color=color, linewidth=1.8, label=name,+ solid_capstyle='round', solid_joinstyle='round', zorder=3)++ ax_k.set_ylim(0, (y_top or 1.0) * dp.HEADROOM)+ dp.style_axes(ax_k)+ dp.value_axis(ax_k, lo, hi, log_x, _xlabel(fps_label, log_x))+ dp.pct_axis(ax_k)+ ax_k.set_ylabel(f'Proportion of clips per bin ({bins} bins)')++ ax_s.set_ylim(0, 1.06)+ dp.style_axes(ax_s)+ dp.value_axis(ax_s, lo, hi, log_x, _xlabel(fps_label, log_x))+ dp.pct_axis(ax_s)+ ax_s.set_ylabel('Share of clips with ≥ N frames')+ crowded = dp.crowded_top(+ lambda t: max(float((f >= t).mean()) for _, f, _ in datasets), shown)+ fmt = _threshold_label(fps_set[0]) if len(fps_set) == 1 else (lambda t: f'{t} f')+ dp.threshold_guides(ax_s, shown, fmt, at_bottom=crowded)+ # Every dataset has a survival step (a density needs >= 2 distinct+ # values), so the legend lives on this panel.+ ax_s.legend(loc='upper right', borderaxespad=0.6, handlelength=1.8)++ subtitle = (f'{len(datasets)} datasets · {all_frames.size:,} clips · '+ + ' · '.join(f'{dp.display_name(lab)} {f.size:,}' for lab, f, _ in datasets))+ return dp.finish_figure(fig, 'Distribution of Clip Lengths across Datasets', subtitle,+ out_base, pdf)+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------++def parse_args():+ parser = argparse.ArgumentParser(+ description='Plot the per-clip frame-count distribution of export-stage '+ 'clip_frames.json files.')+ parser.add_argument('inputs', nargs='*',+ help='Export directories (containing clip_frames.json) or '+ f'clip_frames*.json paths. Default: {DEFAULT_GLOB}')+ parser.add_argument('--output_dir', default=DEFAULT_OUTPUT_DIR,+ help='Where the comparison figure and the summary JSON go '+ f'(default: {DEFAULT_OUTPUT_DIR})')+ parser.add_argument('--per_dataset_dir', default=None,+ help='Collect the per-dataset figures in this directory as '+ '<label>_clip_frames_distribution.{png,pdf}. Default: write '+ 'each one as clip_frames_distribution.png next to its own '+ 'clip_frames.json.')+ parser.add_argument('--thresholds', default=DEFAULT_THRESHOLDS,+ help='Comma-separated frame counts to mark (default: '+ f'{DEFAULT_THRESHOLDS} — the training max_motion_length '+ 'options and stage-4 max_clip_len). Empty string disables.')+ parser.add_argument('--fps', type=int, default=DEFAULT_FPS,+ help='Frame rate for the seconds labels when no sibling '+ f'summary.json records one (default: {DEFAULT_FPS})')+ parser.add_argument('--bins', type=int, default=40,+ help='Histogram bin count (default: 40)')+ parser.add_argument('--linear', action='store_true',+ help='Linear frame axis instead of log scale')+ parser.add_argument('--no_comparison', action='store_true',+ help='Skip the overlaid comparison figure')+ parser.add_argument('--pdf', action=argparse.BooleanOptionalAction, default=True,+ help='Also write a PDF next to the comparison figure, and next '+ 'to the per-dataset figures when --per_dataset_dir is set '+ '(default: on; figures beside the JSONs are always PNG only)')+ return parser.parse_args()+++def main():+ args = parse_args()+ dp.configure_style()+ thresholds = dp.parse_int_list(args.thresholds, '--thresholds')+ paths = dp.resolve_inputs(args.inputs, FILENAME, DEFAULT_GLOB)+ labels = dp.unique_labels(paths, FILENAME)+ log_x = not args.linear+ os.makedirs(args.output_dir, exist_ok=True)++ datasets = []+ summary = {}+ for path, label in zip(paths, labels):+ frames = dp.load_int_map(path)+ fps = dp.sibling_json_field(path, 'summary.json', 'fps', args.fps)+ stats = summarize(frames, fps, thresholds)+ out_base, pdf_ok = dp.per_dataset_out_base(path, label, args.per_dataset_dir, SUFFIX)+ written = plot_dataset(label, frames, fps, stats, thresholds, args.bins,+ log_x, out_base, pdf_ok and args.pdf)+ print(f'[{label}] {frames.size:,} clips from {path} -> {", ".join(written)}')+ datasets.append((label, frames, fps))+ summary[label] = dict(stats, source=os.path.abspath(path))++ if len(datasets) > 1 and not args.no_comparison:+ if len(datasets) > len(dp.SERIES):+ print(f'Skipping the comparison figure: {len(datasets)} inputs exceed the '+ f'{len(dp.SERIES)} distinguishable series; compare in smaller groups.')+ else:+ written = plot_comparison(+ datasets, thresholds, args.bins, log_x,+ os.path.join(args.output_dir, 'clip_frames_distribution_comparison'), args.pdf)+ print(f'[comparison] {len(datasets)} datasets -> {", ".join(written)}')++ summary_path = os.path.join(args.output_dir, 'clip_frames_summary.json')+ with open(summary_path, 'w') as f:+ json.dump(summary, f, indent=2)+ print(f'Summary -> {summary_path}\n')+ print_table(summary, thresholds)+++if __name__ == '__main__':+ main()diff --git a/data_process/tools/vis_joint_count.py b/data_process/tools/vis_joint_count.pynew file mode 100644index 0000000..4cce62f--- /dev/null+++ b/data_process/tools/vis_joint_count.py@@ -0,0 +1,323 @@+"""Plot the joints-per-skeleton distribution of ``joint_count.json`` files.++Stage 1 writes ``<export_dir>/joint_count.json`` — a flat ``{object_type:+n_joints}`` map (see :func:`data_process.utils.blender_export.write_export_summary`),+one entry per exported skeleton after pruning. This tool turns one or more+of those files into paper-style distribution figures plus a summary table,+so the joint-count filters — stage 4's ``--min_joints`` / ``--max_joints``+and the training ``dataset.max_joints`` cap — can be checked against the+data instead of guessed.++Read-only: the JSON inputs are never modified. Styling follows the other+dataset-statistics figures (see :mod:`data_process.utils.dist_plot`).++Outputs:++ * ``<export_dir>/joint_count_distribution.png`` — per file, written next+ to its JSON (PNG only) so every export directory carries its own+ joint-count figure. Two panels:+ - histogram of joints per skeleton as a proportion of the file's+ skeletons, integer-aligned bins (width 1 / 2 / 3 by span), with a+ kernel density estimate and mean / median guides;+ - the cumulative curve "share of skeletons with at most N joints" —+ the fraction a ``max_joints`` cap keeps — with the threshold joint+ counts marked and the share labeled at each.+ ``--per_dataset_dir DIR`` collects them in one directory instead, as+ ``DIR/<label>_joint_count_distribution.{png,pdf}``.+ * ``<output_dir>/joint_count_distribution_comparison.{png,pdf}`` — when+ several files are given: the kernel densities and cumulative curves of+ every dataset overlaid, each normalized to its own skeleton count.+ * ``<output_dir>/joint_count_distribution_pooled.{png,pdf}`` — with+ ``--pooled``: every input's skeletons in one figure (the layout of the+ paper's joint-count figure).+ * ``<output_dir>/joint_count_summary.json`` — the numbers behind the plots+ (percentiles, per-threshold counts and shares), also printed as a table.++A single-skeleton file (mixamo) still gets its figure — one bar, no+density curve — so every export directory is covered.++Usage:+ python -m data_process.tools.vis_joint_count # every dataset/export/*/joint_count.json+ python -m data_process.tools.vis_joint_count dataset/export/objaverse+ python -m data_process.tools.vis_joint_count dataset/export/{truebones,objaverse} \\+ --thresholds 65 --clip_max 90 --pooled+"""++import argparse+import json+import os++import numpy as np++from data_process.utils import dist_plot as dp+++DEFAULT_GLOB = 'dataset/export/*/joint_count.json'+DEFAULT_OUTPUT_DIR = 'outputs/joint_count_vis'+FILENAME = 'joint_count.json'+SUFFIX = 'distribution'+# Stage-4 default --min_joints, the training dataset.max_joints cap, and the+# plotting cap the paper's joint-count figure used.+DEFAULT_THRESHOLDS = '8,65,90'+++# ---------------------------------------------------------------------------+# Statistics+# ---------------------------------------------------------------------------++def summarize(joints, thresholds):+ stats = {'n_skeletons': int(joints.size)}+ stats.update(dp.percentile_stats(joints))+ # Share of skeletons with at most N joints: what a max_joints cap of N+ # keeps (1 - share is what it drops).+ stats['at_most'] = {+ str(t): {'count': int((joints <= t).sum()),+ 'share': float((joints <= t).mean())}+ for t in thresholds+ }+ return stats+++def print_table(stats_by_label, thresholds):+ cols = ['skeletons', 'min', 'p10', 'median', 'mean', 'p90', 'max']+ cols += [f'<={t}j' for t in thresholds]+ width = max(len(lab) for lab in stats_by_label)+ print(f'{"dataset":<{width}} ' + ' '.join(f'{c:>9}' for c in cols))+ for lab, s in stats_by_label.items():+ row = [f'{s["n_skeletons"]:,}', f'{s["min"]}', f'{s["p10"]:.0f}',+ f'{s["median"]:g}', f'{s["mean"]:.1f}', f'{s["p90"]:.0f}', f'{s["max"]}']+ row += [f'{s["at_most"][str(t)]["share"]:.1%}' for t in thresholds]+ print(f'{lab:<{width}} ' + ' '.join(f'{c:>9}' for c in row))+++# ---------------------------------------------------------------------------+# Figures+# ---------------------------------------------------------------------------++def _apply_clip(joints, clip_max):+ """Values shown in a figure and a subtitle note for the ones dropped."""+ if clip_max is None or not (joints > clip_max).any():+ return joints, ''+ kept = joints[joints <= clip_max]+ if kept.size == 0:+ raise ValueError(f'--clip_max {clip_max} drops every skeleton')+ return kept, f' · {joints.size - kept.size} above {clip_max} joints not shown'+++def _joint_bins(joints, bin_width, log_x):+ """Integer-aligned bins on a linear axis; even log-spaced bins otherwise.+ Returns ``(edges, bin_width_in_axis_units, lo, hi)``."""+ if log_x:+ lo, hi = dp.value_range(joints, log_x=True)+ edges = dp.even_bins(lo, hi, bin_width or 40, log_x=True)+ return edges, float(np.diff(dp.to_axis(edges[:2], True))[0]), lo, hi+ edges, width = dp.integer_bins(joints, bin_width)+ return edges, float(width), edges[0] - 0.5, edges[-1] + 0.5+++def plot_dataset(label, joints, stats, thresholds, bin_width, log_x, clip_max,+ out_base, pdf, title=None):+ """Histogram + KDE + mean/median guides, and the cumulative curve with+ threshold guides, for one joint_count.json (or a pooled set)."""+ shown_joints, clip_note = _apply_clip(joints, clip_max)+ fig, (ax_h, ax_c) = dp.two_panel_figure()+ edges, bin_width_axis, lo, hi = _joint_bins(shown_joints, bin_width, log_x)+ shown = [t for t in thresholds if lo <= t <= hi]++ # ---- Histogram (proportion of skeletons) + kernel density ----+ counts, _ = np.histogram(shown_joints, bins=edges)+ props = counts / shown_joints.size+ widths = np.diff(edges)+ ax_h.bar(edges[:-1] + 0.04 * widths, props, width=0.92 * widths, align='edge',+ color=dp.ACCENT, edgecolor='white', linewidth=0.6, alpha=0.92,+ label='Histogram', zorder=2)+ grid = dp.kde_grid(lo, hi, log_x)+ kde = dp.kde_proportion(shown_joints, grid, bin_width_axis, log_x)+ y_top = props.max()+ if kde is not None:+ ax_h.fill_between(grid, kde, color=dp.ACCENT_FL, alpha=0.30, linewidth=0, zorder=1)+ ax_h.plot(grid, kde, color=dp.ACCENT_DK, linewidth=1.8, solid_capstyle='round',+ label='Kernel density', zorder=3)+ y_top = max(y_top, float(kde.max()))+ ax_h.set_ylim(0, y_top * dp.HEADROOM)+ dp.style_axes(ax_h)+ dp.value_axis(ax_h, lo, hi, log_x,+ 'Number of joints' + (' (log scale)' if log_x else ''))+ dp.pct_axis(ax_h)+ ax_h.set_ylabel('Proportion of skeletons')+ mean_v, median_v = float(shown_joints.mean()), float(np.median(shown_joints))+ dp.mean_median_guides(ax_h, mean_v, median_v)+ ax_h.legend(loc=dp.legend_loc_clear_of(ax_h, (mean_v, median_v)),+ borderaxespad=0.6, handlelength=1.8)++ # ---- Cumulative: share of skeletons with at most N joints ----+ xs, ys, where = dp.cdf_curve(shown_joints, span=(lo, hi))+ ax_c.fill_between(xs, ys, step=where, color=dp.ACCENT_FL, alpha=0.30,+ linewidth=0, zorder=1)+ ax_c.step(xs, ys, where=where, color=dp.ACCENT_DK, linewidth=1.8,+ solid_capstyle='round', solid_joinstyle='round', zorder=3)+ ax_c.set_ylim(0, 1.06)+ dp.style_axes(ax_c)+ dp.value_axis(ax_c, lo, hi, log_x,+ 'Number of joints' + (' (log scale)' if log_x else ''))+ dp.pct_axis(ax_c)+ ax_c.set_ylabel('Share of skeletons with ≤ N joints')+ shares = {t: float((shown_joints <= t).mean()) for t in shown}+ dp.threshold_guides(ax_c, shown, lambda t: f'{t} joints',+ at_bottom=dp.crowded_top(shares.get, shown))+ dp.mark_points(ax_c, [(t, shares[t]) for t in shown], prefer='below')++ subtitle = (f'{stats["n_skeletons"]:,} skeletons · median {stats["median"]:g} joints'+ f' · range {stats["min"]}–{stats["max"]}' + clip_note)+ return dp.finish_figure(+ fig, title or f'Distribution of Joint Counts — {dp.display_name(label)}',+ subtitle, out_base, pdf)+++def plot_comparison(datasets, thresholds, bin_width, log_x, clip_max, out_base, pdf):+ """Overlay several datasets: kernel densities (proportion per bin) and+ cumulative curves, each normalized to its own skeleton count.++ ``datasets`` is ``[(label, joints), ...]``; one categorical hue per+ dataset, in input order. Single-skeleton datasets contribute a step to+ the cumulative panel but no density curve.+ """+ shown_sets = [(lab, _apply_clip(j, clip_max)[0]) for lab, j in datasets]+ all_joints = np.concatenate([j for _, j in shown_sets])+ fig, (ax_k, ax_c) = dp.two_panel_figure()+ edges, bin_width_axis, lo, hi = _joint_bins(all_joints, bin_width, log_x)+ shown = [t for t in thresholds if lo <= t <= hi]+ grid = dp.kde_grid(lo, hi, log_x)++ y_top = 0.0+ for i, (label, joints) in enumerate(shown_sets):+ color = dp.SERIES[i]+ name = dp.display_name(label)+ kde = dp.kde_proportion(joints, grid, bin_width_axis, log_x)+ if kde is not None:+ ax_k.fill_between(grid, kde, color=color, alpha=0.12, linewidth=0, zorder=1)+ ax_k.plot(grid, kde, color=color, linewidth=1.8, solid_capstyle='round',+ label=name, zorder=3)+ y_top = max(y_top, float(kde.max()))+ xs, ys, where = dp.cdf_curve(joints, span=(lo, hi))+ ax_c.step(xs, ys, where=where, color=color, linewidth=1.8, label=name,+ solid_capstyle='round', solid_joinstyle='round', zorder=3)++ ax_k.set_ylim(0, (y_top or 1.0) * dp.HEADROOM)+ dp.style_axes(ax_k)+ dp.value_axis(ax_k, lo, hi, log_x, 'Number of joints' + (' (log scale)' if log_x else ''))+ dp.pct_axis(ax_k)+ ax_k.set_ylabel(f'Proportion of skeletons per bin (width {bin_width_axis:g})')++ ax_c.set_ylim(0, 1.06)+ dp.style_axes(ax_c)+ dp.value_axis(ax_c, lo, hi, log_x, 'Number of joints' + (' (log scale)' if log_x else ''))+ dp.pct_axis(ax_c)+ ax_c.set_ylabel('Share of skeletons with ≤ N joints')+ crowded = dp.crowded_top(+ lambda t: max(float((j <= t).mean()) for _, j in shown_sets), shown)+ dp.threshold_guides(ax_c, shown, lambda t: f'{t} joints', at_bottom=crowded)+ # Every dataset has a cumulative step (a density needs >= 2 distinct+ # values), so the legend lives on this panel.+ ax_c.legend(loc='lower right', borderaxespad=0.6, handlelength=1.8)++ n_total = sum(j.size for _, j in datasets)+ subtitle = (f'{len(datasets)} datasets · {n_total:,} skeletons · '+ + ' · '.join(f'{dp.display_name(lab)} {j.size:,}' for lab, j in datasets))+ return dp.finish_figure(fig, 'Distribution of Joint Counts across Datasets',+ subtitle, out_base, pdf)+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------++def parse_args():+ parser = argparse.ArgumentParser(+ description='Plot the joints-per-skeleton distribution of export-stage '+ 'joint_count.json files.')+ parser.add_argument('inputs', nargs='*',+ help='Export directories (containing joint_count.json) or '+ f'joint_count*.json paths. Default: {DEFAULT_GLOB}')+ parser.add_argument('--output_dir', default=DEFAULT_OUTPUT_DIR,+ help='Where the comparison / pooled figures and the summary '+ f'JSON go (default: {DEFAULT_OUTPUT_DIR})')+ parser.add_argument('--per_dataset_dir', default=None,+ help='Collect the per-dataset figures in this directory as '+ '<label>_joint_count_distribution.{png,pdf}. Default: '+ 'write each one as joint_count_distribution.png next to '+ 'its own joint_count.json.')+ parser.add_argument('--thresholds', default=DEFAULT_THRESHOLDS,+ help='Comma-separated joint counts to mark on the cumulative '+ f'panel (default: {DEFAULT_THRESHOLDS} — stage-4 default '+ 'min_joints, the training max_joints cap, the paper '+ 'figure\'s plotting cap). Empty string disables.')+ parser.add_argument('--clip_max', type=int, default=None,+ help='Hide skeletons with more joints than this from the '+ 'figures (the count dropped is noted in the subtitle; '+ 'the summary always covers every skeleton).')+ parser.add_argument('--bin_width', type=int, default=None,+ help='Histogram bin width in joints (default: 1 / 2 / 3 by '+ 'value span); bin COUNT on a log axis (default 40).')+ parser.add_argument('--log', action='store_true',+ help='Log-scaled joint axis instead of linear')+ parser.add_argument('--pooled', action='store_true',+ help='Also plot every input\'s skeletons pooled into one figure')+ parser.add_argument('--no_comparison', action='store_true',+ help='Skip the overlaid comparison figure')+ parser.add_argument('--pdf', action=argparse.BooleanOptionalAction, default=True,+ help='Also write a PDF next to the comparison / pooled figures, '+ 'and next to the per-dataset figures when --per_dataset_dir '+ 'is set (default: on; figures beside the JSONs are PNG only)')+ return parser.parse_args()+++def main():+ args = parse_args()+ dp.configure_style()+ thresholds = dp.parse_int_list(args.thresholds, '--thresholds')+ paths = dp.resolve_inputs(args.inputs, FILENAME, DEFAULT_GLOB)+ labels = dp.unique_labels(paths, FILENAME)+ os.makedirs(args.output_dir, exist_ok=True)++ datasets = []+ summary = {}+ for path, label in zip(paths, labels):+ joints = dp.load_int_map(path)+ stats = summarize(joints, thresholds)+ out_base, pdf_ok = dp.per_dataset_out_base(path, label, args.per_dataset_dir, SUFFIX)+ written = plot_dataset(label, joints, stats, thresholds, args.bin_width,+ args.log, args.clip_max, out_base, pdf_ok and args.pdf)+ print(f'[{label}] {joints.size:,} skeletons from {path} -> {", ".join(written)}')+ datasets.append((label, joints))+ summary[label] = dict(stats, source=os.path.abspath(path))++ if len(datasets) > 1 and not args.no_comparison:+ if len(datasets) > len(dp.SERIES):+ print(f'Skipping the comparison figure: {len(datasets)} inputs exceed the '+ f'{len(dp.SERIES)} distinguishable series; compare in smaller groups.')+ else:+ written = plot_comparison(+ datasets, thresholds, args.bin_width, args.log, args.clip_max,+ os.path.join(args.output_dir, 'joint_count_distribution_comparison'),+ args.pdf)+ print(f'[comparison] {len(datasets)} datasets -> {", ".join(written)}')++ if args.pooled:+ pooled = np.concatenate([j for _, j in datasets])+ written = plot_dataset(+ 'all', pooled, summarize(pooled, thresholds), thresholds, args.bin_width,+ args.log, args.clip_max,+ os.path.join(args.output_dir, 'joint_count_distribution_pooled'), args.pdf,+ title='Distribution of Joint Counts across Skeletons')+ print(f'[pooled] {pooled.size:,} skeletons -> {", ".join(written)}')++ summary_path = os.path.join(args.output_dir, 'joint_count_summary.json')+ with open(summary_path, 'w') as f:+ json.dump(summary, f, indent=2)+ print(f'Summary -> {summary_path}\n')+ print_table(summary, thresholds)+++if __name__ == '__main__':+ main()diff --git a/data_process/tools/vis_motion.py b/data_process/tools/vis_motion.pyindex b375673..0a8f4fd 100644--- a/data_process/tools/vis_motion.py+++ b/data_process/tools/vis_motion.py@@ -32,13 +32,16 @@ import osimport sysfrom pathlib import Path+import imageioimport numpy as npsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))from Animation import Animation, Quaternions, positions_global # noqa: E402from data_process.utils.plotting import render_skeleton_motion_directed # noqa: E402-import imageio # noqa: E402+++DEFAULT_OUTPUT_DIR = "outputs/motion_vis"def load_motion_from_npz(npz_path):@@ -122,9 +125,6 @@ def compute_directions(global_pos, mode, face_joints=None):raise ValueError(f"unknown direction mode: {mode}")-DEFAULT_OUTPUT_DIR = "outputs/motion_vis"--def default_output_path(npz_path):"""Default output: ``<DEFAULT_OUTPUT_DIR>/<stem>_motion_directed.mp4``."""return os.path.join(DEFAULT_OUTPUT_DIR, f"{Path(npz_path).stem}_motion_directed.mp4")diff --git a/data_process/tools/vis_tpose.py b/data_process/tools/vis_tpose.pyindex 4c6b432..1249b53 100644--- a/data_process/tools/vis_tpose.py+++ b/data_process/tools/vis_tpose.py@@ -44,10 +44,10 @@ from data_process.utils.plotting import save_skeleton_tpose_annotated # noqa: EREQUIRED_KEYS = ("rest_local_pos", "rest_local_rot", "names", "parents")+DEFAULT_OUTPUT_DIR = "outputs/face_joints_vis"def load_tpose_from_npz(npz_path):- # type: (str) -> Tuple[np.ndarray, List[str], np.ndarray]"""Load rest-pose data from a motion NPZ and compute global T-pose positions.Returns:@@ -88,7 +88,6 @@ def load_tpose_from_npz(npz_path):def render_one(npz_path, output_path, *, font_size, joint_marker_size,bone_linewidth):- # type: (str, str, int, float, float) -> None"""Render one NPZ as an annotated T-pose PNG."""parents, names, tpose_positions = load_tpose_from_npz(npz_path)os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)@@ -104,7 +103,6 @@ def render_one(npz_path, output_path, *, font_size, joint_marker_size,def find_motion_npz(motions_dir, key):- # type: (str, str) -> Optional[Path]"""Resolve the first motion NPZ whose prefix-before-'-' matches ``key``.Motion files are named ``<key>-<clip_name>.npz`` (e.g.@@ -117,7 +115,6 @@ def find_motion_npz(motions_dir, key):def collect_keys_from_motions_dir(motions_dir):- # type: (str) -> List[str]"""Collect unique keys (prefix before the first ``-``) from NPZs in ``motions_dir``.NPZs without a ``-`` in their stem are treated as their own key.@@ -129,11 +126,7 @@ def collect_keys_from_motions_dir(motions_dir):return sorted(keys)-DEFAULT_OUTPUT_DIR = "outputs/face_joints_vis"--def default_single_output_path(npz_path):- # type: (str) -> str"""Default single-mode output: ``<DEFAULT_OUTPUT_DIR>/<stem>_tpose_annotated.png``."""return os.path.join(DEFAULT_OUTPUT_DIR,"{}_tpose_annotated.png".format(Path(npz_path).stem))@@ -253,8 +246,8 @@ def main():print("Rendering {} T-poses ({})".format(len(keys), source_desc))rendered = skipped_existing = missing_npz = failed = 0- missing_examples = [] # type: List[str]- failed_examples = [] # type: List[str]+ missing_examples = []+ failed_examples = []for key in tqdm(keys, unit="seq", dynamic_ncols=True):out_path = os.path.join(args.output_dir, "{}.png".format(key))diff --git a/data_process/tools/vis_tpose_facing.py b/data_process/tools/vis_tpose_facing.pynew file mode 100644index 0000000..897f587--- /dev/null+++ b/data_process/tools/vis_tpose_facing.py@@ -0,0 +1,429 @@+"""Compare an exported rest pose with its stage-4 facing canonicalization.++The export stage saves every skeleton's rest pose as ``export/<ds>/tpose/<rig>.png``+in the asset's own frame. Stage 4 (``feature_extraction/extract_features.py`` via+``utils/motion_features.process_tpose``) rotates that rest pose so the facing+direction implied by the face-joint pair points to +Z — ``forward = Y x (r_hip -+l_hip)``, or the body axis for ``body_axis`` rigs — then centres, scales and+grounds it. This tool runs exactly that canonicalization on the rest pose and+saves one comparison image per skeleton, same camera as ``tpose/<rig>.png``:++ left — the original rest pose (export frame) with the face joints marked+ right — the same pose after the face-pair correction (facing +Z)++``r_hip`` is red, ``l_hip`` blue (joined by a dashed line), the pair-derived+forward is a green arrow and the grey arrow on the right panel is +Z, where the+green one must end up. The title carries the pair's raw names, source and the+pair's lateral (XZ) separation in the rest pose and at the first animation+frame. Flags: ``COINCIDENT`` — the two joints sit on the midline in both poses,+so the pair yields a meaningless facing (pick another pair);+``REST-DEGENERATE`` — lateral at frame 0 but not in the rest pose, i.e. the+exported rest pose lies on its side and the stage-4 T-pose facing is unreliable+even though the pair is fine; ``UNRESOLVED`` — a named joint is missing from the+skeleton. A ``facing_summary.tsv`` with the same numbers is written next to the+PNGs.++The pair comes from ``<export_dir>/face_joint_names.json`` (the sidecar+``patch_annotations.py`` maintains); pass ``--face_json`` to preview another+sidecar or a ``dataset/UniML3D/patches/<ds>_face_pairs.json`` override file+before applying it.++Usage:+ python -m data_process.tools.vis_tpose_facing --export_dir dataset/export/objaverse+ python -m data_process.tools.vis_tpose_facing --export_dir dataset/export/objaverse --rigs RIG1 RIG2+ python -m data_process.tools.vis_tpose_facing --export_dir dataset/export/truebones \\+ --face_json dataset/UniML3D/patches/truebones_face_pairs.json --output_dir outputs/tmp++See ``data_process/scripts/run_joints_vis_facing.sh`` for the wrapper.+"""++import argparse+import csv+import json+import multiprocessing as mp+import os+import sys+from pathlib import Path++import imageio.v2 as imageio+import numpy as np+from tqdm import tqdm++sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))++from Animation import Animation, Quaternions, positions_global # noqa: E402+from data_process.utils.motion_features import ( # noqa: E402+ DegenerateSkeletonError, process_tpose, resolve_face_joint_idxs,+)+from data_process.utils.plotting import render_skeleton_tpose_facing # noqa: E402+++DEFAULT_OUTPUT_DIR = 'outputs/tpose_facing_vis'+COINCIDENT_SEP = 0.03 # pair separation (fraction of the skeleton extent) below which facing is noise+PANEL_FIGSIZE = (6, 6) # matches export/<ds>/tpose/<rig>.png (save_skeleton_tpose defaults)+PANEL_DPI = 120+++# ---------------------------------------------------------------------------+# Face-pair loading+# ---------------------------------------------------------------------------++def load_face_pairs(path):+ """Load ``face_joint_names.json`` (sidecar) or a ``*_face_pairs.json`` patch.++ Both are normalised to the sidecar layout+ ``{rig: {"r_hip": {"raw", "clean"}, "l_hip": {...}, "source", "body_axis"}}``;+ keys starting with ``_`` (``_comment``) are skipped.+ """+ with open(path) as f:+ data = json.load(f)+ out = {}+ for rig, entry in data.items():+ if rig.startswith('_') or not isinstance(entry, dict):+ continue+ norm = {}+ for key in ('r_hip', 'l_hip'):+ val = entry.get(key, '')+ if isinstance(val, dict):+ norm[key] = {'raw': val.get('raw', ''), 'clean': val.get('clean', '')}+ else:+ norm[key] = {'raw': val or '', 'clean': ''}+ norm['source'] = entry.get('source', '')+ norm['body_axis'] = bool(entry.get('body_axis', False))+ out[rig] = norm+ return out+++def index_motion_npzs(motions_dir):+ """First NPZ per skeleton key (the prefix before the first ``-``), from one+ directory scan — any clip carries the rest pose. Mixamo shares one skeleton+ across un-prefixed clips, so its ``mixamo`` key maps to the first NPZ.+ """+ index = {}+ for p in sorted(Path(motions_dir).glob('*.npz')):+ key = p.stem.split('-', 1)[0] if '-' in p.stem else p.stem+ index.setdefault(key, p)+ index.setdefault('mixamo', p)+ return index+++# ---------------------------------------------------------------------------+# Geometry+# ---------------------------------------------------------------------------++def rest_positions(data):+ """Global rest-pose joint positions (J, 3) of an export NPZ, in export order."""+ parents = np.asarray(data['parents']).astype(int)+ anim = Animation(+ rotations=Quaternions(data['rest_local_rot'][None]),+ positions=data['rest_local_pos'][None],+ orients=Quaternions.id(len(parents)),+ offsets=data['rest_local_pos'],+ parents=parents,+ )+ return positions_global(anim)[0].astype(np.float32), parents+++def first_frame_positions(data):+ """Global joint positions (J, 3) at the first animation frame of an export NPZ."""+ parents = np.asarray(data['parents']).astype(int)+ anim = Animation(+ rotations=Quaternions(data['anim_local_rot'][:1]),+ positions=data['anim_local_pos'][:1],+ orients=Quaternions.id(len(parents)),+ offsets=data['rest_local_pos'],+ parents=parents,+ )+ return positions_global(anim)[0].astype(np.float32)+++def pair_forward(positions, face_joint_idxs, body_axis):+ """Facing direction the pair implies (same math as ``skeleton.get_root_facing_quat``).++ Returns ``(forward (3,), lateral_separation)`` where the separation is the+ horizontal distance between the two joints as a fraction of the skeleton's+ largest extent; ``forward`` is ``None`` for the ``[-1, -1]`` sentinel.+ """+ if face_joint_idxs is None or face_joint_idxs[0] < 0 or face_joint_idxs[1] < 0:+ return None, 0.0+ r, l = face_joint_idxs[:2]+ across = positions[r] - positions[l]+ extent = float(np.ptp(positions, axis=0).max()) or 1.0+ sep = float(np.linalg.norm(across * np.array([1.0, 0.0, 1.0]))) / extent+ n = float(np.linalg.norm(across))+ if n < 1e-9:+ return np.zeros(3, dtype=np.float32), sep+ across = across / n+ forward = np.cross(np.array([0.0, 1.0, 0.0]), across)+ n = float(np.linalg.norm(forward))+ forward = forward / n if n > 1e-9 else np.zeros(3)+ if body_axis:+ rot = Quaternions.from_euler(np.array([0.0, -np.pi / 2, 0.0]), 'xyz')+ forward = np.asarray(rot * forward[None])[0]+ return forward.astype(np.float32), sep+++# ---------------------------------------------------------------------------+# Rendering+# ---------------------------------------------------------------------------++def _fit_height(img, height):+ """Nearest-neighbour resample *img* to *height* rows (keeps aspect)."""+ if img.shape[0] == height:+ return img+ width = max(1, int(round(img.shape[1] * height / img.shape[0])))+ rows = (np.arange(height) * img.shape[0] / height).astype(int)+ cols = (np.arange(width) * img.shape[1] / width).astype(int)+ return img[rows][:, cols]+++def _blank_panel(shape, text):+ """Light-grey panel with a caption, for a missing export PNG."""+ from matplotlib.backends.backend_agg import FigureCanvasAgg+ from matplotlib.figure import Figure+ fig = Figure(figsize=PANEL_FIGSIZE, dpi=PANEL_DPI)+ canvas = FigureCanvasAgg(fig)+ ax = fig.add_subplot(111)+ ax.set_axis_off()+ ax.text(0.5, 0.5, text, ha='center', va='center', fontsize=10, wrap=True)+ canvas.draw()+ w, h = canvas.get_width_height()+ rgb = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8).reshape(h, w, 4)[..., :3]+ return _fit_height(rgb.copy(), shape[0])+++MARKER_STYLES = (('orange', '*'), ('purple', 'v'), ('cyan', 's'), ('yellow', 'D'), ('lime', 'P'))+++def label_markers(labels, mark_labels):+ """``extra_markers`` for :func:`render_skeleton_tpose_facing`: one style per+ requested clean label, joints found by exact label match (``labels`` is+ aligned with the rig's joint order)."""+ if not labels or not mark_labels:+ return None+ out = []+ for k, lab in enumerate(mark_labels):+ idxs = [i for i, l in enumerate(labels) if l == lab]+ if idxs:+ color, marker = MARKER_STYLES[k % len(MARKER_STYLES)]+ out.append((idxs, color, marker, lab))+ return out or None+++def render_rig(rig, npz_path, entry, output_path, labels=None, mark_labels=()):+ """Render the original | corrected comparison for one skeleton; returns the summary row.++ ``labels`` are the rig's clean joint labels aligned with the NPZ joint order+ (optional); joints whose label is in ``mark_labels`` get an extra marker.+ """+ data = np.load(npz_path, allow_pickle=True)+ names = [str(n) for n in data['names']]+ if labels is not None and len(labels) != len(names):+ labels = None+ raw_pos, raw_parents = rest_positions(data)+ raw_idxs, body_axis = resolve_face_joint_idxs(entry, names)+ fwd_raw, sep = pair_forward(raw_pos, raw_idxs, body_axis)+ # the same pair at the first animation frame: a pair that is lateral there+ # but not in the rest pose means the rest pose lies on its side, not that+ # the joints coincide+ f0_pos = first_frame_positions(data)+ _, sep_f0 = pair_forward(f0_pos, raw_idxs, body_axis)++ r_raw, l_raw = entry['r_hip']['raw'], entry['l_hip']['raw']+ flag = ''+ if raw_idxs == [-1, -1]:+ flag = 'UNRESOLVED' if (r_raw or l_raw) else 'EMPTY'+ elif sep < COINCIDENT_SEP and sep_f0 < COINCIDENT_SEP:+ flag = 'COINCIDENT'+ elif sep < COINCIDENT_SEP:+ flag = 'REST-DEGENERATE'+ fx, fz = (float(fwd_raw[0]), float(fwd_raw[2])) if fwd_raw is not None else (float('nan'),) * 2+ pair_txt = 'r_hip={} ({}) l_hip={} ({}) src={}{}'.format(+ r_raw or '-', entry['r_hip']['clean'] or '?', l_raw or '-',+ entry['l_hip']['clean'] or '?', entry['source'] or '-',+ ' body_axis' if body_axis else '')+ info = 'forward=({:+.2f}, {:+.2f}) pair sep rest={:.3f} frame0={:.3f} {}'.format(+ fx, fz, sep, sep_f0, flag).rstrip()++ panel_raw = render_skeleton_tpose_facing(+ raw_parents, raw_pos, raw_idxs, fwd_raw,+ title='{}\nORIGINAL rest pose (export frame)\n{}\n{}'.format(rig, pair_txt, info),+ extra_markers=label_markers(labels, mark_labels),+ figsize=PANEL_FIGSIZE, dpi=PANEL_DPI)++ try:+ (tpos_anim, _, _, _, parents_c, names_c, _, _,+ idxs_c, body_axis_c) = process_tpose(data, face_joints=entry)+ pos_c = positions_global(tpos_anim)[0].astype(np.float32)+ fwd_c, _ = pair_forward(pos_c, idxs_c, body_axis_c)+ cz = float(fwd_c[2]) if fwd_c is not None else float('nan')+ # process_tpose reorders joints (BFS): carry the labels over by name+ labels_c = ([labels[names.index(n)] for n in names_c]+ if labels is not None and all(n in names for n in names_c) else None)+ panel_can = render_skeleton_tpose_facing(+ parents_c, pos_c, idxs_c, fwd_c, target_forward=np.array([0.0, 0.0, 1.0]),+ title='{}\nCORRECTED by face pair (stage-4: facing -> +Z, centred, scaled, grounded)\n'+ '{}\nforward.z after rotation = {:+.2f} (grey arrow = +Z)'.format(rig, pair_txt, cz),+ extra_markers=label_markers(labels_c, mark_labels),+ figsize=PANEL_FIGSIZE, dpi=PANEL_DPI)+ canon_z = cz+ except DegenerateSkeletonError as e:+ panel_can = _blank_panel(panel_raw.shape, 'degenerate skeleton:\n{}'.format(e))+ canon_z = float('nan')+ flag = (flag + ' DEGENERATE').strip()++ os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)+ imageio.imwrite(output_path, np.concatenate([panel_raw, panel_can], axis=1))+ return {'rig': rig, 'r_hip': r_raw, 'l_hip': l_raw, 'source': entry['source'],+ 'body_axis': int(body_axis), 'forward_x': '{:.3f}'.format(fx),+ 'forward_z': '{:.3f}'.format(fz), 'pair_sep': '{:.3f}'.format(sep),+ 'pair_sep_frame0': '{:.3f}'.format(sep_f0),+ 'canon_forward_z': '{:.3f}'.format(canon_z), 'flag': flag,+ 'png': output_path}+++def _worker(task):+ rig, npz_path, entry, output_path, labels, mark_labels = task+ try:+ return render_rig(rig, npz_path, entry, output_path, labels, mark_labels)+ except Exception as e: # noqa: BLE001 — keep the batch going+ return {'rig': rig, 'r_hip': entry['r_hip']['raw'], 'l_hip': entry['l_hip']['raw'],+ 'source': entry['source'], 'body_axis': int(entry.get('body_axis', False)),+ 'forward_x': '', 'forward_z': '', 'pair_sep': '', 'pair_sep_frame0': '',+ 'canon_forward_z': '', 'flag': 'ERROR {}: {}'.format(type(e).__name__, e), 'png': ''}+++SUMMARY_FIELDS = ('rig', 'r_hip', 'l_hip', 'source', 'body_axis', 'forward_x', 'forward_z',+ 'pair_sep', 'pair_sep_frame0', 'canon_forward_z', 'flag', 'png')+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------++def parse_args():+ parser = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument('--export_dir', required=True,+ help='Stage-1 export directory (dataset/export/<ds>): motions/ and '+ 'face_joint_names.json')+ parser.add_argument('--face_json', default=None,+ help='Face pairs to visualize: a face_joint_names.json sidecar or a '+ 'patches/<ds>_face_pairs.json override file '+ '(default: <export_dir>/face_joint_names.json)')+ parser.add_argument('--output_dir', default=None,+ help='Output directory (default: {}/<export_dir basename>)'.format(DEFAULT_OUTPUT_DIR))+ parser.add_argument('--rigs', nargs='*', default=None, help='Only these skeleton keys')+ parser.add_argument('--rigs_file', default=None,+ help='Text file with one skeleton key per line (# comments allowed)')+ parser.add_argument('--source', default=None,+ help='Only pairs whose "source" equals this (e.g. thigh, body_axis)')+ parser.add_argument('--include_empty', action='store_true',+ help='Also render skeletons whose pair is empty (identity facing)')+ parser.add_argument('--limit', type=int, default=None, help='Stop after N skeletons')+ parser.add_argument('--mark_labels', default='',+ help='Comma-separated clean labels to mark with extra symbols on both '+ 'panels, e.g. "Head,Tail End,Toe" (looked up in '+ '<export_dir>/clean_joint_names.json)')+ parser.add_argument('--overwrite', action='store_true', help='Re-render existing PNGs')+ parser.add_argument('--workers', type=int, default=max(1, min(8, (os.cpu_count() or 2) // 2)),+ help='Parallel renderers (default: min(8, cpus/2))')+ return parser.parse_args()+++def main():+ args = parse_args()+ export_dir = args.export_dir.rstrip('/')+ motions_dir = os.path.join(export_dir, 'motions')+ face_json = args.face_json or os.path.join(export_dir, 'face_joint_names.json')+ output_dir = args.output_dir or os.path.join(DEFAULT_OUTPUT_DIR, os.path.basename(export_dir))+ if not os.path.isdir(motions_dir):+ sys.exit('motions dir not found: {}'.format(motions_dir))+ if not os.path.isfile(face_json):+ sys.exit('face json not found: {}'.format(face_json))++ pairs = load_face_pairs(face_json)+ keys = list(pairs)+ if args.rigs_file:+ with open(args.rigs_file) as f:+ wanted = [ln.split('#', 1)[0].strip() for ln in f]+ wanted = [w for w in wanted if w]+ keys = [k for k in wanted if k in pairs] + [k for k in wanted if k not in pairs]+ if args.rigs:+ keys = list(args.rigs)+ missing = [k for k in keys if k not in pairs]+ if missing:+ print('warning: {} requested skeleton(s) not in {}: {}'.format(+ len(missing), face_json, ', '.join(missing[:5])), file=sys.stderr)+ keys = [k for k in keys if k in pairs]+ if args.source:+ keys = [k for k in keys if pairs[k]['source'] == args.source]+ if not args.include_empty:+ keys = [k for k in keys if pairs[k]['r_hip']['raw'] and pairs[k]['l_hip']['raw']]+ if args.limit:+ keys = keys[:args.limit]++ mark_labels = tuple(s.strip() for s in args.mark_labels.split(',') if s.strip())+ clean = {}+ if mark_labels:+ clean_path = os.path.join(export_dir, 'clean_joint_names.json')+ if os.path.isfile(clean_path):+ with open(clean_path) as f:+ clean = json.load(f)+ else:+ print('warning: --mark_labels needs {}; markers disabled'.format(clean_path), file=sys.stderr)+ mark_labels = ()++ npz_index = index_motion_npzs(motions_dir)+ done = set(os.listdir(output_dir)) if os.path.isdir(output_dir) else set()+ tasks, skipped = [], 0+ for rig in keys:+ out = os.path.join(output_dir, '{}.png'.format(rig))+ if '{}.png'.format(rig) in done and not args.overwrite:+ skipped += 1+ continue+ npz = npz_index.get(rig)+ if npz is None:+ print('warning: no motion NPZ for {}'.format(rig), file=sys.stderr)+ continue+ tasks.append((rig, str(npz), pairs[rig], out, clean.get(rig), mark_labels))++ print('{} skeleton(s) to render ({} already done) -> {}'.format(len(tasks), skipped, output_dir))+ os.makedirs(output_dir, exist_ok=True)+ rows = []+ if args.workers > 1 and len(tasks) > 1:+ with mp.Pool(args.workers) as pool:+ for row in tqdm(pool.imap_unordered(_worker, tasks), total=len(tasks), unit='rig'):+ rows.append(row)+ else:+ for task in tqdm(tasks, unit='rig'):+ rows.append(_worker(task))++ rows.sort(key=lambda r: r['rig'])+ summary_path = os.path.join(output_dir, 'facing_summary.tsv')+ existing = {}+ # --overwrite only discards the old summary for a full run; a subset re-render+ # (--rigs/--rigs_file/--source/--limit) merges its rows into the existing file.+ subset = bool(args.rigs or args.rigs_file or args.source or args.limit)+ if os.path.isfile(summary_path) and (subset or not args.overwrite):+ with open(summary_path) as f:+ for r in csv.DictReader(f, delimiter='\t'):+ existing[r['rig']] = r+ for r in rows:+ existing[r['rig']] = r+ with open(summary_path, 'w', newline='') as f:+ w = csv.DictWriter(f, fieldnames=SUMMARY_FIELDS, delimiter='\t')+ w.writeheader()+ for rig in sorted(existing):+ w.writerow({k: existing[rig].get(k, '') for k in SUMMARY_FIELDS})++ flagged = [r for r in rows if r['flag']]+ print('rendered {} skeleton(s); {} flagged -> {}'.format(len(rows), len(flagged), summary_path))+ for r in flagged[:20]:+ print(' {}\t{}\t{} / {}'.format(r['rig'], r['flag'], r['r_hip'], r['l_hip']))+ if len(flagged) > 20:+ print(' ... {} more (see summary)'.format(len(flagged) - 20))+++if __name__ == '__main__':+ main()diff --git a/data_process/utils/blender_export.py b/data_process/utils/blender_export.pyindex ad9276d..d03dc93 100644--- a/data_process/utils/blender_export.py+++ b/data_process/utils/blender_export.py@@ -24,7 +24,7 @@ from data_process.utils.export_markers import ( # noqa: F401 (re-exported)collect_joint_names_from_markers,is_asset_complete,mark_asset_complete,- merge_joint_names as _merge_joint_names,+ merge_joint_names,)@@ -1204,7 +1204,7 @@ def write_export_summary(output_dir, all_joint_names, fps=30, worker_suffix=""):if worker_suffix:merged = dict(all_joint_names)else:- merged = _merge_joint_names(output_dir, all_joint_names, log=logger.info)+ merged = merge_joint_names(output_dir, all_joint_names, log=logger.info)with open(joint_names_path, 'w') as f:json.dump(merged, f, indent=2)logger.info(f"Saved joint names ({len(merged)} entries) to {joint_names_path}")diff --git a/data_process/utils/blender_rig.py b/data_process/utils/blender_rig.pyindex 79a3ecc..2255667 100644--- a/data_process/utils/blender_rig.py+++ b/data_process/utils/blender_rig.py@@ -18,8 +18,8 @@ The counterpart for the *export* direction (Blender scene → NPZ) lives inimport osimport re-import bmeshimport bpy+import bmesh # registered by ``import bpy`` when running on the pip bpy moduleimport numpy as npfrom loguru import loggerfrom mathutils import Matrix, Quaternion@@ -27,7 +27,6 @@ from mathutils import Matrix, Quaternionfrom data_process.utils.blender_export import (bind_action,clear_animation_state,- reset_scene,)RECONSTRUCTED_ACTION_NAME = "Reconstructed_Action"diff --git a/data_process/utils/dist_plot.py b/data_process/utils/dist_plot.pynew file mode 100644index 0000000..eb938e3--- /dev/null+++ b/data_process/utils/dist_plot.py@@ -0,0 +1,482 @@+"""Shared helpers for the dataset-statistics distribution figures.++Used by the ``data_process/tools/vis_*.py`` distribution tools+(``vis_clip_frames.py`` — frames per clip, ``vis_joint_count.py`` — joints+per skeleton). Provides input resolution for the stage-1 summary JSONs+(``{key: int}`` maps next to ``summary.json``), the paper-figure style+shared with the joint-count / category distribution figures — one muted+indigo accent with a soft kernel-density fill, mean / median guides,+proportion axes, PNG + PDF at 300 dpi with embedded TrueType fonts — and+the distribution math behind the panels. Pure numpy + matplotlib: no scipy+(the Gaussian KDE is implemented here) and no bpy.+"""++import glob+import json+import os++import matplotlib+import numpy as np++matplotlib.use('Agg')+import matplotlib.pyplot as plt # noqa: E402+import matplotlib.ticker as mticker # noqa: E402++from data_process.utils.plotting import SANS_STACK # noqa: E402+++# ---------------------------------------------------------------------------+# Palette & style+# ---------------------------------------------------------------------------++# One muted indigo accent (bars, curves) with a soft fill (KDE / area), and+# the category palette's leading hues when several datasets are overlaid so+# a dataset keeps one color across every figure.+ACCENT = '#3D5A80'+ACCENT_DK = '#2A3F5F'+ACCENT_FL = '#98C1D9'+INK = '#1F2937'+MUTED = '#6B7280'+GRID = '#E5E7EB'+EDGE = '#9CA3AF'+SERIES = ('#3B5BA5', '#E25E54', '#43A47F', '#3FA9D6', '#EFA94A', '#A06CD5', '#8C95A8')++KDE_BW = 0.30 # bandwidth factor (× std), as in the joint-count figure+KDE_POINTS = 700+HEADROOM = 1.18 # y-limit over the tallest bar / curve: room for guide labels++# Two-panel layout; the tick-thinning estimate of a panel's width reads it.+FIG_W, FIG_H = 13.0, 4.8+LEFT, RIGHT, TOP, BOTTOM, WSPACE = 0.065, 0.985, 0.80, 0.14, 0.24+TICK_PT = 10.5+++def configure_style():+ """Shared rcParams of the dataset-statistics figures."""+ plt.rcParams.update({+ 'font.family': 'sans-serif',+ # Single source of truth, shared with the clip previews' captions.+ 'font.sans-serif': SANS_STACK,+ 'mathtext.fontset': 'dejavusans',+ 'axes.titlesize': 14,+ 'axes.titleweight': 'semibold',+ 'axes.titlepad': 14,+ 'axes.labelsize': 12,+ 'axes.labelweight': 'medium',+ 'axes.labelcolor': INK,+ 'axes.edgecolor': EDGE,+ 'axes.linewidth': 0.9,+ 'xtick.labelsize': TICK_PT,+ 'ytick.labelsize': TICK_PT,+ 'xtick.color': '#374151',+ 'ytick.color': '#374151',+ 'xtick.direction': 'out',+ 'ytick.direction': 'out',+ 'legend.frameon': False,+ 'legend.fontsize': 10.5,+ 'figure.facecolor': 'white',+ 'axes.facecolor': 'white',+ 'savefig.facecolor': 'white',+ 'savefig.bbox': 'tight',+ 'savefig.dpi': 300,+ 'pdf.fonttype': 42,+ 'ps.fonttype': 42,+ })+++# ---------------------------------------------------------------------------+# Inputs: the stage-1 summary JSONs+# ---------------------------------------------------------------------------++def resolve_inputs(paths, filename, default_glob):+ """Expand export dirs / JSON paths (or *default_glob*) to JSON files.++ A directory argument resolves to ``<dir>/<filename>``; a file argument+ is taken as-is (so worker shards like ``<stem>_worker3.json`` work).+ """+ if not paths:+ paths = sorted(glob.glob(default_glob))+ if not paths:+ raise FileNotFoundError(+ f'No files match {default_glob}; pass export directories or '+ f'{filename} paths explicitly.')+ resolved = []+ for p in paths:+ path = os.path.join(p, filename) if os.path.isdir(p) else p+ if not os.path.isfile(path):+ raise FileNotFoundError(f'{filename} not found: {path}')+ resolved.append(path)+ return resolved+++def label_for(path, filename):+ """Export directory name for the canonical file, else the file stem."""+ base = os.path.basename(path)+ if base == filename:+ return os.path.basename(os.path.dirname(os.path.abspath(path)))+ return os.path.splitext(base)[0]+++def unique_labels(paths, filename):+ """Per-path labels, suffixed when two inputs would otherwise collide."""+ seen = {}+ out = []+ for lab in (label_for(p, filename) for p in paths):+ n = seen.get(lab, 0)+ seen[lab] = n + 1+ out.append(lab if n == 0 else f'{lab}_{n}')+ return out+++def display_name(label):+ """Dataset directory names are lowercase; figures show them capitalized."""+ return label[:1].upper() + label[1:]+++def load_int_map(path):+ """Load a ``{key: int}`` JSON and return the values as an int array."""+ with open(path) as f:+ data = json.load(f)+ if not isinstance(data, dict):+ raise ValueError(f'{path}: expected a {{name: count}} object, '+ f'got {type(data).__name__}')+ values = np.array([int(v) for v in data.values()], dtype=np.int64)+ if values.size == 0:+ raise ValueError(f'{path}: no entries')+ return values+++def sibling_json_field(path, filename, key, default):+ """``key`` from ``<dir of path>/<filename>``, else *default*."""+ sibling = os.path.join(os.path.dirname(path), filename)+ try:+ with open(sibling) as f:+ value = json.load(f).get(key, default)+ return type(default)(value) if default is not None else value+ except (OSError, ValueError, TypeError):+ return default+++def parse_int_list(spec, flag):+ """``"60,90,120"`` → ``[60, 90, 120]`` (sorted, deduped); empty → []."""+ spec = (spec or '').strip()+ if not spec:+ return []+ out = sorted({int(tok) for tok in spec.split(',') if tok.strip()})+ if any(t <= 0 for t in out):+ raise ValueError(f'{flag} must be positive integers, got {spec!r}')+ return out+++def percentile_stats(values):+ """The percentile block shared by every summary."""+ def q(p):+ return float(np.percentile(values, p))+ return {+ 'min': int(values.min()),+ 'p10': q(10), 'p25': q(25), 'median': q(50), 'mean': float(values.mean()),+ 'p75': q(75), 'p90': q(90), 'p99': q(99),+ 'max': int(values.max()),+ }+++# ---------------------------------------------------------------------------+# Distribution math+# ---------------------------------------------------------------------------++def to_axis(x, log_x):+ x = np.asarray(x, dtype=float)+ return np.log10(x) if log_x else x+++def from_axis(u, log_x):+ return 10.0 ** u if log_x else u+++def value_range(values, log_x):+ """Padded axis range: ×1.15 either side on log axes, 3 % on linear."""+ lo, hi = float(values.min()), float(values.max())+ if log_x:+ return max(1.0, lo / 1.15), hi * 1.15+ pad = max(1.0, (hi - lo) * 0.03)+ return max(0.0, lo - pad), hi + pad+++def even_bins(lo, hi, n, log_x):+ """*n* bins of equal width in axis units (decades on a log axis)."""+ return from_axis(np.linspace(*to_axis([lo, hi], log_x), n + 1), log_x)+++def integer_bins(values, width=None):+ """Integer-aligned bins for count data (bars centered on the integers).++ Width defaults to 1 / 2 / 3 for a value span of ≤30 / ≤60 / more, as in+ the joint-count figure. Returns ``(edges, width)``.+ """+ lo, hi = int(values.min()), int(values.max())+ if width is None:+ span = hi - lo+ width = 1 if span <= 30 else (2 if span <= 60 else 3)+ edges = np.arange(lo, hi + width + 1, width) - 0.5+ return edges, width+++def kde_grid(lo, hi, log_x, n=KDE_POINTS):+ return from_axis(np.linspace(*to_axis([lo, hi], log_x), n), log_x)+++def kde_proportion(values, grid, bin_width, log_x, bw=KDE_BW):+ """Gaussian KDE on *grid*, scaled to the expected proportion per bin.++ Evaluated in log10 space for log axes so the curve matches log-spaced+ bins (``bin_width`` is then in decades). Bandwidth is ``bw * std``, the+ scalar-factor rule scipy's ``gaussian_kde`` applies for+ ``bw_method=bw``. Returns None for a degenerate sample (fewer than two+ distinct values).+ """+ u = to_axis(values, log_x)+ if u.size < 2:+ return None+ std = u.std(ddof=1)+ if not std > 0:+ return None+ h = bw * std+ g = to_axis(grid, log_x)+ dens = np.zeros(g.size)+ for start in range(0, u.size, 4096): # bound the (grid × samples) temp+ z = (g[:, None] - u[None, start:start + 4096]) / h+ dens += np.exp(-0.5 * z * z).sum(axis=1)+ dens /= u.size * h * np.sqrt(2.0 * np.pi)+ return dens * bin_width+++def survival_curve(values, span):+ """Share of entries with ``>= x``, as ``(xs, ys, where)`` for ``ax.step``.++ ``P(X >= x)`` holds its value on ``(u[i-1], u[i]]`` and drops just past+ each value, so the step mode is ``'pre'``. The curve is extended across+ *span* ``(lo, hi)``: 1 below the minimum, 0 above the maximum — which+ also makes a single-valued sample visible as one full-height step.+ """+ lo, hi = span+ uniq, counts = np.unique(values, return_counts=True)+ below = np.concatenate([[0], np.cumsum(counts)[:-1]])+ ys = 1.0 - below / values.size+ xs = np.concatenate([[lo], uniq, [hi]])+ ys = np.concatenate([[1.0], ys, [0.0]])+ return xs, ys, 'pre'+++def cdf_curve(values, span):+ """Share of entries with ``<= x``, as ``(xs, ys, where)`` for ``ax.step``.++ ``P(X <= x)`` holds its value on ``[u[i], u[i+1])``, so the step mode is+ ``'post'``. Extended across *span*: 0 below the minimum, 1 above the+ maximum.+ """+ lo, hi = span+ uniq, counts = np.unique(values, return_counts=True)+ ys = np.cumsum(counts) / values.size+ xs = np.concatenate([[lo], uniq, [hi]])+ ys = np.concatenate([[0.0], ys, [1.0]])+ return xs, ys, 'post'+++# ---------------------------------------------------------------------------+# Axes & annotations+# ---------------------------------------------------------------------------++def two_panel_figure():+ return plt.subplots(1, 2, figsize=(FIG_W, FIG_H))+++def style_axes(ax):+ ax.grid(True, axis='y', color=GRID, linewidth=0.7, zorder=0)+ ax.set_axisbelow(True)+ for spine in ('top', 'right', 'left'):+ ax.spines[spine].set_visible(False)+ ax.tick_params(axis='y', length=0, pad=4)+ ax.tick_params(axis='x', length=4)+++def pct_axis(ax):+ ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=0))+ ax.yaxis.set_major_locator(mticker.MaxNLocator(nbins=6, steps=[1, 2, 5, 10]))+++def panel_width_in(ax):+ """Approximate width of one panel in inches under the shared layout."""+ return ax.figure.get_figwidth() * (RIGHT - LEFT) / (2 + WSPACE)+++def _log_tick_candidates(lo, hi):+ """1-2-5 ticks per decade covering [lo, hi]."""+ e_lo, e_hi = int(np.floor(np.log10(lo))), int(np.ceil(np.log10(hi)))+ return [m * 10 ** e for e in range(e_lo, e_hi + 1) for m in (1, 2, 5)+ if lo <= m * 10 ** e <= hi]+++def thin_log_ticks(ticks, lo, hi, panel_in, fmt, font_pt=TICK_PT, gap_pt=8.0):+ """Drop ticks whose labels would overlap the previous kept label.++ Label width is estimated from character count (~0.6 em per glyph);+ positions are compared in points along the log axis.+ """+ pt_per_decade = panel_in * 72.0 / max(np.log10(hi / lo), 1e-9)+ kept, last_center, last_half = [], None, 0.0+ for t in ticks:+ center = np.log10(t) * pt_per_decade+ half = 0.6 * font_pt * len(fmt(t)) / 2.0+ if last_center is None or center - last_center >= last_half + half + gap_pt:+ kept.append(t)+ last_center, last_half = center, half+ return kept+++def value_axis(ax, lo, hi, log_x, xlabel):+ """Integer-formatted x axis: thinned 1-2-5 ticks on log, MaxNLocator on+ linear. Sets the limits and label."""+ fmt = lambda v: f'{int(round(v)):,}' # noqa: E731+ if log_x:+ ax.set_xscale('log')+ ticks = thin_log_ticks(_log_tick_candidates(lo, hi), lo, hi,+ panel_width_in(ax), fmt)+ if len(ticks) < 2:+ ticks = [int(round(lo)), int(round(hi))]+ ax.xaxis.set_major_locator(mticker.FixedLocator(ticks))+ ax.xaxis.set_minor_locator(mticker.NullLocator())+ else:+ ax.xaxis.set_major_locator(mticker.MaxNLocator(integer=True, nbins=8))+ ax.xaxis.set_major_formatter(mticker.FuncFormatter(lambda v, _: fmt(v)))+ ax.set_xlim(lo, hi)+ ax.set_xlabel(xlabel)+++def x_frac(ax, x):+ """Position of data *x* as a fraction of the axis width (log-aware)."""+ lo, hi = ax.get_xlim()+ if ax.get_xscale() == 'log':+ return (np.log10(x) - np.log10(lo)) / (np.log10(hi) - np.log10(lo))+ return (x - lo) / (hi - lo)+++def guide(ax, x, text, color, dash, side, y_frac=0.985, fontsize=10):+ """Vertical guide with an inline label hung from the top of the panel."""+ ax.axvline(x, color=color, linewidth=1.0, linestyle=dash, alpha=0.85, zorder=4)+ ax.text(x, y_frac, f' {text} ', transform=ax.get_xaxis_transform(),+ ha=side, va='top', fontsize=fontsize, color=color, zorder=5,+ bbox=dict(boxstyle='round,pad=0.2', facecolor='white',+ edgecolor='none', alpha=0.85))+++def mean_median_guides(ax, mean_v, median_v, edge_frac=0.15):+ """Mean (dashed, ink) and median (dotted, muted) guides.++ The smaller value is labeled on its left and the larger on its right so+ the labels never cross. When the smaller one sits within *edge_frac* of+ the left edge — where a left-hung label would run into the y tick labels+ — it is labeled on the right instead, one step lower than the other.+ """+ style = {+ 'mean': (lambda v: f'mean {v:.1f}', INK, (0, (5, 3))),+ 'median': (lambda v: f'median {v:g}', MUTED, (0, (1.5, 2.5))),+ }+ (lo_v, lo_kind), (hi_v, hi_kind) = sorted([(mean_v, 'mean'), (median_v, 'median')])+ room_on_left = x_frac(ax, lo_v) >= edge_frac+ for value, kind, side, y_frac in (+ (lo_v, lo_kind, 'right' if room_on_left else 'left', 0.985 if room_on_left else 0.90),+ (hi_v, hi_kind, 'left', 0.985),+ ):+ text, color, dash = style[kind]+ guide(ax, value, text(value), color, dash, side, y_frac=y_frac)+++def legend_loc_clear_of(ax, guide_xs, label_frac=0.2, legend_frac=0.3):+ """Upper corner for the legend that the top-hung guide labels don't reach.++ Guide labels extend ~*label_frac* of the axis from their line (the+ smaller value leftward, the larger rightward); the legend occupies+ ~*legend_frac* from its corner. Prefer upper right; fall back to upper+ left when the rightmost guide label would reach into it.+ """+ fr = [x_frac(ax, x) for x in guide_xs]+ if not fr or max(fr) + label_frac <= 1.0 - legend_frac:+ return 'upper right'+ if min(fr) - label_frac >= legend_frac:+ return 'upper left'+ return 'upper right'+++def threshold_guides(ax, thresholds, fmt, at_bottom=()):+ """Dashed guide per threshold, labeled along the line with ``fmt(t)``.++ Labels hang from the top; thresholds in *at_bottom* (where a curve still+ runs near the top) are labeled from the baseline instead.+ """+ for t in thresholds:+ ax.axvline(t, color=EDGE, linewidth=1.0, linestyle=(0, (5, 3)), zorder=3)+ bottom = t in at_bottom+ ax.annotate(fmt(t), xy=(t, 0.03 if bottom else 0.985),+ xycoords=ax.get_xaxis_transform(),+ xytext=(4, 0), textcoords='offset points',+ rotation=90, ha='left', va='bottom' if bottom else 'top',+ fontsize=9, color=MUTED, zorder=4)+++def crowded_top(value_at, thresholds, limit=0.8):+ """Thresholds where the curve value ``value_at(t)`` is high enough to+ collide with a top-hung label."""+ return {t for t in thresholds if value_at(t) > limit}+++def mark_points(ax, points, fmt=lambda y: f'{y:.1%}', color=ACCENT_DK,+ prefer='above', edge=0.1):+ """Filled markers with a white ring and an offset value label.++ *prefer* puts the label above-right (free space beside a falling+ survival curve) or below-right (free space beside a rising cumulative+ curve); within *edge* of the y-range's top or bottom the side flips so+ the label stays inside the panel.+ """+ y_lo, y_hi = ax.get_ylim()+ span = y_hi - y_lo+ for x, y in points:+ ax.plot([x], [y], marker='o', markersize=6.5, color=color,+ markeredgecolor='white', markeredgewidth=1.2, zorder=6)+ above = prefer == 'above'+ if above and y > y_hi - edge * span:+ above = False+ elif not above and y < y_lo + edge * span:+ above = True+ ax.annotate(fmt(y), (x, y), xytext=(6, 5 if above else -6),+ textcoords='offset points', va='bottom' if above else 'top',+ fontsize=10, color=INK, zorder=6)+++def finish_figure(fig, title, subtitle, out_base, pdf):+ """Title + subtitle, shared layout, save PNG (+ PDF), close. Returns the+ written paths."""+ fig.suptitle(title, y=0.985, fontsize=14, fontweight='semibold', color=INK)+ fig.text(0.5, 0.895, subtitle, ha='center', va='top', fontsize=10.5, color=MUTED)+ fig.subplots_adjust(left=LEFT, right=RIGHT, top=TOP, bottom=BOTTOM, wspace=WSPACE)+ os.makedirs(os.path.dirname(os.path.abspath(out_base)), exist_ok=True)+ written = [out_base + '.png']+ fig.savefig(written[0])+ if pdf:+ written.append(out_base + '.pdf')+ fig.savefig(written[1])+ plt.close(fig)+ return written+++def per_dataset_out_base(path, label, per_dataset_dir, suffix):+ """Where a per-dataset figure goes and whether a PDF is allowed.++ Default: beside the source JSON as ``<stem>_<suffix>`` (PNG only, so the+ export directory carries its own figure). With *per_dataset_dir*:+ ``<dir>/<label>_<stem>_<suffix>`` (PDF allowed).+ """+ stem = os.path.splitext(os.path.basename(path))[0]+ if per_dataset_dir:+ return os.path.join(per_dataset_dir, f'{label}_{stem}_{suffix}'), True+ return os.path.join(os.path.dirname(os.path.abspath(path)), f'{stem}_{suffix}'), Falsediff --git a/data_process/utils/fbx2glb.py b/data_process/utils/fbx2glb.pynew file mode 100644index 0000000..463c63f--- /dev/null+++ b/data_process/utils/fbx2glb.py@@ -0,0 +1,69 @@+"""Shared batch driver for the per-file FBX -> GLB conversion tools.++``tools/truebones_fbx2glb.py`` (per-clip animation) and+``tools/character_fbx2glb.py`` (rigged T-pose character) differ only in what one+conversion does; the CLI around it — sharding across workers, resume, per-worker+error log — is identical and lives here.++bpy-free: only the ``convert`` callback touches Blender, so this module imports+in a plain Python process.+"""++import argparse+import os+import sys++from loguru import logger+++def parse_batch_args(description):+ """The fbx2glb CLI, parsed from the argv Blender leaves after ``--``."""+ parser = argparse.ArgumentParser(description=description)+ parser.add_argument('--data_dir', type=str, required=True,+ help='Flat directory of input FBX files.')+ parser.add_argument('--output_dir', type=str, required=True,+ help='Destination directory for the GLB files.')+ parser.add_argument('--worker_id', type=int, default=0,+ help='Worker index for sharding across workers.')+ parser.add_argument('--num_workers', type=int, default=1,+ help='Total number of workers.')+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]+ return parser.parse_args(argv)+++def run_batch(args, convert, unit='FBX files'):+ """Run ``convert(fbx_path, glb_path)`` over every FBX under ``args.data_dir``.++ Resumable (an existing GLB is skipped) and fault-tolerant: a file that raises+ is recorded in ``<output_dir>/fbx2glb_errors_worker<id>.log`` and the batch+ goes on. Exits non-zero if anything failed.+ """+ fbx_files = sorted(f for f in os.listdir(args.data_dir) if f.lower().endswith('.fbx'))+ logger.info(f"Found {len(fbx_files)} {unit} in {args.data_dir}")++ if args.num_workers > 1:+ fbx_files = fbx_files[args.worker_id::args.num_workers]+ logger.info(f"Worker {args.worker_id}/{args.num_workers}: {len(fbx_files)} files")++ os.makedirs(args.output_dir, exist_ok=True)+ error_log = os.path.join(args.output_dir, f'fbx2glb_errors_worker{args.worker_id}.log')++ n_ok = n_skip = n_fail = 0+ for fbx_file in fbx_files:+ glb_path = os.path.join(args.output_dir, os.path.splitext(fbx_file)[0] + '.glb')+ if os.path.exists(glb_path):+ n_skip += 1+ continue+ try:+ convert(os.path.join(args.data_dir, fbx_file), glb_path)+ n_ok += 1+ except Exception as e: # noqa: BLE001 — keep the batch going+ logger.error(f"Failed to convert {fbx_file}: {e}")+ with open(error_log, 'a') as f:+ f.write(f"{fbx_file}\t{e}\n")+ n_fail += 1++ logger.info(f"Done: {n_ok} converted, {n_skip} skipped, {n_fail} failed "+ f"-> {args.output_dir}")+ if n_fail:+ sys.exit(1)diff --git a/data_process/utils/motion_features.py b/data_process/utils/motion_features.pyindex 36ece22..e35e1c5 100644--- a/data_process/utils/motion_features.py+++ b/data_process/utils/motion_features.py@@ -58,8 +58,7 @@ from data_process.utils.plotting import (save_skeleton_motion,save_skeleton_motion_ground,save_skeleton_motion_spectral,- save_skeleton_tpose,- save_skeleton_tpos_spectral,+ save_skeleton_tpose_ground,)from data_process.feature_extraction.metadata import (atomic_output_path,@@ -72,6 +71,16 @@ from data_process.feature_extraction.metadata import (# by zero).MIN_SKELETON_DIAMETER = 1e-8+# Preview geometry, shared by the clip MP4s and the T-pose cards so the two+# read as one set. The cost of a frame is dominated by matplotlib's 3D+# projection, not by rasterising it: measured on a 60-frame clip, 960x960 runs+# within 4% of 640x640 (45 -> 47 ms/frame) while 1280x1280 costs 36% more. 150+# dpi is therefore close to free, and dpi (rather than figsize) is the knob to+# turn — it leaves the point-based layout, and so the caption's wrapping and+# relative type size, exactly as it was.+PREVIEW_FIGSIZE = (6.4, 6.4)+PREVIEW_DPI = 150+class DegenerateSkeletonError(ValueError):"""Raised when a T-pose cannot be canonicalized (e.g. zero-length bones).@@ -236,11 +245,19 @@ def _load_npz_anim(object_npz_path, raw_parents, raw_njoints,motion_anim = motion_anim[:, corps_idxs]motion_anim = motion_anim[:, bfs_order]- if fps >= 60:+ # ``fps`` is the object-level rate, read once from the T-pose reference+ # NPZ; a clip re-exported at a different rate carries its own, which wins.+ clip_fps = int(anim_data['fps']) if 'fps' in anim_data else int(fps)+ if clip_fps != int(fps):+ logger.warning(f'Clip fps {clip_fps} differs from the object-level '+ f'{int(fps)} fps; using the clip\'s own: {object_npz_path}')++ # Halve until below 60 fps. A single halving leaves a 120 fps source at+ # 60, i.e. twice the per-frame velocity scale of every 30 fps clip.+ motion_fps = clip_fps+ while motion_fps >= 60 and len(motion_anim) > 1:motion_anim = motion_anim[::2]- motion_fps = fps // 2- else:- motion_fps = fps+ motion_fps //= 2return motion_anim, motion_fps, None@@ -473,6 +490,47 @@ def _activity_below_threshold(global_positions, threshold):return is_low, metrics+def _discontinuity_metrics(global_positions):+ """Per-frame mean joint displacement in body units, plus its median / max.++ A clip stitched together from several actions (or one with a teleporting+ root) shows a single frame whose displacement dwarfs the rest of the clip.+ """+ if len(global_positions) < 2:+ return {'step_med': 0.0, 'step_max': 0.0, 'jump_ratio': 0.0, 'jump_frames': 0}+ extent = float(np.ptp(global_positions.reshape(-1, 3), axis=0).max()) or 1.0+ step = np.linalg.norm(np.diff(global_positions, axis=0), axis=2).mean(1) / extent+ med = float(np.median(step))+ mx = float(step.max())+ return {'step_med': med, 'step_max': mx,+ 'jump_ratio': float(mx / med) if med > 1e-9 else float('inf'),+ 'jump_frames': int((step > max(6 * med, 0.05)).sum())}+++def _discontinuity_above_threshold(global_positions, step_threshold, ratio_threshold):+ """Return (is_discontinuous, metrics).++ Flags a clip when one frame moves the skeleton at least *step_threshold*+ body lengths AND that step is at least *ratio_threshold* times the clip's+ median step — the signature of concatenated actions, not of fast motion,+ which raises the median too. Non-finite input counts as discontinuous.+ """+ if not np.isfinite(global_positions).all():+ return True, {'step_med': 0.0, 'step_max': float('inf'),+ 'jump_ratio': float('inf'), 'jump_frames': len(global_positions)}+ metrics = _discontinuity_metrics(global_positions)+ is_bad = (metrics['step_max'] >= step_threshold+ and metrics['jump_ratio'] >= ratio_threshold)+ return is_bad, metrics+++def _format_discontinuity(metrics):+ return (f'max_step={metrics["step_max"]:.3f} body/frame, '+ f'median={metrics["step_med"]:.4f}, '+ f'ratio={metrics["jump_ratio"]:.1f}, '+ f'jump_frames={metrics["jump_frames"]}')++def _format_activity(metrics):return (f'joint={metrics["joint_activity"]:.4f}, 'f'topk={metrics["joint_activity_topk"]:.4f}, '@@ -523,7 +581,7 @@ def save_clip(clip_name,save_path=clip_vis_path, parents=parents,positions=global_positions, spectral_feats=spectral_feats,fps=int(motion_fps), title=title,- figsize=(6.4, 6.4), dpi=100,+ figsize=PREVIEW_FIGSIZE, dpi=PREVIEW_DPI,)returnif spectral_feats is not None:@@ -531,34 +589,34 @@ def save_clip(clip_name,save_path=clip_vis_path, parents=parents,positions=global_positions, spectral_feats=spectral_feats,fps=int(motion_fps), title=title,- figsize=(6.4, 6.4), dpi=100,+ figsize=PREVIEW_FIGSIZE, dpi=PREVIEW_DPI,)else:save_skeleton_motion(save_path=clip_vis_path, parents=parents,positions=global_positions, fps=int(motion_fps), title=title,- figsize=(6.4, 6.4), dpi=100,+ figsize=PREVIEW_FIGSIZE, dpi=PREVIEW_DPI,)def _save_tpose_vis(save_dir, object_type, parents, tpos_anim,spectral_feats=None):+ """Write the object's canonical rest pose as ``tpose/<object_type>.png``.++ Same checkerboard floor, framing and caption type as the clip previews+ beside it, captioned with the object type, so a T-pose card and the+ object's MP4s read as one set. ``spectral_feats``, when given, colours+ the joints with the same PCA palette the previews use.+ """tpos_save_dir = pjoin(save_dir, 'tpose')os.makedirs(tpos_save_dir, exist_ok=True)tpos_vis_path = pjoin(tpos_save_dir, f'{object_type}.png')tpos_global_pos = positions_global(tpos_anim)[0]- if spectral_feats is not None:- save_skeleton_tpos_spectral(- save_path=tpos_vis_path, parents=parents,- positions=tpos_global_pos, spectral_feats=spectral_feats,- figsize=(6.4, 6.4), dpi=100,- )- else:- save_skeleton_tpose(- save_path=tpos_vis_path, parents=parents,- positions=tpos_global_pos,- figsize=(6.4, 6.4), dpi=100,- )+ save_skeleton_tpose_ground(+ save_path=tpos_vis_path, parents=parents,+ positions=tpos_global_pos, spectral_feats=spectral_feats,+ title=object_type, figsize=PREVIEW_FIGSIZE, dpi=PREVIEW_DPI,+ )# ===========================================================================@@ -625,6 +683,16 @@ def _process_motion_file(object_npz_path, ctx):})continue+ is_jumpy, jump_metrics = _discontinuity_above_threshold(+ clip_global_positions, ctx['jump_step_threshold'],+ ctx['jump_ratio_threshold'])+ if is_jumpy:+ filtered.append({+ 'name': clip_name,+ 'reason': f'discontinuous motion: {_format_discontinuity(jump_metrics)}',+ })+ continue+save_clip(clip_name,clip_global_positions, clip_local_rotations,@@ -655,6 +723,7 @@ def process_object(object_type, object_npzs, save_dir,expected_names=None, require_face=False,target_diameter=2.0, activity_threshold=0.02,static_threshold=1e-05, min_frames=8,+ jump_step_threshold=0.2, jump_ratio_threshold=8.0,min_joints=None, max_joints=None,use_tpos_ground_height=False, save_vis=True,vis_ground=False):@@ -777,6 +846,8 @@ def process_object(object_type, object_npzs, save_dir,'activity_threshold': activity_threshold,'static_threshold': static_threshold,'min_frames': min_frames,+ 'jump_step_threshold': jump_step_threshold,+ 'jump_ratio_threshold': jump_ratio_threshold,# I/O'motions_save_dir': motions_save_dir,'animations_save_dir': animations_save_dir,diff --git a/data_process/utils/plotting.py b/data_process/utils/plotting.pyindex 19f3c87..e4ebebe 100644--- a/data_process/utils/plotting.py+++ b/data_process/utils/plotting.py@@ -14,6 +14,7 @@ Two families of functions:save_skeleton_* -> write PNG (pose) / MP4 (motion) to disk"""+import textwrapfrom pathlib import Pathfrom typing import List, Optional, Sequence, Tuple@@ -364,6 +365,85 @@ def render_skeleton_tpose(parents: Sequence[int], positions,return _capture_rgb(canvas)+def render_skeleton_tpose_facing(parents: Sequence[int], positions,+ face_joint_idxs: Optional[Sequence[int]] = None,+ forward=None,+ target_forward=None,+ elev: float = 30,+ azim: float = -60,+ rotate_root: bool = True,+ arrow_scale: float = 0.35,+ title: Optional[str] = None,+ extra_markers=None,+ figsize: Tuple[float, float] = (6, 6),+ dpi: int = 120) -> np.ndarray:+ """Rest pose with its facing pair highlighted, as an (H, W, 3) uint8 image.++ ``face_joint_idxs`` is ``[r_hip, l_hip]`` (drawn red / blue, joined by a+ dashed magenta line); ``forward`` is the facing direction those joints+ imply, drawn as a green arrow from the root, and ``target_forward`` (e.g.+ +Z after canonicalization) as a grey arrow. Arrows are ``arrow_scale``+ times the cubic-bound side. ``extra_markers`` is an optional list of+ ``(joint_indices, color, marker, label)`` tuples drawn on top (with a+ legend) — e.g. the Head / Tail End joints, to read the facing at a glance.+ Same camera as :func:`render_skeleton_tpose`, so the image lines up with+ the export-stage ``tpose/<rig>.png``.+ """+ pts = _as_xyz(positions).reshape(-1, 3)+ pts = _maybe_rotate_y_up(pts, rotate_root)+ edges = _edges_from_parents(parents)+ bounds = _cubic_bounds(pts)+ x_min, x_max, y_min, y_max, z_min, z_max = bounds+ arrow_len = max(x_max - x_min, y_max - y_min, z_max - z_min) * arrow_scale++ fig, canvas, ax = _new_figure(bounds, elev, azim, figsize=figsize, dpi=dpi)+ _draw_static_skeleton(ax, pts, parents, edges)++ if face_joint_idxs is not None and len(face_joint_idxs) >= 2 \+ and min(face_joint_idxs[:2]) >= 0:+ r, l = int(face_joint_idxs[0]), int(face_joint_idxs[1])+ for j, color in ((r, 'red'), (l, 'blue')):+ ax.scatter(pts[j:j + 1, 0], pts[j:j + 1, 1], pts[j:j + 1, 2],+ s=90, c=color, edgecolors='black', linewidths=1.0,+ depthshade=False, zorder=12)+ ax.plot([pts[r, 0], pts[l, 0]], [pts[r, 1], pts[l, 1]],+ [pts[r, 2], pts[l, 2]], color='magenta', linestyle='--',+ linewidth=1.5, zorder=11)++ root = pts[0]+ for vec, color, width in ((target_forward, '0.55', 3.0), (forward, 'green', 2.5)):+ if vec is None:+ continue+ d = np.asarray(vec, dtype=np.float32).reshape(3)+ n = float(np.linalg.norm(d))+ if n < 1e-8:+ continue+ d = _maybe_rotate_y_up(d / n, rotate_root)+ ax.quiver(root[0], root[1], root[2], d[0], d[1], d[2],+ length=arrow_len, normalize=False, color=color,+ linewidth=width, arrow_length_ratio=0.25, zorder=13)++ if extra_markers:+ drawn = False+ for idxs, color, marker, label in extra_markers:+ idxs = [int(i) for i in idxs if 0 <= int(i) < len(pts)]+ if not idxs:+ continue+ ax.scatter(pts[idxs, 0], pts[idxs, 1], pts[idxs, 2], s=110, c=color,+ marker=marker, edgecolors='black', linewidths=0.8,+ depthshade=False, zorder=14, label=label)+ drawn = True+ if drawn:+ handles, labels = ax.get_legend_handles_labels()+ fig.legend(handles, labels, loc='lower center', ncol=max(1, len(labels)),+ fontsize=7, framealpha=0.8, bbox_to_anchor=(0.5, 0.012))++ if title:+ fig.suptitle(title, fontsize=9, wrap=True, y=0.99)+ fig.subplots_adjust(top=0.90)+ return _capture_rgb(canvas)++def render_skeleton_tpose_annotated(parents: Sequence[int], positions,joint_names: Sequence[str],elev: float = 30,@@ -554,8 +634,7 @@ def render_skeleton_motion(parents: Sequence[int], positions,bounds = _cubic_bounds(pts)fig, canvas, ax = _new_figure(bounds, elev, azim, figsize=figsize, dpi=dpi)if title:- fig.suptitle(title, fontsize=12, fontweight='bold', wrap=True, y=0.98)- fig.subplots_adjust(top=0.90)+ _draw_caption(fig, title, figsize)joint_colors = np.where(np.asarray(parents) == -1, 'r', 'b')segs, lc, sc = _init_motion_artists(ax, edges, pts[0], joint_colors,@@ -601,8 +680,7 @@ def render_skeleton_motion_spectral(parents: Sequence[int], positions,bounds = _cubic_bounds(pts)fig, canvas, ax = _new_figure(bounds, elev, azim, figsize=figsize, dpi=dpi)if title:- fig.suptitle(title, fontsize=12, fontweight='bold', wrap=True, y=0.98)- fig.subplots_adjust(top=0.90)+ _draw_caption(fig, title, figsize)colors = _spectral_to_rgb(spectral_feats)segs, lc, sc = _init_motion_artists(@@ -696,59 +774,159 @@ def render_skeleton_motion_directed(parents: Sequence[int], positions,return np.stack(frames, axis=0)-_CHECKER_COLORS = ((0.93, 0.93, 0.93), (0.885, 0.885, 0.885))---def _checker_platform_local(platform_half: float, n_tiles: int, z: float):- """A RIGID checker platform in platform-local coordinates.+# ============================================================================+# Ground-plane motion render+# ============================================================================- Returns ``(quads, colors)`` for an ``n_tiles`` × ``n_tiles`` board- centered on the origin. The pattern is glued to the platform: the whole- board is translated rigidly per frame, so nothing about the ground ever- changes on screen (world-anchored tiles clipped to a sliding window- made the edge tiles boil). Keeping the board small and near the camera- also avoids matplotlib's broken projection of far/behind-camera quads.- """- tile = 2.0 * platform_half / n_tiles- quads, colors = [], []- for i in range(n_tiles):- xa = -platform_half + i * tile- for j in range(n_tiles):- ya = -platform_half + j * tile- quads.append([(xa, ya, z), (xa + tile, ya, z),- (xa + tile, ya + tile, z), (xa, ya + tile, z)])- colors.append(_CHECKER_COLORS[(i + j) % 2])- return np.asarray(quads, dtype=np.float32), colors---def _checker_tiles_window(cx: float, cy: float, view_half: float,- tile: float, z: float, margin_tiles: int = 2):- """WHOLE world-anchored tiles covering the view window plus a margin.-- Every tile is drawn complete (never clipped), and the drawn set only- changes by whole tiles entering/leaving beyond the visible edge — so a- sliding camera sees a rigid floor scrolling underfoot with no edge- boiling. The margin keeps the set's boundary off screen while staying- small enough to avoid matplotlib's broken far/behind-camera projection.+# Two checker greys plus the background the floor dissolves into toward the+# horizon. Cool-tinted and more separated than a hairline pair: the tiles+# must read as a floor at 640 px without competing with the skeleton.+_CHECKER_COLORS = np.array([(0.910, 0.917, 0.930),+ (0.822, 0.834, 0.860)], dtype=np.float32)+_GROUND_BG = np.array([1.0, 1.0, 1.0], dtype=np.float32)+_SHADOW_COLOR = (0.55, 0.57, 0.61)+_TRAIL_COLOR = (0.95, 0.49, 0.11)+_BONE_COLOR = (0.27, 0.29, 0.33)+++def _ground_tiles(ax, cx: float, cy: float, azim: float, view_half: float,+ tile: float, z: float,+ fade_start: float = 1.0, fade_end: float = 4.5,+ fade_subdiv: int = 2):+ """World-anchored whole checker tiles for the ground under the camera.++ Every tile is drawn complete, so the drawn set only changes by whole+ tiles entering/leaving as the camera glides — a rigid floor scrolling+ underfoot, with no edge boiling and no clipped slivers.++ Two things keep the floor from reading as a floating slab. Candidate+ tiles are culled by projecting their corners to pixels and keeping only+ those the frame actually shows, so the near floor stays solid into the+ bottom corners while the drawn set stays small. And the fade runs along+ the camera's view direction alone, from ``fade_start`` to ``fade_end``+ (multiples of ``view_half``): the floor dissolves into the background+ toward the horizon and nowhere else.++ A flat-shaded quad can only carry one colour, so a fade evaluated per+ tile quantises into tile-sized steps — and against the alternating+ checker those steps read as hard banding at the horizon. Each tile is+ therefore split into ``fade_subdiv`` x ``fade_subdiv`` sub-quads that+ share the tile's checker colour but fade individually, which divides the+ step size by ``fade_subdiv`` without touching the pattern — the fade then+ reads as a gradient across each tile rather than as a flat step between+ tiles. Only tiles inside the ramp are split (see below); 2 buys most of+ the smoothing at ~1.6x the frame cost, 3 is smoother again at ~2.5x.++ Returns ``(quads (N, 4, 3), colors (N, 3))``."""- i0 = int(np.floor((cx - view_half) / tile)) - margin_tiles- i1 = int(np.floor((cx + view_half) / tile)) + margin_tiles- j0 = int(np.floor((cy - view_half) / tile)) - margin_tiles- j1 = int(np.floor((cy + view_half) / tile)) + margin_tiles- quads, colors = [], []- for i in range(i0, i1 + 1):- xa = i * tile- for j in range(j0, j1 + 1):- ya = j * tile- quads.append([(xa, ya, z), (xa + tile, ya, z),- (xa + tile, ya + tile, z), (xa, ya + tile, z)])- colors.append(_CHECKER_COLORS[(i + j) % 2])+ theta = np.deg2rad(azim)+ # Horizontal direction the camera looks along (it sits at ``azim``), and+ # its normal: "deeper into the scene" and "across it".+ u_hat = np.array([-np.cos(theta), -np.sin(theta)], dtype=np.float32)+ v_hat = np.array([-u_hat[1], u_hat[0]], dtype=np.float32)++ # Candidate window: the axis-aligned bounds of a ground wedge that+ # comfortably contains everything the camera can see out to fade_end.+ near, width, spread = 3.0, 3.8, 1.2+ far_width = width + spread * fade_end+ corners = np.array([(-near, -width), (-near, width),+ (fade_end, -far_width), (fade_end, far_width)],+ dtype=np.float32) * view_half+ world = (corners[:, :1] * u_hat + corners[:, 1:] * v_hat+ + np.array([cx, cy], dtype=np.float32))+ i0 = int(np.floor(world[:, 0].min() / tile))+ i1 = int(np.floor(world[:, 0].max() / tile))+ j0 = int(np.floor(world[:, 1].min() / tile))+ j1 = int(np.floor(world[:, 1].max() / tile))+ ii, jj = np.meshgrid(np.arange(i0, i1 + 1), np.arange(j0, j1 + 1),+ indexing='ij')+ ii = ii.ravel()+ jj = jj.ravel()+ xa = (ii * tile).astype(np.float32)+ ya = (jj * tile).astype(np.float32)++ # Coarse cull first, in the wedge's own frame: it drops the ~half of the+ # index rectangle that lies outside the wedge for the price of two dot+ # products, so the exact (but pricier) pixel test below runs on far+ # fewer tiles.+ dx = xa + tile / 2 - cx+ dy = ya + tile / 2 - cy+ du = dx * u_hat[0] + dy * u_hat[1]+ dv = dx * v_hat[0] + dy * v_hat[1]+ inside = ((du > -near * view_half - tile) &+ (du < fade_end * view_half + tile) &+ (np.abs(dv) < width * view_half+ + spread * np.maximum(du, 0.0) + tile))+ ii, jj = ii[inside], jj[inside]+ xa, ya, du = xa[inside], ya[inside], du[inside]++ zc = np.full_like(xa, z)+ quads = np.stack([+ np.stack([xa, ya, zc], axis=1),+ np.stack([xa + tile, ya, zc], axis=1),+ np.stack([xa + tile, ya + tile, zc], axis=1),+ np.stack([xa, ya + tile, zc], axis=1),+ ], axis=1)+ # The pixel cull below runs on whole tiles — cheaper, and a sub-quad can+ # never fall outside its parent.++ # Keep a tile when any corner lands on (or just off) the canvas.+ flat = quads.reshape(-1, 3)+ sx, sy, _ = proj3d.proj_transform(flat[:, 0], flat[:, 1], flat[:, 2],+ ax.get_proj())+ scr = ax.transData.transform(np.column_stack([sx, sy]))+ scr = scr.reshape(-1, 4, 2)+ w, h = ax.figure.bbox.size+ pad = 0.05 * max(w, h)+ on_screen = ((scr[..., 0] > -pad) & (scr[..., 0] < w + pad) &+ (scr[..., 1] > -pad) & (scr[..., 1] < h + pad)).any(axis=1)+ ii, jj, du = ii[on_screen], jj[on_screen], du[on_screen]+ quads = quads[on_screen]++ # Sub-divide, but only across the ramp: nearer than fade_start every+ # sub-quad would come out at f = 0 and beyond fade_end at f = 1, so+ # splitting there buys nothing and the extra polygons are drawn on every+ # frame, not just on a floor rebuild. One tile of margin covers the tiles+ # that straddle either end.+ n = max(1, int(fade_subdiv))+ if n > 1:+ margin = tile / max(view_half, 1e-9)+ dun = du / max(view_half, 1e-9)+ in_ramp = (dun > fade_start - margin) & (dun < fade_end + margin)+ if in_ramp.any():+ sub = tile / n+ off = np.arange(n, dtype=np.float32) * sub+ ox, oy = np.meshgrid(off, off, indexing='ij')+ ox, oy = ox.ravel(), oy.ravel() # (n*n,)+ qr = quads[in_ramp]+ xs = (qr[:, 0, 0][:, None] + ox[None, :]).ravel()+ ys = (qr[:, 0, 1][:, None] + oy[None, :]).ravel()+ zs = np.full_like(xs, z)+ sub_quads = np.stack([+ np.stack([xs, ys, zs], axis=1),+ np.stack([xs + sub, ys, zs], axis=1),+ np.stack([xs + sub, ys + sub, zs], axis=1),+ np.stack([xs, ys + sub, zs], axis=1),+ ], axis=1)+ dx = xs + sub / 2 - cx+ dy = ys + sub / 2 - cy+ quads = np.concatenate([quads[~in_ramp], sub_quads], axis=0)+ du = np.concatenate([du[~in_ramp],+ dx * u_hat[0] + dy * u_hat[1]])+ ii = np.concatenate([ii[~in_ramp], np.repeat(ii[in_ramp], n * n)])+ jj = np.concatenate([jj[~in_ramp], np.repeat(jj[in_ramp], n * n)])++ base = _CHECKER_COLORS[(ii + jj) % 2]+ du = du / max(view_half, 1e-9)+ f = np.clip((du - fade_start) / max(fade_end - fade_start, 1e-9), 0.0, 1.0)+ f = (f * f * (3.0 - 2.0 * f))[:, None] # smoothstep+ colors = base * (1.0 - f) + _GROUND_BG * freturn quads, colorsdef _smooth_path(path: np.ndarray, window: int) -> np.ndarray:"""Moving-average smoothing with edge padding; kills gait sway so the- follow camera and platform glide instead of bobbing with each step."""+ follow camera glides instead of bobbing with each step."""if window <= 1 or len(path) < 3:return pathkernel = np.ones(window, dtype=np.float32) / window@@ -758,6 +936,96 @@ def _smooth_path(path: np.ndarray, window: int) -> np.ndarray:for d in range(path.shape[1])], axis=1)+# The house sans stack, shared with the dataset-statistics figures: those+# import SANS_STACK from here for their ``font.sans-serif``, so a caption in a+# clip preview and a label in clip_frames_distribution.png are the same face by+# construction and cannot drift apart. Order and contents are the figures'+# original list, kept verbatim.+SANS_STACK = ['Helvetica', 'Arial', 'DejaVu Sans', 'Liberation Sans']+++def _installed_family(preferred):+ """Keep only the faces this machine actually has, + the bundled fallback.++ Naming a missing family makes matplotlib emit one ``findfont: Font family+ ... not found`` warning per text draw — tens of thousands of lines over a+ dataset render — so the stack is resolved once, at import. DejaVu Sans+ ships with matplotlib itself, so the result is never empty.+ """+ try:+ from matplotlib import font_manager as fm+ have = {f.name for f in fm.fontManager.ttflist}+ except Exception: # noqa: BLE001 — never fail an import over fonts+ have = set()+ stack = [f for f in preferred if f in have]+ if 'DejaVu Sans' not in stack:+ stack.append('DejaVu Sans')+ return stack+++# Caption typography for the rendered clip previews and T-pose cards.+CAPTION_FONT_FAMILY = _installed_family(SANS_STACK)+CAPTION_FONT_SIZE = 13.0+# dist_plot.finish_figure titles at this weight. DejaVu Sans has no semibold+# face, so matplotlib resolves it to DejaVuSans-Bold.ttf — matching the family+# is not enough, the weight is what picks the actual font file.+CAPTION_FONT_WEIGHT = 'semibold'+CAPTION_COLOR = '#1F2937' # dist_plot.INK+# Figure-fraction height one caption line costs the plot area, per point of+# type. Multiplied by the font size and the line count by _draw_caption.+_CAPTION_LINE_DROP = 0.0042+++def _mean_advance_pt(font_pt: float, family=None) -> float:+ """Mean glyph advance of *family* at *font_pt*, in points.++ Measured from the real face rather than assumed, so the wrap width stays+ right when the caption font or size changes (DejaVu averages ~0.545 em,+ Nimbus Sans ~0.50 — hard-coding either mis-wraps the other).+ """+ probe = ('abcdefghijklmnopqrstuvwxyz '+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ etaoinshrdlu')+ try:+ from matplotlib.font_manager import FontProperties+ from matplotlib.textpath import TextPath+ fp = FontProperties(family=family or CAPTION_FONT_FAMILY, size=font_pt,+ weight=CAPTION_FONT_WEIGHT)+ width = TextPath((0, 0), probe, prop=fp).get_extents().width+ if width > 0:+ return float(width) / len(probe)+ except Exception: # noqa: BLE001 — fall back rather than fail a render+ pass+ return 0.545 * font_pt+++def _wrap_title(text: str, fig_width_in: float, font_pt: float,+ family=None, fill: float = 0.92) -> str:+ """Hard-wrap a caption to the figure width (suptitle's own wrapping is+ unreliable and long captions ran off both edges).++ ``fill`` is the share of the figure width a full line may occupy.+ """+ chars = max(24, int(fig_width_in * 72.0 * fill / _mean_advance_pt(font_pt, family)))+ return '\n'.join(textwrap.wrap(text, chars)) or text+++def _draw_caption(fig, text: str, figsize, font_pt: float = CAPTION_FONT_SIZE,+ top_base: float = 0.94) -> None:+ """Draw a wrapped clip caption across the top of *fig* and make room for it.++ Plain label type, not a heading: a caption is there to be read off, not to+ be the loudest thing in the frame. The plot area gives up height in+ proportion to the type size and the number of wrapped lines, so a long+ caption never lands on top of the subject.+ """+ wrapped = _wrap_title(text, figsize[0], font_pt, CAPTION_FONT_FAMILY)+ n_lines = wrapped.count('\n') + 1+ fig.text(0.5, 0.988, wrapped, ha='center', va='top',+ color=CAPTION_COLOR, fontsize=font_pt,+ fontfamily=CAPTION_FONT_FAMILY, fontweight=CAPTION_FONT_WEIGHT)+ fig.subplots_adjust(top=top_base - _CAPTION_LINE_DROP * font_pt * n_lines)++def render_skeleton_motion_ground(parents: Sequence[int], positions,spectral_feats=None,elev: float = 20,@@ -765,17 +1033,29 @@ def render_skeleton_motion_ground(parents: Sequence[int], positions,rotate_root: bool = True,follow: bool = True,title: Optional[str] = None,- joint_marker_size: float = 14.0,- bone_linewidth: float = 1.6,+ title_font_size: float = CAPTION_FONT_SIZE,+ joint_marker_size: float = 18.0,+ bone_linewidth: float = 1.9,+ shadow: bool = True,+ trail: bool = True,+ view_margin: float = 1.0,figsize: Tuple[float, float] = (6, 6),dpi: int = 120) -> np.ndarray:- """Motion render with a checkerboard ground plane and root trajectory;- the camera follows the subject.-- The ground sits at the motion's lowest point, the view window is sized to- the subject (not the whole trajectory, so a long walk doesn't shrink the- character to a speck), and each frame re-centers the window on the root —- the checker tiles scrolling past convey world-space travel. Joints use+ """Motion render on a checkerboard floor, with a camera that follows the+ subject, a contact shadow and a fading root trail.++ The floor sits at the motion's lowest point and is world-anchored and+ unbounded (tiles are rebuilt around the camera each frame and fade out+ toward the horizon), so travel reads off the tiles scrolling underfoot+ rather than off a slab edge sweeping past. The view window is sized to+ the subject, not to the trajectory, so a long walk does not shrink the+ character to a speck.++ ``shadow`` drops the skeleton straight down onto the floor, which is what+ makes ground contact (and its absence, in a jump) legible. ``trail``+ draws the path the root has travelled so far, fading with age. ``title``+ is drawn as a plain black caption (hard-wrapped to the figure width) in+ the same label type the annotated T-pose renderer uses. Joints usethe spectral PCA palette when ``spectral_feats`` is given, else thedefault root-red / joint-blue scheme."""@@ -786,34 +1066,31 @@ def render_skeleton_motion_ground(parents: Sequence[int], positions,edges = _edges_from_parents(parents)ground_z = float(pts[..., 2].min())- root_xy = pts[:, 0, :2] # (T, 2)+ root_xy = pts[:, 0, :2].astype(np.float32) # (T, 2)# Window half-extent from the subject's own size, not the trajectory.radius_xy = float(np.abs(pts[..., :2] - root_xy[:, None, :]).max())height = float(pts[..., 2].max() - ground_z)- half = max(radius_xy * 1.08, height * 0.52, 1e-3)+ # ``view_margin`` > 1 pulls the camera back. The default frames a moving+ # subject tightly; a still pose is read for its shape, and a rest pose+ # that spreads its limbs along the ground (or rears a tail overhead)+ # wants the extra room so nothing touches the frame edge.+ half = max(radius_xy * 1.05, height * 0.50, 1e-3) * max(view_margin, 1e-3)# Coordinated motion: the camera GLIDES after the subject (smoothed root- # path) while the ground stays fixed in the WORLD — subject, ground and- # camera all move together, and world travel reads off the stage sliding- # through the frame plus the trail. The ground itself has two forms:- # stage — modest travel: one rigid bounded platform covering the- # whole trajectory, built once, world-fixed.- # scroll — extreme travel: world-anchored whole-tile floor windowed- # around the camera (a trajectory-sized stage would need far- # too many quads and far-away quads project badly).+ # path) while the floor stays fixed in the WORLD, so subject, floor and+ # camera all move together and world travel reads off the tiles sliding+ # through the frame plus the trail.traj_center = 0.5 * (root_xy.max(axis=0) + root_xy.min(axis=0))traj_half = float((root_xy.max(axis=0) - root_xy.min(axis=0)).max()) / 2.0- stage_half = traj_half + half * 1.05- scroll_mode = stage_half > 4.0 * half- view_half = half if follow else max(stage_half, half)+ view_half = half if follow else max(traj_half + half, half)centers = _smooth_path(root_xy, window=max(5, T // 12)) if follow \else np.repeat(traj_center[None, :], T, axis=0)center0 = centers[0]# Vertical extent hugs the subject (tall bipeds and flat crawlers both# fill the frame); the box aspect mirrors the ranges to avoid distortion.- z_top = ground_z + max(height * 1.18, view_half * 0.3)+ z_top = ground_z + max(height * 1.15, view_half * 0.3)bounds = (center0[0] - view_half, center0[0] + view_half,center0[1] - view_half, center0[1] + view_half,ground_z, z_top)@@ -822,59 +1099,74 @@ def render_skeleton_motion_ground(parents: Sequence[int], positions,box_aspect=(1.0, 1.0, (z_top - ground_z) / (2 * view_half)))ax.set_axis_off()# Fill the canvas: with the axes cage hidden there is nothing to clip,- # so spill the 3D box past the figure edges.- fig.subplots_adjust(left=-0.22, right=1.22, top=1.18, bottom=-0.18)+ # so spill the 3D box past the figure edges. The bottom stays the most+ # conservative side — the subject's lowest joint sits exactly on the+ # lower z limit, so cropping there would cut its feet.+ fig.subplots_adjust(left=-0.26, right=1.26, top=1.24, bottom=-0.18)if title:- fig.suptitle(title, fontsize=12, fontweight='bold', wrap=True, y=0.97)- fig.subplots_adjust(top=1.02)+ _draw_caption(fig, title, figsize, title_font_size, top_base=1.15)from mpl_toolkits.mplot3d.art3d import Poly3DCollection- # Tile size from BOTH body dimensions — the geometric mean of height- # and horizontal span: an upright biped and a sprawling low body each- # get tiles proportioned to their overall bulk, and neither dimension- # alone can blow the scale up. View-based clamps keep it sane on- # degenerate shapes.+ # Tile size from BOTH body dimensions — the geometric mean of height and+ # horizontal span: an upright biped and a sprawling low body each get+ # tiles proportioned to their bulk, and neither dimension alone can blow+ # the scale up. The view-based clamp keeps 6-10 tiles across the window,+ # which is what makes travel legible without turning the floor into a+ # busy grid.body_span = 2.0 * radius_xytile = float(np.clip(0.35 * np.sqrt(max(height * body_span, 1e-12)),- half / 6.0, half / 2.0))- if scroll_mode:- # World-anchored whole tiles, refreshed per frame around the camera.- platform_half = 10 * view_half # trail clip bound (window handles it)- quads, cols = _checker_tiles_window(*center0, view_half, tile, ground_z)- platform = Poly3DCollection(quads, facecolors=cols,- edgecolors='none', zorder=0)- ax.add_collection3d(platform)- else:- # One rigid bounded stage, world-fixed, tiles glued to it. The- # following camera slides over it; the stage edges sweeping through- # the frame are what makes the travel visible.- platform_half = stage_half- n_tiles = int(np.clip(round(2 * platform_half / tile), 4, 16))- local_quads, quad_colors = _checker_platform_local(- platform_half, n_tiles=n_tiles, z=ground_z)- platform = Poly3DCollection(local_quads + np.array(- [traj_center[0], traj_center[1], 0.0], dtype=np.float32),- facecolors=quad_colors, edgecolors='none', zorder=0)- ax.add_collection3d(platform)+ view_half / 5.0, view_half / 3.0))+ quads, cols = _ground_tiles(ax, *center0, azim, view_half, tile,+ ground_z)+ # Stroking each tile in its own fill colour closes the hairline seams+ # matplotlib leaves between adjacent quads (they show up as white pin+ # dots where four tiles meet).+ platform = Poly3DCollection(quads, facecolors=cols, edgecolors=cols,+ linewidths=0.6, zorder=0)+ ax.add_collection3d(platform)+ # Rebuilding the floor is the single most expensive thing per frame, and+ # the tiles are world-anchored: nothing about them changes until the+ # camera has moved. Rebuild only after a fraction of a tile of travel+ # (an in-place motion then builds the floor exactly once); the cull pad+ # covers the tiles that enter during the interval.+ rebuild_at = np.array(center0, dtype=np.float32)+ rebuild_step = 0.2 * tileif spectral_feats is not None:spectral_feats = np.asarray(spectral_feats, dtype=np.float32)assert spectral_feats.shape[0] == Jjoint_colors = _spectral_to_rgb(spectral_feats)- edge_kwargs = dict(joint_edgecolors='k', joint_edgewidth=0.4)+ edge_kwargs = dict(joint_edgecolors='0.15', joint_edgewidth=0.4)else:joint_colors = np.where(np.asarray(parents) == -1, 'r', 'b')edge_kwargs = {}- # The trajectory sits just above the tiles to avoid z-fighting.- eps = half * 4e-3- trail, = ax.plot(root_xy[:1, 0], root_xy[:1, 1], [ground_z + eps],- color='tab:orange', linewidth=1.6, alpha=0.9, zorder=1)+ # Ground-level artists sit just above the tiles to avoid z-fighting.+ eps = max(view_half * 4e-3, 1e-6)+ shadow_lc = None+ if shadow:+ # A straight-down projection of the bones. Cheap, but it is what+ # makes foot contact — and its absence during a jump — legible.+ shadow_lc = Line3DCollection(np.zeros((len(edges), 2, 3), np.float32),+ colors=[_SHADOW_COLOR],+ linewidths=bone_linewidth * 1.5,+ alpha=0.28, zorder=1)+ ax.add_collection3d(shadow_lc)++ trail_lc = None+ if trail:+ # Age-faded so the head of the path (where the subject is now) is the+ # strongest mark and the tail recedes instead of ringing the floor.+ trail_lc = Line3DCollection(np.zeros((0, 2, 3), np.float32),+ linewidths=1.6, zorder=2)+ ax.add_collection3d(trail_lc)segs, lc, sc = _init_motion_artists(ax, edges, pts[0], joint_colors,- joint_size=joint_marker_size, bone_color='dimgray',+ joint_size=joint_marker_size, bone_color=_BONE_COLOR,bone_linewidth=bone_linewidth, **edge_kwargs)+ lc.set_zorder(3)+ sc.set_zorder(4)# The root must never be occluded: inside a single scatter, points paint# in array order, so joints drawn after index 0 cover it. Re-draw the# root as its own topmost scatter (same size; red in the default@@ -882,10 +1174,15 @@ def render_skeleton_motion_ground(parents: Sequence[int], positions,root_color = ([joint_colors[0]] if spectral_feats is not None else 'r')sc_root = ax.scatter(pts[0, 0:1, 0], pts[0, 0:1, 1], pts[0, 0:1, 2],s=joint_marker_size, c=root_color,- depthshade=False, zorder=10, **(- dict(edgecolors='k', linewidths=0.4)+ depthshade=False, zorder=5, **(+ dict(edgecolors='0.15', linewidths=0.4)if spectral_feats is not None else {}))+ shadow_segs = np.zeros((len(edges), 2, 3), np.float32)+ shadow_segs[..., 2] = ground_z + eps+ trail_rgba = np.zeros((max(T - 1, 1), 4), np.float32)+ trail_rgba[:, :3] = _TRAIL_COLOR+frames: List[np.ndarray] = []for t in range(T):P = pts[t]@@ -895,20 +1192,40 @@ def render_skeleton_motion_ground(parents: Sequence[int], positions,sc._offsets3d = (P[:, 0], P[:, 1], P[:, 2])sc_root._offsets3d = (P[0:1, 0], P[0:1, 1], P[0:1, 2])cx, cy = centers[t]- tx = root_xy[:t + 1, 0].astype(np.float32).copy()- ty = root_xy[:t + 1, 1].astype(np.float32).copy()- off = (np.abs(tx - traj_center[0]) > platform_half) | \- (np.abs(ty - traj_center[1]) > platform_half)- tx[off] = np.nan- trail.set_data_3d(tx, ty, np.full(t + 1, ground_z + eps))- if scroll_mode:- quads, cols = _checker_tiles_window(cx, cy, view_half, tile,- ground_z)- platform.set_verts(quads)- platform.set_facecolor(cols)++ if shadow_lc is not None:+ shadow_segs[..., :2] = segs[..., :2]+ shadow_lc.set_segments(shadow_segs)++ if trail_lc is not None and t >= 1:+ path = root_xy[:t + 1]+ # Drop the part of the path that has left the faded floor, so the+ # trail never hangs in empty white space.+ keep = np.max(np.abs(path - np.array([cx, cy], np.float32)),+ axis=1) < 1.6 * view_half+ keep = keep[:-1] & keep[1:]+ seg = np.empty((t, 2, 3), np.float32)+ seg[:, 0, :2] = path[:-1]+ seg[:, 1, :2] = path[1:]+ seg[..., 2] = ground_z + eps+ rgba = trail_rgba[:t].copy()+ rgba[:, 3] = np.linspace(0.04, 0.7, t) * keep+ trail_lc.set_segments(seg)+ trail_lc.set_color(rgba)++ # The limits move the camera, and the tile cull projects through+ # them, so pan first and rebuild the floor after.if follow:ax.set_xlim(cx - view_half, cx + view_half)ax.set_ylim(cy - view_half, cy + view_half)+ if t == 0 or max(abs(cx - rebuild_at[0]),+ abs(cy - rebuild_at[1])) > rebuild_step:+ quads, cols = _ground_tiles(ax, cx, cy, azim, view_half, tile,+ ground_z)+ platform.set_verts(quads)+ platform.set_facecolor(cols)+ platform.set_edgecolor(cols)+ rebuild_at = np.array([cx, cy], dtype=np.float32)frames.append(_capture_rgb(canvas))return np.stack(frames, axis=0)@@ -1022,12 +1339,72 @@ def save_skeleton_motion_spectral(save_path: str, parents: Sequence[int],_write_video(save_path, frames, fps)+def render_skeleton_tpose_ground(parents: Sequence[int], positions,+ spectral_feats=None,+ elev: float = 20,+ azim: float = -60,+ rotate_root: bool = True,+ title: Optional[str] = None,+ title_font_size: float = CAPTION_FONT_SIZE,+ joint_marker_size: float = 18.0,+ bone_linewidth: float = 1.9,+ shadow: bool = True,+ view_margin: float = 1.25,+ figsize: Tuple[float, float] = (6, 6),+ dpi: int = 120) -> np.ndarray:+ """A single rest pose on the clip previews' checkerboard floor.++ Same framing, floor, contact shadow, spectral palette and caption type as+ :func:`render_skeleton_motion_ground`, so an object's T-pose card and its+ clip previews read as one set. Rendered as a one-frame motion with the+ camera parked (``follow=False``) and no root trail — there is nothing+ moving to follow or to trace.++ ``positions`` is one pose, ``(J, 3)``; a ``(1, J, 3)`` sequence is+ accepted too. ``title`` is normally the object type.+ """+ pts = _as_xyz(positions)+ if pts.ndim == 2:+ pts = pts[None]+ assert pts.ndim == 3 and pts.shape[0] == 1, (+ f"a T-pose is one frame, got {pts.shape}")+ return render_skeleton_motion_ground(+ parents, pts, spectral_feats=spectral_feats, elev=elev, azim=azim,+ rotate_root=rotate_root, follow=False, title=title,+ title_font_size=title_font_size,+ joint_marker_size=joint_marker_size, bone_linewidth=bone_linewidth,+ shadow=shadow, trail=False, view_margin=view_margin,+ figsize=figsize, dpi=dpi)[0]+++def save_skeleton_tpose_ground(save_path: str, parents: Sequence[int],+ positions, spectral_feats=None,+ elev: float = 20, azim: float = -60,+ rotate_root: bool = True,+ title: Optional[str] = None,+ title_font_size: float = CAPTION_FONT_SIZE,+ shadow: bool = True,+ view_margin: float = 1.25,+ figsize: Tuple[float, float] = (6, 6),+ dpi: int = 120) -> None:+ """Render and save a ground-plane T-pose PNG (see+ :func:`render_skeleton_tpose_ground`)."""+ _write_image(save_path, render_skeleton_tpose_ground(+ parents, positions, spectral_feats=spectral_feats, elev=elev,+ azim=azim, rotate_root=rotate_root, title=title,+ title_font_size=title_font_size, shadow=shadow,+ view_margin=view_margin, figsize=figsize, dpi=dpi))++def save_skeleton_motion_ground(save_path: str, parents: Sequence[int],positions, spectral_feats=None,fps: int = 20, elev: float = 20,azim: float = -60, rotate_root: bool = True,follow: bool = True,title: Optional[str] = None,+ title_font_size: float = CAPTION_FONT_SIZE,+ shadow: bool = True, trail: bool = True,+ view_margin: float = 1.0,figsize: Tuple[float, float] = (6, 6),dpi: int = 120) -> None:"""Render and save a ground-plane motion MP4 (see@@ -1035,5 +1412,6 @@ def save_skeleton_motion_ground(save_path: str, parents: Sequence[int],frames = render_skeleton_motion_ground(parents, positions, spectral_feats=spectral_feats, elev=elev,azim=azim, rotate_root=rotate_root, follow=follow, title=title,- figsize=figsize, dpi=dpi)+ title_font_size=title_font_size, shadow=shadow, trail=trail,+ view_margin=view_margin, figsize=figsize, dpi=dpi)_write_video(save_path, frames, fps)diff --git a/data_process/utils/vlm.py b/data_process/utils/vlm.pyindex a596af0..0ccb63f 100644--- a/data_process/utils/vlm.py+++ b/data_process/utils/vlm.py@@ -86,7 +86,7 @@ def select_frame_paths(paths, downsample_rate=1, max_frames=None):# type: (List[Path], int, Optional[int]) -> List[Path]"""Choose which frames of one view to send to the VLM.- ``downsample_rate`` applies the legacy fixed stride first (the last+ ``downsample_rate`` applies a fixed stride first (the lastframe is re-appended — a bare ``[::rate]`` drops it whenever the countis not a multiple of the stride), then ``max_frames`` uniformly samplesthe remainder down to that budget.@@ -497,12 +497,22 @@ def load_qwen_model(gpu_id=None,):# type: (str, str, Optional[str], int, int, Optional[int]) -> Tuple- """Load Qwen3-VL model and processor.+ """Load a Qwen3.5 / Qwen3-VL multimodal model and its processor.++ Qwen3.5 (the default everywhere in this pipeline) and Qwen3.8 (the+ 27B option; same ``qwen3_5`` model type and processor) are natively+ multimodal: the model card loads them with ``AutoModelForMultimodalLM``,+ which resolves to ``Qwen3_5ForConditionalGeneration`` — the same class+ ``AutoModelForImageTextToText`` maps to, kept as the fallback for older+ transformers. Its vision tower uses 16-px patches merged 2x2, so one+ visual token covers 32x32 pixels (``h*w/(32*32) + 2`` tokens per image,+ per the Qwen3.5 model card); the Qwen3-VL guide recommends budgets of+ 256–1280 visual tokens per image (256*32*32 .. 1280*32*32 pixels).Args:model_name: HuggingFace model ID or local path- (e.g., "Qwen/Qwen3-VL-8B-Instruct", or "Qwen/Qwen3.5-9B" —- the qwen3_5 architecture needs transformers>=5).+ (default in this pipeline "Qwen/Qwen3.5-9B"; also+ "Qwen/Qwen3-VL-8B-Instruct" — qwen3_5 needs transformers>=5).device_map: Device placement strategy (default "auto").torch_dtype: Override dtype ("float16", "bfloat16", or None for auto).min_pixels: Minimum pixels per image (default 200704 = 256*28*28).@@ -517,7 +527,11 @@ def load_qwen_model(Returns:(model, processor) tuple."""- from transformers import AutoModelForImageTextToText, AutoProcessor+ from transformers import AutoProcessor+ try: # transformers>=5.x: the class the Qwen3.5 model card uses+ from transformers import AutoModelForMultimodalLM as _AutoModel+ except ImportError:+ from transformers import AutoModelForImageTextToText as _AutoModeldtype = torch.bfloat16if torch_dtype == "float16":@@ -539,7 +553,7 @@ def load_qwen_model(logger.info("Loading model: {} (dtype={}, device_map={}, attn={})".format(model_name, dtype, device_map, attn_implementation))- model = AutoModelForImageTextToText.from_pretrained(+ model = _AutoModel.from_pretrained(model_name,dtype=dtype,device_map=device_map,@@ -551,9 +565,12 @@ def load_qwen_model(max_pixels=max_pixels,)- logger.info("Model loaded (min_pixels={}, max_pixels={}, "- "~{} visual tokens per image)".format(- min_pixels, max_pixels, max_pixels // (28 * 28)))+ ip = getattr(processor, "image_processor", None)+ px_per_token = (getattr(ip, "patch_size", 16) * getattr(ip, "merge_size", 2)) ** 2+ logger.info("Model loaded: {} ({}; min_pixels={}, max_pixels={}, "+ "{}-{} visual tokens per image at {} px/token)".format(+ type(model).__name__, model_name, min_pixels, max_pixels,+ min_pixels // px_per_token, max_pixels // px_per_token, px_per_token))return model, processor@@ -633,7 +650,12 @@ def qwen_generate(model, processor, messages, max_tokens=300,gen_kwargs = dict(max_new_tokens=max_tokens)if do_sample:- gen_kwargs.update(do_sample=True, temperature=0.7, top_p=0.8, top_k=20)+ # Qwen3.5 model card, "Instruct / General" row (thinking off):+ # temperature 0.7, top_p 0.8, top_k 20, min_p 0.0,+ # repetition_penalty 1.0 (presence_penalty 1.5 is a vLLM/SGLang+ # sampler knob with no transformers equivalent).+ gen_kwargs.update(do_sample=True, temperature=0.7, top_p=0.8, top_k=20,+ min_p=0.0, repetition_penalty=1.0)else:gen_kwargs.update(do_sample=False, temperature=None, top_p=None,top_k=None)@@ -666,10 +688,10 @@ def qwen_generate(model, processor, messages, max_tokens=300,def add_qwen_model_args(parser):"""Add common Qwen model CLI arguments to an argparse parser."""parser.add_argument('--model', type=str,- default='Qwen/Qwen3-VL-8B-Instruct',- help='HuggingFace model ID or local path '- '(e.g., Qwen/Qwen3-VL-8B-Instruct, '- 'Qwen/Qwen3-VL-72B-Instruct, Qwen/Qwen3.5-9B).')+ default='Qwen/Qwen3.5-9B',+ help='HuggingFace model ID or local path. Default Qwen/Qwen3.5-9B; '+ 'alternatives: Qwen/Qwen3.8-27B (same qwen3_5 architecture, '+ '~56 GB bf16 -> one 80 GB GPU) and Qwen/Qwen3-VL-{8B,32B,72B}-Instruct.')parser.add_argument('--torch_dtype', type=str, default=None,choices=['float16', 'bfloat16'],help='Override model dtype (default: bfloat16).')diff --git a/data_process/vlm_caption/caption_motion.py b/data_process/vlm_caption/caption_motion.pyindex 51e7ea7..9beb41f 100644--- a/data_process/vlm_caption/caption_motion.py+++ b/data_process/vlm_caption/caption_motion.py@@ -409,10 +409,10 @@ def parse_args():# ── Model ───────────────────────────────────────────────────────────────parser.add_argument('--model', type=str,- default='Qwen/Qwen3-VL-8B-Instruct',+ default='Qwen/Qwen3.5-9B',help='Model name. For qwen: HuggingFace model ID '- '(default Qwen/Qwen3-VL-8B-Instruct; also e.g. '- 'Qwen/Qwen3.5-9B). For openai: '+ '(default Qwen/Qwen3.5-9B; also Qwen/Qwen3.8-27B or '+ 'Qwen/Qwen3-VL-8B-Instruct). For openai: ''API model (e.g., gpt-5-mini). For gemini: API model ''(e.g., gemini-3-flash-preview).')diff --git a/data_process/vlm_caption/caption_rewrite_llm.py b/data_process/vlm_caption/caption_rewrite_llm.pynew file mode 100644index 0000000..75d3931--- /dev/null+++ b/data_process/vlm_caption/caption_rewrite_llm.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3+"""LLM rewrite pass for captions that name props or scenery.++The rendered clips contain only the rigged body — no weapons, balls, phones,+furniture, ladders, walls, ... — yet the VLM captioner sometimes copies a+prop from the catalogue hint or infers one from the pose ("aims a rifle",+"kicks a ball", "climbs a ladder"). This pass finds those captions with a+word list, asks a text LLM to rewrite each one so that it describes only the+body's motion, validates the answer (no prop word, subject preserved, short,+one sentence) and retries with sampling until it passes.++Nothing is modified in place: the result is a patch JSON+``{clip: {"old": ..., "new": ..., "ok": bool, "tries": n}}`` that+``data_process/tools/patch_annotations.py`` applies (after review) to+``motion_captions.json``.++Usage:+ python data_process/vlm_caption/caption_rewrite_llm.py \\+ --captions dataset/export/mixamo/motion_captions.json \\+ --output dataset/UniML3D/patches/mixamo_captions_llm.json \\+ [--model Qwen/Qwen3.5-9B | gpt-5-mini | deepseek-v4-flash] \\+ [--clips list.txt] [--pattern REGEX] [--max_tries 4]+"""++import argparse+import json+import os+import re+import sys+import time++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))++from data_process.joint_annotation.llm import LLMClient, strip_llm_noise # noqa: E402++# Object nouns that never exist in the renders. Scene words that describe the+# body's own situation ("ground", "floor", "air", "water") are deliberately+# absent: "falls to the ground" is body motion, not a prop.+PROP_WORDS = (+ 'rifle|pistol|gun|firearm|sword|shield|ball|phone|arrow|axe|staff|knife|dagger|briefcase|'+ 'lightsaber|spear|hammer|mace|flower|book|cup|bottle|dice|guitar|weapon|soccer ball|basketball|'+ 'football|baseball|bag|cigarette|umbrella|wand|rope|ladder|wall|chair|table|bench|steering wheel|'+ 'door|barrel|crate|gift|basket|oar|racket|broom|mop|shovel|pickaxe|lantern|candle|helmet|'+ 'hat|cape|bucket|stone|pole|tree|branch|fence|obstacle|platform|stairs|bed|pillow|tool|item|prop|'+ 'frisbee|puck|javelin|discus|shot put|kettlebell|dumbbell|barbell|controller|joystick|camera|'+ 'microphone|mic|piano|violin|flute|trumpet|lasso|bike|bicycle|motorcycle|horse|car|vehicle|boat|'+ 'skateboard|surfboard|snowboard|skis|sled|glider|parachute|balloon|kite|scope|grenade|bomb|'+ 'scabbard|holster|quiver|weights'+)+# Nouns that are also verbs ("bows", "steps back", "rocks", "boxes", "drums"):+# only counted when a determiner / handling verb precedes them.+AMBIGUOUS_WORDS = 'bow|box|rock|drum|whip|net|bat|glass|stick|club|torch|cane|handle|wheel|bell|hose|step|card|key|coin|rail|drink|paddle'+PROP_RE = re.compile(+ r'\b(?:%s)s?\b|\b(?:a|an|the|their|his|her|its|one|two|with|holding|carrying|swinging|using|'+ r'grabbing|lifting|raising|throwing|catching|kicking|hitting|striking|drawing|aiming)\s+'+ r'(?:%s)s?\b' % (PROP_WORDS, AMBIGUOUS_WORDS), re.IGNORECASE)+SUBJECT_RE = re.compile(r'^(A person|An object|An animal)\b')++SYSTEM_PROMPT = """You edit captions for a motion-capture dataset. Each caption describes a short animation of a rigged body rendered WITHOUT any props, weapons, tools, scenery or other objects: only the body itself is visible.++Rewrite the caption so that it names NO object at all and describes only the body's motion (limbs, torso, head, hands, feet) while keeping everything that is not about an object unchanged.++Rules:+- Keep the subject phrase exactly as given ("A person", "An object" or "An animal").+- One sentence, present tense, at most 15 words, ending with a period.+- Do not add actions that are not implied by the original caption; do not drop actions that are.+- Where a pose clearly implies handling something, you may write "as if holding something", "as if aiming" or "as if carrying something" (at most once). Never say what the thing is.+- Forbidden words: any object noun (rifle, sword, ball, phone, ladder, wall, chair, ...), and also weapon, item, tool, prop, object (except in the subject "An object").+- Do not mention that anything is invisible, imaginary or missing.+- Output only the rewritten caption, nothing else.++Examples:+A person sits and aims a pistol. -> A person sits and extends one arm forward as if aiming.+A person crouches and walks backward while aiming a rifle, then stops. -> A person crouches and walks backward with both hands raised as if aiming, then stops.+A person kicks a soccer ball. -> A person kicks forward with one leg.+A person swings a sword downward. -> A person swings one arm downward as if holding something.+A person climbs a ladder. -> A person climbs upward, alternating hands and feet.+A person talks on the phone while walking. -> A person walks while holding one hand to the ear.+An object crouches while holding a shield and sword. -> An object crouches with both arms raised as if holding something.+A person reloads a rifle while standing. -> A person stands and moves both hands in front of the chest.+A person leans against a wall. -> A person leans sideways with the shoulder raised.+A person sits in a chair and crosses their legs. -> A person sits and crosses their legs."""+++def load_json(path):+ with open(path) as f:+ return json.load(f)+++def clean_answer(text):+ text = strip_llm_noise(text)+ line = next((ln.strip() for ln in text.splitlines() if ln.strip()), '')+ line = re.sub(r'^(?:Rewritten|Caption|Output|Answer)\s*:\s*', '', line, flags=re.IGNORECASE)+ line = line.strip().strip('"“”\'')+ if line and not line.endswith('.'):+ line += '.'+ return line+++def validate(new, old, pattern):+ if not new:+ return 'empty'+ subj = SUBJECT_RE.match(old)+ if subj and not new.startswith(subj.group(1)):+ return 'subject changed'+ if pattern.search(new):+ return 'prop word: ' + pattern.search(new).group(0)+ if len(new.split()) > 18:+ return 'too long'+ if new.count('.') > 1:+ return 'multiple sentences'+ if re.search(r'\b(invisible|imaginary|unseen|not shown|no object)\b', new, re.IGNORECASE):+ return 'meta wording'+ return ''+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])+ ap.add_argument('--captions', required=True, help='motion_captions.json to scan')+ ap.add_argument('--output', required=True, help='patch JSON {clip: {old, new, ok, tries}}')+ ap.add_argument('--clips', default=None,+ help='Optional txt with clip names to rewrite (one per line); '+ 'default: every caption matching --pattern')+ ap.add_argument('--pattern', default=None, help='Regex override for the prop detector')+ ap.add_argument('--model', default='Qwen/Qwen3.5-9B')+ ap.add_argument('--backend', default=None)+ ap.add_argument('--max_tokens', type=int, default=64)+ ap.add_argument('--max_tries', type=int, default=4)+ ap.add_argument('--limit', type=int, default=0, help='Debug: stop after N captions')+ args = ap.parse_args()++ pattern = re.compile(args.pattern, re.IGNORECASE) if args.pattern else PROP_RE+ captions = load_json(args.captions)+ if args.clips:+ with open(args.clips) as f:+ clips = [ln.strip() for ln in f if ln.strip() and not ln.startswith('#')]+ else:+ clips = [c for c, v in captions.items() if pattern.search(v)]+ if args.limit:+ clips = clips[:args.limit]+ print(f'{len(clips)} captions to rewrite from {args.captions}', flush=True)++ result = load_json(args.output) if os.path.isfile(args.output) else {}+ client = LLMClient(args.model, backend=args.backend)+ print(client, flush=True)++ t0 = time.time()+ n_ok = 0+ for k, clip in enumerate(clips, 1):+ old = captions[clip]+ if clip in result and result[clip].get('ok') and result[clip].get('old') == old:+ n_ok += 1+ continue+ best, best_err, tries = '', 'no answer', 0+ for tries in range(1, args.max_tries + 1):+ raw = client.generate(SYSTEM_PROMPT, f'Caption: {old}', args.max_tokens)+ new = clean_answer(raw)+ err = validate(new, old, pattern)+ if not err:+ best, best_err = new, ''+ break+ if not best or best_err.startswith('empty'):+ best, best_err = new, err+ ok = not best_err+ n_ok += int(ok)+ result[clip] = {'old': old, 'new': best, 'ok': ok, 'tries': tries}+ if not ok:+ result[clip]['error'] = best_err+ flag = '' if ok else f' !! {best_err}'+ print(f'[{k}/{len(clips)}] {clip}\n {old}\n -> {best}{flag}', flush=True)+ if k % 20 == 0 or k == len(clips):+ with open(args.output, 'w') as f:+ json.dump(result, f, indent=1, ensure_ascii=False)+ with open(args.output, 'w') as f:+ json.dump(result, f, indent=1, ensure_ascii=False)+ print(f'done: {n_ok}/{len(clips)} passed validation in {time.time() - t0:.0f}s -> {args.output}')+++if __name__ == '__main__':+ main()diff --git a/data_process/vlm_caption/classify_category.py b/data_process/vlm_caption/classify_category.pyindex c236663..fd1d20b 100644--- a/data_process/vlm_caption/classify_category.py+++ b/data_process/vlm_caption/classify_category.py@@ -1,39 +1,63 @@-"""Classify 3D assets into body-plan categories using a local Qwen3-VL model.--Input is a 2x2 multi-view grid PNG per asset (front, back, plus two side-views, T-pose). Two render layouts are supported and auto-detected:-- Flat (e.g. objaverse): <render_root>/<asset_id>.png- Nested (e.g. truebones): <render_root>/<NAME-MOTION>/tpose_grid.png+"""Classify 3D assets into body-plan categories with a local Qwen3.5 / Qwen3-VL model.++Per asset the model sees three kinds of evidence:++ * the rest-pose render — the 2x2 T-pose grid PNG split into its four views+ (``--no-split_grid`` passes the grid as one image);+ * the first frame of one animation clip from the same four cameras+ (``--motion_render_root``, i.e. ``dataset/render/<dataset>``): the+ character in its natural stance, which matters because a rest pose can+ be lying flat on the ground, floating or rotated;+ * skeleton facts derived from the export (``--export_dir``): joint count,+ a histogram of the cleaned joint labels (``Wing x8``, ``Pectoral Fin x2``,+ ``Thigh x2``), the body extents and which labelled parts exist;+ * up to ``--max_captions`` motion captions of the asset's clips+ (``<export_dir>/motion_captions.json``).++It answers with a small JSON object (evidence fields + category ++confidence). ``--votes N`` samples N answers with the official non-thinking+sampling parameters and takes the majority; a tie, a low-confidence majority+or the model's own ``uncertain`` verdict lands in the ``uncertain`` bucket+so it can be reviewed instead of silently mis-filed.++Two render layouts are supported and auto-detected:+ Flat (objaverse, truebones): <render_root>/<asset_id>.png+ Nested: <render_root>/<NAME-MOTION>/tpose_grid.pngObject types are grouped by the segment before '-'; one- classification per type is then propagated to every clip of that- type.+ classification per type is then propagated to every clip of that type.Output:* ``category_groups.json`` — {category: [asset_id, ...]} for assets- that classified successfully.- * ``category_groups_errors.json`` (sibling, same directory)- — {asset_id: error_message} for assets- whose retries were exhausted. ERROR- entries are NOT in category_groups.json- so a re-run will retry them automatically;- the error log persists the last reason.+ that classified (``uncertain`` included).+ * ``category_groups_review.json`` (sibling) — per asset: final category,+ confidence, the votes and the parsed+ evidence of every answer, for manual review.+ * ``category_groups_errors.json`` (sibling) — {asset_id: error_message}+ for assets whose retries were exhausted.+ ERROR entries are NOT in category_groups.json+ so a re-run retries them automatically.++Resumability: assets already in ``category_groups.json`` are skipped, except+those under ``unknown`` (always re-attempted) and, with ``--retry_uncertain``,+those under ``uncertain``.Usage:- # Objaverse (flat layout)- python -m data_process.vlm_caption.classify_category \- --render_root dataset/render/objaverse_tpose-- # Truebones (nested layout)- python -m data_process.vlm_caption.classify_category \- --render_root dataset/render/truebones_tpose+ python -m data_process.vlm_caption.classify_category \\+ --render_root dataset/render/objaverse_tpose \\+ --export_dir dataset/export/objaverse \\+ --category_groups_json dataset/export/objaverse/category_groups.json"""import argparse+import glob+import json+import os+import reimport time-from collections import defaultdict+from collections import Counter, defaultdictfrom pathlib import Path+import numpy as npfrom loguru import loggerfrom PIL import Imagefrom tqdm import tqdm@@ -48,7 +72,6 @@ from data_process.utils.vlm import (save_json,)-# ─────────────────────────────────────────────────────────────────────────────# Constants# ─────────────────────────────────────────────────────────────────────────────@@ -57,76 +80,324 @@ VALID_CATEGORIES = ["bipedal", "quadrupedal", "insectoid", "avian", "marine","serpentine", "articulated_rigid",]-UNKNOWN_CATEGORY = "unknown" # fallback when the model output matches no valid category+UNCERTAIN_CATEGORY = "uncertain" # model / vote could not decide — kept for review+UNKNOWN_CATEGORY = "unknown" # unparseable output — re-attempted on resume+CONFIDENCES = ("high", "medium", "low")# Per-asset retry policy: up to NUM_RETRIES additional attempts after the-# initial try (5 total). Retries cover both exceptions (image I/O, CUDA OOM,-# generation failure) and unparseable model outputs (UNKNOWN_CATEGORY) so-# stochastic decoding gets a second chance to land on a valid category.+# initial try (5 total). Retries cover exceptions (image I/O, CUDA OOM,+# generation failure) and rounds where too few votes could be parsed.NUM_RETRIES = 4RETRY_BACKOFF_SECONDS = 2.0+SAVE_EVERY = 20 # assets per incremental JSON flush (all output files)++# Labels that define limbs: always listed in the histogram shown to the model.+LIMB_WORDS = ("Leg", "Thigh", "Shin", "Foot", "Toe", "Arm", "Forearm", "Hand", "Wing",+ "Fin", "Flipper", "Tail", "Hip", "Claw", "Paw", "Hoof", "Pincer", "Mandible",+ "Antenna", "Tentacle", "Knee", "Elbow", "Shoulder")+MAX_LABELS = 20+# Joint labels that carry body-plan evidence, reported as flags (whole words).+LABEL_FLAGS = {+ "wings": ("Wing", "Feather"),+ "fins": ("Fin", "Flipper"),+ "tail": ("Tail",),+ "antennae_or_mandibles": ("Antenna", "Mandible", "Pincer", "Fang", "Stinger"),+ "tentacles": ("Tentacle",),+}+-SAVE_EVERY = 20 # assets per incremental JSON flush (both output files)+def _has_word(label, words):+ return any(re.search(r"\b{}\b".format(w), label) for w in words)++_JSON_RE = re.compile(r"\{.*?\}", re.DOTALL)+_CATEGORY_RE = re.compile(r'"?category"?\s*[:=]\s*"?([A-Za-z_ ]+)"?', re.IGNORECASE)+_CONFIDENCE_RE = re.compile(r'"?confidence"?\s*[:=]\s*"?(high|medium|low)', re.IGNORECASE)# ─────────────────────────────────────────────────────────────────────────────-# Core classification+# Evidence: skeleton facts and captions from the export# ─────────────────────────────────────────────────────────────────────────────-def classify_asset(- tpose_image,- asset_id,- model,- processor,- max_tokens=10,- system_prompt=CATEGORY_PROMPT,- do_sample=False,-):- # type: (Image.Image, str, object, object, int, str, bool) -> str- """Classify one asset from its 2x2 T-pose grid PNG.+class ExportEvidence:+ """Lazy reader of the stage-1/2/3 sidecars used as text evidence."""++ def __init__(self, export_dir, max_captions=6, motion_render_root=None):+ self.export_dir = export_dir+ self.max_captions = max_captions+ self.motion_render_root = motion_render_root+ self.joint_names = load_json(os.path.join(export_dir, "joint_names.json")) if export_dir else {}+ self.clean_names = load_json(os.path.join(export_dir, "clean_joint_names.json")) if export_dir else {}+ captions = load_json(os.path.join(export_dir, "motion_captions.json")) if export_dir else {}+ self.captions_by_asset = defaultdict(list) # type: dict+ for clip, text in captions.items():+ self.captions_by_asset[clip.split("-", 1)[0]].append(text)+ if export_dir:+ logger.info("Export evidence: {} rigs with joint names, {} with clean labels, "+ "captions for {} assets".format(+ len(self.joint_names), len(self.clean_names),+ len(self.captions_by_asset)))++ # -- skeleton --------------------------------------------------------+ def _rest_positions(self, asset_id):+ paths = sorted(glob.glob(os.path.join(self.export_dir, "motions", asset_id + "-*.npz")))+ if not paths:+ paths = [p for p in [os.path.join(self.export_dir, "motions", asset_id + ".npz")]+ if os.path.isfile(p)]+ if not paths:+ return None, None+ from Animation import Animation, Quaternions, positions_global+ d = np.load(paths[0], allow_pickle=True)+ parents = d["parents"]+ anim = Animation(+ rotations=Quaternions(d["rest_local_rot"][None]),+ positions=d["rest_local_pos"][None],+ orients=Quaternions.id(len(parents)),+ offsets=d["rest_local_pos"],+ parents=parents,+ )+ return positions_global(anim)[0], parents++ def skeleton_facts(self, asset_id):+ """Return (dict, text) or (None, "") when the export has no such rig."""+ names = self.joint_names.get(asset_id)+ if not names:+ return None, ""+ clean = self.clean_names.get(asset_id) or []+ facts = {"joints": len(names)}+ base = [re.sub(r"^(Left|Right) ", "", c) for c in clean]+ hist = Counter(b for b in base if b not in ("Bone", "Bone End", "Root", "Root End"))+ # Limb-defining labels always make the list (a T-rex's two Thigh+ # joints matter more than its twelve tail joints); the rest by count.+ limb = [(lab, n) for lab, n in hist.most_common() if _has_word(lab, LIMB_WORDS)]+ rest = [(lab, n) for lab, n in hist.most_common() if not _has_word(lab, LIMB_WORDS)]+ facts["labels"] = (limb + rest)[:MAX_LABELS]+ for flag, keys in LABEL_FLAGS.items():+ facts[flag] = any(_has_word(b, keys) for b in base)+ try:+ g, _ = self._rest_positions(asset_id)+ except Exception as e: # noqa: BLE001 — evidence is optional+ logger.warning("rest pose FK failed for {}: {}".format(asset_id, e))+ g = None+ if g is not None:+ height = float(np.ptp(g[:, 1])) or 1.0+ ext = sorted(float(v) / height for v in (np.ptp(g[:, 0]), np.ptp(g[:, 2])))+ facts["horizontal_extents"] = [round(ext[1], 2), round(ext[0], 2)]+ lines = ["Skeleton facts (from the rig itself):",+ "- {} joints".format(facts["joints"])]+ if "horizontal_extents" in facts:+ lines.append("- horizontal extents {} and {} (relative to height 1.0)".format(+ *facts["horizontal_extents"]))+ if facts["labels"]:+ lines.append("- joint labels: " + ", ".join(+ "{} x{}".format(lab, n) for lab, n in facts["labels"]))+ else:+ lines.append("- joint names are opaque (no anatomical labels)")+ flags = [f.replace("_", " ") for f in LABEL_FLAGS if facts.get(f)]+ if flags:+ lines.append("- labelled parts present: " + ", ".join(flags))+ return facts, "\n".join(lines)++ # -- first animation frame, four cameras ------------------------------+ def first_frame_views(self, asset_id, num_views=4):+ """First rendered frame of the asset's first clip from every camera+ (``<root>/<asset_id>-<clip>/v00k/0000.png``); [] when unavailable."""+ if not self.motion_render_root:+ return []+ clip_dirs = sorted(glob.glob(os.path.join(self.motion_render_root, asset_id + "-*")))+ if not clip_dirs and os.path.isdir(os.path.join(self.motion_render_root, asset_id)):+ clip_dirs = [os.path.join(self.motion_render_root, asset_id)]+ for clip_dir in clip_dirs:+ frames = []+ for k in range(num_views):+ pngs = sorted(glob.glob(os.path.join(clip_dir, "v{:03d}".format(k), "*.png")))+ if not pngs:+ break+ frames.append(flatten_rgba(Image.open(pngs[0])))+ if len(frames) == num_views:+ return frames+ return []++ # -- captions --------------------------------------------------------+ def captions(self, asset_id):+ seen, out = set(), []+ for text in self.captions_by_asset.get(asset_id, []):+ if text not in seen:+ seen.add(text)+ out.append(text)+ if len(out) >= self.max_captions:+ break+ if not out:+ return ""+ return ("Motion captions of this asset's clips (written from rendered videos "+ "by a separate pass):\n" + "\n".join("- " + c for c in out))- Returns one of ``VALID_CATEGORIES`` or ``UNKNOWN_CATEGORY`` if the- model output cannot be parsed into a known category.++# ─────────────────────────────────────────────────────────────────────────────+# Answer parsing and voting+# ─────────────────────────────────────────────────────────────────────────────++def _normalize_category(text):+ t = text.lower().replace(" ", "_").strip("_*`'\".,;:!?()[]\n\t ")+ if t in VALID_CATEGORIES or t == UNCERTAIN_CATEGORY:+ return t+ if t in ("quadruped", "quadrupeds"):+ return "quadrupedal"+ if t in ("biped", "bipeds", "humanoid"):+ return "bipedal"+ if t in ("insect", "arthropod"):+ return "insectoid"+ if t in ("flying", "winged", "bird"):+ return "avian"+ if t in ("aquatic", "fish"):+ return "marine"+ if t in ("snake", "limbless"):+ return "serpentine"+ if t in ("rigid", "mechanical", "articulated", "articulated-rigid"):+ return "articulated_rigid"+ return None+++def parse_answer(raw):+ """Parse one model answer into {category, confidence, evidence, raw}.++ Accepts the requested JSON object, a JSON object embedded in prose, or a+ bare category token. ``category`` is None when nothing parses.+ """+ answer = {"category": None, "confidence": None, "evidence": {}, "raw": raw}+ m = _JSON_RE.search(raw)+ if m:+ try:+ obj = json.loads(m.group(0))+ except ValueError:+ obj = None+ if isinstance(obj, dict):+ cat = obj.get("category")+ answer["category"] = _normalize_category(str(cat)) if cat is not None else None+ conf = str(obj.get("confidence", "")).lower()+ answer["confidence"] = conf if conf in CONFIDENCES else None+ answer["evidence"] = {k: v for k, v in obj.items()+ if k not in ("category", "confidence")}+ if answer["category"] is None:+ m = _CATEGORY_RE.search(raw)+ if m:+ answer["category"] = _normalize_category(m.group(1))+ if answer["category"] is None:+ # Bare token / prose fallback: earliest valid category mentioned.+ low = raw.lower().replace(" ", "_")+ hits = sorted((low.find(v), v) for v in VALID_CATEGORIES + [UNCERTAIN_CATEGORY] if v in low)+ if hits:+ answer["category"] = hits[0][1]+ if answer["confidence"] is None:+ m = _CONFIDENCE_RE.search(raw)+ answer["confidence"] = m.group(1).lower() if m else None+ return answer+++def aggregate_votes(answers, votes):+ """Majority vote over parsed answers → (category, confidence).++ * unanimous valid votes → that category, ``high``+ * a strict majority → that category, ``medium`` (``low`` if every+ majority vote reported low confidence)+ * otherwise, or a majority for the model's own ``uncertain`` → the+ ``uncertain`` bucket, ``low``"""- messages = [+ cats = [a["category"] for a in answers if a["category"]]+ if not cats:+ return None, None+ top, n_top = Counter(cats).most_common(1)[0]+ if top == UNCERTAIN_CATEGORY or n_top * 2 <= votes:+ return UNCERTAIN_CATEGORY, "low"+ majority_conf = [a["confidence"] for a in answers if a["category"] == top]+ if votes == 1:+ conf = majority_conf[0] or "medium" # single answer: the model's own confidence+ elif n_top == votes:+ conf = "high"+ else:+ conf = "medium"+ if majority_conf and all(c == "low" for c in majority_conf):+ conf = "low"+ if conf == "low":+ return UNCERTAIN_CATEGORY, "low"+ return top, conf+++# ─────────────────────────────────────────────────────────────────────────────+# Core classification+# ─────────────────────────────────────────────────────────────────────────────++def split_grid(image):+ """Split a 2x2 grid into its four tiles (TL, TR, BL, BR)."""+ w, h = image.size+ boxes = [(0, 0, w // 2, h // 2), (w // 2, 0, w, h // 2),+ (0, h // 2, w // 2, h), (w // 2, h // 2, w, h)]+ return [image.crop(b) for b in boxes]+++def build_messages(images, asset_id, facts_text, captions_text, system_prompt,+ motion_images=()):+ n = len(images)+ intro = ("Classify this 3D asset (id: '{}'). ".format(asset_id) ++ ("The next {} images are rest-pose (T-pose) views of the same asset "+ "from four cameras 90 degrees apart (nominally the asset's front, "+ "back, left and right; the character itself may face any "+ "direction).".format(n)+ if n > 1 else+ "The next image is a 2x2 grid of four canonical rest-pose views."))+ content = [{"type": "text", "text": intro}]+ for img in images:+ content.append({"type": "image", "image": img})+ if motion_images:+ content.append({"type": "text", "text": (+ "The next {} images are the FIRST FRAME of one of this asset's "+ "animation clips, seen from four static cameras 90 degrees apart. "+ "They show the character in its natural stance and orientation; "+ "the rest pose above may be lying flat on the ground, floating or "+ "rotated, so judge upright vs. horizontal and which limbs touch "+ "the ground from these frames.".format(len(motion_images)))})+ for img in motion_images:+ content.append({"type": "image", "image": img})+ extra = "\n\n".join(t for t in (facts_text, captions_text) if t)+ if extra:+ content.append({"type": "text", "text": extra})+ content.append({"type": "text", "text": "Answer with the JSON object only."})+ return [{"role": "system", "content": [{"type": "text", "text": system_prompt}]},- {"role": "user", "content": [- {"type": "text", "text": (- "Classify this 3D asset (id: '{}'). The image is a 2x2 grid "- "of four canonical T-pose views.".format(asset_id)- )},- {"type": "image", "image": tpose_image},- ]},+ {"role": "user", "content": content},]- raw = qwen_generate(model, processor, messages, max_tokens=max_tokens,- do_sample=do_sample).lower()- # Accept "articulated rigid" (space) as well as "articulated_rigid" (underscore).- raw_normalized = raw.replace(" ", "_").strip()- # Bare token after stripping quotes/punctuation — the expected reply.- bare = raw_normalized.strip("_*`'\".,;:!?()[]\n\t ")- if bare in VALID_CATEGORIES:- category = bare- else:- # Take the category that appears EARLIEST in the response, not the- # first one in VALID_CATEGORIES order: "quadrupedal (not bipedal)"- # must resolve to quadrupedal.- hits = sorted((raw_normalized.find(v), v)- for v in VALID_CATEGORIES if v in raw_normalized)- if len(hits) > 1:- logger.warning("Ambiguous category response '{}' for '{}': {} — "- "taking the earliest match '{}'".format(- raw, asset_id,- ", ".join(v for _, v in hits), hits[0][1]))- category = hits[0][1] if hits else None- if category is None:- logger.warning("Unexpected category '{}' for '{}', mapping to '{}'".format(- raw, asset_id, UNKNOWN_CATEGORY))- category = UNKNOWN_CATEGORY-- logger.info("Category for '{}': {}".format(asset_id, category))- return category+def classify_asset(images, asset_id, model, processor, facts_text="",+ captions_text="", max_tokens=96, votes=3,+ system_prompt=CATEGORY_PROMPT, motion_images=()):+ """Classify one asset. Returns (category, review_record).++ ``category`` is one of VALID_CATEGORIES, ``uncertain``, or None when+ fewer than half of the votes could be parsed (caller retries).+ """+ messages = build_messages(images, asset_id, facts_text, captions_text, system_prompt,+ motion_images=motion_images)+ answers = []+ for v in range(votes):+ raw = qwen_generate(model, processor, messages, max_tokens=max_tokens,+ do_sample=votes > 1)+ answers.append(parse_answer(raw))+ n_parsed = sum(1 for a in answers if a["category"])+ if n_parsed * 2 <= votes and n_parsed < votes:+ logger.warning("Only {}/{} votes parsed for '{}': {}".format(+ n_parsed, votes, asset_id, [a["raw"][:80] for a in answers]))+ return None, None+ category, confidence = aggregate_votes(answers, votes)+ record = {+ "category": category,+ "confidence": confidence,+ "votes": [a["category"] for a in answers],+ "answers": [{"category": a["category"], "confidence": a["confidence"],+ **a["evidence"]} for a in answers],+ }+ logger.info("Category for '{}': {} ({}; votes={})".format(+ asset_id, category, confidence, record["votes"]))+ return category, record# ─────────────────────────────────────────────────────────────────────────────@@ -134,7 +405,6 @@ def classify_asset(# ─────────────────────────────────────────────────────────────────────────────def _discover_assets(render_root):- # type: (Path) -> Tuple[str, List[Tuple[str, Path]]]"""Locate (asset_id, tpose_png) pairs under ``render_root``.Auto-detects the layout:@@ -142,31 +412,25 @@ def _discover_assets(render_root):* nested — ``<render_root>/<NAME-MOTION>/tpose_grid.png`` (multi-clip;grouped by the segment before '-' so every object type isclassified exactly once via its first available render).-Returns ``(layout, items)`` where ``items`` is sorted by asset_id."""flat_pngs = sorted(p for p in render_root.glob("*.png") if p.is_file())if flat_pngs:- items = [(p.stem, p) for p in flat_pngs]- return "flat", items-+ return "flat", [(p.stem, p) for p in flat_pngs]char_dirs = sorted(d for d in render_root.iterdir()if d.is_dir() and (d / "tpose_grid.png").exists())- type_to_png = {} # type: Dict[str, Path]+ type_to_png = {}for d in char_dirs:obj_type = d.name.split("-", 1)[0] if "-" in d.name else d.nametype_to_png.setdefault(obj_type, d / "tpose_grid.png")- items = sorted(type_to_png.items())- return "nested", items+ return "nested", sorted(type_to_png.items())-def _error_log_path_for(category_groups_json):- # type: (str) -> str- """Sibling error-log path next to ``category_groups.json``."""+def _sibling(category_groups_json, suffix):p = Path(category_groups_json)- return str(p.with_name(p.stem + "_errors.json"))+ return str(p.with_name(p.stem + suffix + ".json"))def classify_batch(@@ -174,144 +438,113 @@ def classify_batch(model,processor,category_groups_json=None,- max_tokens=10,+ evidence=None,+ max_tokens=96,+ votes=3,+ split=True,+ retry_uncertain=False,system_prompt=CATEGORY_PROMPT,):- """Classify every asset under ``render_root``.-- Outputs:- * ``category_groups.json`` — {category: [asset_id, ...]} for the- assets that classified successfully.- * ``<stem>_errors.json`` — {asset_id: error_message} for assets- whose retries were exhausted (siblings of the groups JSON).-- Both files are read on entry for resumability — successful asset_ids- are skipped, and stale error entries (now-successful assets) are- pruned. Re-runs only re-attempt assets in the error log plus any- assets the discovery pass found that aren't yet classified.- """+ """Classify every asset under ``render_root`` (see module docstring)."""render_root = Path(render_root)-if category_groups_json is None:category_groups_json = str(render_root / "category_groups.json")- error_log_path = _error_log_path_for(category_groups_json)+ error_log_path = _sibling(category_groups_json, "_errors")+ review_path = _sibling(category_groups_json, "_review")- existing_groups = load_json(category_groups_json) # type: Dict[str, List[str]]- already_classified = {} # type: Dict[str, str]+ existing_groups = load_json(category_groups_json)+ already_classified = {}for cat, members in existing_groups.items():+ if cat == UNKNOWN_CATEGORY or (retry_uncertain and cat == UNCERTAIN_CATEGORY):+ continuefor asset_id in members:already_classified[asset_id] = cat-- # Prune stale errors (assets now successfully classified) and retain- # the rest as the running error log for this run.- existing_errors = load_json(error_log_path) # type: Dict[str, str]- asset_errors = {- aid: err for aid, err in existing_errors.items()- if aid not in already_classified- } # type: Dict[str, str]+ existing_errors = load_json(error_log_path)+ asset_errors = {aid: err for aid, err in existing_errors.items()+ if aid not in already_classified}+ review = {aid: rec for aid, rec in load_json(review_path).items()+ if aid in already_classified}layout, items = _discover_assets(render_root)- logger.info("Layout: {} | Found {} assets in {}".format(- layout, len(items), render_root))-- asset_categories = dict(already_classified) # type: Dict[str, str]+ logger.info("Layout: {} | Found {} assets in {}".format(layout, len(items), render_root))+ asset_categories = dict(already_classified)to_classify = [(aid, p) for aid, p in items if aid not in already_classified]logger.info("{} already classified, {} remaining ({} previously errored)".format(len(already_classified), len(to_classify), len(asset_errors)))- pbar = tqdm(to_classify, desc="Classifying", unit="asset",- dynamic_ncols=True)+ evidence = evidence or ExportEvidence(None)+ pbar = tqdm(to_classify, desc="Classifying", unit="asset", dynamic_ncols=True)total_attempts = NUM_RETRIES + 1n_unsaved = 0def _flush():- """Write both output files (called every SAVE_EVERY assets)."""_save_category_groups(asset_categories, category_groups_json)save_json(asset_errors, error_log_path)+ save_json(review, review_path)try:for asset_id, png_path in pbar:pbar.set_postfix_str(asset_id, refresh=False)- result = None- last_error = None+ facts, facts_text = evidence.skeleton_facts(asset_id)+ captions_text = evidence.captions(asset_id)+ motion_images = evidence.first_frame_views(asset_id)+ result, record, last_error = None, None, Nonefor attempt in range(1, total_attempts + 1):try:- tpose_image = flatten_rgba(Image.open(str(png_path)))- # Greedy first, sampled on retries — a greedy retry would- # deterministically repeat the same unparseable output.- category = classify_asset(- tpose_image, asset_id,- model=model, processor=processor,- max_tokens=max_tokens, system_prompt=system_prompt,- do_sample=attempt > 1,- )- if category != UNKNOWN_CATEGORY:- result = category+ image = flatten_rgba(Image.open(str(png_path)))+ images = split_grid(image) if split else [image]+ result, record = classify_asset(+ images, asset_id, model, processor,+ facts_text=facts_text, captions_text=captions_text,+ max_tokens=max_tokens, votes=votes, system_prompt=system_prompt,+ motion_images=motion_images)+ if result is not None:break- last_error = ValueError(- "model output did not match any valid category")- except Exception as e:+ last_error = ValueError("too few parseable votes")+ except Exception as e: # noqa: BLE001 — retried belowlast_error = elogger.warning("Attempt {}/{} failed for {}: {}".format(attempt, total_attempts, asset_id, e))-if attempt < total_attempts:time.sleep(RETRY_BACKOFF_SECONDS)-if result is not None:asset_categories[asset_id] = result- asset_errors.pop(asset_id, None) # success clears any prior error+ asset_errors.pop(asset_id, None)+ if facts:+ record["skeleton"] = {k: v for k, v in facts.items() if k != "labels"}+ record["motion_frames"] = len(motion_images)+ review[asset_id] = recordelse:- # Exhausted retries on either exceptions or unparseable output.- # Mark as ERROR so _save_category_groups drops it from the JSON- # and a later re-run will retry from scratch. Record the reason- # in the sibling error log for visibility.- if isinstance(last_error, ValueError):- err_msg = "All {} attempts produced unparseable output".format(- total_attempts)- else:- err_msg = "All {} attempts failed: {}".format(- total_attempts, last_error)+ err_msg = "All {} attempts failed: {}".format(total_attempts, last_error)logger.error("[{}] {}".format(asset_id, err_msg))asset_categories[asset_id] = "ERROR: {}".format(last_error)asset_errors[asset_id] = err_msg-- # Rewriting both JSONs per asset is O(n^2) over a large run;- # batch it (a crash loses at most SAVE_EVERY classifications).+ review.pop(asset_id, None)n_unsaved += 1if n_unsaved >= SAVE_EVERY:_flush()n_unsaved = 0finally:_flush()- n_ok = sum(- 1 for c in asset_categories.values()- if isinstance(c, str) and not c.startswith("ERROR:")- )- logger.info("Done. {} classified, {} errored (logged to {})".format(- n_ok, len(asset_errors), error_log_path))++ counts = Counter(c for c in asset_categories.values()+ if isinstance(c, str) and not c.startswith("ERROR:"))+ logger.info("Done. {} classified {}, {} errored (logged to {})".format(+ sum(counts.values()), dict(counts), len(asset_errors), error_log_path))return asset_categoriesdef _save_category_groups(asset_categories, output_path):- # type: (Dict[str, str], str) -> None"""Invert {asset_id: category} into {category: [asset_id, ...]} and save.- ERROR entries are dropped so a re-run will retry those assets. After- retries are exhausted (in classify_batch) the asset is marked ERROR- and recorded in the sibling error log instead of leaking into the- groups JSON.+ ERROR entries are dropped so a re-run will retry those assets."""- assets_by_category = defaultdict(list) # type: Dict[str, List[str]]+ assets_by_category = defaultdict(list)for asset_id, cat in sorted(asset_categories.items()):if isinstance(cat, str) and cat.startswith("ERROR:"):continueassets_by_category[cat].append(asset_id)-- category_assets = {- cat: sorted(assets) for cat, assets in sorted(assets_by_category.items())- } # type: Dict[str, List[str]]- save_json(category_assets, output_path)+ save_json({cat: sorted(a) for cat, a in sorted(assets_by_category.items())}, output_path)# ─────────────────────────────────────────────────────────────────────────────@@ -320,32 +553,51 @@ def _save_category_groups(asset_categories, output_path):def parse_args():parser = argparse.ArgumentParser(- description="Classify 3D assets into body-plan categories "- "using a local Qwen3-VL model."+ description="Classify 3D assets into body-plan categories with a local "+ "Qwen3.5 / Qwen3-VL model (T-pose views + skeleton facts + captions).")-parser.add_argument('--render_root', type=str, required=True,help='Root directory holding T-pose 2x2 grid PNGs ''(flat <asset_id>.png or nested ''<NAME-MOTION>/tpose_grid.png — auto-detected).')-+ parser.add_argument('--export_dir', type=str, default=None,+ help='Stage-1/2/3 export folder of the dataset '+ '(joint_names.json, clean_joint_names.json, '+ 'motion_captions.json, motions/). Optional but '+ 'strongly recommended: supplies the skeleton facts '+ 'and captions.')parser.add_argument('--category_groups_json', type=str, default=None,- help='Output JSON file mapping '- '{category: [asset_id, ...]}. '- 'Defaults to <render_root>/category_groups.json. '- 'A sibling <stem>_errors.json records assets '- 'whose retries were exhausted. Both files are '- 're-read on entry for resumability.')+ help='Output JSON {category: [asset_id, ...]} '+ '(default <render_root>/category_groups.json). '+ 'Siblings <stem>_review.json and <stem>_errors.json '+ 'are written next to it; all are re-read on entry.')+ parser.add_argument('--motion_render_root', type=str, default=None,+ help='Stage-2a motion renders (dataset/render/<dataset>): the '+ 'first frame of the asset\'s first clip from all four '+ 'cameras is shown as the natural-stance reference. '+ 'Optional but recommended: rest poses can lie flat.')+ parser.add_argument('--votes', type=int, default=3,+ help='Sampled answers per asset; majority wins (default 3; '+ '1 = single greedy answer).')+ parser.add_argument('--max_captions', type=int, default=6,+ help='Captions of the asset shown to the model (default 6).')+ parser.add_argument('--split_grid', action=argparse.BooleanOptionalAction, default=True,+ help='Pass the four views of the grid as separate images '+ '(default) or the grid as one image.')+ parser.add_argument('--retry_uncertain', action='store_true',+ help='Also re-attempt assets currently under "uncertain".')add_qwen_model_args(parser)- parser.add_argument('--max_tokens', type=int, default=10,- help='Max new tokens to generate (default: 10).')-+ # The captioner defaults (256*28*28 both ways) are far below the+ # 256–1280 visual tokens the Qwen3-VL guide recommends per image; the+ # 512x512 tiles of the grid pass through untouched with these bounds.+ parser.set_defaults(min_pixels=256 * 32 * 32, max_pixels=1280 * 32 * 32)+ parser.add_argument('--max_tokens', type=int, default=96,+ help='Max new tokens per answer (default 96: one JSON object).')return parser.parse_args()def main():args = parse_args()-qwen_model, qwen_processor = load_qwen_model(args.model,device_map=args.device_map,@@ -353,12 +605,17 @@ def main():min_pixels=args.min_pixels,max_pixels=args.max_pixels,)-+ evidence = ExportEvidence(args.export_dir, max_captions=args.max_captions,+ motion_render_root=args.motion_render_root)classify_batch(render_root=args.render_root,model=qwen_model, processor=qwen_processor,category_groups_json=args.category_groups_json,+ evidence=evidence,max_tokens=args.max_tokens,+ votes=args.votes,+ split=args.split_grid,+ retry_uncertain=args.retry_uncertain,)diff --git a/data_process/vlm_caption/eval/truebones_category_truth.json b/data_process/vlm_caption/eval/truebones_category_truth.jsonnew file mode 100644index 0000000..595380a--- /dev/null+++ b/data_process/vlm_caption/eval/truebones_category_truth.json@@ -0,0 +1,22 @@+{+ "_comment": "Hand truth for the 74 Truebones species (2026-09-05). Lists = every acceptable category.",+ "Alligator": ["quadrupedal"], "Anaconda": ["serpentine"], "Ant": ["insectoid"], "Bat": ["avian"],+ "Bear": ["quadrupedal"], "Bird": ["avian"], "BrownBear": ["quadrupedal"], "Buffalo": ["quadrupedal"],+ "Buzzard": ["avian"], "Camel": ["quadrupedal"], "Cat": ["quadrupedal"], "Centipede": ["insectoid"],+ "Chicken": ["bipedal"], "Comodoa": ["quadrupedal"], "Coyote": ["quadrupedal"], "Crab": ["insectoid"],+ "Cricket": ["insectoid"], "Crocodile": ["quadrupedal"], "Crow": ["avian"], "Deer": ["quadrupedal"],+ "Dog": ["quadrupedal"], "Dog2": ["quadrupedal"], "Dragon": ["avian"], "Eagle": ["avian"],+ "Elephant": ["quadrupedal"], "FireAnt": ["insectoid"], "Flamingo": ["bipedal", "avian"], "Fox": ["quadrupedal"],+ "Gazelle": ["quadrupedal"], "Giantbee": ["insectoid"], "Goat": ["quadrupedal"], "Hamster": ["quadrupedal"],+ "HermitCrab": ["insectoid"], "Hippopotamus": ["quadrupedal"], "Horse": ["quadrupedal"], "Hound": ["quadrupedal"],+ "Isopetra": ["insectoid"], "Jaguar": ["quadrupedal"], "Jaws": ["marine"], "KingCobra": ["serpentine"],+ "Leapord": ["quadrupedal"], "Lion": ["quadrupedal"], "Lynx": ["quadrupedal"], "Mammoth": ["quadrupedal"],+ "Monkey": ["quadrupedal", "bipedal"], "Ostrich": ["bipedal"], "Parrot": ["avian"], "Parrot2": ["avian"],+ "Pigeon": ["avian"], "Pirrana": ["marine"], "PolarBear": ["quadrupedal"], "PolarBearB": ["quadrupedal"],+ "Pteranodon": ["avian"], "Puppy": ["quadrupedal"], "Raindeer": ["quadrupedal"], "Raptor": ["bipedal"],+ "Raptor2": ["bipedal"], "Raptor3": ["bipedal"], "Rat": ["quadrupedal"], "Rhino": ["quadrupedal"],+ "Roach": ["insectoid"], "SabreToothTiger": ["quadrupedal"], "SandMouse": ["quadrupedal"], "Scorpion": ["insectoid"],+ "Scorpion2": ["insectoid"], "Skunk": ["quadrupedal"], "Spider": ["insectoid"], "SpiderG": ["insectoid"],+ "Stego": ["quadrupedal"], "Trex": ["bipedal"], "Tricera": ["quadrupedal"], "Tukan": ["avian"],+ "Turtle": ["quadrupedal"], "Tyranno": ["bipedal"]+}diff --git a/data_process/vlm_caption/prompts.py b/data_process/vlm_caption/prompts.pyindex 91aa04c..32da6e3 100644--- a/data_process/vlm_caption/prompts.py+++ b/data_process/vlm_caption/prompts.py@@ -304,77 +304,109 @@ TRUEBONES_PROMPT = _caption_prompt(CATEGORY_PROMPT = ("# Role\n"- "You classify the body plan of a single 3D asset into exactly ONE of "- "seven categories. The output is consumed by an automated pipeline — "- "it must be one exact token, no prose, no punctuation.\n\n"- "# Input\n"- "ONE image: a 2x2 grid of four canonical views of the asset in T-pose "- "(front, back, and two orthogonal side / top views). The exact panel "- "ordering is not guaranteed. Use ALL four panels — never decide from a "- "single panel — and reason from silhouette, limb count, and proportions. "- "T-pose means a canonical rest pose with limbs spread; there is no "- "motion to read. If the asset appears horizontal in some panels, that "- "is just a top-down or side view of the same rest pose — judge body "- "plan from the panel that most clearly shows the limb topology.\n\n"+ "You classify the body plan of ONE rigged 3D asset into exactly one "+ "category for a motion-generation dataset. The category describes how "+ "the skeleton is built and how the character moves; it is consumed by "+ "an automated pipeline.\n\n"+ "# Evidence you receive\n"+ "1. Rest-pose (T-pose) renders: four canonical views of the asset "+ "(front, back and two sides — order not guaranteed), or one 2x2 grid of "+ "them. T-pose is a canonical rest pose with limbs spread; there is no "+ "motion to read. A view looking straight along an elongated body may "+ "show only a compact silhouette — rely on the other views. The rest "+ "pose is NOT a reliable guide to stance: some rigs rest lying flat on "+ "the ground, floating, or rotated.\n"+ "1b. First-frame views of one animation clip (when available): the same "+ "four cameras at the first frame of a motion, showing the character in "+ "its natural stance and orientation. Judge upright vs. horizontal and "+ "which limbs bear weight from these frames, not from the rest pose.\n"+ "2. Skeleton facts extracted from the rig (when available): joint "+ "count, a histogram of the cleaned joint labels (e.g. 'Wing x8', "+ "'Pectoral Fin x2', 'Thigh x2' + 'Upper Arm x2' = four limbs), the "+ "body extents and which labelled parts exist.\n"+ "3. Motion captions of the asset's clips (when available), written by "+ "a separate pass from rendered videos ('walks on all fours', 'flaps its "+ "wings', 'slithers forward').\n"+ "Weigh them together. The skeleton facts and captions describe the "+ "rig directly, so when they clearly state the limb count or the "+ "locomotion they outrank your reading of the images; the images "+ "decide what the text leaves open (shape, mechanical vs creature, "+ "wings that the rig labels as generic bones). Joint labels can be "+ "missing or generic ('Bone') — then the images decide.\n\n""# Categories\n"- "- bipedal: organism with TWO legs as primary stance / locomotion. "- "Humans, humanoids, apes, bipedal dinosaurs (T-Rex, raptors), "- "flightless upright birds (ostrich, penguin), humanoid robots and "- "mechs (head + torso + two arms + two legs).\n"- "- quadrupedal: organism with FOUR legs as primary stance. Dogs, "- "cats, horses, bears, deer, lizards, turtles, four-legged dinosaurs, "+ "- bipedal: TWO legs as primary stance / locomotion. Humans, "+ "humanoids, apes, bipedal dinosaurs (T-Rex, raptors), flightless "+ "upright birds (ostrich, penguin, chicken), humanoid robots and mechs "+ "(head + torso + two arms + two legs).\n"+ "- quadrupedal: FOUR legs as primary stance. Dogs, cats, horses, "+ "bears, elephants, deer, lizards, turtles, four-legged dinosaurs, ""quadruped robots. Centaurs and four-leg hybrids belong here.\n""- insectoid: arthropod body plan — SIX OR MORE articulated legs, "- "typically segmented thorax/abdomen, often antennae. Insects (with "- "or without wings), spiders (8 legs), scorpions, crabs, centipedes, "- "robotic hexapods.\n"- "- avian: vertebrate defined by TWO LARGE WINGS used for flight, "- "usually paired with legs. Flying birds, bats, pterosaurs, dragons, "- "wyverns, winged humanoids / angels. Wings must be a dominant "- "feature, not vestigial decoration.\n"- "- marine: streamlined aquatic body propelled by fins/flippers/tail, "- "with NO walking legs. Fish, sharks, rays, dolphins, whales, "+ "usually segmented thorax/abdomen, often antennae, mandibles or "+ "pincers. Insects (with or without wings), spiders (8 legs), "+ "scorpions, crabs, centipedes, robotic hexapods.\n"+ "- avian: vertebrate whose TWO LARGE WINGS are the dominant limbs and "+ "whose clips (if given) fly, flap, glide or hover. Flying birds, bats, "+ "pterosaurs, dragons, wyverns, winged humanoids. Wings must be "+ "dominant, not vestigial decoration.\n"+ "- marine: streamlined aquatic body propelled by fins, flippers or "+ "tail, with NO walking legs. Fish, sharks, rays, dolphins, whales, ""octopuses, seahorses. Mermaids belong here.\n"- "- serpentine: elongated, LIMBLESS, tubular body. Snakes, eels, "- "worms, legless lizards. Any visible legs disqualify this category.\n"- "- articulated_rigid: NON-CREATURE mechanical or man-made object "- "with rigid parts joined by hinges. Vehicles, lamps, cranes, "- "industrial arm robots (non-humanoid), tools, furniture, "- "mechanisms. Use this ONLY when the asset clearly does not read as "- "a creature.\n\n"+ "- serpentine: elongated, LIMBLESS, tubular body. Snakes, eels, worms, "+ "legless lizards. Any visible legs disqualify this category.\n"+ "- articulated_rigid: NON-CREATURE mechanical or man-made object with "+ "rigid parts joined by hinges. Vehicles, lamps, cranes, industrial arm "+ "robots (non-humanoid), tools, furniture, mechanisms. Only when the "+ "asset clearly does not read as a creature.\n"+ "- uncertain: the evidence conflicts or none of the above fits. Use "+ "this instead of guessing; a human reviews these.\n\n""# Decision priority (apply in order; stop at the first match)\n"- "1. Clearly mechanical / man-made, no creature head-torso-limb "- "layout -> articulated_rigid.\n"- "2. Six or more legs OR arthropod silhouette (segmented body, "- "exoskeleton plates, antennae) -> insectoid. THIS OVERRIDES WINGS — "- "a bee or butterfly is insectoid, not avian.\n"- "3. Two large flight wings paired with the torso, wings are a "- "dominant feature -> avian.\n"- "4. No walking limbs, body shaped for swimming with fins/tail "- "-> marine.\n"+ "1. Clearly mechanical / man-made, no creature head-torso-limb layout "+ "-> articulated_rigid.\n"+ "2. Six or more legs OR arthropod silhouette / labels (antennae, "+ "mandibles, pincers, stinger, segmented body) -> insectoid. THIS "+ "OVERRIDES WINGS — a bee or butterfly is insectoid, not avian.\n"+ "3. Two large flight wings that dominate the limbs (Wing joints, or "+ "an obviously winged silhouette) and, when captions are given, clips "+ "that fly or flap -> avian.\n"+ "4. No walking limbs, body shaped for swimming with fins / tail -> "+ "marine.\n""5. No limbs at all, long tubular body -> serpentine.\n"- "6. Four legs as primary ground stance -> quadrupedal.\n"+ "6. Four legs as primary ground stance (labels list four leg chains, "+ "e.g. 'Thigh x2' + 'Upper Arm x2' or 'Front Leg' + 'Hind Leg'; captions "+ "say 'on all fours', 'gallops', 'trots') -> quadrupedal.\n""7. Two legs as primary ground stance -> bipedal.\n"- "8. Anything still ambiguous -> articulated_rigid.\n\n"+ "8. Evidence conflicts or nothing fits -> uncertain.\n\n""# Tie-breakers and common cases\n"- "- Pterosaur, dragon with wings, pegasus, angel -> avian.\n"- "- Wingless dragon with four legs -> quadrupedal.\n"- "- Wyvern (two legs + two wings) -> avian.\n"- "- Penguin, ostrich, T-Rex, raptor -> bipedal.\n"- "- Bee, butterfly, dragonfly, ladybug -> insectoid.\n"- "- Centaur -> quadrupedal. Mermaid -> marine.\n"- "- Spider robot / hexapod robot -> insectoid.\n"- "- Humanoid robot / mech with two arms and two legs -> bipedal.\n"- "- Quadruped robot (Spot-style, four legs) -> quadrupedal.\n"- "- Industrial robot arm, crane, lamp, loose mechanism -> "+ "- Pterosaur, dragon with wings, pegasus, angel -> avian. Wingless "+ "dragon with four legs -> quadrupedal. Wyvern (two legs + two wings) "+ "-> avian.\n"+ "- Penguin, ostrich, chicken, T-Rex, raptor -> bipedal. A bird whose "+ "clips only walk and peck is still bipedal only if it is a flightless "+ "kind; otherwise avian.\n"+ "- Bee, butterfly, dragonfly, ladybug -> insectoid. Centaur -> "+ "quadrupedal. Mermaid -> marine.\n"+ "- Spider robot / hexapod robot -> insectoid. Humanoid robot / mech "+ "with two arms and two legs -> bipedal. Quadruped robot (Spot-style) "+ "-> quadrupedal. Industrial robot arm, crane, lamp, loose mechanism -> ""articulated_rigid.\n"- "- Lizard with small limbs (gecko, salamander) -> quadrupedal.\n"- "- Snake, eel, worm -> serpentine.\n\n"+ "- Lizard with small limbs (gecko, salamander, crocodile) -> "+ "quadrupedal. Snake, eel, worm -> serpentine.\n"+ "- Elephants, mammoths, rhinos, hippos and big cats are quadrupedal "+ "even when the rest pose looks upright or the front legs are raised.\n"+ "- A humanoid whose rest pose lies flat on the ground is still bipedal "+ "if the animation frames show it standing on two legs.\n\n""# Output\n"- "Reply with EXACTLY one of these tokens, lowercase, no punctuation, "- "no explanation, no quotes:\n"- "bipedal | quadrupedal | insectoid | avian | marine | serpentine | "- "articulated_rigid"+ "Reply with ONE JSON object and nothing else — no prose, no code "+ "fence:\n"+ "{\"legs_on_ground\": <integer>, \"wings\": <true|false>, "+ "\"fins\": <true|false>, \"mechanical\": <true|false>, "+ "\"category\": \"<bipedal|quadrupedal|insectoid|avian|marine|"+ "serpentine|articulated_rigid|uncertain>\", "+ "\"confidence\": \"<high|medium|low>\", "+ "\"reason\": \"<at most 12 words>\"}\n"+ "Fill the evidence fields from what you actually see and read; the "+ "category must follow from them.")# ── Caption task registry ────────────────────────────────────────────────────