Expose Kimodo generation options

This commit is contained in:
Meta Vens 2026-06-13 00:55:34 +01:00
commit 16d74cb674
4 changed files with 352 additions and 33 deletions

View file

@ -44,6 +44,72 @@ Important routes:
- `GET /smoke`
- `POST /motion/generate`
## Motion Generation
`POST /motion/generate` exposes Kimodo's generation surface through the
resident worker. Vili owns job identity, persistence, timeout handling, worker
lifecycle, and the output stem; Kimodo owns synthesis and model-specific export
formats.
Minimal request:
```json
{
"prompt": "a person gives a small friendly wave",
"duration": 1,
"diffusionSteps": 20,
"bvh": true
}
```
Batch requests can use Kimodo-style metadata:
```json
{
"meta": {
"texts": [
"a person gives a small friendly wave",
"a person takes one careful step"
],
"durations": [0.5, 0.5],
"num_samples": 1,
"diffusion_steps": 20
},
"numTransitionFrames": 3,
"cfgType": "regular",
"cfgWeight": [1.5],
"seed": 6101,
"bvh": true,
"bvhStandardTpose": true,
"saveExampleDir": true
}
```
Supported request fields:
- `prompt` / `utterance` plus `duration` / `durationSeconds`
- `texts` plus `durations`, or a full `meta` object
- `inputFolder` / `input_folder` for a container-visible Kimodo input folder
with `meta.json` and optional `constraints.json`
- `model`; changing the requested model restarts the single resident worker
- `diffusionSteps` / `diffusion_steps`
- `numSamples` / `num_samples`
- `numTransitionFrames` / `num_transition_frames`
- `constraints` as an object/list, or `constraints`, `constraintsPath`, or
`constraints_path` as a container-visible path
- `seed`
- `cfg`, `cfgType` / `cfg_type`, `cfgWeight` / `cfg_weight`
- `bvh`, `bvhStandardTpose` / `bvh_standard_tpose`
- `noPostprocess` / `no_postprocess`
- `saveExampleDir` / `save_example_dir`
- `timeoutMs`, `workerTimeoutMs`
Vili intentionally does not accept an arbitrary Kimodo output path. Generated
artifacts are written under `.vili/artifacts/{jobId}/` and referenced from the
job record. `Kimodo-SOMA-RP-v1.1` produces NPZ and optional BVH output,
`Kimodo-SMPLX-RP-v1.1` also exports AMASS NPZ, and `Kimodo-G1-RP-v1.1` also
exports CSV when that model is resident.
## Current Runtime State
Raven has a Hugging Face token installed at

View file

@ -32,19 +32,72 @@ animation job schema stabilizes.
## Command Boundary
`POST /motion/generate` accepts an explicit animation request:
`POST /motion/generate` accepts an explicit animation request and forwards the
supported Kimodo generation controls to the resident worker. Vili owns job
identity, request persistence, worker lifecycle, timeout handling, and the
artifact stem. Kimodo owns synthesis and model-specific export.
```json
{
"prompt": "a person gives a small friendly wave",
"duration": 2,
"duration": 1,
"diffusionSteps": 20,
"seed": 123,
"output": "wave-test",
"bvh": true
}
```
Kimodo metadata can be sent directly when callers need multi-segment or
multi-sample generation:
```json
{
"meta": {
"texts": [
"a person gives a small friendly wave",
"a person takes one careful step"
],
"durations": [0.5, 0.5],
"num_samples": 1,
"diffusion_steps": 20
},
"model": "Kimodo-SOMA-RP-v1.1",
"numTransitionFrames": 3,
"cfgType": "regular",
"cfgWeight": [1.5],
"seed": 6101,
"bvh": true,
"bvhStandardTpose": true,
"saveExampleDir": true
}
```
Request fields accepted by Vili:
- `prompt` / `utterance` plus `duration` / `durationSeconds`
- `texts` plus `durations`, or a full `meta` object
- `inputFolder` / `input_folder` for a container-visible Kimodo input folder
containing `meta.json` and optional `constraints.json`
- `model`; the daemon keeps one resident model loaded, so a model change
restarts `vili-kimodo-worker`
- `diffusionSteps` / `diffusion_steps`
- `numSamples` / `num_samples`
- `numTransitionFrames` / `num_transition_frames`
- `constraints` as an object/list, or `constraints`, `constraintsPath`, or
`constraints_path` as a container-visible path
- `seed`
- `cfg`, `cfgType` / `cfg_type`, `cfgWeight` / `cfg_weight`
- `bvh`, `bvhStandardTpose` / `bvh_standard_tpose`
- `noPostprocess` / `no_postprocess`
- `saveExampleDir` / `save_example_dir`
- `timeoutMs`, `workerTimeoutMs`
Vili does not accept arbitrary `output` paths from callers. Every generation
writes beneath `.vili/artifacts/{jobId}/`, with the worker receiving
`/outputs/{jobId}/motion`. The job record is the authority for artifact refs.
Model-specific exports are preserved: SOMA writes NPZ and optional BVH, SMPLX
also writes AMASS NPZ, and G1 also writes CSV.
The daemon may reject or defer requests when:
- Kimodo image is unavailable.
@ -53,7 +106,9 @@ The daemon may reject or defer requests when:
access.
- The resident Kimodo worker cannot start or does not become healthy before the
request timeout.
- The request omits a concrete prompt.
- The request omits concrete prompt, metadata, batch text, or input-folder
intent.
- Batch `texts` are provided without matching `durations`.
## Credential State

View file

@ -2,6 +2,7 @@
import argparse
import json
import os
import shutil
import time
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@ -13,6 +14,7 @@ import torch
from kimodo import DEFAULT_MODEL, load_model
from kimodo.constraints import load_constraints_lst
from kimodo.exports.motion_io import save_kimodo_npz
from kimodo.meta import parse_prompts_from_meta
from kimodo.model.registry import get_model_info
from kimodo.scripts.generate import (
_output_dir_and_path,
@ -20,7 +22,7 @@ from kimodo.scripts.generate import (
get_texts_and_num_frames_from_prompt,
resolve_cfg_kwargs,
)
from kimodo.tools import seed_everything
from kimodo.tools import save_json, seed_everything
def parse_args():
@ -86,6 +88,35 @@ def save_outputs(output, output_base, export_bvh, bvh_standard_tpose):
save_kimodo_npz(npz_path, single)
files.append(npz_path)
if resolved_model == "kimodo-smplx-rp":
from kimodo.exports.smplx import AMASSConverter
converter = AMASSConverter(skeleton=model.skeleton, fps=model.fps)
if n_samples == 1:
amass_path = _single_file_path(output_base + "_amass", ".npz")
converter.convert_save_npz(output, amass_path)
files.append(amass_path)
else:
out_dir, _, _ = _output_dir_and_path(output_base, "amass", ".npz")
amass_path = os.path.join(out_dir, "amass.npz")
converter.convert_save_npz(output, amass_path)
files.append(amass_path)
if resolved_model == "kimodo-g1-rp":
from kimodo.exports.mujoco import MujocoQposConverter
converter = MujocoQposConverter(model.skeleton)
qpos = converter.dict_to_qpos(output, device)
if n_samples == 1:
csv_path = _single_file_path(output_base, ".csv")
converter.save_csv(qpos, csv_path)
files.append(csv_path)
else:
out_dir, _, base_name = _output_dir_and_path(output_base, "qpos", ".csv")
csv_path = os.path.join(out_dir, base_name + ".csv")
converter.save_csv(qpos, csv_path)
files.append(csv_path)
if export_bvh:
skeleton = model.skeleton
if "somaskel" in skeleton.name:
@ -131,23 +162,103 @@ def save_outputs(output, output_base, export_bvh, bvh_standard_tpose):
return files
def generate(payload):
global generation_count
def save_example_dirs(output_base, texts, num_frames, num_samples, constraints_path):
output_stem = os.path.splitext(output_base)[0].rstrip(os.sep)
base_name = os.path.basename(output_stem)
if num_samples == 1:
parent_dir = None
example_dirs = [output_stem + "_example"]
else:
parent_dir = output_stem + "_examples"
if os.path.exists(parent_dir):
raise FileExistsError(f"Example directory already exists: {parent_dir}")
os.makedirs(parent_dir)
example_dirs = [
os.path.join(parent_dir, f"{base_name}_example_{index:02d}")
for index in range(num_samples)
]
durations_sec = [frame_count / model.fps for frame_count in num_frames]
if len(texts) == 1:
meta_info = {"text": texts[0], "duration": durations_sec[0]}
else:
meta_info = {"texts": texts, "durations": durations_sec}
meta_info["num_samples"] = num_samples
files = []
for example_dir in example_dirs:
os.makedirs(example_dir, exist_ok=False)
motion_path = os.path.join(example_dir, "motion.npz")
source_path = _single_file_path(output_base, ".npz")
if num_samples > 1:
index = example_dirs.index(example_dir)
source_path = os.path.join(output_stem, f"{base_name}_{index:02d}.npz")
shutil.copyfile(source_path, motion_path)
files.append(motion_path)
meta_path = os.path.join(example_dir, "meta.json")
save_json(meta_path, meta_info)
files.append(meta_path)
if constraints_path:
constraints_copy_path = os.path.join(example_dir, "constraints.json")
shutil.copyfile(constraints_path, constraints_copy_path)
files.append(constraints_copy_path)
return files
def get_generation_prompts(payload):
if isinstance(payload.get("meta"), dict):
texts, durations_sec = parse_prompts_from_meta(payload["meta"])
return texts, [int(float(duration) * model.fps) for duration in durations_sec]
if payload.get("inputFolder") or payload.get("input_folder"):
input_folder = payload.get("inputFolder") or payload.get("input_folder")
meta_path = os.path.join(input_folder, "meta.json")
with open(meta_path, "r", encoding="utf-8") as handle:
meta = json.load(handle)
texts, durations_sec = parse_prompts_from_meta(meta)
return texts, [int(float(duration) * model.fps) for duration in durations_sec]
if isinstance(payload.get("texts"), list):
texts = [str(text) for text in payload["texts"]]
durations = payload.get("durations") or payload.get("durationSeconds") or payload.get("duration")
if not isinstance(durations, list):
raise ValueError("When 'texts' is provided, 'durations' must be a list.")
if len(texts) != len(durations):
raise ValueError("'texts' and 'durations' must have the same length.")
return texts, [int(float(duration) * model.fps) for duration in durations]
prompt = str(payload.get("prompt") or payload.get("utterance") or "").strip()
if not prompt:
raise ValueError("Missing prompt or utterance.")
output_base = str(payload.get("output") or "/outputs/motion")
raise ValueError("Missing prompt, utterance, texts, meta, or inputFolder.")
duration = str(payload.get("durationSeconds") or payload.get("duration") or 4)
diffusion_steps = max(1, int(payload.get("diffusionSteps") or payload.get("diffusion_steps") or 20))
num_samples = max(1, int(payload.get("numSamples") or payload.get("num_samples") or 1))
return get_texts_and_num_frames_from_prompt(prompt, duration, model.fps)
def generate(payload):
global generation_count
requested_model = payload.get("model")
if requested_model and requested_model != resolved_model and requested_model != display_model:
raise ValueError(f"Worker model is {resolved_model}; request asked for {requested_model}.")
meta = payload.get("meta") if isinstance(payload.get("meta"), dict) else {}
output_base = str(payload.get("output") or "/outputs/motion")
diffusion_steps = max(1, int(payload.get("diffusionSteps") or payload.get("diffusion_steps") or meta.get("diffusion_steps") or 20))
num_samples = max(1, int(payload.get("numSamples") or payload.get("num_samples") or meta.get("num_samples") or 1))
num_transition_frames = int(payload.get("numTransitionFrames") or payload.get("num_transition_frames") or 5)
constraints_path = payload.get("constraints")
input_folder = payload.get("inputFolder") or payload.get("input_folder")
if constraints_path is None and input_folder:
default_constraints_path = os.path.join(input_folder, "constraints.json")
if os.path.exists(default_constraints_path):
constraints_path = default_constraints_path
seed = payload.get("seed")
seed = int(seed) if seed is not None else None
texts, num_frames = get_texts_and_num_frames_from_prompt(prompt, duration, model.fps)
texts, num_frames = get_generation_prompts(payload)
constraint_lst = load_constraints_lst(constraints_path, model.skeleton) if constraints_path else []
if seed is not None:
seed_everything(seed)
@ -183,6 +294,8 @@ def generate(payload):
request_bool(payload, "bvh"),
request_bool(payload, "bvhStandardTpose") or request_bool(payload, "bvh_standard_tpose"),
)
if request_bool(payload, "saveExampleDir") or request_bool(payload, "save_example_dir"):
files.extend(save_example_dirs(output_base, texts, num_frames, num_samples, constraints_path))
generation_count += 1
finished = time.time()
@ -198,6 +311,8 @@ def generate(payload):
"clipSeconds": clip_seconds,
"diffusionSteps": diffusion_steps,
"numSamples": num_samples,
"numTransitionFrames": num_transition_frames,
"constraints": constraints_path,
"seed": seed,
"files": files,
"timing": {

View file

@ -87,6 +87,14 @@ function shQuote(value) {
return `'${String(value).replaceAll("'", "'\\''")}'`;
}
function firstDefined(...values) {
return values.find((value) => value !== undefined && value !== null);
}
function boolValue(value) {
return value === true || String(value).toLowerCase() === "true" || String(value) === "1";
}
async function wslJson(script, options = {}) {
const result = await wsl(script, options);
if (!result.ok) return { ...result, body: null };
@ -267,7 +275,7 @@ async function kimodoWorkerHealth(timeout = 10000) {
return wslJson(`curl -fsS --max-time ${Math.ceil(timeout / 1000)} ${shQuote(`${kimodoWorkerUrl}/health`)}`, { timeout });
}
async function startKimodoWorker() {
async function startKimodoWorker({ model = null } = {}) {
const script = [
"set -e",
"service docker start >/dev/null 2>&1 || true",
@ -289,16 +297,20 @@ async function startKimodoWorker() {
"python",
"/opt/vili/kimodo-resident-worker.py",
`--port ${kimodoWorkerPort}`,
model ? `--model ${shQuote(model)}` : "",
].join(" "),
].join("; ");
return wsl(script, { timeout: 30000 });
}
async function ensureKimodoWorker({ timeoutMs = 1000 * 60 * 8 } = {}) {
async function ensureKimodoWorker({ timeoutMs = 1000 * 60 * 8, model = null } = {}) {
const health = await kimodoWorkerHealth(10000);
if (health.ok && health.body?.ok) return health;
if (health.ok && health.body?.ok) {
if (!model || health.body.model === model || health.body.displayModel === model) return health;
await wsl(`docker rm -f ${shQuote(kimodoWorkerName)} >/dev/null 2>&1 || true`, { timeout: 30000 });
}
const started = await startKimodoWorker();
const started = await startKimodoWorker({ model });
if (!started.ok) return started;
const deadline = Date.now() + timeoutMs;
@ -334,44 +346,112 @@ async function generateMotion(request, response) {
}
const prompt = String(body.prompt || body.utterance || "").trim();
if (!prompt) {
json(response, 400, { ok: false, error: "Missing prompt or utterance." });
const hasPromptInput = Boolean(prompt)
|| Array.isArray(body.texts)
|| typeof body.meta === "object"
|| body.inputFolder
|| body.input_folder;
if (!hasPromptInput) {
json(response, 400, { ok: false, error: "Missing prompt, utterance, texts, meta, or inputFolder." });
return;
}
if (Array.isArray(body.texts) && !Array.isArray(body.durations)) {
json(response, 400, { ok: false, error: "Batch text requests require a durations array." });
return;
}
const jobId = `vili-${Date.now()}`;
const artifactDir = path.join(args.stateRoot, "artifacts", jobId);
await mkdir(artifactDir, { recursive: true });
const duration = Number(body.durationSeconds || body.duration || 4);
const diffusionSteps = Math.max(1, Number(body.diffusionSteps || body.diffusion_steps || 20));
const duration = firstDefined(body.durationSeconds, body.duration, 4);
const bodyMeta = typeof body.meta === "object" && body.meta ? body.meta : {};
const diffusionSteps = Math.max(1, Number(firstDefined(
body.diffusionSteps,
body.diffusion_steps,
bodyMeta.diffusion_steps,
20,
)));
const seed = body.seed === undefined ? null : Number(body.seed);
const meta = {
text: prompt,
duration,
num_samples: Math.max(1, Number(body.numSamples || body.num_samples || 1)),
diffusion_steps: diffusionSteps,
};
const numSamples = Math.max(1, Number(firstDefined(
body.numSamples,
body.num_samples,
bodyMeta.num_samples,
1,
)));
const meta = Object.keys(bodyMeta).length > 0
? { ...bodyMeta }
: Array.isArray(body.texts)
? { texts: body.texts, durations: body.durations }
: {
text: prompt,
duration,
};
meta.num_samples = Math.max(1, Number(firstDefined(body.numSamples, body.num_samples, meta.num_samples, 1)));
meta.diffusion_steps = diffusionSteps;
if (Number.isFinite(seed)) meta.seed = seed;
if (body.cfg) meta.cfg = body.cfg;
const constraintsPath = (() => {
if (typeof body.constraints === "string") return body.constraints;
if (body.constraints_path) return body.constraints_path;
if (body.constraintsPath) return body.constraintsPath;
if (body.constraints !== undefined) return `/outputs/${jobId}/constraints.json`;
return undefined;
})();
if (body.constraints !== undefined && typeof body.constraints !== "string") {
await writeFile(path.join(artifactDir, "constraints.json"), JSON.stringify(body.constraints, null, 2));
}
const requestRecord = {
schema: "gamecult.vili.motion_request.v0",
prompt: prompt || undefined,
texts: Array.isArray(body.texts) ? body.texts : undefined,
meta,
model: body.model,
duration,
numSamples,
diffusion_steps: diffusionSteps,
numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames),
constraints: constraintsPath,
seed: Number.isFinite(seed) ? seed : undefined,
cfg: body.cfg,
cfgType: firstDefined(body.cfgType, body.cfg_type),
cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight),
bvh: boolValue(body.bvh),
bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)),
noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)),
saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)),
inputFolder: firstDefined(body.inputFolder, body.input_folder),
};
await writeFile(path.join(artifactDir, "meta.json"), JSON.stringify(meta, null, 2));
const worker = await ensureKimodoWorker({ timeoutMs: Number(body.workerTimeoutMs || 1000 * 60 * 8) });
const worker = await ensureKimodoWorker({
timeoutMs: Number(firstDefined(body.workerTimeoutMs, body.worker_timeout_ms, 1000 * 60 * 8)),
model: body.model || null,
});
let result = worker;
if (worker.ok) {
const workerRequest = {
prompt,
model: body.model,
prompt: prompt || undefined,
texts: Array.isArray(body.texts) ? body.texts : undefined,
meta,
inputFolder: firstDefined(body.inputFolder, body.input_folder),
duration,
diffusionSteps,
numSamples: meta.num_samples,
numSamples,
numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames),
constraints: constraintsPath,
seed: Number.isFinite(seed) ? seed : undefined,
cfg: body.cfg,
bvh: body.bvh === true,
bvhStandardTpose: body.bvhStandardTpose === true || body.bvh_standard_tpose === true,
noPostprocess: body.noPostprocess === true || body.no_postprocess === true,
cfgType: firstDefined(body.cfgType, body.cfg_type),
cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight),
bvh: boolValue(body.bvh),
bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)),
noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)),
saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)),
output: `/outputs/${jobId}/motion`,
};
await writeFile(path.join(artifactDir, "request.json"), JSON.stringify(workerRequest, null, 2));
const curlCommand = [
`curl -fsS --max-time ${Math.ceil(Number(body.timeoutMs || 1000 * 60 * 30) / 1000)}`,
`curl -sS --max-time ${Math.ceil(Number(body.timeoutMs || 1000 * 60 * 30) / 1000)}`,
"-H 'content-type: application/json'",
`--data-binary @${shQuote(`/mnt/e/Projects/Vili/.vili/artifacts/${jobId}/request.json`)}`,
shQuote(`${kimodoWorkerUrl}/generate`),
@ -380,13 +460,16 @@ async function generateMotion(request, response) {
"set -e",
curlCommand,
].join("; "), { timeout: Number(body.timeoutMs || 1000 * 60 * 30) });
if (result.body?.ok === false) result = { ...result, ok: false };
}
const job = {
schema: "gamecult.vili.motion_job.v0",
jobId,
createdAt: new Date().toISOString(),
prompt,
prompt: prompt || null,
model: body.model || result.body?.model || null,
request: requestRecord,
durationSeconds: duration,
diffusionSteps,
seed,