Nekochu commited on
Commit
a8e08c2
·
1 Parent(s): 1f2ad82

merge Kimodo-cpp into MoMask as two tabs

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.so filter=lfs diff=lfs merge=lfs -text
37
+ *.so.* filter=lfs diff=lfs merge=lfs -text
38
+ runtime/kmd-encode filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,39 +1,124 @@
1
  ---
2
- title: MoMask
3
- emoji: 🎭
4
  colorFrom: pink
5
  colorTo: purple
6
  sdk: gradio
7
- sdk_version: "6.1.0"
8
- app_file: app_new.py
9
- pinned: false
10
  python_version: "3.10"
11
- short_description: Text-to-3D motion generation using ONNX models
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
- # MoMask: Text-to-Motion Generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- Generate 3D human skeleton animations from text descriptions using [MoMask](https://github.com/EricGuo5513/momask-codes).
 
 
 
 
17
 
18
- ## Features
19
- - Text-to-motion generation with classifier-free guidance
20
- - Download BVH files for Blender import
21
- - ~7 seconds of motion per generation
22
 
23
- ## Model Architecture (ONNX FP32, ~416MB total)
24
- | Model | Size | Purpose |
25
- |-------|------|---------|
26
- | CLIP Text Encoder | 254MB | Text embedding |
27
- | Mask Transformer | 56MB | Initial motion tokens |
28
- | Residual Transformer | 55MB | Refine motion details |
29
- | VQ-VAE Decoder | 46MB | Decode to motion |
30
- | Length Estimator | 0.5MB | Predict motion length |
31
 
32
- ## Usage
33
- 1. Enter a text description (e.g., "A person walks forward")
34
- 2. Optionally set duration and seed
35
- 3. Click Generate
36
- 4. Download MP4 video or BVH for Blender
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  ## Credits
39
- Based on [MoMask](https://github.com/EricGuo5513/momask-codes) by Chuan Guo et al.
 
 
 
 
1
  ---
2
+ title: Kimodo cpp + MoMask
3
+ emoji: 🕺
4
  colorFrom: pink
5
  colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 6.3.0
 
 
8
  python_version: "3.10"
9
+ app_file: app.py
10
+ pinned: false
11
+ fullWidth: true
12
+ license: other
13
+ license_name: nvidia-open-model-license
14
+ license_link: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/
15
+ short_description: Two CPU text-to-motion models, Kimodo GGML and MoMask ONNX
16
+ startup_duration_timeout: 1h
17
+ preload_from_hub:
18
+ - LocalAI-io/Kimodo-SOMA-RP-v1.1-GGML models/kimodo-soma-rp-v1.1-f32.gguf
19
+ - LocalAI-io/Kimodo-SOMA-SEED-v1.1-GGML models/kimodo-soma-seed-v1.1-f32.gguf
20
+ - LocalAI-io/Kimodo-G1-RP-v1-GGML models/kimodo-g1-rp-v1-f32.gguf
21
+ - LocalAI-io/Kimodo-G1-SEED-v1-GGML models/kimodo-g1-seed-v1-f32.gguf
22
+ - LocalAI-io/Llama-3-Kimodo-GGML
23
  ---
24
 
25
+ # Kimodo cpp + MoMask
26
+
27
+ Two text-to-motion models on one free CPU Space, a tab each. Both take a plain
28
+ English description and return a skeletal animation plus a BVH file for Blender.
29
+
30
+ This Space merges [WeReCooking2/Kimodo-cpp](https://huggingface.co/spaces/WeReCooking2/Kimodo-cpp)
31
+ into what was `Luminia/momask-codes`.
32
+
33
+ ## Which tab to use
34
+
35
+ | | Kimodo | MoMask |
36
+ | --- | --- | --- |
37
+ | Runtime | kimodo.cpp, GGML | ONNX Runtime |
38
+ | Rigs | SOMA 30 joint human, Unitree G1 34 joint robot | 22 joint human |
39
+ | Outputs | glTF orbit preview, BVH, MP4 | MP4, BVH |
40
+ | First run on a new prompt | ~2 min, one LLM2Vec encode | ~10 s |
41
+ | Repeat prompt | sampling only | same |
42
+
43
+ MoMask is the one to reach for first because it is roughly an order of magnitude
44
+ cheaper. Kimodo is worth the wait when you want the robot rig, a longer clip, or
45
+ its markedly better motion quality.
46
+
47
+ Kimodo's cost is not the sampling, it is the text encode. It conditions on a
48
+ 4096 float LLM2Vec embedding produced by a Llama 3 bundle of 35 files, and
49
+ `kmd-encode` reopens all of them per call, so one prompt costs one full pass
50
+ regardless of length. Embeddings are memoised on the prompt text, so re-rolling a
51
+ seed or changing the frame count afterwards costs nothing extra. MoMask has no
52
+ equivalent step because CLIP text encoding is inside its ONNX graph.
53
+
54
+ ## Keeping two native stacks in one process
55
+
56
+ The two pipelines do not share anything, and the merge is mostly about making
57
+ sure they do not stand on each other.
58
+
59
+ **Import order is load-bearing.** matplotlib's `ft2font` is a pybind11 extension
60
+ built against the system libstdc++ and fails to initialise if a differently
61
+ linked libstdc++ is already resident. So `app.py` imports the drawing stack
62
+ first, before anything native.
63
 
64
+ **MoMask's backends are deferred.** torch, onnxruntime and CLIP each bring their
65
+ own libstdc++ and libgomp, and Kimodo dlopens `libkimodo.so` together with its
66
+ own bundled `libgomp.so.1` into the same process. `momask_core._ensure_backends()`
67
+ holds them back until the MoMask tab is actually used, so a visitor who only
68
+ generates with Kimodo never loads them at all.
69
 
70
+ **Each pipeline keeps its own weights.** Kimodo runs GGUF checkpoints, MoMask
71
+ runs its own ONNX graphs. Nothing is deduplicated or substituted across them,
72
+ which keeps any quality complaint attributable to one model.
 
73
 
74
+ Two vCPUs run one job at a time, so a second visitor queues. The browser shows a
75
+ queue position; an API caller does not.
 
 
 
 
 
 
76
 
77
+ ## Models
78
+
79
+ Kimodo, about 1.13 GB each, all preloaded at build time so a wake costs no
80
+ download. One is resident at a time.
81
+
82
+ | Checkpoint | Rig | Joints |
83
+ | --- | --- | --- |
84
+ | SOMA RP v1.1 | `soma30` | 30 |
85
+ | SOMA SEED v1.1 | `soma30` | 30 |
86
+ | G1 RP v1 | `g1skel34` | 34 |
87
+ | G1 SEED v1 | `g1skel34` | 34 |
88
+
89
+ MoMask, about 417 MB of ONNX in this repo: CLIP text encoder 254 MB, mask
90
+ transformer 56 MB, residual transformer 55 MB, VQ-VAE decoder 46 MB, length
91
+ estimator 0.5 MB.
92
+
93
+ ## Calling it from the API
94
+
95
+ Two named endpoints, `/generate` for Kimodo and `/momask_generate` for MoMask.
96
+ Read them from `/gradio_api/info` rather than guessing.
97
+
98
+ The Space is also an MCP server at `/gradio_api/mcp/sse`, so an LLM client can
99
+ call either tab as a tool.
100
+
101
+ Watch out for one thing on the streamed response. `data: null` is the heartbeat
102
+ payload, not a result and not a failure. It arrives every 15 seconds for as long
103
+ as the job is queued or running, so read the `event:` line and treat only
104
+ `complete` and `error` as terminal:
105
+
106
+ ```python
107
+ event = None
108
+ for line in stream:
109
+ if line.startswith("event: "):
110
+ event = line[7:].strip()
111
+ elif line.startswith("data: ") and event in ("complete", "error"):
112
+ payload = line[6:]
113
+ break
114
+ ```
115
+
116
+ `POST /gradio_api/call/generate` returns 200 with an event id whatever happens
117
+ next, so judging success by that status is misleading. The outcome is only on
118
+ the stream.
119
 
120
  ## Credits
121
+
122
+ [NVIDIA Kimodo](https://www.nvidia.com/) through
123
+ [kimodo.cpp](https://github.com/localai-org/kimodo.cpp).
124
+ [MoMask](https://github.com/EricGuo5513/momask-codes) by Chuan Guo et al.
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two CPU text-to-motion models in one Space, one tab each.
2
+
3
+ Import order matters here and is not cosmetic. matplotlib's ft2font is a
4
+ pybind11 extension built against the system libstdc++ and fails to initialise if
5
+ a differently linked libstdc++ is already resident, so the drawing stack is
6
+ imported before anything native. Kimodo then dlopens libkimodo.so together with
7
+ its own bundled libgomp at generate time, while MoMask's torch, onnxruntime and
8
+ CLIP are held back behind momask_core._ensure_backends() until that tab is
9
+ actually used. A visitor who only generates with Kimodo never loads them.
10
+
11
+ Each pipeline keeps its own weights. Kimodo runs GGUF checkpoints through the
12
+ kimodo.cpp GGML port; MoMask runs its own ONNX graphs. Nothing is shared or
13
+ substituted between them.
14
+ """
15
+
16
+ import matplotlib
17
+ matplotlib.use("Agg")
18
+ import matplotlib.pyplot as plt # noqa: E402,F401
19
+
20
+ import gradio as gr # noqa: E402
21
+
22
+ import kimodo_core as K # noqa: E402
23
+ import momask_core as M # noqa: E402
24
+
25
+ CSS = K.CSS + """
26
+ #mm_log textarea { font-family: ui-monospace, monospace; font-size: 0.8em; }
27
+ .tabs { gap: 0 !important; }
28
+ """
29
+
30
+ HEADER = (f"CPU text to motion · **Kimodo** through "
31
+ f"[kimodo.cpp](https://github.com/localai-org/kimodo.cpp) GGML, "
32
+ f"**MoMask** through ONNX · {K.CPUS} threads")
33
+
34
+
35
+ def momask_generate(text, length, seed):
36
+ """Generate a 3D skeletal animation from a text description of a motion.
37
+
38
+ Runs MoMask on CPU through ONNX Runtime. Returns a rendered preview and a
39
+ BVH file for Blender. Far cheaper than the Kimodo tab because there is no
40
+ LLM2Vec encode: CLIP text encoding is part of the graph.
41
+
42
+ Args:
43
+ text: Plain English description of the motion, for example "a person walks forward".
44
+ length: Clip length in seconds. 0 asks the length estimator to pick one.
45
+ seed: Random seed. The same seed and text reproduce a clip exactly.
46
+ """
47
+ if not (text or "").strip():
48
+ raise gr.Error("Describe a motion first, for example "
49
+ "\"a person walks forward\".")
50
+ _joints, video_path, bvh_path = M.generate_motion(
51
+ text, float(length or 0), int(seed) if seed is not None else None)
52
+ if video_path is None:
53
+ raise gr.Error("MoMask returned no motion. Try a shorter, plainer "
54
+ "description, or set Duration above 0.")
55
+ return video_path, gr.update(value=bvh_path, interactive=bvh_path is not None)
56
+
57
+
58
+ def kimodo_tab():
59
+ """Kimodo's own layout, unchanged apart from living inside a tab."""
60
+ with gr.Row():
61
+ with gr.Column(scale=4):
62
+ prompt = gr.Textbox(
63
+ value="a person runs forward and jumps over an obstacle",
64
+ label="Describe the motion", lines=1, max_lines=1,
65
+ placeholder="a person performs a spinning back kick")
66
+ run = gr.Button(
67
+ f"Generate ({K._duration(K.ENCODE_S + K.sampling_seconds(120, 20))})",
68
+ variant="primary")
69
+ gr.Examples(
70
+ examples=["a person walks forward at a steady pace",
71
+ "a person performs a roundhouse kick",
72
+ "a person sits down on a chair",
73
+ "a person dances happily in place"],
74
+ example_labels=["walks forward", "roundhouse kick",
75
+ "sits down on a chair", "dances in place"],
76
+ inputs=prompt, label="Examples")
77
+ status = gr.Textbox(lines=8, max_lines=K.LOG_LINES + 2,
78
+ autoscroll=True, show_label=False,
79
+ container=False, elem_id="log")
80
+ with gr.Column(scale=3):
81
+ model_label = gr.Dropdown(
82
+ choices=[c.label for c in K.CHECKPOINTS],
83
+ value=K.CHECKPOINTS[0].label, label="Motion model",
84
+ info="SOMA is a 30 joint human rig, G1 a 34 joint Unitree "
85
+ "robot. RP and SEED are different checkpoints of each.")
86
+ frames = gr.Slider(30, 240, value=120, step=10,
87
+ label=f"Frames ({120 / K.FPS:.1f} s clip)")
88
+ with gr.Accordion("Advanced", open=False):
89
+ with gr.Row():
90
+ steps = gr.Slider(4, 50, value=20, step=1, scale=3,
91
+ label="Diffusion steps (20)",
92
+ info="More steps, cleaner motion.")
93
+ seed = gr.Number(value=7, precision=0, label="Seed", scale=1)
94
+ with gr.Row():
95
+ text_cfg = gr.Slider(1.0, 5.0, value=2.0, step=0.5, scale=3,
96
+ label="Guidance")
97
+ deskate = gr.Checkbox(value=True, scale=1,
98
+ label="Reduce foot skating")
99
+ with gr.Column(scale=5):
100
+ viewer = gr.Model3D(label="Skeleton", interactive=False, height=260)
101
+ video = gr.Video(label="Preview", autoplay=True, height=180)
102
+ bvh = gr.DownloadButton("Download BVH for Blender", size="sm",
103
+ interactive=False)
104
+
105
+ for control in (prompt, frames, steps):
106
+ control.change(K.control_labels, inputs=[prompt, frames, steps],
107
+ outputs=[frames, steps, run], queue=False,
108
+ api_visibility="private")
109
+ run.click(K.generate,
110
+ inputs=[prompt, model_label, frames, steps, seed, text_cfg, deskate],
111
+ outputs=[video, viewer, bvh, status],
112
+ api_name="generate").then(
113
+ K.control_labels, inputs=[prompt, frames, steps],
114
+ outputs=[frames, steps, run], queue=False, api_visibility="private")
115
+
116
+
117
+ def momask_tab():
118
+ """Same shape as the Kimodo tab so switching tabs does not relayout the page:
119
+ inputs left, settings middle, outputs right."""
120
+ with gr.Row():
121
+ with gr.Column(scale=4):
122
+ text = gr.Textbox(value="a person walks forward",
123
+ label="Describe the motion", lines=1, max_lines=1,
124
+ placeholder="a person does a salsa dance")
125
+ run = gr.Button("Generate (~10 s)", variant="primary")
126
+ gr.Examples(
127
+ examples=["a person walks forward",
128
+ "a person is running on a treadmill",
129
+ "a person jumps up and then lands",
130
+ "a person does a salsa dance"],
131
+ example_labels=["walks forward", "running", "jumps and lands",
132
+ "salsa dance"],
133
+ inputs=text, label="Examples")
134
+ with gr.Column(scale=3):
135
+ length = gr.Slider(0, 10, value=0, step=0.5,
136
+ label="Duration (0 = estimate it)",
137
+ info="Seconds. The length estimator picks one "
138
+ "from the text when this is 0.")
139
+ seed = gr.Number(value=42, precision=0, label="Seed")
140
+ with gr.Column(scale=5):
141
+ video = gr.Video(label="Preview", autoplay=True, height=260)
142
+ bvh = gr.DownloadButton("Download BVH for Blender", size="sm",
143
+ interactive=False)
144
+
145
+ run.click(momask_generate, inputs=[text, length, seed],
146
+ outputs=[video, bvh], api_name="momask_generate")
147
+
148
+
149
+ with gr.Blocks(title="Kimodo cpp + MoMask", fill_width=True) as demo:
150
+ gr.Markdown(HEADER, elem_id="foot")
151
+ with gr.Tabs():
152
+ with gr.Tab("Kimodo (GGML)"):
153
+ kimodo_tab()
154
+ with gr.Tab("MoMask (ONNX)"):
155
+ momask_tab()
156
+
157
+ if __name__ == "__main__":
158
+ demo.queue(max_size=8, default_concurrency_limit=1).launch(
159
+ css=CSS, mcp_server=True)
kimodo_core.py ADDED
@@ -0,0 +1,1105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kimodo text to motion on a free CPU Space, via the kimodo.cpp GGML port.
2
+
3
+ All logic lives here: the ctypes bridge to libkimodo.so, the SOMA 30 joint and
4
+ Unitree G1 34 joint rigs, forward kinematics, the GLB, BVH and MP4 writers, and
5
+ the UI. Nothing downstream assumes a joint count: the rig is selected from the
6
+ joint count the model returns and cross checked against the one its checkpoint
7
+ declares, so a mismatched entry raises instead of rendering the wrong figure.
8
+
9
+ Prompts are free text. The 15.18 GB LLM2Vec encoder is preloaded at build time
10
+ by preload_from_hub, so it sits on local disk and no wake pays to fetch it. One
11
+ encode is one pass over that bundle, a fixed price per distinct prompt, so
12
+ embeddings are memoised on the text.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ctypes
18
+ import json
19
+ import math
20
+ import os
21
+ import struct
22
+ import subprocess
23
+ import tempfile
24
+ import time
25
+ from pathlib import Path
26
+ from typing import NamedTuple
27
+
28
+ import gradio as gr
29
+ import matplotlib
30
+ import numpy as np
31
+
32
+ # Import the drawing stack before any native library is dlopened. matplotlib's
33
+ # ft2font is a pybind11 extension built against the system libstdc++, and it
34
+ # fails to initialise if a differently linked libstdc++ has already been pulled
35
+ # into the process.
36
+ matplotlib.use("Agg")
37
+ import matplotlib.pyplot as plt # noqa: E402
38
+ from matplotlib.animation import FFMpegWriter, FuncAnimation # noqa: E402
39
+
40
+
41
+ def container_cpus() -> int:
42
+ """CPUs this container may actually use.
43
+
44
+ os.cpu_count() reports the Space host, not the cgroup quota, so on a
45
+ cpu-basic Space it over-reports badly and GGML would spawn threads that
46
+ only fight each other for the two vCPUs the container is allowed.
47
+ """
48
+ for quota_path, period_path in (("/sys/fs/cgroup/cpu.max", None),
49
+ ("/sys/fs/cgroup/cpu/cpu.cfs_quota_us",
50
+ "/sys/fs/cgroup/cpu/cpu.cfs_period_us")):
51
+ try:
52
+ raw = Path(quota_path).read_text().split()
53
+ if period_path is None:
54
+ quota, period = raw[0], raw[1]
55
+ else:
56
+ quota, period = raw[0], Path(period_path).read_text().strip()
57
+ if quota != "max" and int(quota) > 0:
58
+ return max(1, int(quota) // int(period))
59
+ except Exception:
60
+ continue
61
+ return max(1, os.cpu_count() or 2)
62
+
63
+
64
+ # GGML reads its thread count from the environment at backend init, and the
65
+ # threads field of kimodo_runtime_options does not reach the motion backend.
66
+ # Both must be set before the shared library is first used.
67
+ CPUS = container_cpus()
68
+ os.environ.setdefault("KIMODO_THREADS", str(CPUS))
69
+ os.environ.setdefault("OMP_NUM_THREADS", str(CPUS))
70
+
71
+ HERE = Path(__file__).parent
72
+ RUNTIME_DIR = HERE / "runtime"
73
+ FPS = 30
74
+ # The full LLM2Vec bundle, preloaded at build time by preload_from_hub, so it
75
+ # is on local disk rather than fetched per wake.
76
+ TEXT_REPO = "LocalAI-io/Llama-3-Kimodo-GGML"
77
+ TEXT_BUNDLE_SUBDIR = "generated/llm2vec-text-bundle"
78
+
79
+ # Copied from kimodo.cpp src/skeleton.hpp, which in turn copies NVIDIA
80
+ # Kimodo's Apache-2.0 kimodo/skeleton/definitions.py. Offsets are parent-local.
81
+ SOMA30_NAMES = [
82
+ "Hips", "Spine1", "Spine2", "Chest", "Neck1", "Neck2", "Head", "Jaw",
83
+ "LeftEye", "RightEye", "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",
84
+ "LeftHandThumbEnd", "LeftHandMiddleEnd", "RightShoulder", "RightArm",
85
+ "RightForeArm", "RightHand", "RightHandThumbEnd", "RightHandMiddleEnd",
86
+ "LeftLeg", "LeftShin", "LeftFoot", "LeftToeBase", "RightLeg", "RightShin",
87
+ "RightFoot", "RightToeBase",
88
+ ]
89
+
90
+ SOMA30_PARENTS = np.array([
91
+ -1, 0, 1, 2, 3, 4, 5, 6, 6, 6, 3, 10, 11, 12, 13, 13, 3, 16, 17, 18, 19,
92
+ 19, 0, 22, 23, 24, 0, 26, 27, 28,
93
+ ], dtype=np.int32)
94
+
95
+ SOMA30_OFFSETS = np.array([
96
+ [0, 0, 0],
97
+ [-.00013727, .0500376256, -.00053726669],
98
+ [-1.86574103e-9, .0712530139, -.000298248546],
99
+ [-5.75188398e-9, .0755006305, -.00815970992],
100
+ [-.00181676517, .263112953, -.00553348292],
101
+ [-2.85102231e-8, .0770939664, .0230258546],
102
+ [-4.5975437e-8, .0612891595, .0195370861],
103
+ [2.63687901e-5, .0047559225, .0309494062],
104
+ [.0320638079, .0538020513, .0758688308],
105
+ [-.0322244017, .05361869, .0755823359],
106
+ [.0162165175, .232371641, .0511341324],
107
+ [.149198457, 2.19397873e-8, -.0550232576],
108
+ [.287393078, 2.50268389e-9, -2.58787737e-5],
109
+ [.270939812, -7.06625108e-9, 2.60897248e-5],
110
+ [.122686267, -.0322017573, .0483306876],
111
+ [.190119595, -.00312878387, -.000339570373],
112
+ [-.0138011824, .231803086, .0521415786],
113
+ [-.150371962, 1.17387901e-7, -.0554560437],
114
+ [-.287366393, 1.87628082e-8, -2.59709359e-5],
115
+ [-.271336198, -1.16767401e-9, 2.61269368e-5],
116
+ [-.122642483, -.0321145448, .0480403904],
117
+ [-.190005945, -.00306615542, -.0003157343],
118
+ [.10043214, -.0843452671, .0259565473],
119
+ [-1e-8, -.432217537, -.00802912805],
120
+ [1e-8, -.421550959, -.0348152298],
121
+ [0, -.0505947206, .132315294],
122
+ [-.10047278, -.0829525995, .0262031695],
123
+ [1e-8, -.433622059, -.00805555828],
124
+ [2e-8, -.421173943, -.0347839785],
125
+ [-3.42907669e-9, -.0507960932, .132841956],
126
+ ], dtype=np.float32)
127
+
128
+ # Unitree G1, 34 joints. Ported from kimodo.cpp demo/skeletons_extra.go, key
129
+ # g1skel34, which copies NVIDIA's Apache-2.0 definitions. Offsets are
130
+ # parent-local, same convention as SOMA.
131
+ G1SKEL34_NAMES = [
132
+ "pelvis_skel", "left_hip_pitch_skel", "left_hip_roll_skel",
133
+ "left_hip_yaw_skel", "left_knee_skel", "left_ankle_pitch_skel",
134
+ "left_ankle_roll_skel", "left_toe_base", "right_hip_pitch_skel",
135
+ "right_hip_roll_skel", "right_hip_yaw_skel", "right_knee_skel",
136
+ "right_ankle_pitch_skel", "right_ankle_roll_skel", "right_toe_base",
137
+ "waist_yaw_skel", "waist_roll_skel", "waist_pitch_skel",
138
+ "left_shoulder_pitch_skel", "left_shoulder_roll_skel",
139
+ "left_shoulder_yaw_skel", "left_elbow_skel", "left_wrist_roll_skel",
140
+ "left_wrist_pitch_skel", "left_wrist_yaw_skel", "left_hand_roll_skel",
141
+ "right_shoulder_pitch_skel", "right_shoulder_roll_skel",
142
+ "right_shoulder_yaw_skel", "right_elbow_skel", "right_wrist_roll_skel",
143
+ "right_wrist_pitch_skel", "right_wrist_yaw_skel", "right_hand_roll_skel",
144
+ ]
145
+
146
+ G1SKEL34_PARENTS = np.array([
147
+ -1, 0, 1, 2, 3, 4, 5, 6, 0, 8, 9, 10, 11, 12, 13, 0, 15, 16, 17, 18, 19,
148
+ 20, 21, 22, 23, 24, 17, 26, 27, 28, 29, 30, 31, 32,
149
+ ], dtype=np.int32)
150
+
151
+ G1SKEL34_OFFSETS = np.array([
152
+ [0, 0, 0],
153
+ [.064452, -.1027, 0], [.052, -.030465, 0], [0, -.12412, .025001],
154
+ [.0021489, -.17734, -.078273], [-.000094445, -.30001, 0],
155
+ [0, -.017558, 0], [0, -.035, .14],
156
+ [-.064452, -.1027, 0], [-.052, -.030465, 0], [0, -.12412, .025001],
157
+ [-.0021489, -.17734, -.078273], [.000094445, -.30001, 0],
158
+ [0, -.017558, 0], [0, -.035, .14],
159
+ [0, 0, 0], [0, .044, -.0039635], [0, 0, 0],
160
+ [.10022, .24778, .0039563], [.038, -.013831, 0], [.00624, -.1032, 0],
161
+ [0, -.080518, .015783], [.00188791, -.01, .1], [0, 0, .038],
162
+ [0, 0, .046], [0, 0, .1],
163
+ [-.10021, .24778, .0039563], [-.038, -.013831, 0], [-.00624, -.1032, 0],
164
+ [0, -.080518, .015783], [-.00188791, -.01, .1], [0, 0, .038],
165
+ [0, 0, .046], [0, 0, .1],
166
+ ], dtype=np.float32)
167
+
168
+
169
+ class Skeleton(NamedTuple):
170
+ """One rig, carried with the checkpoint that produced it.
171
+
172
+ Everything downstream reads shape and scale from here. Nothing may fall
173
+ back to a module constant or to a bounds check: on a 34 joint rig, indices
174
+ written for a 30 joint one all still exist and name different joints, so a
175
+ stale constant produces a plausible wrong answer instead of an error.
176
+ """
177
+ key: str
178
+ names: list[str]
179
+ parents: np.ndarray
180
+ offsets: np.ndarray
181
+ chains: list[list[int]] # colour groups for the preview
182
+ feet: tuple[int, ...] # ankles and toes, for the deskating heuristic
183
+ stature: float # rough standing height, metres
184
+ bvh_scale: float # BVH is conventionally centimetres
185
+ bone_thickness: float # preview bone box, sized to the rig
186
+ plant_speed: float # deskating: horizontal metres per frame
187
+ plant_height: float # deskating: metres above the lowest joint
188
+
189
+ @property
190
+ def joints(self) -> int:
191
+ return len(self.names)
192
+
193
+
194
+ def make_skeleton(**fields) -> Skeleton:
195
+ """Build a rig and refuse a malformed one at import, not mid render."""
196
+ skeleton = Skeleton(**fields)
197
+ joints = skeleton.joints
198
+ if not (len(skeleton.parents) == len(skeleton.offsets) == joints):
199
+ raise ValueError(f"{skeleton.key}: names, parents and offsets disagree")
200
+ if int(skeleton.parents[0]) != -1:
201
+ raise ValueError(f"{skeleton.key}: joint 0 must be the root")
202
+ # Forward kinematics is a single forward pass, so a parent must already be
203
+ # solved when its child is reached. Assert it once here rather than let the
204
+ # loop read uninitialised memory and return a garbled figure in silence.
205
+ for joint in range(1, joints):
206
+ parent = int(skeleton.parents[joint])
207
+ if not 0 <= parent < joint:
208
+ raise ValueError(
209
+ f"{skeleton.key}: joint {joint} has parent {parent}, so the "
210
+ f"rig is not topologically sorted and FK would read "
211
+ f"uninitialised memory")
212
+ for index in {j for chain in skeleton.chains for j in chain} | set(skeleton.feet):
213
+ if not 0 <= index < joints:
214
+ raise ValueError(f"{skeleton.key}: index {index} is out of range")
215
+ return skeleton
216
+
217
+
218
+ def children_of(skeleton: Skeleton) -> list[list[int]]:
219
+ """Parent to children map, derived once per rig rather than per writer."""
220
+ children: list[list[int]] = [[] for _ in range(skeleton.joints)]
221
+ for joint, parent in enumerate(skeleton.parents):
222
+ if int(parent) >= 0:
223
+ children[int(parent)].append(joint)
224
+ return children
225
+
226
+
227
+ SOMA30 = make_skeleton(
228
+ key="soma30", names=SOMA30_NAMES, parents=SOMA30_PARENTS,
229
+ offsets=SOMA30_OFFSETS,
230
+ chains=[
231
+ [0, 1, 2, 3, 4, 5, 6], # spine and head
232
+ [3, 10, 11, 12, 13], # left arm
233
+ [3, 16, 17, 18, 19], # right arm
234
+ [0, 22, 23, 24, 25], # left leg
235
+ [0, 26, 27, 28, 29], # right leg
236
+ ],
237
+ # skeleton.hpp soma30_spec end_effectors {24, 28, 13, 19}, plus the toes.
238
+ feet=(24, 25, 28, 29),
239
+ stature=1.65, bvh_scale=100.0, bone_thickness=0.035,
240
+ plant_speed=0.02, plant_height=0.06,
241
+ )
242
+
243
+ G1SKEL34 = make_skeleton(
244
+ key="g1skel34", names=G1SKEL34_NAMES, parents=G1SKEL34_PARENTS,
245
+ offsets=G1SKEL34_OFFSETS,
246
+ chains=[
247
+ [0, 15, 16, 17], # pelvis and waist
248
+ [17, 18, 19, 20, 21, 22, 23, 24, 25], # left arm
249
+ [17, 26, 27, 28, 29, 30, 31, 32, 33], # right arm
250
+ [0, 1, 2, 3, 4, 5, 6, 7], # left leg
251
+ [0, 8, 9, 10, 11, 12, 13, 14], # right leg
252
+ ],
253
+ # skeleton.hpp g1skel34_spec end_effectors {6, 13, 24, 32}, plus the toes.
254
+ feet=(6, 7, 13, 14),
255
+ # The G1 is a 1.1 m robot, so the thresholds and the bone boxes that suit a
256
+ # 1.65 m human are all proportionally too big for it.
257
+ stature=1.10, bvh_scale=100.0, bone_thickness=0.024,
258
+ plant_speed=0.013, plant_height=0.04,
259
+ )
260
+
261
+ SKELETONS = {skeleton.key: skeleton for skeleton in (SOMA30, G1SKEL34)}
262
+ SKELETON_BY_JOINTS = {skeleton.joints: skeleton for skeleton in SKELETONS.values()}
263
+
264
+ EMBEDDING_WIDTH = 4096
265
+
266
+
267
+ class _RuntimeOptions(ctypes.Structure):
268
+ _fields_ = [
269
+ ("size", ctypes.c_uint32),
270
+ ("threads", ctypes.c_uint32),
271
+ ("device", ctypes.c_int),
272
+ ("backend_dir", ctypes.c_char_p),
273
+ ]
274
+
275
+
276
+ class _GenerationOptions(ctypes.Structure):
277
+ _fields_ = [
278
+ ("size", ctypes.c_uint32),
279
+ ("seed", ctypes.c_uint64),
280
+ ("frames", ctypes.c_uint32),
281
+ ("diffusion_steps", ctypes.c_uint32),
282
+ ("text_cfg_weight", ctypes.c_float),
283
+ ("constraint_cfg_weight", ctypes.c_float),
284
+ ]
285
+
286
+
287
+ class _Embedding(ctypes.Structure):
288
+ _fields_ = [
289
+ ("data", ctypes.POINTER(ctypes.c_float)),
290
+ ("values", ctypes.c_uint32),
291
+ ]
292
+
293
+
294
+ def _bind(library: ctypes.CDLL) -> ctypes.CDLL:
295
+ library.kimodo_abi_version.restype = ctypes.c_int
296
+ library.kimodo_model_load.restype = ctypes.c_void_p
297
+ library.kimodo_model_load.argtypes = [
298
+ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
299
+ ctypes.POINTER(_RuntimeOptions), ctypes.c_char_p, ctypes.c_int,
300
+ ]
301
+ library.kimodo_model_free.argtypes = [ctypes.c_void_p]
302
+ library.kimodo_generate_embedding.restype = ctypes.c_void_p
303
+ library.kimodo_generate_embedding.argtypes = [
304
+ ctypes.c_void_p, ctypes.POINTER(_Embedding),
305
+ ctypes.POINTER(_GenerationOptions), ctypes.c_char_p, ctypes.c_int,
306
+ ]
307
+ library.kimodo_motion_free.argtypes = [ctypes.c_void_p]
308
+ library.kimodo_motion_frames.restype = ctypes.c_int
309
+ library.kimodo_motion_frames.argtypes = [ctypes.c_void_p]
310
+ library.kimodo_motion_joints.restype = ctypes.c_int
311
+ library.kimodo_motion_joints.argtypes = [ctypes.c_void_p]
312
+ library.kimodo_motion_local_rotations_xyzw.restype = ctypes.POINTER(ctypes.c_float)
313
+ library.kimodo_motion_local_rotations_xyzw.argtypes = [ctypes.c_void_p]
314
+ library.kimodo_motion_root_positions.restype = ctypes.POINTER(ctypes.c_float)
315
+ library.kimodo_motion_root_positions.argtypes = [ctypes.c_void_p]
316
+ return library
317
+
318
+
319
+ class KimodoError(RuntimeError):
320
+ pass
321
+
322
+
323
+ class KimodoModel:
324
+ """Owns one loaded motion GGUF and its GGML backend."""
325
+
326
+ def __init__(self, library_dir: str | os.PathLike, motion_gguf: str | os.PathLike,
327
+ threads: int = 0):
328
+ library_dir = Path(library_dir)
329
+ target = library_dir / "libkimodo.so"
330
+ if not target.exists():
331
+ raise KimodoError(
332
+ f"{target} is missing; runtime dir holds "
333
+ f"{sorted(p.name for p in library_dir.glob('*'))}")
334
+ # Loaded RTLD_LOCAL, which is ctypes' default. This build links
335
+ # libstdc++ statically, so exporting its symbols globally would shadow
336
+ # the system libstdc++ that other extension modules are built against,
337
+ # and matplotlib's pybind11 ft2font module then fails to import. The
338
+ # $ORIGIN rpath resolves libggml and libgomp from this directory, so no
339
+ # preloading is needed either way.
340
+ self._lib = _bind(ctypes.CDLL(str(target)))
341
+ if self._lib.kimodo_abi_version() != 1:
342
+ raise KimodoError("unexpected kimodo C ABI version")
343
+ options = _RuntimeOptions(size=ctypes.sizeof(_RuntimeOptions),
344
+ threads=threads, device=1, backend_dir=None)
345
+ error = ctypes.create_string_buffer(512)
346
+ handle = self._lib.kimodo_model_load(
347
+ str(motion_gguf).encode(), None, None, ctypes.byref(options), error, 512)
348
+ if not handle:
349
+ raise KimodoError(error.value.decode(errors="replace") or "model load failed")
350
+ self._handle = ctypes.c_void_p(handle)
351
+
352
+ def generate(self, embedding: np.ndarray, frames: int = 100, steps: int = 20,
353
+ seed: int = 0, text_cfg: float = 2.0,
354
+ constraint_cfg: float = 2.0) -> tuple[np.ndarray, np.ndarray]:
355
+ """Returns local rotations [T, J, 4] XYZW and root positions [T, 3]."""
356
+ values = np.ascontiguousarray(embedding, dtype=np.float32).reshape(-1)
357
+ if values.size != EMBEDDING_WIDTH:
358
+ raise KimodoError(f"embedding must hold {EMBEDDING_WIDTH} values")
359
+ payload = _Embedding(
360
+ data=values.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
361
+ values=EMBEDDING_WIDTH)
362
+ options = _GenerationOptions(
363
+ size=ctypes.sizeof(_GenerationOptions), seed=seed, frames=frames,
364
+ diffusion_steps=steps, text_cfg_weight=text_cfg,
365
+ constraint_cfg_weight=constraint_cfg)
366
+ error = ctypes.create_string_buffer(512)
367
+ motion = self._lib.kimodo_generate_embedding(
368
+ self._handle, ctypes.byref(payload), ctypes.byref(options), error, 512)
369
+ if not motion:
370
+ raise KimodoError(error.value.decode(errors="replace") or "generation failed")
371
+ motion = ctypes.c_void_p(motion)
372
+ try:
373
+ count = self._lib.kimodo_motion_frames(motion)
374
+ joints = self._lib.kimodo_motion_joints(motion)
375
+ rotations = np.ctypeslib.as_array(
376
+ self._lib.kimodo_motion_local_rotations_xyzw(motion),
377
+ shape=(count * joints * 4,)).reshape(count, joints, 4).copy()
378
+ root = np.ctypeslib.as_array(
379
+ self._lib.kimodo_motion_root_positions(motion),
380
+ shape=(count * 3,)).reshape(count, 3).copy()
381
+ finally:
382
+ self._lib.kimodo_motion_free(motion)
383
+ return rotations, root
384
+
385
+ def close(self) -> None:
386
+ handle = getattr(self, "_handle", None)
387
+ if handle:
388
+ self._lib.kimodo_model_free(handle)
389
+ self._handle = None
390
+
391
+ def __del__(self):
392
+ try:
393
+ self.close()
394
+ except Exception:
395
+ pass
396
+
397
+
398
+ def quaternions_to_matrix(q: np.ndarray) -> np.ndarray:
399
+ """XYZW quaternions to rotation matrices, matching scripts/fk_compare_fixture.py."""
400
+ x, y, z, w = np.moveaxis(q, -1, 0)
401
+ return np.stack((
402
+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
403
+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
404
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y),
405
+ ), axis=-1).reshape(q.shape[:-1] + (3, 3))
406
+
407
+
408
+ def forward_kinematics(rotations: np.ndarray, root: np.ndarray,
409
+ skeleton: Skeleton) -> np.ndarray:
410
+ """Local rotations plus root translation to world joint positions [T, J, 3].
411
+
412
+ Same recurrence as the upstream FK reference in scripts/fk_compare_fixture.py:
413
+ a joint sits at its parent's position plus the parent's global rotation
414
+ applied to the fixed parent-local bone offset.
415
+ """
416
+ offsets, parents = skeleton.offsets, skeleton.parents
417
+ joints = rotations.shape[1]
418
+ if joints != skeleton.joints:
419
+ raise KimodoError(
420
+ f"model returned {joints} joints but the {skeleton.key} rig has "
421
+ f"{skeleton.joints}")
422
+ local = quaternions_to_matrix(rotations.astype(np.float32))
423
+ world = np.empty_like(local)
424
+ positions = np.empty((rotations.shape[0], joints, 3), dtype=np.float32)
425
+ world[:, 0] = local[:, 0]
426
+ positions[:, 0] = root
427
+ for joint in range(1, joints):
428
+ parent = int(parents[joint])
429
+ world[:, joint] = world[:, parent] @ local[:, joint]
430
+ positions[:, joint] = positions[:, parent] + np.einsum(
431
+ "tij,j->ti", world[:, parent], offsets[joint])
432
+ return positions
433
+
434
+
435
+ def fix_foot_skating(positions: np.ndarray, skeleton: Skeleton) -> np.ndarray:
436
+ """Pin the root when a foot is planted, removing most sliding.
437
+
438
+ Adapted from the momask-codes demo. A foot counts as planted when it is
439
+ both low and slow; while one is planted, the horizontal drift it picked up
440
+ that frame is subtracted from every joint. Only the slowest planted foot is
441
+ used, so a step-through does not fight itself.
442
+ """
443
+ if positions.shape[0] < 2:
444
+ return positions
445
+ result = positions.copy()
446
+ ground = result[..., 1].min()
447
+ correction = np.zeros(3, dtype=np.float32)
448
+ for frame in range(1, result.shape[0]):
449
+ result[frame] += correction
450
+ drift = None
451
+ for foot in skeleton.feet:
452
+ height = result[frame, foot, 1] - ground
453
+ step = result[frame, foot] - result[frame - 1, foot]
454
+ speed = float(np.linalg.norm(step[[0, 2]]))
455
+ if height < skeleton.plant_height and speed < skeleton.plant_speed:
456
+ candidate = np.array([step[0], 0.0, step[2]], dtype=np.float32)
457
+ if drift is None or np.linalg.norm(candidate) < np.linalg.norm(drift):
458
+ drift = candidate
459
+ if drift is not None:
460
+ correction = correction - drift
461
+ result[frame] -= drift
462
+ return result
463
+
464
+
465
+ def ground_and_centre(positions: np.ndarray) -> np.ndarray:
466
+ """Drop the lowest joint to y=0 and centre the first frame horizontally."""
467
+ result = positions.copy()
468
+ result[..., 1] -= result[..., 1].min()
469
+ result[..., 0] -= result[0, 0, 0]
470
+ result[..., 2] -= result[0, 0, 2]
471
+ return result
472
+
473
+
474
+
475
+
476
+ def _unit_box() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
477
+ """A box spanning y in [0, 1] and x, z in [-0.5, 0.5], with flat normals.
478
+
479
+ Bones are drawn by scaling this along y to the bone length, so a bone runs
480
+ exactly from its parent joint to its child joint.
481
+ """
482
+ faces = [
483
+ ((1, 0, 0), [(.5, 0, -.5), (.5, 1, -.5), (.5, 1, .5), (.5, 0, .5)]),
484
+ ((-1, 0, 0), [(-.5, 0, .5), (-.5, 1, .5), (-.5, 1, -.5), (-.5, 0, -.5)]),
485
+ ((0, 1, 0), [(-.5, 1, -.5), (-.5, 1, .5), (.5, 1, .5), (.5, 1, -.5)]),
486
+ ((0, -1, 0), [(-.5, 0, .5), (-.5, 0, -.5), (.5, 0, -.5), (.5, 0, .5)]),
487
+ ((0, 0, 1), [(-.5, 0, .5), (.5, 0, .5), (.5, 1, .5), (-.5, 1, .5)]),
488
+ ((0, 0, -1), [(.5, 0, -.5), (-.5, 0, -.5), (-.5, 1, -.5), (.5, 1, -.5)]),
489
+ ]
490
+ positions, normals, indices = [], [], []
491
+ for face, (normal, corners) in enumerate(faces):
492
+ positions.extend(corners)
493
+ normals.extend([normal] * 4)
494
+ base = face * 4
495
+ indices.extend([base, base + 1, base + 2, base, base + 2, base + 3])
496
+ return (np.array(positions, dtype="<f4"), np.array(normals, dtype="<f4"),
497
+ np.array(indices, dtype="<u2"))
498
+
499
+
500
+ def _align_y_to(direction: np.ndarray) -> list[float]:
501
+ """Shortest-arc XYZW quaternion taking +Y onto `direction`."""
502
+ target = np.asarray(direction, dtype=np.float64)
503
+ length = float(np.linalg.norm(target))
504
+ if length < 1e-12:
505
+ return [0.0, 0.0, 0.0, 1.0]
506
+ target = target / length
507
+ up = np.array([0.0, 1.0, 0.0])
508
+ dot = float(np.dot(up, target))
509
+ if dot < -0.999999:
510
+ return [1.0, 0.0, 0.0, 0.0] # 180 degrees about X
511
+ axis = np.cross(up, target)
512
+ quaternion = np.array([axis[0], axis[1], axis[2], 1.0 + dot])
513
+ quaternion /= np.linalg.norm(quaternion)
514
+ return [float(v) for v in quaternion]
515
+
516
+
517
+ def write_glb(path: str | Path, root: np.ndarray, rotations: np.ndarray,
518
+ skeleton: Skeleton, fps: int = FPS, geometry: bool = True,
519
+ ) -> str:
520
+ """glTF binary of the animated joint hierarchy.
521
+
522
+ The node hierarchy, the joint names and the animation channels follow
523
+ kimodo.cpp demo/main.go writeSkeletonGLB exactly, so the export stays
524
+ faithful to what the model predicted. With `geometry` set, each bone also
525
+ gets a box mesh parented to the joint it hangs from, purely so the file is
526
+ visible in a plain glTF viewer. Delete those nodes, or pass geometry=False,
527
+ to get the original mesh-free skeleton.
528
+ """
529
+ names, parents, offsets = skeleton.names, skeleton.parents, skeleton.offsets
530
+ root = np.ascontiguousarray(root, dtype="<f4")
531
+ rotations = np.ascontiguousarray(rotations, dtype="<f4")
532
+ frames, joints = rotations.shape[0], rotations.shape[1]
533
+ if root.shape != (frames, 3) or len(names) != joints:
534
+ raise ValueError("motion does not match the skeleton")
535
+
536
+ binary = bytearray()
537
+ views: list[dict] = []
538
+
539
+ def add_view(values: np.ndarray, dtype: str = "<f4") -> int:
540
+ offset = len(binary)
541
+ binary.extend(np.ascontiguousarray(values, dtype=dtype).tobytes())
542
+ views.append({"buffer": 0, "byteOffset": offset,
543
+ "byteLength": len(binary) - offset})
544
+ return len(views) - 1
545
+
546
+ times = (np.arange(frames, dtype=np.float32) / float(fps))
547
+ time_view = add_view(times)
548
+ root_view = add_view(root)
549
+ rotation_views = [add_view(rotations[:, joint, :]) for joint in range(joints)]
550
+
551
+ accessors: list[dict] = [
552
+ {"bufferView": time_view, "componentType": 5126, "count": frames,
553
+ "type": "SCALAR", "min": [float(times[0])], "max": [float(times[-1])]},
554
+ {"bufferView": root_view, "componentType": 5126, "count": frames, "type": "VEC3"},
555
+ ]
556
+ accessors += [{"bufferView": view, "componentType": 5126, "count": frames,
557
+ "type": "VEC4"} for view in rotation_views]
558
+
559
+ nodes: list[dict] = []
560
+ for joint in range(joints):
561
+ node: dict = {"name": names[joint]}
562
+ if joint != 0:
563
+ node["translation"] = [float(v) for v in offsets[joint]]
564
+ children = [child for child in range(joints) if int(parents[child]) == joint]
565
+ if children:
566
+ node["children"] = children
567
+ nodes.append(node)
568
+
569
+ document_extras: dict = {}
570
+ meshes: list[dict] = []
571
+ materials: list[dict] = []
572
+ if geometry:
573
+ box_positions, box_normals, box_indices = _unit_box()
574
+ position_view = add_view(box_positions)
575
+ normal_view = add_view(box_normals)
576
+ index_offset = len(binary)
577
+ binary.extend(box_indices.tobytes())
578
+ views.append({"buffer": 0, "byteOffset": index_offset,
579
+ "byteLength": len(binary) - index_offset})
580
+ index_view = len(views) - 1
581
+ position_accessor = len(accessors)
582
+ accessors.append({
583
+ "bufferView": position_view, "componentType": 5126,
584
+ "count": len(box_positions), "type": "VEC3",
585
+ "min": [float(v) for v in box_positions.min(axis=0)],
586
+ "max": [float(v) for v in box_positions.max(axis=0)]})
587
+ normal_accessor = len(accessors)
588
+ accessors.append({"bufferView": normal_view, "componentType": 5126,
589
+ "count": len(box_normals), "type": "VEC3"})
590
+ index_accessor = len(accessors)
591
+ accessors.append({"bufferView": index_view, "componentType": 5123,
592
+ "count": len(box_indices), "type": "SCALAR"})
593
+ materials.append({
594
+ "name": "bone",
595
+ "pbrMetallicRoughness": {"baseColorFactor": [0.85, 0.83, 0.92, 1.0],
596
+ "metallicFactor": 0.1,
597
+ "roughnessFactor": 0.7},
598
+ "doubleSided": True})
599
+ meshes.append({"name": "bone", "primitives": [{
600
+ "attributes": {"POSITION": position_accessor,
601
+ "NORMAL": normal_accessor},
602
+ "indices": index_accessor, "material": 0}]})
603
+ for joint in range(joints):
604
+ parent = int(parents[joint])
605
+ if parent < 0:
606
+ continue
607
+ offset = np.asarray(offsets[joint], dtype=np.float64)
608
+ length = float(np.linalg.norm(offset))
609
+ if length < 1e-6:
610
+ continue
611
+ nodes.append({
612
+ "name": f"{names[joint]}_bone",
613
+ "mesh": 0,
614
+ "rotation": _align_y_to(offset),
615
+ "scale": [skeleton.bone_thickness, length,
616
+ skeleton.bone_thickness]})
617
+ nodes[parent].setdefault("children", []).append(len(nodes) - 1)
618
+ document_extras["bone_geometry"] = True
619
+
620
+ samplers: list[dict] = []
621
+ channels: list[dict] = []
622
+
623
+ def add_channel(node: int, output: int, path_name: str) -> None:
624
+ samplers.append({"input": 0, "output": output, "interpolation": "LINEAR"})
625
+ channels.append({"sampler": len(samplers) - 1,
626
+ "target": {"node": node, "path": path_name}})
627
+
628
+ add_channel(0, 1, "translation")
629
+ for joint in range(joints):
630
+ add_channel(joint, joint + 2, "rotation")
631
+
632
+ document = {
633
+ "asset": {"version": "2.0", "generator": "kimodo.cpp skeleton exporter"},
634
+ "scene": 0,
635
+ "scenes": [{"nodes": [0]}],
636
+ "nodes": nodes,
637
+ "buffers": [{"byteLength": len(binary)}],
638
+ "bufferViews": views,
639
+ "accessors": accessors,
640
+ "animations": [{"name": "KimodoMotion", "samplers": samplers,
641
+ "channels": channels}],
642
+ "extras": {"skeleton": skeleton.key, "fps": fps,
643
+ "rotation_order": "xyzw", **document_extras},
644
+ }
645
+ if meshes:
646
+ document["meshes"] = meshes
647
+ document["materials"] = materials
648
+
649
+ json_chunk = json.dumps(document, separators=(",", ":")).encode()
650
+ json_chunk += b" " * (-len(json_chunk) % 4)
651
+ binary.extend(b"\0" * (-len(binary) % 4))
652
+ total = 12 + 8 + len(json_chunk) + 8 + len(binary)
653
+ out = bytearray()
654
+ out += struct.pack("<III", 0x46546C67, 2, total)
655
+ out += struct.pack("<II", len(json_chunk), 0x4E4F534A) + json_chunk
656
+ out += struct.pack("<II", len(binary), 0x004E4942) + bytes(binary)
657
+ Path(path).write_bytes(bytes(out))
658
+ return str(path)
659
+
660
+
661
+ def _quaternion_to_euler_zyx(q: np.ndarray) -> np.ndarray:
662
+ """XYZW quaternions to BVH ZYX Euler degrees, shape [..., 3] as (z, y, x)."""
663
+ x, y, z, w = np.moveaxis(q, -1, 0)
664
+ rz = np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
665
+ ry = np.arcsin(np.clip(2 * (w * y - z * x), -1.0, 1.0))
666
+ rx = np.arctan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y))
667
+ return np.degrees(np.stack((rz, ry, rx), axis=-1))
668
+
669
+
670
+ def write_bvh(path: str | Path, root: np.ndarray, rotations: np.ndarray,
671
+ skeleton: Skeleton, fps: int = FPS) -> str:
672
+ """BVH built from the model's own local rotations, so nothing is inferred."""
673
+ names, parents, offsets = skeleton.names, skeleton.parents, skeleton.offsets
674
+ scale = skeleton.bvh_scale
675
+ frames, joints = rotations.shape[0], rotations.shape[1]
676
+ children = children_of(skeleton)
677
+ euler = _quaternion_to_euler_zyx(np.asarray(rotations, dtype=np.float64))
678
+
679
+ lines: list[str] = ["HIERARCHY"]
680
+
681
+ def write_joint(index: int, depth: int) -> None:
682
+ pad = " " * depth
683
+ label = "ROOT" if index == 0 else "JOINT"
684
+ offset = np.asarray(offsets[index], dtype=np.float64) * scale
685
+ lines.append(f"{pad}{label} {names[index]}")
686
+ lines.append(f"{pad}{{")
687
+ lines.append(f"{pad} OFFSET {offset[0]:.6f} {offset[1]:.6f} {offset[2]:.6f}")
688
+ chans = ("6 Xposition Yposition Zposition Zrotation Yrotation Xrotation"
689
+ if index == 0 else "3 Zrotation Yrotation Xrotation")
690
+ lines.append(f"{pad} CHANNELS {chans}")
691
+ if children[index]:
692
+ for child in children[index]:
693
+ write_joint(child, depth + 1)
694
+ else:
695
+ lines.append(f"{pad} End Site")
696
+ lines.append(f"{pad} {{")
697
+ lines.append(f"{pad} OFFSET 0.000000 0.000000 0.000000")
698
+ lines.append(f"{pad} }}")
699
+ lines.append(f"{pad}}}")
700
+
701
+ write_joint(0, 0)
702
+ lines.append("MOTION")
703
+ lines.append(f"Frames: {frames}")
704
+ lines.append(f"Frame Time: {1.0 / fps:.6f}")
705
+ for frame in range(frames):
706
+ values = list(np.asarray(root[frame], dtype=np.float64) * scale)
707
+ for joint in range(joints):
708
+ values.extend(euler[frame, joint])
709
+ lines.append(" ".join(f"{value:.6f}" for value in values))
710
+ text = "\n".join(lines) + "\n"
711
+ Path(path).write_text(text, encoding="utf-8")
712
+ return str(path)
713
+
714
+
715
+ def render_mp4(path: str | Path, positions: np.ndarray, title: str,
716
+ skeleton: Skeleton, fps: int = FPS, spin: float = 0.35) -> str:
717
+ """Matplotlib preview of the skeleton, adapted from the momask donor Space."""
718
+ chains = skeleton.chains
719
+ colors = ["#ff6b6b", "#4ecdc4", "#ffe66d", "#95e1d3", "#dda0dd"]
720
+ figure = plt.figure(figsize=(6, 6), facecolor="#1a1a2e")
721
+ axes = figure.add_subplot(111, projection="3d", facecolor="#1a1a2e")
722
+
723
+ # The camera follows the root. A locomotion prompt can travel ten metres or
724
+ # more, and a fixed frame around the whole trajectory shrinks the figure to
725
+ # a speck. The span is sized to the body, not to the path.
726
+ root_track = positions[:, 0, :]
727
+ reach = float(np.abs(positions - root_track[:, None, :]).max())
728
+ span = max(1.0, reach * 1.25)
729
+ height = max(skeleton.stature * 1.25,
730
+ float(positions[..., 1].max() - positions[..., 1].min()) * 1.15)
731
+
732
+ def style():
733
+ axes.set_zlim(0, height)
734
+ axes.set_box_aspect((1, 1, height / (2 * span)))
735
+ axes.set_xlabel("X", color="white")
736
+ axes.set_ylabel("Z", color="white")
737
+ axes.set_zlabel("Y (up)", color="white")
738
+ axes.set_title(title, color="white", fontsize=11, pad=10)
739
+ axes.tick_params(colors="white", labelsize=7)
740
+ for pane in (axes.xaxis.pane, axes.yaxis.pane, axes.zaxis.pane):
741
+ pane.fill = False
742
+ pane.set_edgecolor("#333355")
743
+ axes.grid(True, alpha=0.3, color="#555577")
744
+
745
+ def init():
746
+ style()
747
+ axes.set_xlim(root_track[0, 0] - span, root_track[0, 0] + span)
748
+ axes.set_ylim(root_track[0, 2] - span, root_track[0, 2] + span)
749
+ return []
750
+
751
+ if len(chains) > len(colors):
752
+ raise KimodoError(
753
+ f"{skeleton.key} has {len(chains)} chains but only "
754
+ f"{len(colors)} colours, so two would be drawn alike")
755
+ lines = []
756
+ for index in range(len(chains)):
757
+ line, = axes.plot([], [], [], color=colors[index],
758
+ linewidth=2.5, marker="o", markersize=3)
759
+ lines.append(line)
760
+ trail, = axes.plot([], [], [], color="#8888aa", linewidth=1.0, alpha=0.7)
761
+
762
+ def update(frame):
763
+ data = positions[frame]
764
+ for index, chain in enumerate(chains):
765
+ lines[index].set_data([data[j, 0] for j in chain],
766
+ [data[j, 2] for j in chain])
767
+ lines[index].set_3d_properties([data[j, 1] for j in chain])
768
+ travelled = root_track[:frame + 1]
769
+ trail.set_data(travelled[:, 0], travelled[:, 2])
770
+ trail.set_3d_properties(np.zeros(len(travelled)))
771
+ centre = root_track[frame]
772
+ axes.set_xlim(centre[0] - span, centre[0] + span)
773
+ axes.set_ylim(centre[2] - span, centre[2] + span)
774
+ axes.view_init(elev=18, azim=45 + frame * spin)
775
+ return lines + [trail]
776
+
777
+ animation = FuncAnimation(figure, update, frames=len(positions),
778
+ init_func=init, blit=False, interval=1000 // fps)
779
+ animation.save(str(path), writer=FFMpegWriter(fps=fps, bitrate=2200))
780
+ plt.close(figure)
781
+ return str(path)
782
+
783
+
784
+ class Checkpoint(NamedTuple):
785
+ label: str
786
+ repo: str
787
+ filename: str
788
+ skeleton: Skeleton
789
+
790
+
791
+ # All four published checkpoints. Every one conditions on the same 4096 float
792
+ # LLM2Vec embedding: kimodo_generate_embedding takes a fixed size array and the
793
+ # C++ side selects the rig from the GGUF's own kimodo.skeleton key, so the
794
+ # same prompt encodes once and works on all four.
795
+ CHECKPOINTS = [
796
+ Checkpoint("SOMA RP v1.1 (30 joint human)",
797
+ "LocalAI-io/Kimodo-SOMA-RP-v1.1-GGML",
798
+ "models/kimodo-soma-rp-v1.1-f32.gguf", SOMA30),
799
+ Checkpoint("SOMA SEED v1.1 (30 joint human)",
800
+ "LocalAI-io/Kimodo-SOMA-SEED-v1.1-GGML",
801
+ "models/kimodo-soma-seed-v1.1-f32.gguf", SOMA30),
802
+ Checkpoint("G1 RP v1 (34 joint Unitree robot)",
803
+ "LocalAI-io/Kimodo-G1-RP-v1-GGML",
804
+ "models/kimodo-g1-rp-v1-f32.gguf", G1SKEL34),
805
+ Checkpoint("G1 SEED v1 (34 joint Unitree robot)",
806
+ "LocalAI-io/Kimodo-G1-SEED-v1-GGML",
807
+ "models/kimodo-g1-seed-v1-f32.gguf", G1SKEL34),
808
+ ]
809
+ CHECKPOINT_BY_LABEL = {c.label: c for c in CHECKPOINTS}
810
+
811
+ _model: KimodoModel | None = None
812
+ _model_label: str | None = None
813
+ _text_bundle: Path | None = None
814
+ # Insertion ordered, so the oldest distinct prompt is evicted first. Each entry
815
+ # is 16 KB, so the cap is about memory hygiene rather than pressure.
816
+ _embedding_cache: dict[str, np.ndarray] = {}
817
+ EMBEDDING_CACHE_LIMIT = 512
818
+
819
+
820
+ def text_bundle_dir() -> Path:
821
+ """Directory holding the 35 LLM2Vec component GGUFs, from the build cache."""
822
+ global _text_bundle
823
+ if _text_bundle is None:
824
+ from huggingface_hub import hf_hub_download
825
+ anchor = hf_hub_download(repo_id=TEXT_REPO,
826
+ filename=f"{TEXT_BUNDLE_SUBDIR}/tokenizer.gguf")
827
+ bundle = Path(anchor).parent
828
+ missing = [name for name in
829
+ ["tokenizer.gguf", "embedding.gguf", "final-norm.gguf"]
830
+ + [f"layer-{i:02d}.gguf" for i in range(32)]
831
+ if not (bundle / name).is_file()]
832
+ if missing:
833
+ raise gr.Error(
834
+ f"The text encoder bundle at {bundle} is missing "
835
+ f"{len(missing)} of 35 files, first {missing[0]}.")
836
+ _text_bundle = bundle
837
+ return _text_bundle
838
+
839
+
840
+ def encode_prompt(prompt: str) -> tuple[np.ndarray, float]:
841
+ """Prompt to its 4096 float LLM2Vec embedding, memoised on the text.
842
+
843
+ kmd-encode reopens all 35 bundle GGUFs on every call, so a prompt costs one
844
+ full pass over 15.18 GB no matter how short it is. That makes it a fixed
845
+ price per distinct prompt, unrelated to frames or steps, and makes caching
846
+ the single change that matters: re-rolling the seed on the same text, or
847
+ switching checkpoint, then costs nothing.
848
+ """
849
+ key = prompt.strip()
850
+ cached = _embedding_cache.get(key)
851
+ if cached is not None:
852
+ return cached, 0.0
853
+ bundle = text_bundle_dir()
854
+ encoder = RUNTIME_DIR / "kmd-encode"
855
+ if not os.access(encoder, os.X_OK):
856
+ # Cloning on a filesystem without permission bits can drop the mode.
857
+ os.chmod(encoder, os.stat(encoder).st_mode | 0o111)
858
+ started = time.time()
859
+ with tempfile.TemporaryDirectory(prefix="kimodo-encode-") as work:
860
+ prompt_path = Path(work) / "prompt.txt"
861
+ # No trailing newline: kmd-encode reads the whole file, and a stray
862
+ # newline is a real token that moves the embedding by cosine 0.947.
863
+ prompt_path.write_text(key, encoding="utf-8")
864
+ out_path = Path(work) / "embedding.f32"
865
+ environment = dict(os.environ, KIMODO_TEXT_LAYER_CHUNK="1",
866
+ KIMODO_BACKEND="cpu")
867
+ finished = subprocess.run(
868
+ [str(encoder), str(bundle), str(prompt_path), str(out_path)],
869
+ capture_output=True, text=True, env=environment, timeout=1800)
870
+ if finished.returncode != 0:
871
+ detail = (finished.stderr or finished.stdout or "").strip()
872
+ raise gr.Error(f"Encoding failed: {detail[:400]}")
873
+ values = np.fromfile(out_path, dtype="<f4")
874
+ if values.size != EMBEDDING_WIDTH:
875
+ raise gr.Error(f"Encoder returned {values.size} values, expected "
876
+ f"{EMBEDDING_WIDTH}")
877
+ if len(_embedding_cache) >= EMBEDDING_CACHE_LIMIT:
878
+ _embedding_cache.pop(next(iter(_embedding_cache)))
879
+ _embedding_cache[key] = values
880
+ return values, time.time() - started
881
+
882
+
883
+ def get_model(checkpoint: Checkpoint) -> KimodoModel:
884
+ """One resident checkpoint at a time.
885
+
886
+ Each is 1.13 GB of F32 weights once resident. Keeping the previous one
887
+ alive while loading the next would double that for no benefit, since only
888
+ one generation runs at a time anyway.
889
+ """
890
+ global _model, _model_label
891
+ if _model is not None and _model_label == checkpoint.label:
892
+ return _model
893
+ if _model is not None:
894
+ _model.close()
895
+ _model = None
896
+ _model_label = None
897
+ from huggingface_hub import hf_hub_download
898
+ path = hf_hub_download(repo_id=checkpoint.repo, filename=checkpoint.filename)
899
+ _model = KimodoModel(RUNTIME_DIR, path, threads=CPUS)
900
+ _model_label = checkpoint.label
901
+ return _model
902
+
903
+
904
+ LOG_LINES = 12
905
+
906
+
907
+ def _elapsed(since: float) -> str:
908
+ """[+M:SS] from job start.
909
+
910
+ The delta between two lines is the only ETA instrument a viewer has on a
911
+ job this long, so this is elapsed time, never a wall clock.
912
+ """
913
+ seconds = int(time.time() - since)
914
+ if seconds >= 3600:
915
+ return f"[+{seconds // 3600}:{seconds // 60 % 60:02d}:{seconds % 60:02d}]"
916
+ return f"[+{seconds // 60}:{seconds % 60:02d}]"
917
+
918
+
919
+ # A DownloadButton needs its value and its interactive state moved together.
920
+ # gr.update patches the live component; constructing a fresh gr.DownloadButton
921
+ # would rebuild it with Gradio's defaults, the same trap as the sliders.
922
+ _BVH_IDLE = gr.update(value=None, interactive=False)
923
+
924
+
925
+ def _bvh_ready(path: str):
926
+ return gr.update(value=path, interactive=True)
927
+
928
+
929
+ def generate(prompt: str, model_label: str, frames: int, steps: int, seed: int,
930
+ text_cfg: float, deskate: bool):
931
+ """Generate a 3D skeletal animation from a text description of a motion.
932
+
933
+ Runs NVIDIA's Kimodo motion diffusion model on CPU through the kimodo.cpp GGML port. Returns the animation as glTF and BVH plus a rendered preview. A prompt not generated before also pays a one off encode of roughly two minutes, cached afterwards for that exact text.
934
+
935
+ Args:
936
+ prompt: Plain English description of the motion, for example "a person runs forward and jumps over an obstacle". Up to 511 tokens.
937
+ model_label: Which checkpoint and rig to use, exactly one of "SOMA RP v1.1 (30 joint human)", "SOMA SEED v1.1 (30 joint human)", "G1 RP v1 (34 joint Unitree robot)", "G1 SEED v1 (34 joint Unitree robot)". SOMA is a human skeleton, G1 a Unitree humanoid robot. An unknown value is refused rather than substituted.
938
+ frames: Length of the clip in frames at 30 fps, from 30 to 240, so 120 is four seconds.
939
+ steps: Diffusion steps, from 4 to 50. More is cleaner, and steps cost far more time than extra frames do.
940
+ seed: Random seed. The same seed, prompt and settings reproduce a clip exactly.
941
+ text_cfg: Guidance weight from 1.0 to 5.0. Higher follows the prompt more literally at the cost of natural movement.
942
+ deskate: Pin the root while a foot is planted, which removes most foot sliding from both the preview and the exports.
943
+
944
+ Returns:
945
+ Four values. A preview MP4, a glTF binary carrying the model's own local rotations, a BVH of the same motion, and a status log of each stage with elapsed time. The glTF is the faithful export and the video is only a preview.
946
+ """
947
+ prompt = (prompt or "").strip()
948
+ if not prompt:
949
+ raise gr.Error("Describe a motion first, for example a person runs "
950
+ "forward and jumps over an obstacle.")
951
+ if len(prompt) > 1200:
952
+ raise gr.Error("That prompt is too long. The encoder accepts up to 511 "
953
+ "tokens, so keep it to a sentence or two.")
954
+ # No fallback. The dropdown cannot produce a bad label, so the only caller
955
+ # who reaches this is an API caller, and quietly running a different
956
+ # checkpoint would make their result unattributable: they would inspect a
957
+ # 30 joint SOMA figure and conclude G1 support is broken.
958
+ checkpoint = CHECKPOINT_BY_LABEL.get(model_label)
959
+ if checkpoint is None:
960
+ known = "; ".join(c.label for c in CHECKPOINTS)
961
+ raise gr.Error(f"Unknown motion model {model_label!r}. Valid: {known}")
962
+ frames, steps, seed = int(frames), int(steps), int(seed)
963
+
964
+ began = time.time()
965
+ lines: list[str] = []
966
+
967
+ def say(message: str) -> str:
968
+ # Ring buffer, so a long run cannot grow the textbox without bound.
969
+ lines.append(f"{_elapsed(began)} {message}")
970
+ del lines[:-LOG_LINES]
971
+ return "\n".join(lines)
972
+
973
+ yield None, None, _BVH_IDLE, say(f"Loading {checkpoint.label}")
974
+ model = get_model(checkpoint)
975
+
976
+ cached = prompt in _embedding_cache
977
+ yield None, None, _BVH_IDLE, say(
978
+ "Embedding cached, skipping encode" if cached else
979
+ "Encoding prompt, 35 files, once per distinct text")
980
+ embedding, encoded = encode_prompt(prompt)
981
+
982
+ yield None, None, _BVH_IDLE, say(
983
+ f"{'Cached' if cached else f'Encoded in {encoded:.0f} s'}. "
984
+ f"Sampling {frames} frames at {steps} steps")
985
+ started = time.time()
986
+ rotations, root = model.generate(
987
+ embedding, frames=frames, steps=steps, seed=seed,
988
+ text_cfg=float(text_cfg), constraint_cfg=float(text_cfg))
989
+ sampled = time.time() - started
990
+
991
+ # Trust the model over the label: the C++ side picks the rig from the GGUF's
992
+ # own kimodo.skeleton key, so match on what came back.
993
+ skeleton = SKELETON_BY_JOINTS.get(rotations.shape[1])
994
+ if skeleton is None:
995
+ raise gr.Error(f"Model returned {rotations.shape[1]} joints, which "
996
+ f"matches no rig this app knows")
997
+ # The checkpoint declares a rig too. If the two disagree the entry points at
998
+ # the wrong file, and every index downstream would still be in range on the
999
+ # other rig, so the result would be a plausible wrong figure rather than an
1000
+ # error. Refuse instead.
1001
+ if skeleton is not checkpoint.skeleton:
1002
+ raise gr.Error(
1003
+ f"{checkpoint.label} declares the {checkpoint.skeleton.key} rig with "
1004
+ f"{checkpoint.skeleton.joints} joints, but the model returned "
1005
+ f"{rotations.shape[1]}, which is {skeleton.key}. That checkpoint "
1006
+ f"entry points at the wrong weights.")
1007
+
1008
+ positions = forward_kinematics(rotations, root, skeleton)
1009
+ raw_root = positions[:, 0].copy()
1010
+ if deskate:
1011
+ positions = fix_foot_skating(positions, skeleton)
1012
+ positions = ground_and_centre(positions)
1013
+ # Both passes translate every joint by the same per frame offset and leave
1014
+ # rotations untouched, so folding that offset into the root translation puts
1015
+ # the identical correction in the exports. No inverse kinematics, nothing
1016
+ # reconstructed: the preview and the downloads are the same motion.
1017
+ export_root = root + (positions[:, 0] - raw_root)
1018
+
1019
+ output = Path(tempfile.mkdtemp(prefix="kimodo-"))
1020
+ stem = f"kimodo-{skeleton.key}-{seed}"
1021
+ glb = write_glb(output / f"{stem}.glb", export_root, rotations, skeleton)
1022
+ bvh = write_bvh(output / f"{stem}.bvh", export_root, rotations, skeleton)
1023
+
1024
+ yield None, glb, _bvh_ready(bvh), say(
1025
+ f"Sampled in {sampled:.0f} s, {skeleton.joints} joints. "
1026
+ f"Rendering preview")
1027
+ rendered = time.time()
1028
+ video = render_mp4(output / f"{stem}.mp4", positions, prompt, skeleton)
1029
+ rendered = time.time() - rendered
1030
+
1031
+ encode_line = ("embedding reused from cache" if cached else
1032
+ f"encode {encoded:.0f} s")
1033
+ yield video, glb, _bvh_ready(bvh), say(
1034
+ f"Done. {prompt}\n"
1035
+ f"{checkpoint.label}, rig {skeleton.key}, {rotations.shape[1]} joints, "
1036
+ f"{frames} frames at {steps} steps, seed {seed}.\n"
1037
+ f"{CPUS} vCPU: {encode_line}, sample {sampled:.0f} s, "
1038
+ f"render {rendered:.0f} s.\n"
1039
+ f"The GLB carries the model's own local rotations and is the faithful "
1040
+ f"export. The video is a preview.")
1041
+
1042
+
1043
+ CSS = """
1044
+ .gradio-container { padding: 4px !important; max-width: 100% !important; }
1045
+ .form { gap: 2px !important; }
1046
+ #foot { margin: 0 0 2px 0 !important; opacity: 0.7; }
1047
+ #foot p { margin: 0 !important; font-size: 0.8em; }
1048
+ #log textarea { font-family: ui-monospace, monospace; font-size: 0.8em; }
1049
+ footer { display: none !important; }
1050
+ :where(button, input, textarea, select, [role="button"], [tabindex]):focus-visible {
1051
+ outline: 2px solid var(--color-accent) !important; outline-offset: 2px;
1052
+ }
1053
+ @media (prefers-reduced-motion: reduce) {
1054
+ *, *::before, *::after { animation-duration: 0.01ms !important;
1055
+ transition-duration: 0.01ms !important; }
1056
+ }
1057
+ """
1058
+
1059
+
1060
+ # Sampling cost, fitted to measurements on this Space's two vCPUs. Steps dominate,
1061
+ # frames are close to free, which is why the step label carries the total.
1062
+ SAMPLE_BASE_S = 4.0
1063
+ SAMPLE_S_PER_FRAME = 0.048
1064
+
1065
+
1066
+ def _duration(seconds: float) -> str:
1067
+ return f"{seconds:.0f} s" if seconds < 90 else f"{seconds / 60:.0f} min"
1068
+
1069
+
1070
+ def sampling_seconds(frames: float, steps: float) -> float:
1071
+ return int(steps) * (SAMPLE_BASE_S + SAMPLE_S_PER_FRAME * int(frames))
1072
+
1073
+
1074
+ ENCODE_S = 110.0 # measured 85 to 128 s across runs, quoted at the high end
1075
+
1076
+
1077
+ def control_labels(prompt: str, frames: float, steps: float):
1078
+ """Each slider states what it produces. The button states what it costs.
1079
+
1080
+ Both sliders scale the wait, so putting a duration on either one reads as
1081
+ that slider's own cost. Worse, the two would look alike while meaning
1082
+ opposite things: the frame count is how long the CLIP is, the wait is how
1083
+ long YOU are. The total belongs on the control that spends it.
1084
+
1085
+ gr.update patches the label in place. Returning a fresh gr.Slider would
1086
+ build a new component with Gradio's defaults and render a second, empty
1087
+ slider beside the real one.
1088
+ """
1089
+ total = sampling_seconds(frames, steps)
1090
+ # A prompt not yet encoded pays one full pass over the text bundle. Quoting
1091
+ # sampling alone understated a first run by about two minutes.
1092
+ if (prompt or "").strip() not in _embedding_cache:
1093
+ total += ENCODE_S
1094
+ return (gr.update(label=f"Frames ({int(frames) / FPS:.1f} s clip)"),
1095
+ gr.update(label=f"Diffusion steps ({int(steps)})"),
1096
+ gr.update(value=f"Generate ({_duration(total)})"))
1097
+
1098
+
1099
+ def header_line() -> str:
1100
+ """One line naming the backend. The rig and the encoder are already visible
1101
+ in the model picker and the run log, so they are not repeated here."""
1102
+ return ("NVIDIA Kimodo through "
1103
+ "[kimodo.cpp](https://github.com/localai-org/kimodo.cpp) on CPU")
1104
+
1105
+
app_new.py → momask_core.py RENAMED
@@ -1,551 +1,502 @@
1
- """
2
- MoMask: Text-to-Motion Generation
3
- https://github.com/EricGuo5513/momask-codes
4
- Compact HuggingFace Space implementation using ONNX INT8 models.
5
- """
6
- import os
7
- import sys
8
- import tempfile
9
- import numpy as np
10
- import torch
11
- import onnxruntime as ort
12
- import clip
13
- import matplotlib
14
- matplotlib.use('Agg')
15
- import matplotlib.pyplot as plt
16
- from matplotlib.animation import FuncAnimation, FFMpegWriter
17
- from pathlib import Path
18
-
19
- # ============ Quaternion Operations ============
20
- def qinv(q):
21
- """Invert quaternion"""
22
- assert q.shape[-1] == 4
23
- mask = torch.ones_like(q)
24
- mask[..., 1:] = -mask[..., 1:]
25
- return q * mask
26
-
27
- def qrot(q, v):
28
- """Rotate vector(s) v by quaternion(s) q"""
29
- assert q.shape[-1] == 4
30
- assert v.shape[-1] == 3
31
- assert q.shape[:-1] == v.shape[:-1]
32
-
33
- original_shape = list(v.shape)
34
- q = q.contiguous().view(-1, 4)
35
- v = v.contiguous().view(-1, 3)
36
-
37
- qvec = q[:, 1:]
38
- uv = torch.cross(qvec, v, dim=1)
39
- uuv = torch.cross(qvec, uv, dim=1)
40
- return (v + 2 * (q[:, :1] * uv + uuv)).view(original_shape)
41
-
42
- # ============ Configuration ============
43
- ONNX_DIR = Path(__file__).parent / "onnx_models"
44
- DEVICE = "cpu"
45
- JOINTS_NUM = 22
46
- TIMESTEPS = 18
47
- MASK_COND_SCALE = 4.0 # CFG scale for mask transformer
48
- RES_COND_SCALE = 5.0 # CFG scale for residual transformer
49
- TEMPERATURE = 1.0
50
- TOPK_FILTER = 0.9
51
-
52
- # Kinematic chain for visualization
53
- T2M_KINEMATIC_CHAIN = [
54
- [0, 2, 5, 8, 11], # Right leg
55
- [0, 1, 4, 7, 10], # Left leg
56
- [0, 3, 6, 9, 12, 15], # Spine
57
- [9, 14, 17, 19, 21], # Right arm
58
- [9, 13, 16, 18, 20] # Left arm
59
- ]
60
-
61
- # ============ ONNX Sessions ============
62
- sessions = {}
63
-
64
- def get_session(name):
65
- if name not in sessions:
66
- path = ONNX_DIR / f"{name}.onnx"
67
- if not path.exists():
68
- raise FileNotFoundError(f"Model not found: {path}")
69
- sessions[name] = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
70
- return sessions[name]
71
-
72
- # ============ Motion Recovery ============
73
- def recover_root_rot_pos(data):
74
- """Recover root rotation and position from motion data"""
75
- rot_vel = data[..., 0]
76
- r_rot_ang = torch.zeros_like(rot_vel)
77
- r_rot_ang[..., 1:] = rot_vel[..., :-1]
78
- r_rot_ang = torch.cumsum(r_rot_ang, dim=-1)
79
-
80
- r_rot_quat = torch.zeros(data.shape[:-1] + (4,))
81
- r_rot_quat[..., 0] = torch.cos(r_rot_ang)
82
- r_rot_quat[..., 2] = torch.sin(r_rot_ang)
83
-
84
- r_pos = torch.zeros(data.shape[:-1] + (3,))
85
- r_pos[..., 1:, [0, 2]] = data[..., :-1, 1:3]
86
- r_pos = qrot(qinv(r_rot_quat), r_pos)
87
- r_pos = torch.cumsum(r_pos, dim=-2)
88
- r_pos[..., 1] = data[..., 3]
89
-
90
- return r_rot_quat, r_pos
91
-
92
- def recover_from_ric(data, joints_num=22):
93
- """Convert 263-dim motion representation to 3D joint positions"""
94
- r_rot_quat, r_pos = recover_root_rot_pos(data)
95
- positions = data[..., 4:(joints_num - 1) * 3 + 4]
96
- positions = positions.view(positions.shape[:-1] + (-1, 3))
97
- positions = qrot(qinv(r_rot_quat[..., None, :]).expand(positions.shape[:-1] + (4,)), positions)
98
- positions[..., 0] += r_pos[..., 0:1]
99
- positions[..., 2] += r_pos[..., 2:3]
100
- positions = torch.cat([r_pos.unsqueeze(-2), positions], dim=-2)
101
- return positions
102
-
103
- # ============ Foot Skating Fix ============
104
- def fix_foot_skating(joints, vel_threshold=0.01, height_threshold=0.08):
105
- """
106
- Simple foot skating fix by pinning feet during contact frames.
107
-
108
- Args:
109
- joints: numpy array (frames, 22, 3)
110
- vel_threshold: velocity threshold for contact detection
111
- height_threshold: height threshold for contact detection
112
-
113
- Returns:
114
- Fixed joints array
115
- """
116
- joints = joints.copy()
117
- n_frames = len(joints)
118
-
119
- # Foot indices: 7=LeftFoot, 8=RightFoot, 10=LeftToe, 11=RightToe
120
- foot_idx = {'left': [7, 10], 'right': [8, 11]}
121
-
122
- for side, indices in foot_idx.items():
123
- # Get foot positions (use toe for contact)
124
- toe_idx = indices[1]
125
- foot_pos = joints[:, toe_idx, :] # (frames, 3)
126
-
127
- # Compute velocity (frame-to-frame displacement)
128
- vel = np.zeros(n_frames)
129
- vel[1:] = np.linalg.norm(foot_pos[1:] - foot_pos[:-1], axis=1)
130
-
131
- # Detect contact: low velocity AND low height
132
- height = foot_pos[:, 1] # Y is up
133
- floor_height = np.percentile(height, 10) # Estimate floor
134
- contact = (vel < vel_threshold) & (height < floor_height + height_threshold)
135
-
136
- # Find contact regions and pin feet
137
- in_contact = False
138
- contact_start = 0
139
- contact_pos = None
140
-
141
- for f in range(n_frames):
142
- if contact[f] and not in_contact:
143
- # Start of contact
144
- in_contact = True
145
- contact_start = f
146
- contact_pos = foot_pos[f].copy()
147
- contact_pos[1] = floor_height # Pin to floor
148
- elif contact[f] and in_contact:
149
- # Continue contact - pin both foot joints to contact position
150
- for idx in indices:
151
- offset = joints[contact_start, idx] - joints[contact_start, toe_idx]
152
- joints[f, idx] = contact_pos + offset
153
- joints[f, idx, 1] = max(floor_height, joints[f, idx, 1] - (foot_pos[f, 1] - floor_height))
154
- elif not contact[f] and in_contact:
155
- # End of contact
156
- in_contact = False
157
-
158
- return joints
159
-
160
- # ============ Visualization ============
161
- def plot_3d_motion(save_path, joints, title, fps=20):
162
- """Create MP4 video of 3D skeleton motion (dark mode)"""
163
- fig = plt.figure(figsize=(8, 8), facecolor='#1a1a2e')
164
- ax = fig.add_subplot(111, projection="3d", facecolor='#1a1a2e')
165
-
166
- # Bright colors for dark background
167
- COLORS = ["#ff6b6b", "#4ecdc4", "#ffe66d", "#95e1d3", "#dda0dd"]
168
-
169
- def init():
170
- ax.set_xlim(-1.5, 1.5)
171
- ax.set_ylim(-1.5, 1.5)
172
- ax.set_zlim(0, 2)
173
- ax.set_xlabel("X", color='white')
174
- ax.set_ylabel("Z", color='white')
175
- ax.set_zlabel("Y (up)", color='white')
176
- ax.set_title(title, color='white', fontsize=12, pad=10)
177
- # Dark mode styling
178
- ax.tick_params(colors='white')
179
- ax.xaxis.pane.fill = False
180
- ax.yaxis.pane.fill = False
181
- ax.zaxis.pane.fill = False
182
- ax.xaxis.pane.set_edgecolor('#333355')
183
- ax.yaxis.pane.set_edgecolor('#333355')
184
- ax.zaxis.pane.set_edgecolor('#333355')
185
- ax.grid(True, alpha=0.3, color='#555577')
186
- return []
187
-
188
- lines = []
189
- for i, chain in enumerate(T2M_KINEMATIC_CHAIN):
190
- line, = ax.plot([], [], [], color=COLORS[i], linewidth=2.5, marker="o", markersize=4)
191
- lines.append(line)
192
-
193
- def update(frame):
194
- data = joints[frame]
195
- for i, chain in enumerate(T2M_KINEMATIC_CHAIN):
196
- x = [data[j, 0] for j in chain]
197
- y = [data[j, 2] for j in chain]
198
- z = [data[j, 1] for j in chain]
199
- lines[i].set_data(x, y)
200
- lines[i].set_3d_properties(z)
201
- ax.view_init(elev=20, azim=45 + frame * 0.5)
202
- return lines
203
-
204
- ani = FuncAnimation(fig, update, frames=len(joints), init_func=init, blit=False, interval=1000//fps)
205
- writer = FFMpegWriter(fps=fps, bitrate=2000)
206
- ani.save(save_path, writer=writer)
207
- plt.close()
208
- # ============ BVH Export with Simple IK ============
209
- def _quat_mul(q1, q2):
210
- """Quaternion multiplication (w,x,y,z format)."""
211
- w1, x1, y1, z1 = q1
212
- w2, x2, y2, z2 = q2
213
- return np.array([
214
- w1*w2 - x1*x2 - y1*y2 - z1*z2,
215
- w1*x2 + x1*w2 + y1*z2 - z1*y2,
216
- w1*y2 - x1*z2 + y1*w2 + z1*x2,
217
- w1*z2 + x1*y2 - y1*x2 + z1*w2
218
- ])
219
-
220
- def _quat_inv(q):
221
- """Quaternion inverse."""
222
- return np.array([q[0], -q[1], -q[2], -q[3]])
223
-
224
- def _quat_from_two_vectors(v1, v2):
225
- """Quaternion rotating v1 to v2."""
226
- v1 = v1 / (np.linalg.norm(v1) + 1e-10)
227
- v2 = v2 / (np.linalg.norm(v2) + 1e-10)
228
- cross = np.cross(v1, v2)
229
- dot = np.dot(v1, v2)
230
- if dot < -0.999999: # Opposite vectors
231
- return np.array([0, 1, 0, 0])
232
- w = 1.0 + dot
233
- q = np.array([w, cross[0], cross[1], cross[2]])
234
- return q / (np.linalg.norm(q) + 1e-10)
235
-
236
- def _quat_to_euler_zyx(q):
237
- """Quaternion to Euler ZYX order (degrees) - standard BVH format."""
238
- w, x, y, z = q
239
- # Z rotation (yaw)
240
- siny = 2 * (w * z + x * y)
241
- cosy = 1 - 2 * (y * y + z * z)
242
- rz = np.arctan2(siny, cosy)
243
- # Y rotation (pitch)
244
- sinp = 2 * (w * y - z * x)
245
- ry = np.arcsin(np.clip(sinp, -1, 1))
246
- # X rotation (roll)
247
- sinr = 2 * (w * x + y * z)
248
- cosr = 1 - 2 * (x * x + y * y)
249
- rx = np.arctan2(sinr, cosr)
250
- return np.degrees([rz, ry, rx]) # ZYX order for BVH
251
-
252
- def joints_to_bvh(joints, output_path, fps=20):
253
- """Convert joint positions to BVH with proper local rotations."""
254
- n_frames, n_joints, _ = joints.shape
255
- joint_names = ["Hips", "LeftUpLeg", "RightUpLeg", "Spine", "LeftLeg", "RightLeg",
256
- "Spine1", "LeftFoot", "RightFoot", "Spine2", "LeftToe", "RightToe",
257
- "Neck", "LeftShoulder", "RightShoulder", "Head", "LeftArm", "RightArm",
258
- "LeftForeArm", "RightForeArm", "LeftHand", "RightHand"]
259
- parents = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
260
-
261
- children = [[] for _ in range(n_joints)]
262
- for i, p in enumerate(parents):
263
- if p >= 0: children[p].append(i)
264
-
265
- # Rest pose offsets
266
- offsets = np.zeros((n_joints, 3))
267
- for i in range(n_joints):
268
- if parents[i] >= 0:
269
- offsets[i] = joints[0, i] - joints[0, parents[i]]
270
-
271
- scale = 100.0
272
- all_rotations = np.zeros((n_frames, n_joints, 3))
273
-
274
- # Compute local rotations per frame using simple IK
275
- for frame in range(n_frames):
276
- global_quats = [np.array([1, 0, 0, 0])] * n_joints
277
-
278
- for j in range(n_joints):
279
- if not children[j]: continue
280
- child = children[j][0]
281
-
282
- # Rest pose direction (local)
283
- rest_dir = offsets[child]
284
- if np.linalg.norm(rest_dir) < 1e-6: continue
285
-
286
- # Current direction (global)
287
- curr_dir = joints[frame, child] - joints[frame, j]
288
- if np.linalg.norm(curr_dir) < 1e-6: continue
289
-
290
- # Global rotation to align rest to current
291
- global_rot = _quat_from_two_vectors(rest_dir, curr_dir)
292
-
293
- # Convert to local (relative to parent)
294
- if parents[j] >= 0:
295
- parent_inv = _quat_inv(global_quats[parents[j]])
296
- local_rot = _quat_mul(parent_inv, global_rot)
297
- else:
298
- local_rot = global_rot
299
-
300
- global_quats[j] = global_rot
301
- all_rotations[frame, j] = _quat_to_euler_zyx(local_rot)
302
-
303
- # Write BVH (ZYX rotation order - standard for BVH)
304
- with open(output_path, "w") as f:
305
- f.write("HIERARCHY\n")
306
- def write_joint(idx, indent):
307
- name, off = joint_names[idx], offsets[idx] * scale
308
- pre = " " * indent
309
- f.write(f"{'ROOT' if idx==0 else pre+'JOINT'} {name}\n{pre}{{\n")
310
- f.write(f"{pre} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}\n")
311
- f.write(f"{pre} CHANNELS {'6 Xposition Yposition Zposition ' if idx==0 else '3 '}Zrotation Yrotation Xrotation\n")
312
- if children[idx]:
313
- for c in children[idx]: write_joint(c, indent + 1)
314
- else:
315
- f.write(f"{pre} End Site\n{pre} {{\n{pre} OFFSET 0.0 0.0 0.0\n{pre} }}\n")
316
- f.write(f"{pre}}}\n")
317
- write_joint(0, 0)
318
-
319
- f.write(f"MOTION\nFrames: {n_frames}\nFrame Time: {1.0/fps:.6f}\n")
320
- for frame in range(n_frames):
321
- vals = list(joints[frame, 0] * scale) # Root position
322
- for j in range(n_joints):
323
- vals.extend(all_rotations[frame, j])
324
- f.write(" ".join(f"{v:.6f}" for v in vals) + "\n")
325
- return output_path
326
-
327
- # ============ Sampling Utilities ============
328
- def cosine_schedule(t):
329
- """Cosine noise schedule"""
330
- return torch.cos(t * np.pi * 0.5)
331
-
332
- def top_k_filter(logits, k=0.9):
333
- """Apply top-k filtering"""
334
- k = int((1 - k) * logits.shape[-1])
335
- val, ind = torch.topk(logits, k, dim=-1)
336
- probs = torch.full_like(logits, float("-inf"))
337
- probs.scatter_(-1, ind, val)
338
- return probs
339
-
340
- def gumbel_sample(logits, temperature=1.0):
341
- """Gumbel softmax sampling"""
342
- gumbels = -torch.log(-torch.log(torch.rand_like(logits) + 1e-8) + 1e-8)
343
- return ((logits / max(temperature, 1e-10)) + gumbels).argmax(dim=-1)
344
- # ============ Main Generation Pipeline ============
345
- def generate_motion(text, motion_length=0, seed=None):
346
- """Generate motion from text prompt with CFG"""
347
- if seed is not None:
348
- torch.manual_seed(seed)
349
- np.random.seed(seed)
350
-
351
- mean = np.load(ONNX_DIR / "mean.npy")
352
- std = np.load(ONNX_DIR / "std.npy")
353
-
354
- tokens = clip.tokenize([text], truncate=True)
355
-
356
- clip_sess = get_session("clip_text")
357
- text_emb = clip_sess.run(None, {"text_tokens": tokens.numpy()})[0]
358
- zero_emb = np.zeros_like(text_emb) # For CFG unconditional path
359
-
360
- if motion_length <= 0:
361
- len_sess = get_session("length_estimator")
362
- len_logits = len_sess.run(None, {"text_embedding": text_emb})[0]
363
- probs = torch.softmax(torch.from_numpy(len_logits), dim=-1)
364
- token_len = torch.multinomial(probs, 1).item()
365
- else:
366
- token_len = int(motion_length * 20 / 4)
367
-
368
- token_len = max(2, min(token_len, 49))
369
- m_length = token_len * 4
370
- max_len = 49
371
-
372
- print(f"Generating motion: '{text}' ({m_length} frames, {m_length/20:.1f}s)")
373
-
374
- mask_id = 512
375
- pad_id = 513
376
- ids = torch.full((1, max_len), pad_id, dtype=torch.long)
377
- ids[:, :token_len] = mask_id
378
- scores = torch.zeros(1, max_len)
379
- scores[:, token_len:] = 1e5
380
-
381
- padding_mask = np.zeros((1, max_len), dtype=bool)
382
- padding_mask[:, token_len:] = True
383
-
384
- mask_sess = get_session("mask_transformer")
385
-
386
- for step in range(TIMESTEPS):
387
- t = step / TIMESTEPS
388
- rand_mask_prob = cosine_schedule(torch.tensor(t)).item()
389
- num_masked = max(1, int(rand_mask_prob * token_len))
390
-
391
- valid_scores = scores[:, :token_len].clone()
392
- _, sorted_idx = valid_scores.sort(dim=1)
393
- mask_pos = sorted_idx[:, :num_masked]
394
- is_mask = torch.zeros(1, token_len, dtype=torch.bool)
395
- is_mask.scatter_(1, mask_pos, True)
396
-
397
- ids[:, :token_len] = torch.where(is_mask, mask_id, ids[:, :token_len])
398
-
399
- # CFG: conditional and unconditional logits
400
- cond_logits = mask_sess.run(None, {
401
- "motion_ids": ids.numpy(),
402
- "cond_vector": text_emb,
403
- "padding_mask": padding_mask
404
- })[0]
405
- uncond_logits = mask_sess.run(None, {
406
- "motion_ids": ids.numpy(),
407
- "cond_vector": zero_emb,
408
- "padding_mask": padding_mask
409
- })[0]
410
- logits = uncond_logits + (cond_logits - uncond_logits) * MASK_COND_SCALE
411
-
412
- logits = torch.from_numpy(logits)
413
- logits = logits[:, :512, :token_len]
414
- logits = logits.permute(0, 2, 1)
415
-
416
- filtered_logits = top_k_filter(logits / TEMPERATURE, TOPK_FILTER)
417
- new_ids = gumbel_sample(filtered_logits, TEMPERATURE)
418
-
419
- probs = torch.softmax(filtered_logits, dim=-1)
420
- new_scores = probs.gather(-1, new_ids.unsqueeze(-1)).squeeze(-1)
421
-
422
- ids[:, :token_len] = torch.where(is_mask, new_ids, ids[:, :token_len])
423
- scores[:, :token_len] = torch.where(is_mask, new_scores, scores[:, :token_len])
424
- res_sess = get_session("residual_transformer")
425
- num_quantizers = 6
426
-
427
- res_token_embed = np.load(ONNX_DIR / "res_token_embed.npy")
428
-
429
- all_codes = torch.zeros(1, max_len, num_quantizers, dtype=torch.long)
430
- all_codes[:, :, 0] = ids
431
-
432
- history_sum = np.zeros((1, max_len, 512), dtype=np.float32)
433
- motion_ids = ids.clone()
434
-
435
- for q in range(1, num_quantizers):
436
- token_embed = res_token_embed[q-1]
437
- clamped_ids = np.clip(motion_ids[0].numpy(), 0, 512)
438
- gathered = token_embed[clamped_ids]
439
- history_sum += gathered[np.newaxis, :, :]
440
-
441
- q_id = np.array([q], dtype=np.int64)
442
-
443
- # CFG for residual transformer
444
- cond_logits = res_sess.run(None, {
445
- "motion_codes": history_sum.astype(np.float32),
446
- "q_id": q_id,
447
- "cond_vector": text_emb,
448
- "padding_mask": padding_mask
449
- })[0]
450
- uncond_logits = res_sess.run(None, {
451
- "motion_codes": history_sum.astype(np.float32),
452
- "q_id": q_id,
453
- "cond_vector": zero_emb,
454
- "padding_mask": padding_mask
455
- })[0]
456
- logits = uncond_logits + (cond_logits - uncond_logits) * RES_COND_SCALE
457
-
458
- logits = torch.from_numpy(logits)[:, :512, :token_len].permute(0, 2, 1)
459
- new_ids_q = gumbel_sample(logits, 1.0)
460
- all_codes[:, :token_len, q] = new_ids_q
461
- motion_ids[:, :token_len] = new_ids_q
462
-
463
- decoder_sess = get_session("vqvae_decoder")
464
- valid_codes = all_codes[:, :token_len, :].numpy()
465
- motion = decoder_sess.run(None, {
466
- "code_indices": valid_codes
467
- })[0]
468
-
469
- # Decoder already upsamples 4x internally, just slice to exact length
470
- motion = motion[:, :m_length, :]
471
- motion = motion * std + mean
472
-
473
- motion_tensor = torch.from_numpy(motion).float()
474
- joints = recover_from_ric(motion_tensor, JOINTS_NUM)
475
- joints = joints.squeeze(0).numpy()
476
-
477
- # Apply foot skating fix
478
- joints = fix_foot_skating(joints)
479
-
480
- video_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
481
- plot_3d_motion(video_path, joints, text, fps=20)
482
-
483
- bvh_path = tempfile.NamedTemporaryFile(suffix=".bvh", delete=False).name
484
- joints_to_bvh(joints, bvh_path, fps=20)
485
-
486
- return joints, video_path, bvh_path
487
- # ============ Gradio Interface ============
488
- def create_demo():
489
- import gradio as gr
490
-
491
- def generate_fn(text, length, seed):
492
- if not text or text.strip() == "":
493
- return None, None
494
- seed = int(seed) if seed else None
495
- length = float(length) if length else 0
496
- joints, video_path, bvh_path = generate_motion(text, length, seed)
497
- return video_path, bvh_path
498
-
499
- with gr.Blocks(title="MoMask") as demo:
500
- gr.Markdown("## [MoMask](https://github.com/EricGuo5513/momask-codes) - Text to Motion")
501
- gr.Markdown("Generate 3D human skeleton animations from text descriptions. Download BVH for Blender!")
502
-
503
- with gr.Row():
504
- with gr.Column():
505
- text = gr.Textbox(label="Prompt Motion",
506
- placeholder="A person walks forward",
507
- value="A person walks forward",
508
- lines=2)
509
- with gr.Row():
510
- length = gr.Number(label="Duration (sec)", value=0,
511
- info="0 = auto-estimate")
512
- seed = gr.Number(label="Seed", value=42,
513
- info="For reproducibility")
514
- btn = gr.Button("Generate", variant="primary")
515
-
516
- with gr.Column():
517
- video = gr.Video(label="Generated Motion")
518
- bvh_file = gr.File(label="BVH Download (for Blender)")
519
-
520
- gr.Examples(
521
- examples=[
522
- ["A person walks forward", 0, 42],
523
- ["A person is running on a treadmill", 0, 123],
524
- ["A person jumps up and then lands", 0, 456],
525
- ["A person does a salsa dance", 0, 789],
526
- ["A person kicks with their right leg", 0, 101],
527
- ],
528
- inputs=[text, length, seed],
529
- outputs=[video, bvh_file],
530
- fn=generate_fn,
531
- cache_examples=False,
532
- )
533
-
534
- btn.click(fn=generate_fn, inputs=[text, length, seed], outputs=[video, bvh_file])
535
-
536
- return demo
537
-
538
- # ============ CLI ============
539
- if __name__ == "__main__":
540
- if len(sys.argv) > 1:
541
- text = sys.argv[1]
542
- length = float(sys.argv[2]) if len(sys.argv) > 2 else 0
543
- seed = int(sys.argv[3]) if len(sys.argv) > 3 else 42
544
-
545
- joints, video_path, bvh_path = generate_motion(text, length, seed)
546
- print(f"Video: {video_path}")
547
- print(f"BVH: {bvh_path}")
548
- print(f"Joints shape: {joints.shape}")
549
- else:
550
- demo = create_demo()
551
- demo.launch()
 
1
+ """
2
+ MoMask: Text-to-Motion Generation
3
+ https://github.com/EricGuo5513/momask-codes
4
+ Compact HuggingFace Space implementation using ONNX INT8 models.
5
+ """
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import numpy as np
10
+ torch = None # bound by _ensure_backends()
11
+ ort = None
12
+ clip = None
13
+ import matplotlib
14
+ matplotlib.use('Agg')
15
+ import matplotlib.pyplot as plt
16
+ from matplotlib.animation import FuncAnimation, FFMpegWriter
17
+ from pathlib import Path
18
+
19
+ # ============ Quaternion Operations ============
20
+ def qinv(q):
21
+ """Invert quaternion"""
22
+ assert q.shape[-1] == 4
23
+ mask = torch.ones_like(q)
24
+ mask[..., 1:] = -mask[..., 1:]
25
+ return q * mask
26
+
27
+ def qrot(q, v):
28
+ """Rotate vector(s) v by quaternion(s) q"""
29
+ assert q.shape[-1] == 4
30
+ assert v.shape[-1] == 3
31
+ assert q.shape[:-1] == v.shape[:-1]
32
+
33
+ original_shape = list(v.shape)
34
+ q = q.contiguous().view(-1, 4)
35
+ v = v.contiguous().view(-1, 3)
36
+
37
+ qvec = q[:, 1:]
38
+ uv = torch.cross(qvec, v, dim=1)
39
+ uuv = torch.cross(qvec, uv, dim=1)
40
+ return (v + 2 * (q[:, :1] * uv + uuv)).view(original_shape)
41
+
42
+ def _ensure_backends():
43
+ """Import the heavy native stack on first MoMask use, not at startup.
44
+
45
+ Kimodo dlopens libkimodo.so plus its own libgomp into this same process. The
46
+ fewer competing OpenMP and libstdc++ copies are resident when that happens,
47
+ the better, and a visitor who only uses the Kimodo tab never pays for these.
48
+ """
49
+ global torch, ort, clip
50
+ if torch is None:
51
+ import torch as _torch
52
+ import onnxruntime as _ort
53
+ import clip as _clip
54
+ torch, ort, clip = _torch, _ort, _clip
55
+
56
+ # ============ Configuration ============
57
+ ONNX_DIR = Path(__file__).parent / "onnx_models"
58
+ DEVICE = "cpu"
59
+ JOINTS_NUM = 22
60
+ TIMESTEPS = 18
61
+ MASK_COND_SCALE = 4.0 # CFG scale for mask transformer
62
+ RES_COND_SCALE = 5.0 # CFG scale for residual transformer
63
+ TEMPERATURE = 1.0
64
+ TOPK_FILTER = 0.9
65
+
66
+ # Kinematic chain for visualization
67
+ T2M_KINEMATIC_CHAIN = [
68
+ [0, 2, 5, 8, 11], # Right leg
69
+ [0, 1, 4, 7, 10], # Left leg
70
+ [0, 3, 6, 9, 12, 15], # Spine
71
+ [9, 14, 17, 19, 21], # Right arm
72
+ [9, 13, 16, 18, 20] # Left arm
73
+ ]
74
+
75
+ # ============ ONNX Sessions ============
76
+ sessions = {}
77
+
78
+ def get_session(name):
79
+ _ensure_backends()
80
+ if name not in sessions:
81
+ path = ONNX_DIR / f"{name}.onnx"
82
+ if not path.exists():
83
+ raise FileNotFoundError(f"Model not found: {path}")
84
+ sessions[name] = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
85
+ return sessions[name]
86
+
87
+ # ============ Motion Recovery ============
88
+ def recover_root_rot_pos(data):
89
+ """Recover root rotation and position from motion data"""
90
+ rot_vel = data[..., 0]
91
+ r_rot_ang = torch.zeros_like(rot_vel)
92
+ r_rot_ang[..., 1:] = rot_vel[..., :-1]
93
+ r_rot_ang = torch.cumsum(r_rot_ang, dim=-1)
94
+
95
+ r_rot_quat = torch.zeros(data.shape[:-1] + (4,))
96
+ r_rot_quat[..., 0] = torch.cos(r_rot_ang)
97
+ r_rot_quat[..., 2] = torch.sin(r_rot_ang)
98
+
99
+ r_pos = torch.zeros(data.shape[:-1] + (3,))
100
+ r_pos[..., 1:, [0, 2]] = data[..., :-1, 1:3]
101
+ r_pos = qrot(qinv(r_rot_quat), r_pos)
102
+ r_pos = torch.cumsum(r_pos, dim=-2)
103
+ r_pos[..., 1] = data[..., 3]
104
+
105
+ return r_rot_quat, r_pos
106
+
107
+ def recover_from_ric(data, joints_num=22):
108
+ """Convert 263-dim motion representation to 3D joint positions"""
109
+ r_rot_quat, r_pos = recover_root_rot_pos(data)
110
+ positions = data[..., 4:(joints_num - 1) * 3 + 4]
111
+ positions = positions.view(positions.shape[:-1] + (-1, 3))
112
+ positions = qrot(qinv(r_rot_quat[..., None, :]).expand(positions.shape[:-1] + (4,)), positions)
113
+ positions[..., 0] += r_pos[..., 0:1]
114
+ positions[..., 2] += r_pos[..., 2:3]
115
+ positions = torch.cat([r_pos.unsqueeze(-2), positions], dim=-2)
116
+ return positions
117
+
118
+ # ============ Foot Skating Fix ============
119
+ def fix_foot_skating(joints, vel_threshold=0.01, height_threshold=0.08):
120
+ """
121
+ Simple foot skating fix by pinning feet during contact frames.
122
+
123
+ Args:
124
+ joints: numpy array (frames, 22, 3)
125
+ vel_threshold: velocity threshold for contact detection
126
+ height_threshold: height threshold for contact detection
127
+
128
+ Returns:
129
+ Fixed joints array
130
+ """
131
+ joints = joints.copy()
132
+ n_frames = len(joints)
133
+
134
+ # Foot indices: 7=LeftFoot, 8=RightFoot, 10=LeftToe, 11=RightToe
135
+ foot_idx = {'left': [7, 10], 'right': [8, 11]}
136
+
137
+ for side, indices in foot_idx.items():
138
+ # Get foot positions (use toe for contact)
139
+ toe_idx = indices[1]
140
+ foot_pos = joints[:, toe_idx, :] # (frames, 3)
141
+
142
+ # Compute velocity (frame-to-frame displacement)
143
+ vel = np.zeros(n_frames)
144
+ vel[1:] = np.linalg.norm(foot_pos[1:] - foot_pos[:-1], axis=1)
145
+
146
+ # Detect contact: low velocity AND low height
147
+ height = foot_pos[:, 1] # Y is up
148
+ floor_height = np.percentile(height, 10) # Estimate floor
149
+ contact = (vel < vel_threshold) & (height < floor_height + height_threshold)
150
+
151
+ # Find contact regions and pin feet
152
+ in_contact = False
153
+ contact_start = 0
154
+ contact_pos = None
155
+
156
+ for f in range(n_frames):
157
+ if contact[f] and not in_contact:
158
+ # Start of contact
159
+ in_contact = True
160
+ contact_start = f
161
+ contact_pos = foot_pos[f].copy()
162
+ contact_pos[1] = floor_height # Pin to floor
163
+ elif contact[f] and in_contact:
164
+ # Continue contact - pin both foot joints to contact position
165
+ for idx in indices:
166
+ offset = joints[contact_start, idx] - joints[contact_start, toe_idx]
167
+ joints[f, idx] = contact_pos + offset
168
+ joints[f, idx, 1] = max(floor_height, joints[f, idx, 1] - (foot_pos[f, 1] - floor_height))
169
+ elif not contact[f] and in_contact:
170
+ # End of contact
171
+ in_contact = False
172
+
173
+ return joints
174
+
175
+ # ============ Visualization ============
176
+ def plot_3d_motion(save_path, joints, title, fps=20):
177
+ """Create MP4 video of 3D skeleton motion (dark mode)"""
178
+ fig = plt.figure(figsize=(8, 8), facecolor='#1a1a2e')
179
+ ax = fig.add_subplot(111, projection="3d", facecolor='#1a1a2e')
180
+
181
+ # Bright colors for dark background
182
+ COLORS = ["#ff6b6b", "#4ecdc4", "#ffe66d", "#95e1d3", "#dda0dd"]
183
+
184
+ def init():
185
+ ax.set_xlim(-1.5, 1.5)
186
+ ax.set_ylim(-1.5, 1.5)
187
+ ax.set_zlim(0, 2)
188
+ ax.set_xlabel("X", color='white')
189
+ ax.set_ylabel("Z", color='white')
190
+ ax.set_zlabel("Y (up)", color='white')
191
+ ax.set_title(title, color='white', fontsize=12, pad=10)
192
+ # Dark mode styling
193
+ ax.tick_params(colors='white')
194
+ ax.xaxis.pane.fill = False
195
+ ax.yaxis.pane.fill = False
196
+ ax.zaxis.pane.fill = False
197
+ ax.xaxis.pane.set_edgecolor('#333355')
198
+ ax.yaxis.pane.set_edgecolor('#333355')
199
+ ax.zaxis.pane.set_edgecolor('#333355')
200
+ ax.grid(True, alpha=0.3, color='#555577')
201
+ return []
202
+
203
+ lines = []
204
+ for i, chain in enumerate(T2M_KINEMATIC_CHAIN):
205
+ line, = ax.plot([], [], [], color=COLORS[i], linewidth=2.5, marker="o", markersize=4)
206
+ lines.append(line)
207
+
208
+ def update(frame):
209
+ data = joints[frame]
210
+ for i, chain in enumerate(T2M_KINEMATIC_CHAIN):
211
+ x = [data[j, 0] for j in chain]
212
+ y = [data[j, 2] for j in chain]
213
+ z = [data[j, 1] for j in chain]
214
+ lines[i].set_data(x, y)
215
+ lines[i].set_3d_properties(z)
216
+ ax.view_init(elev=20, azim=45 + frame * 0.5)
217
+ return lines
218
+
219
+ ani = FuncAnimation(fig, update, frames=len(joints), init_func=init, blit=False, interval=1000//fps)
220
+ writer = FFMpegWriter(fps=fps, bitrate=2000)
221
+ ani.save(save_path, writer=writer)
222
+ plt.close()
223
+ # ============ BVH Export with Simple IK ============
224
+ def _quat_mul(q1, q2):
225
+ """Quaternion multiplication (w,x,y,z format)."""
226
+ w1, x1, y1, z1 = q1
227
+ w2, x2, y2, z2 = q2
228
+ return np.array([
229
+ w1*w2 - x1*x2 - y1*y2 - z1*z2,
230
+ w1*x2 + x1*w2 + y1*z2 - z1*y2,
231
+ w1*y2 - x1*z2 + y1*w2 + z1*x2,
232
+ w1*z2 + x1*y2 - y1*x2 + z1*w2
233
+ ])
234
+
235
+ def _quat_inv(q):
236
+ """Quaternion inverse."""
237
+ return np.array([q[0], -q[1], -q[2], -q[3]])
238
+
239
+ def _quat_from_two_vectors(v1, v2):
240
+ """Quaternion rotating v1 to v2."""
241
+ v1 = v1 / (np.linalg.norm(v1) + 1e-10)
242
+ v2 = v2 / (np.linalg.norm(v2) + 1e-10)
243
+ cross = np.cross(v1, v2)
244
+ dot = np.dot(v1, v2)
245
+ if dot < -0.999999: # Opposite vectors
246
+ return np.array([0, 1, 0, 0])
247
+ w = 1.0 + dot
248
+ q = np.array([w, cross[0], cross[1], cross[2]])
249
+ return q / (np.linalg.norm(q) + 1e-10)
250
+
251
+ def _quat_to_euler_zyx(q):
252
+ """Quaternion to Euler ZYX order (degrees) - standard BVH format."""
253
+ w, x, y, z = q
254
+ # Z rotation (yaw)
255
+ siny = 2 * (w * z + x * y)
256
+ cosy = 1 - 2 * (y * y + z * z)
257
+ rz = np.arctan2(siny, cosy)
258
+ # Y rotation (pitch)
259
+ sinp = 2 * (w * y - z * x)
260
+ ry = np.arcsin(np.clip(sinp, -1, 1))
261
+ # X rotation (roll)
262
+ sinr = 2 * (w * x + y * z)
263
+ cosr = 1 - 2 * (x * x + y * y)
264
+ rx = np.arctan2(sinr, cosr)
265
+ return np.degrees([rz, ry, rx]) # ZYX order for BVH
266
+
267
+ def joints_to_bvh(joints, output_path, fps=20):
268
+ """Convert joint positions to BVH with proper local rotations."""
269
+ n_frames, n_joints, _ = joints.shape
270
+ joint_names = ["Hips", "LeftUpLeg", "RightUpLeg", "Spine", "LeftLeg", "RightLeg",
271
+ "Spine1", "LeftFoot", "RightFoot", "Spine2", "LeftToe", "RightToe",
272
+ "Neck", "LeftShoulder", "RightShoulder", "Head", "LeftArm", "RightArm",
273
+ "LeftForeArm", "RightForeArm", "LeftHand", "RightHand"]
274
+ parents = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
275
+
276
+ children = [[] for _ in range(n_joints)]
277
+ for i, p in enumerate(parents):
278
+ if p >= 0: children[p].append(i)
279
+
280
+ # Rest pose offsets
281
+ offsets = np.zeros((n_joints, 3))
282
+ for i in range(n_joints):
283
+ if parents[i] >= 0:
284
+ offsets[i] = joints[0, i] - joints[0, parents[i]]
285
+
286
+ scale = 100.0
287
+ all_rotations = np.zeros((n_frames, n_joints, 3))
288
+
289
+ # Compute local rotations per frame using simple IK
290
+ for frame in range(n_frames):
291
+ global_quats = [np.array([1, 0, 0, 0])] * n_joints
292
+
293
+ for j in range(n_joints):
294
+ if not children[j]: continue
295
+ child = children[j][0]
296
+
297
+ # Rest pose direction (local)
298
+ rest_dir = offsets[child]
299
+ if np.linalg.norm(rest_dir) < 1e-6: continue
300
+
301
+ # Current direction (global)
302
+ curr_dir = joints[frame, child] - joints[frame, j]
303
+ if np.linalg.norm(curr_dir) < 1e-6: continue
304
+
305
+ # Global rotation to align rest to current
306
+ global_rot = _quat_from_two_vectors(rest_dir, curr_dir)
307
+
308
+ # Convert to local (relative to parent)
309
+ if parents[j] >= 0:
310
+ parent_inv = _quat_inv(global_quats[parents[j]])
311
+ local_rot = _quat_mul(parent_inv, global_rot)
312
+ else:
313
+ local_rot = global_rot
314
+
315
+ global_quats[j] = global_rot
316
+ all_rotations[frame, j] = _quat_to_euler_zyx(local_rot)
317
+
318
+ # Write BVH (ZYX rotation order - standard for BVH)
319
+ with open(output_path, "w") as f:
320
+ f.write("HIERARCHY\n")
321
+ def write_joint(idx, indent):
322
+ name, off = joint_names[idx], offsets[idx] * scale
323
+ pre = " " * indent
324
+ f.write(f"{'ROOT' if idx==0 else pre+'JOINT'} {name}\n{pre}{{\n")
325
+ f.write(f"{pre} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}\n")
326
+ f.write(f"{pre} CHANNELS {'6 Xposition Yposition Zposition ' if idx==0 else '3 '}Zrotation Yrotation Xrotation\n")
327
+ if children[idx]:
328
+ for c in children[idx]: write_joint(c, indent + 1)
329
+ else:
330
+ f.write(f"{pre} End Site\n{pre} {{\n{pre} OFFSET 0.0 0.0 0.0\n{pre} }}\n")
331
+ f.write(f"{pre}}}\n")
332
+ write_joint(0, 0)
333
+
334
+ f.write(f"MOTION\nFrames: {n_frames}\nFrame Time: {1.0/fps:.6f}\n")
335
+ for frame in range(n_frames):
336
+ vals = list(joints[frame, 0] * scale) # Root position
337
+ for j in range(n_joints):
338
+ vals.extend(all_rotations[frame, j])
339
+ f.write(" ".join(f"{v:.6f}" for v in vals) + "\n")
340
+ return output_path
341
+
342
+ # ============ Sampling Utilities ============
343
+ def cosine_schedule(t):
344
+ """Cosine noise schedule"""
345
+ return torch.cos(t * np.pi * 0.5)
346
+
347
+ def top_k_filter(logits, k=0.9):
348
+ """Apply top-k filtering"""
349
+ k = int((1 - k) * logits.shape[-1])
350
+ val, ind = torch.topk(logits, k, dim=-1)
351
+ probs = torch.full_like(logits, float("-inf"))
352
+ probs.scatter_(-1, ind, val)
353
+ return probs
354
+
355
+ def gumbel_sample(logits, temperature=1.0):
356
+ """Gumbel softmax sampling"""
357
+ gumbels = -torch.log(-torch.log(torch.rand_like(logits) + 1e-8) + 1e-8)
358
+ return ((logits / max(temperature, 1e-10)) + gumbels).argmax(dim=-1)
359
+ # ============ Main Generation Pipeline ============
360
+ def generate_motion(text, motion_length=0, seed=None):
361
+ _ensure_backends()
362
+ """Generate motion from text prompt with CFG"""
363
+ if seed is not None:
364
+ torch.manual_seed(seed)
365
+ np.random.seed(seed)
366
+
367
+ mean = np.load(ONNX_DIR / "mean.npy")
368
+ std = np.load(ONNX_DIR / "std.npy")
369
+
370
+ tokens = clip.tokenize([text], truncate=True)
371
+
372
+ clip_sess = get_session("clip_text")
373
+ text_emb = clip_sess.run(None, {"text_tokens": tokens.numpy()})[0]
374
+ zero_emb = np.zeros_like(text_emb) # For CFG unconditional path
375
+
376
+ if motion_length <= 0:
377
+ len_sess = get_session("length_estimator")
378
+ len_logits = len_sess.run(None, {"text_embedding": text_emb})[0]
379
+ probs = torch.softmax(torch.from_numpy(len_logits), dim=-1)
380
+ token_len = torch.multinomial(probs, 1).item()
381
+ else:
382
+ token_len = int(motion_length * 20 / 4)
383
+
384
+ token_len = max(2, min(token_len, 49))
385
+ m_length = token_len * 4
386
+ max_len = 49
387
+
388
+ print(f"Generating motion: '{text}' ({m_length} frames, {m_length/20:.1f}s)")
389
+
390
+ mask_id = 512
391
+ pad_id = 513
392
+ ids = torch.full((1, max_len), pad_id, dtype=torch.long)
393
+ ids[:, :token_len] = mask_id
394
+ scores = torch.zeros(1, max_len)
395
+ scores[:, token_len:] = 1e5
396
+
397
+ padding_mask = np.zeros((1, max_len), dtype=bool)
398
+ padding_mask[:, token_len:] = True
399
+
400
+ mask_sess = get_session("mask_transformer")
401
+
402
+ for step in range(TIMESTEPS):
403
+ t = step / TIMESTEPS
404
+ rand_mask_prob = cosine_schedule(torch.tensor(t)).item()
405
+ num_masked = max(1, int(rand_mask_prob * token_len))
406
+
407
+ valid_scores = scores[:, :token_len].clone()
408
+ _, sorted_idx = valid_scores.sort(dim=1)
409
+ mask_pos = sorted_idx[:, :num_masked]
410
+ is_mask = torch.zeros(1, token_len, dtype=torch.bool)
411
+ is_mask.scatter_(1, mask_pos, True)
412
+
413
+ ids[:, :token_len] = torch.where(is_mask, mask_id, ids[:, :token_len])
414
+
415
+ # CFG: conditional and unconditional logits
416
+ cond_logits = mask_sess.run(None, {
417
+ "motion_ids": ids.numpy(),
418
+ "cond_vector": text_emb,
419
+ "padding_mask": padding_mask
420
+ })[0]
421
+ uncond_logits = mask_sess.run(None, {
422
+ "motion_ids": ids.numpy(),
423
+ "cond_vector": zero_emb,
424
+ "padding_mask": padding_mask
425
+ })[0]
426
+ logits = uncond_logits + (cond_logits - uncond_logits) * MASK_COND_SCALE
427
+
428
+ logits = torch.from_numpy(logits)
429
+ logits = logits[:, :512, :token_len]
430
+ logits = logits.permute(0, 2, 1)
431
+
432
+ filtered_logits = top_k_filter(logits / TEMPERATURE, TOPK_FILTER)
433
+ new_ids = gumbel_sample(filtered_logits, TEMPERATURE)
434
+
435
+ probs = torch.softmax(filtered_logits, dim=-1)
436
+ new_scores = probs.gather(-1, new_ids.unsqueeze(-1)).squeeze(-1)
437
+
438
+ ids[:, :token_len] = torch.where(is_mask, new_ids, ids[:, :token_len])
439
+ scores[:, :token_len] = torch.where(is_mask, new_scores, scores[:, :token_len])
440
+ res_sess = get_session("residual_transformer")
441
+ num_quantizers = 6
442
+
443
+ res_token_embed = np.load(ONNX_DIR / "res_token_embed.npy")
444
+
445
+ all_codes = torch.zeros(1, max_len, num_quantizers, dtype=torch.long)
446
+ all_codes[:, :, 0] = ids
447
+
448
+ history_sum = np.zeros((1, max_len, 512), dtype=np.float32)
449
+ motion_ids = ids.clone()
450
+
451
+ for q in range(1, num_quantizers):
452
+ token_embed = res_token_embed[q-1]
453
+ clamped_ids = np.clip(motion_ids[0].numpy(), 0, 512)
454
+ gathered = token_embed[clamped_ids]
455
+ history_sum += gathered[np.newaxis, :, :]
456
+
457
+ q_id = np.array([q], dtype=np.int64)
458
+
459
+ # CFG for residual transformer
460
+ cond_logits = res_sess.run(None, {
461
+ "motion_codes": history_sum.astype(np.float32),
462
+ "q_id": q_id,
463
+ "cond_vector": text_emb,
464
+ "padding_mask": padding_mask
465
+ })[0]
466
+ uncond_logits = res_sess.run(None, {
467
+ "motion_codes": history_sum.astype(np.float32),
468
+ "q_id": q_id,
469
+ "cond_vector": zero_emb,
470
+ "padding_mask": padding_mask
471
+ })[0]
472
+ logits = uncond_logits + (cond_logits - uncond_logits) * RES_COND_SCALE
473
+
474
+ logits = torch.from_numpy(logits)[:, :512, :token_len].permute(0, 2, 1)
475
+ new_ids_q = gumbel_sample(logits, 1.0)
476
+ all_codes[:, :token_len, q] = new_ids_q
477
+ motion_ids[:, :token_len] = new_ids_q
478
+
479
+ decoder_sess = get_session("vqvae_decoder")
480
+ valid_codes = all_codes[:, :token_len, :].numpy()
481
+ motion = decoder_sess.run(None, {
482
+ "code_indices": valid_codes
483
+ })[0]
484
+
485
+ # Decoder already upsamples 4x internally, just slice to exact length
486
+ motion = motion[:, :m_length, :]
487
+ motion = motion * std + mean
488
+
489
+ motion_tensor = torch.from_numpy(motion).float()
490
+ joints = recover_from_ric(motion_tensor, JOINTS_NUM)
491
+ joints = joints.squeeze(0).numpy()
492
+
493
+ # Apply foot skating fix
494
+ joints = fix_foot_skating(joints)
495
+
496
+ video_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
497
+ plot_3d_motion(video_path, joints, text, fps=20)
498
+
499
+ bvh_path = tempfile.NamedTemporaryFile(suffix=".bvh", delete=False).name
500
+ joints_to_bvh(joints, bvh_path, fps=20)
501
+
502
+ return joints, video_path, bvh_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt CHANGED
@@ -1,11 +1,13 @@
1
- # MoMask HuggingFace Space requirements (CPU)
2
- gradio>=6.1.0
 
 
 
 
3
  onnxruntime>=1.16.0
4
- torch>=2.0.0
5
- numpy
6
  ftfy
7
  regex
8
  tqdm
9
- matplotlib
10
  Pillow
11
  git+https://github.com/openai/CLIP.git
 
1
+ gradio[mcp]
2
+ uvicorn>=0.31.1
3
+ pydantic>=2.11.10
4
+ numpy>=1.26
5
+ matplotlib>=3.8
6
+ huggingface_hub>=0.26
7
  onnxruntime>=1.16.0
8
+ torch
 
9
  ftfy
10
  regex
11
  tqdm
 
12
  Pillow
13
  git+https://github.com/openai/CLIP.git
runtime/kmd-encode ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0a92fe6f7c31c55f0f2115e54e56da13e8e0246060b0c1442b1aae7f6a2e2f9
3
+ size 173088
runtime/libggml-base.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71c6e7cd31e6b94aa48bcb5ddec946e1fdb81aa76570af5d5810bd15d70d7de2
3
+ size 1231064
runtime/libggml-cpu.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddca1713c4eba3a8d47b6cd75a8bfc7dd47aa48bd859d27e6d6ac155ed56e934
3
+ size 1070448
runtime/libggml.so.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab1eb5de1538bbdef3ed65ec89777ae7294232e5d3e9689740c6166a4ddd0e39
3
+ size 1896280
runtime/libgomp.so.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d46f9225c1883039e8a6853e6d96ca1af11d034ce186a090952e4a7c8a7c2fdc
3
+ size 298776
runtime/libkimodo.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc9c158f0f317b0472cb11161d087b7f68b5b39013135d5041a7a1fdfe75d459
3
+ size 300872