Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(video): a horse is not told a person's walk — --body-plan

Soohong Kim8618faad1277
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d5e443..a57358b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,12 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+## Unreleased (v2.32.0) - A horse is not told a person's walk
+
+- **Fix: an animal's walk and idle named a person's arms and feet.** The walk and run sentences have named no limb since 2.0.0 ("`video-set` motion templates no longer assume a biped"), but four sentences added later were measured on people and said to every body: the Lite walk calm ("a gentle arm swing close to the body", 2.18.0), the Lite back-diagonal head hold ("only the legs, arms and the ends of the hair move", 2.18.0), the idle ("both feet planted flat", chest, shoulders and arms, 2.9.0) and the front or back walk's mid-step redraw ("one foot … directly under its own hip … the arms swing", 2.18.0). Said of a horse, they walk it on a person's legs or stand it up on two. Not a regression of the 2.0.0 fix: these paths came after it.
+- **New `--body-plan` on `video-set` and `video-prompt`** (`build_prompt(body_plan=...)`, `walk_start_prompt(body_plan=...)`, `sprite_gen/video/body_plan.py`): `biped` (default), `quadruped` or `legless`, or one `"<figure>=<plan>"` per figure of a scene (`--body-plan "the man=biped" --body-plan "the horse=quadruped"`). Any body but one biped gets those four sentences without the parts it lacks (`IDLE_TEXT_ANY_BODY`, `LITE_WALK_TEXT_LEGGED` / `LITE_WALK_TEXT_LEGLESS`, `LITE_HEAD_TEXT_ANY_BODY`, `WALK_START_TEXT_ANY_BODY`) and, after the motion sentence or the caller's `--motion`, what it stands on: "It stays on all four legs, as in the image, and never rises onto its hind legs."; a scene says it per figure. A body without legs has no mid-step redraw. `video-set` and `video-prompt --json` record `body_plan`. No body plan, or one biped, keeps every prompt byte for byte (`tests/gen/test_prompt_freeze.py`). The new sentences are not yet measured on clips. [docs/video-pipeline.md](docs/video-pipeline.md#a-body-that-is-not-a-person----body-plan).
+- **`tests/video/test_body_plan.py`** draws every walk, run, idle and jump prompt (built-in and `--motion`, every model, `video-prompt`, the mid-step redraw) for a quadruped, a body without legs and a person leading a horse, and finds no arm, hand, wrist, shoulder, chest, hip, knee or counted foot in any; five of them are pinned as snapshots.
+
## v2.31.0 - A loop whose foot the set alignment cannot name is told it, one loop at a time
- **New `video-cycle-align --foot <loop>=left|right`** (repeatable; the loop named as for `--cycles`: its `--loop-dir`, its strip's name, its directory's name or a `video-set` item's name) and **`video-set --align-foot <item>=left|right`**: which own foot lands on a loop's first strike, as seen by whoever looked at it — a person, the agent, or a vision call. Where a loop's view cannot tell its feet apart (`start_foot: null`), `--start-foot` was set-wide and there was no way to say "this loop's larger strike is its left foot". Now that loop alone starts as the set's start foot lands — on its first strike, or half a cycle on — and every other loop comes out byte for byte as without it. The answer is about the loop as filmed (its strikes are read from `cycle.source/`), so it holds for a later alignment at the same length; like `--cycles` it is not remembered. A foot given for a loop the view did name is taken too, and where it disagrees the row carries `foot_disagrees` and a warning. A `--foot` that names no loop or two, or is not `left`/`right`, is refused before anything is rewritten; `video-set` refuses an `--align-foot` item that is not a walk or run filmed in two or more directions before filming, and names one given for an item that failed or whose state was not aligned in that state's `feet_unused` and a warning. The way feet are named from the pixels is unchanged.
diff --git a/SKILL.md b/SKILL.md
index 32f3bf5..397ee8f 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -75,6 +75,7 @@ it never changes the requested direction. Image correction requires explicit opt
| `video --direction` | `side`, `front`, `back`, `front_diagonal`, `back_diagonal`; unset by default | `side` opts into facing inspection and a matching prompt requirement; the others skip it. The two diagonals are three-quarter views turned right (`VIEW_TEXT`); a walk or run in one is filmed pinned (`pins_last_frame`). |
| `video --facing`, `video-set --facing` | `right` (default), `left`; `video-set` also `right,left` | Required side direction. `right,left` films every side and diagonal view both ways, each from its own still (`--base side@left=…`); none is mirrored. |
| `gen --direction`, `--handed`; `video-prompt` / `video-set --handed` | a view; `"<item>=<left\|right> [part]"` | An item on one of the character's own sides: the still and clip prompts say where it is in each view, and mirroring is refused. |
+| `video-prompt` / `video-set --body-plan` | `biped` (default), `quadruped`, `legless`; or `"<figure>=<plan>"` per figure of a scene | What the subject stands on: no clip or redraw prompt names a part it lacks (a horse is not walked on a person's legs or stood up), and a scene says it per figure. |
| `video --facing-fix`, `video-set --facing-fix` | `none` (default), `mirror` | Record the observation; opt into mirroring an observed opposite in a copy. Batch side inspection is enabled by default. |
Direction is requested through the generation and motion prompts, which cannot guarantee model compliance.
diff --git a/docs/prompt-assembly.md b/docs/prompt-assembly.md
index 00d5706..86997f3 100644
--- a/docs/prompt-assembly.md
+++ b/docs/prompt-assembly.md
@@ -53,6 +53,12 @@ each time that arm swings forward
([handedness](video-pipeline.md#handedness--an-item-on-one-side)). An item anywhere else — an ear,
the head, a tail, the body, a leg, a shoulder — gets only where it is, and no arm sentence.
+**A body that is not a person** (`--body-plan`, `video/body_plan.py`): with no body plan, or one
+biped, nothing changes. A quadruped, a body without legs or a scene of several figures has the idle,
+the Lite walk sentences and the mid-step redraw said without the parts it lacks, and what it stands
+on said after the motion paragraph
+([body plan](video-pipeline.md#a-body-that-is-not-a-person----body-plan)).
+
**A front or back walk's start still** (`batch.walk_start_prompt`): the mid-step redraw sentence,
the key background line, then the still's handed sentences.
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 08f460e..66c478d 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -253,6 +253,36 @@ back walk, on the base's own key, kept as `walk-start.png` with its report and r
prompt and base are the same; a base on no chroma key is refused with `--walk-start as-given`, which
films from the base itself. Side and diagonal walks, and every other state, film from the base.
+### A body that is not a person — `--body-plan`
+
+The measured sentences above were measured on people, and four of them name what only a person has:
+the Lite walk calm swings the arms (`LITE_WALK_TEXT`), the Lite back-diagonal head hold moves the
+arms (`LITE_HEAD_TEXT`), the idle plants both feet and settles the chest, shoulders and arms
+(`MOTION_TEXT["idle"]`), and the front or back mid-step redraw puts one foot under each hip with the
+arms swinging (`WALK_START_TEXT`). Said of a horse, a pig or a dog, they walk it on a person's legs or
+stand it up on two. The walk and run sentences themselves name no limb (since 2.0.0's "`video-set`
+motion templates no longer assume a biped"); these four came later (idle 2.9.0, the rest 2.18.0) and
+were said to every body.
+
+`video-set --body-plan`, `video-prompt --body-plan` and `build_prompt(body_plan=...)`,
+`walk_start_prompt(body_plan=...)` name what the subject stands on (`sprite_gen/video/body_plan.py`):
+`biped` (the default), `quadruped` or `legless` for the character, or one `<figure>=<plan>` per figure
+of a scene (`--body-plan "the man=biped" --body-plan "the horse=quadruped"`). No body plan, or one
+biped, keeps every prompt byte for byte. Any other body gets:
+
+| Sentence | for a body that is not one biped |
+|---|---|
+| after the motion sentence (or the caller's `--motion`) | what it stands on (`body_plan.text`): "It stays on all four legs, as in the image, and never rises onto its hind legs." / "It has no legs, as in the image, and never grows legs or feet." / "Each figure keeps the body it has in the image: the man on two legs; the horse on all four legs, never rising onto its hind legs." |
+| idle | `IDLE_TEXT_ANY_BODY`: the same stillness, standing or resting as in the image, no feet counted, no chest, shoulders or arms |
+| Lite walk calm | `LITE_WALK_TEXT_LEGGED` (no arm swing; never trotting or galloping) or, with a figure without legs, `LITE_WALK_TEXT_LEGLESS` (no steps or feet) |
+| Lite back-diagonal head hold | `LITE_HEAD_TEXT_ANY_BODY`: what moves is what it moves on and its loose ends (a tail, a mane, hair) |
+| front or back mid-step redraw | `WALK_START_TEXT_ANY_BODY`: one leg lifted, the others planted, then what it stands on; a body without legs has no step to catch and films from its base (`starts_mid_step` is false, `video-prompt` gives no `start_still`) |
+
+Only the biped sentences were measured on clips; the others say no part the body lacks and are not
+yet measured. `--handed` keeps its own sentences (its arm sentences are for an item on an arm), and an
+attack's grip sentence (`HOLD_TEXT["attack"]`) still speaks of hands. `video-set` and `video-prompt
+--json` record the plan as `body_plan`.
+
### A clip from a video MCP on your agent — ZCRE
sprite-gen never calls a video MCP. When your own agent (Claude, Codex) has one connected — ZCRE's
@@ -306,7 +336,7 @@ ends on the canvas (`last_frame`), the loop cut (`cycle`) and the canvas, clip,
commands with placeholders; a front or back walk adds `start_still`, the mid-step redraw `video-set`
makes before its canvas (`sprite-gen gen --ref`, your image provider). Its `loop` command names no
`--anchor` and it lists no set command: add `--anchor motion-auto` for a walk or run, and run
-`video-cycle-align` for a set, as above. `--character`, `--motion` and `--model` reach the
+`video-cycle-align` for a set, as above. `--character`, `--motion`, `--model` and `--body-plan` reach the
prompt as they reach `build_prompt`. What the ZCRE route supports:
| | Through ZCRE's MCP |
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index b5d833e..3a7a61c 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -35,6 +35,8 @@ from sprite_gen.video import canvas as canvas_mod
from sprite_gen.video import frames as frames_mod
from sprite_gen.video import loop as loop_mod
from sprite_gen.video import align as align_mod
+from sprite_gen.video import body_plan as body_mod
+from sprite_gen.video.body_plan import Body
from sprite_gen.video import rife as rife_mod
START_GAP_SECONDS = 2.0
@@ -160,6 +162,14 @@ MOTION_TEXT = {
"cheer": "celebrates in place: rises into a raised, spread-out cheer pose, holds it for a beat, then settles back to the exact starting stance, repeating at an even rhythm.",
"wave": "waves in place: lifts one side into a friendly wave, sways it a few times, then settles back to the exact starting stance, repeating at an even rhythm.",
}
+# The idle for a body that is not one biped (`body_plan`): the same stillness, with no feet counted and no
+# chest, shoulders or arms named, so a horse is not stood up on two feet. Not measured on a clip.
+IDLE_TEXT_ANY_BODY = (
+ "stays still in a relaxed idle pose, standing or resting on the ground exactly as in the image for the whole "
+ "clip: slow, gentle breathing that softly rises and falls in the body, a slight settle of loose parts such as "
+ "hair, a mane, a tail or cloth, and one natural blink if a face has eyes. Whatever it stands or rests on never "
+ "lifts, steps, shuffles or slides — no walking, no marching in place, no turning."
+)
# A walk or run seen from the front or from behind, in place of the side view's sentences above. Every
# gait says only that it moves naturally, which way it faces and that it stays in place. Asked for "an
# even left-right or front-back rhythm", a walk that faces the viewer stepped sideways or turned the body
@@ -219,6 +229,13 @@ LITE_WALK_TEXT = (
"A slow, relaxed, unhurried walk: small, low steps with the feet barely leaving the ground, a gentle arm swing "
"close to the body and no bounce — never running, jogging, skipping or hopping."
)
+# The same calm for a body that is not one biped (`body_plan`): no arm swing, and a four-legged walk is not to
+# trot or gallop; a body without legs has no steps or feet. Not measured on a clip.
+LITE_WALK_TEXT_LEGGED = (
+ "A slow, relaxed, unhurried walk: small, low steps with the feet barely leaving the ground and no bounce — never "
+ "trotting, galloping, running, jogging, skipping or hopping."
+)
+LITE_WALK_TEXT_LEGLESS = "A slow, relaxed, unhurried pace: small, even movements — never rushing, running or leaping."
# Lite's back-diagonal walk swayed its head 2.7-3.8 % of the body height side to side against Pro's
# 0.88 %; with this sentence four takes swayed 1.7-3.1 % (2026-10-03). Measured on that view only.
LITE_HEAD_TEXT = {
@@ -229,6 +246,15 @@ LITE_HEAD_TEXT = {
}
+# The head hold for a body that is not one biped: what moves is what it moves on and its loose ends, no arms.
+LITE_HEAD_TEXT_ANY_BODY = {
+ "back_diagonal": (
+ "The head stays level and steady over the body the whole time: it does not bob, nod, tilt or sway from side to "
+ "side; only what it moves on and its loose ends, such as a tail, a mane or hair, move."
+ ),
+}
+
+
def is_lite(model: str | None) -> bool:
return model in LITE_VIDEO_MODELS
@@ -278,15 +304,16 @@ def _staggered_start(gap: float) -> None:
def build_prompt(direction: str, state: str, character: str | None, facing: str = "right", motion: str | None = None,
- pinned: bool | None = None, model: str | None = None, handed: list[Handed] | None = None) -> str:
+ pinned: bool | None = None, model: str | None = None, handed: list[Handed] | None = None,
+ body_plan: list[Body] | None = None) -> str:
"""The clip prompt for one (direction, state): `clip_prompt_parts(...).text`."""
return clip_prompt_parts(direction, state, character, facing=facing, motion=motion, pinned=pinned, model=model,
- handed=handed).text
+ handed=handed, body_plan=body_plan).text
def clip_prompt_parts(direction: str, state: str, character: str | None, facing: str = "right", motion: str | None = None,
pinned: bool | None = None, model: str | None = None,
- handed: list[Handed] | None = None) -> prompt_parts.Prompt:
+ handed: list[Handed] | None = None, body_plan: list[Body] | None = None) -> prompt_parts.Prompt:
"""The clip prompt for one (direction, state), as its pieces (`prompt_parts.Prompt`: `.text` is the
prompt, `.notes` what the caller's own words say against or again after the engine's).
@@ -305,7 +332,12 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
clause after the built-in walk sentence (`LITE_WALK_TEXT`; a caller's own motion is left as
written), and a Lite walk in a view where its head sways gets `LITE_HEAD_TEXT`.
- Without `handed` the prompt is 2.22.0's, to the byte (`tests/gen/test_prompt_freeze.py`). `handed` lists
+ `body_plan` (`body_plan.parse_all`) says what the subject stands on, one plan or one per figure of a scene.
+ None, or one biped, keeps the sentences measured on people; any other body gets them without a part it
+ lacks (`IDLE_TEXT_ANY_BODY`, `LITE_WALK_TEXT_LEGGED` / `_LEGLESS`, `LITE_HEAD_TEXT_ANY_BODY`) and, after the
+ motion sentence or the caller's paragraph, what it stands on (`body_plan.text`).
+
+ Without `handed` or `body_plan` the prompt is 2.22.0's, to the byte (`tests/gen/test_prompt_freeze.py`). `handed` lists
the character's asymmetric items (`handedness.parse`): the prompt ends with where each one stays, anchored
to the first frame (`handedness.text(clip=True)`), the one piece `prompt_parts.Prompt.add` checks.
"""
@@ -318,6 +350,8 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
template = PINNED_LOOP_TEXT
else:
template = COMMON_TEXT
+ stands_on = body_mod.text(body_plan)
+ stands_on = f" {stands_on}" if stands_on else ""
if motion is not None:
motion = " ".join(motion.split())
if not motion:
@@ -328,16 +362,19 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
hold += f" {GAIT_HOLD_TEXT[direction].format(facing=facing)}"
repeat = f" {REPEAT_TEXT[state]}" if state in REPEAT_TEXT else ""
subject = character.strip().rstrip(".") if character else "The character"
- text = (f"2D game sprite animation. {motion}{hold}{repeat} {subject} is {view}." + template[len(head):]
- + _lite_text(state, direction, model, built_in=False))
+ text = (f"2D game sprite animation. {motion}{stands_on}{hold}{repeat} {subject} is {view}." + template[len(head):]
+ + _lite_text(state, direction, model, built_in=False, body_plan=body_plan))
caller = f"{motion} {character or ''}"
else:
built_in = (VIEW_MOTION_TEXT[(state, direction)].format(facing=facing) if (state, direction) in VIEW_MOTION_TEXT
+ else IDLE_TEXT_ANY_BODY if state == "idle" and not body_mod.biped(body_plan)
else MOTION_TEXT.get(state, f"performs the '{state}' action in place, repeating at an even rhythm."))
- text = template.format(motion=built_in, view=view)
+ text = template.format(motion=built_in + stands_on, view=view)
text = ((text.replace("The character", character, 1) if character else text)
- + _lite_text(state, direction, model, built_in=True))
+ + _lite_text(state, direction, model, built_in=True, body_plan=body_plan))
caller = character or ""
+ if body_plan:
+ caller = f"{caller} {body_mod.figures(body_plan)}"
parts = prompt_parts.Prompt(text, caller=caller, sep=" ")
# the caller's words against the view the engine's sentence turns the clip to (a note, never an edit)
parts.note(facing=turned or prompt_parts.NO_TURN)
@@ -346,13 +383,20 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
return parts
-def _lite_text(state: str, direction: str, model: str | None, *, built_in: bool) -> str:
- """What a Lite walk adds after the prompt, in the order it was measured: the calm walk, then the head."""
+def _lite_text(state: str, direction: str, model: str | None, *, built_in: bool,
+ body_plan: list[Body] | None = None) -> str:
+ """What a Lite walk adds after the prompt, in the order it was measured: the calm walk, then the head;
+ for a body that is not one biped, the same without the parts it lacks."""
if state != "walk" or not is_lite(model):
return ""
- text = f" {LITE_WALK_TEXT}" if built_in else ""
- if direction in LITE_HEAD_TEXT:
- text += f" {LITE_HEAD_TEXT[direction]}"
+ if body_mod.biped(body_plan):
+ calm, head = LITE_WALK_TEXT, LITE_HEAD_TEXT
+ else:
+ calm = LITE_WALK_TEXT_LEGLESS if any(b.plan == "legless" for b in body_plan or []) else LITE_WALK_TEXT_LEGGED
+ head = LITE_HEAD_TEXT_ANY_BODY
+ text = f" {calm}" if built_in else ""
+ if direction in head:
+ text += f" {head[direction]}"
return text
@@ -382,20 +426,56 @@ WALK_START_TEXT = {
"margin above the head and below the feet; all of the hair stays well inside the image."
),
}
+# The same redraw for a body that is not one biped (`body_plan`): one leg lifted and the others planted, with
+# no hips, knees or arms, then what each figure stands on (`body_plan.text`), so a horse is not drawn
+# standing on two legs. `{who}` is "the character" or "every figure"; not measured on a clip.
+WALK_START_TEXT_ANY_BODY = {
+ "front": (
+ "Redraw {what} in the attached image as the same 2D game sprite, keeping the design, outfit, colors, body "
+ "proportions and art style exactly as they are. Only the pose changes: {who} is caught mid-step while walking "
+ "straight toward the viewer, facing the viewer directly with the body square. {legs} {stands_on} Full body, "
+ "centered, seen at eye level, with generous empty margin all around."
+ ),
+ "back": (
+ "Redraw {what} in the attached image as the same 2D game sprite, keeping the design, outfit, colors, hair, body "
+ "proportions and art style exactly as they are, and keeping the same view: seen directly from behind, the back "
+ "of {who} toward the viewer. Only the pose changes: {who} is caught mid-step while walking straight away from "
+ "the viewer, with the body square to the viewer and not turned to either side. {legs} {stands_on} Full body, "
+ "centered, seen at eye level, with generous empty margin all around; all of the hair, mane and tail stay well "
+ "inside the image."
+ ),
+}
+WALK_START_LEGS_TEXT = {
+ "one": "One leg is lifted a little while the others stay planted, each under the body where it is in the image, "
+ "with clear gaps between the legs.",
+ "scene": "Each figure that walks on legs has one leg lifted a little and the others planted, with clear gaps "
+ "between the legs.",
+}
WALK_START_MODES = ("redraw", "as-given")
-def starts_mid_step(state: str, direction: str) -> bool:
- """Whether the clip of (state, direction) starts from a still redrawn mid-step (`WALK_START_TEXT`)."""
- return state == "walk" and direction in WALK_START_TEXT
+def starts_mid_step(state: str, direction: str, body_plan: list[Body] | None = None) -> bool:
+ """Whether the clip of (state, direction) starts from a still redrawn mid-step (`WALK_START_TEXT`); a body
+ without legs has no step to catch and films from its base."""
+ return state == "walk" and direction in WALK_START_TEXT and not body_mod.legless(body_plan)
-def walk_start_prompt(direction: str, key: str | None = None, handed: list[Handed] | None = None) -> str:
+def walk_start_prompt(direction: str, key: str | None = None, handed: list[Handed] | None = None,
+ body_plan: list[Body] | None = None) -> str:
"""The redraw sentence for a walk's mid-step start still; with `key` (green / magenta) the background line,
- then with `handed` where each asymmetric item is in this view (`handedness.text`, the still's sentences)."""
+ then with `handed` where each asymmetric item is in this view (`handedness.text`, the still's sentences).
+ A `body_plan` that is not one biped gets `WALK_START_TEXT_ANY_BODY`; one without legs is refused."""
if direction not in WALK_START_TEXT:
raise SystemExit(f"video: no mid-step start still for the {direction} view (only {', '.join(WALK_START_TEXT)})")
- text = WALK_START_TEXT[direction]
+ if body_mod.legless(body_plan):
+ raise SystemExit("video: a body without legs has no mid-step start still; it films from its base")
+ if body_mod.biped(body_plan):
+ text = WALK_START_TEXT[direction]
+ else:
+ scene = body_mod.scene(body_plan)
+ text = WALK_START_TEXT_ANY_BODY[direction].format(
+ what="the figures" if scene else "the character", who="every figure" if scene else "the character",
+ legs=WALK_START_LEGS_TEXT["scene" if scene else "one"], stands_on=body_mod.text(body_plan))
if key is not None:
if key not in KEY_BACKGROUND_TEXT:
raise SystemExit(f"video: a mid-step start still is drawn on a green or magenta key, not {key!r}")
@@ -425,7 +505,8 @@ def run_redraw_cli(base: Path, prompt: str, out: Path, report: Path, *, log: Pat
def walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, force: bool,
runner: Callable[..., int] = run_redraw_cli, provider: str | None = None,
- handed: list[Handed] | None = None) -> tuple[Path, dict[str, Any]]:
+ handed: list[Handed] | None = None,
+ body_plan: list[Body] | None = None) -> tuple[Path, dict[str, Any]]:
"""The base still redrawn mid-step for a front or back walk (`WALK_START_TEXT`), on the base's own key,
told where each `handed` item is (a redraw from a reference alone can move it to the other side).
@@ -435,7 +516,7 @@ def walk_start_still(base: Path, direction: str, item_dir: Path, *, key: str, fo
if kind not in KEY_BACKGROUND_TEXT:
raise SystemExit(f"the {direction} walk starts from a still redrawn mid-step on a green or magenta key, and this "
f"base's corners are not one (key {key}); pass --walk-start as-given to film from the base itself")
- prompt = walk_start_prompt(direction, kind, handed)
+ prompt = walk_start_prompt(direction, kind, handed, body_plan)
out, report = item_dir / "walk-start.png", item_dir / "walk-start.report.json"
if out.is_file() and report.is_file() and not force:
try:
@@ -477,6 +558,7 @@ def run_item(
redraw_runner: Callable[..., int] = run_redraw_cli,
still_provider: str | None = None,
handed: list[Handed] | None = None,
+ body_plan: list[Body] | None = None,
) -> dict[str, Any]:
if walk_start not in WALK_START_MODES:
raise SystemExit(f"video-set: --walk-start must be one of {', '.join(WALK_START_MODES)}")
@@ -495,7 +577,7 @@ def run_item(
if direction in handed_mod.LATERAL_VIEWS:
result["turned"] = facing
try:
- parts = clip_prompt_parts(direction, state, character, facing=facing, handed=handed)
+ parts = clip_prompt_parts(direction, state, character, facing=facing, handed=handed, body_plan=body_plan)
prompt = parts.text
if parts.notes:
result["prompt_notes"] = parts.notes
@@ -536,9 +618,10 @@ def run_item(
else:
still = base
facing_report = None
- if starts_mid_step(state, direction) and walk_start == "redraw":
+ if starts_mid_step(state, direction, body_plan) and walk_start == "redraw":
still, result["walk_start"] = walk_start_still(base, direction, item_dir, key=key, force=force,
- runner=redraw_runner, provider=still_provider, handed=handed)
+ runner=redraw_runner, provider=still_provider, handed=handed,
+ body_plan=body_plan)
if direction == "side":
if prepare_side is not None:
still, facing_report = prepare_side(base)
@@ -789,6 +872,7 @@ def run_set(
still_provider: str | None = None,
handed: list[Handed] | None = None,
align_feet: dict[str, str] | None = None,
+ body_plan: list[Body] | None = None,
) -> dict[str, Any]:
"""`bases` maps a view to its still; `facing` is right, left or `right,left` (`facings_of`), and a view filmed
both ways is keyed `view@right` and `view@left` (`resolve_bases`). `handed` (`handedness.parse`) puts each
@@ -840,7 +924,7 @@ def run_set(
return prepare_side
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=b, root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=f, facing_fix=facing_fix, prepare_side=side_preparer(f), body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider, handed=handed): i for i, d, s, f, b in items}
+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=b, root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=f, facing_fix=facing_fix, prepare_side=side_preparer(f), body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider, handed=handed, body_plan=body_plan): i for i, d, s, f, b in items}
for fut in as_completed(futures):
r = fut.result()
results.append(r)
@@ -861,7 +945,7 @@ def run_set(
warnings += [f"cycle-align:{st}: {line}" for st, a in aligned.items() for line in a.get("warnings", [])]
warnings += [f"cycle-align:{st}: --align-foot {item}={foot} not applied ({a.get('why') or a.get('error') or 'the item failed'})"
for st, a in aligned.items() for item, foot in a.get("feet_unused", {}).items()]
- payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}
+ payload = {"kind": "sprite-gen-video-set-report", "root": str(root), "states": states, "facing": facing, "facing_fix": facing_fix, "directions": list(bases), **({"handed": [vars(h) for h in handed]} if handed else {}), **({"body_plan": [vars(b) for b in body_plan]} if body_plan else {}), "body_height": body_height, "ok": sum(1 for r in results if r.get("ok")), "failed": failed, "warnings": warnings, "items": results, "cycle_align": aligned}
atomic_write_text(root / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
print(table)
return payload
@@ -887,6 +971,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--facing", default="right", help="which way the side and diagonal views face, for both prompt and canvas: right (default), left, or right,left to film each of them both ways from a still drawn each way (no mirroring); ignored for front/back")
parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="side inputs: record only (none, default), or opt into mirror (refused with --handed)")
parser.add_argument("--handed", action="append", default=[], metavar="ITEM=SIDE [PART]", help="an asymmetric item on one of the character's own sides, e.g. 'the black smartwatch=left wrist' (repeatable): every clip prompt says where it is in its view and that it stays there")
+ parser.add_argument("--body-plan", action="append", default=[], metavar="PLAN | FIGURE=PLAN", help="what the character stands on: biped (default), quadruped or legless; a scene of several figures names each, e.g. 'the man=biped' 'the horse=quadruped' (repeatable): no prompt names a part the body lacks")
parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states")
parser.add_argument("--out-dir", required=True, type=Path, help="batch root; one folder per direction-state")
parser.add_argument("--character", help="short subject phrase used in the prompts (e.g. 'The armored knight')")
@@ -927,6 +1012,7 @@ def run(**kwargs: object) -> int:
walk_start=str(kwargs.get("walk_start") or "redraw"), still_provider=kwargs.get("still_provider"), # type: ignore[arg-type]
handed=handed_mod.parse_all(list(kwargs.get("handed") or [])) or None, # type: ignore[arg-type]
align_feet=align_mod.parse_feet(list(kwargs.get("align_foot") or []), prog="video-set", flag="--align-foot"),
+ body_plan=body_mod.parse_all(list(kwargs.get("body_plan") or [])) or None, # type: ignore[arg-type]
)
return 0 if not payload["failed"] else 1
diff --git a/sprite_gen/video/body_plan.py b/sprite_gen/video/body_plan.py
new file mode 100644
index 0000000..39b459f
--- /dev/null
+++ b/sprite_gen/video/body_plan.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Body plan: what a clip's subject stands and walks on, so no sentence names a part the body lacks.
+
+The engine's measured walk and idle sentences were measured on people, and some name what only a person
+has: the Lite walk's arm swing (`batch.LITE_WALK_TEXT`), the arms in the Lite back-diagonal head hold
+(`LITE_HEAD_TEXT`), the idle's two feet, chest, shoulders and arms (`MOTION_TEXT["idle"]`), and the front
+or back walk's mid-step redraw, one foot under each hip and the arms swinging (`WALK_START_TEXT`). Said of a
+horse, they walk it on a person's legs or stand it up on two. The caller names the body plan (`parse`,
+`--body-plan`): one for the character ("quadruped"), or one per figure in a scene ("the man=biped",
+"the horse=quadruped").
+
+| plan | stands on | the engine says |
+|---|---|---|
+| biped | two legs | the measured sentences, as without a body (the default) |
+| quadruped | four legs | it stays on all four legs and never rises onto its hind legs |
+| legless | no legs | it has no legs and never grows any; no mid-step redraw (no step to catch) |
+
+No body, or one biped, is the 2.22.0 prompt to the byte (`tests/gen/test_prompt_freeze.py`). Any other
+body gets the sentences without the parts it lacks and, after the motion sentence, what it stands on
+(`text`); a scene of several figures says it per figure. Only the biped sentences were measured; the
+others say no part the body lacks and are not yet measured on a clip.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+PLANS = ("biped", "quadruped", "legless")
+SPEC_FORM = "'<biped|quadruped|legless>' for the character, or '<figure>=<plan>' per figure in a scene, e.g. 'the horse=quadruped'"
+# What each figure of a scene stands on, after its name (`text`).
+SCENE_TEXT = {
+ "biped": "on two legs",
+ "quadruped": "on all four legs, never rising onto its hind legs",
+ "legless": "without legs, never growing any",
+}
+# One figure, after the motion sentence (`text`). A biped says nothing: the measured sentences are its own.
+ONE_TEXT = {
+ "quadruped": "It stays on all four legs, as in the image, and never rises onto its hind legs.",
+ "legless": "It has no legs, as in the image, and never grows legs or feet.",
+}
+
+
+@dataclass(frozen=True)
+class Body:
+ """One figure's body plan, and the figure's name when the clip is a scene of several."""
+
+ plan: str
+ figure: str = ""
+
+
+def parse(spec: str) -> Body:
+ """'quadruped' -> Body("quadruped"); 'the horse=quadruped' -> Body("quadruped", "the horse")."""
+ figure, plan = (s.strip() for s in spec.rsplit("=", 1)) if "=" in spec else ("", spec.strip())
+ if plan.lower() not in PLANS or ("=" in spec and not figure):
+ raise SystemExit(f"body plan: expected {SPEC_FORM}, got {spec!r}")
+ return Body(plan=plan.lower(), figure=" ".join(figure.split()))
+
+
+def parse_all(specs: list[str] | None) -> list[Body]:
+ """Every `--body-plan`: one for the character, or one per figure, each named once."""
+ bodies = [parse(s) for s in (specs or [])]
+ if len(bodies) > 1 and not all(b.figure for b in bodies):
+ raise SystemExit(f"body plan: a scene names each figure ({SPEC_FORM}); got {', '.join(map(repr, specs or []))}")
+ figures = [b.figure.lower() for b in bodies if b.figure]
+ if len(set(figures)) != len(figures):
+ raise SystemExit(f"body plan: each figure is named once; got {', '.join(map(repr, specs or []))}")
+ return bodies
+
+
+def biped(bodies: list[Body] | None) -> bool:
+ """Whether every figure stands on two legs (no body named is a biped): the measured sentences apply."""
+ return all(b.plan == "biped" for b in bodies or [])
+
+
+def legless(bodies: list[Body] | None) -> bool:
+ """Whether a body is named and none of its figures has legs."""
+ return bool(bodies) and all(b.plan == "legless" for b in bodies or [])
+
+
+def scene(bodies: list[Body] | None) -> bool:
+ return len(bodies or []) > 1
+
+
+def text(bodies: list[Body] | None) -> str:
+ """What the subject stands on, said after the motion sentence; "" for no body or one biped."""
+ if not bodies or (not scene(bodies) and bodies[0].plan == "biped"):
+ return ""
+ if not scene(bodies):
+ return ONE_TEXT[bodies[0].plan]
+ return "Each figure keeps the body it has in the image: " + "; ".join(
+ f"{b.figure} {SCENE_TEXT[b.plan]}" for b in bodies) + "."
+
+
+def figures(bodies: list[Body] | None) -> str:
+ """The figure names, as the caller wrote them (they are the caller's words in the prompt)."""
+ return " ".join(b.figure for b in bodies or [] if b.figure)
diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.py
index 49bcd9f..ecf1815 100644
--- a/sprite_gen/video/clip_prompt.py
+++ b/sprite_gen/video/clip_prompt.py
@@ -25,6 +25,8 @@ from sprite_gen.gen.facing import FACINGS
from sprite_gen.gen import handedness as handed_mod
from sprite_gen.gen.handedness import Handed
from sprite_gen.video import batch as batch_mod
+from sprite_gen.video import body_plan as body_mod
+from sprite_gen.video.body_plan import Body
DEFAULT_MODEL = "grok-imagine-video-1.5"
START_STILL_KEYS = ("green", "magenta")
@@ -33,9 +35,10 @@ START_STILL_KEYS = ("green", "magenta")
def plan_prompt(*, direction: str, state: str, facing: str = "right", character: str | None = None,
motion: str | None = None, model: str = DEFAULT_MODEL, last_frame: bool = True,
unpinned: bool = False, duration: int | None = None, key: str = "green",
- handed: list[Handed] | None = None) -> dict[str, Any]:
+ handed: list[Handed] | None = None, body_plan: list[Body] | None = None) -> dict[str, Any]:
"""The prompt `video-set` would send for (direction, state), and how its clip is to be cut. `handed`
- (`handedness.parse`) adds where each asymmetric item is in this view, as `video-set --handed` does."""
+ (`handedness.parse`) adds where each asymmetric item is in this view, as `video-set --handed` does;
+ `body_plan` (`body_plan.parse_all`) what the subject stands on, as `video-set --body-plan` does."""
if direction not in batch_mod.VIEW_TEXT:
raise SystemExit(f"video-prompt: --direction must be one of {', '.join(sorted(batch_mod.VIEW_TEXT))}, got {direction!r}")
if key not in START_STILL_KEYS:
@@ -56,14 +59,14 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
warnings.append(f"{direction} {state} filmed without its end-frame pin: the loop is searched, not cut whole, and may not close")
pins = wants_pin and last_frame
parts = batch_mod.clip_prompt_parts(direction, state, character, facing=facing, motion=motion, pinned=pinned,
- model=model, handed=handed)
+ model=model, handed=handed, body_plan=body_plan)
prompt = parts.text
# the caller's own words (--character, --motion) against the engine's: a conflict is a warning
warnings += [note["text"] for note in parts.notes if note["kind"] == "conflict"]
cycle = "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"
# as video-set places and cuts: a side or diagonal view takes the facing, front and back face right
canvas_facing = loop_facing = facing if direction in handed_mod.LATERAL_VIEWS else "right"
- mid_step = batch_mod.starts_mid_step(state, direction)
+ mid_step = batch_mod.starts_mid_step(state, direction, body_plan)
still = "<dir>/walk-start.png" if mid_step else "<still.png>"
duration = batch_mod.duration_for(state, duration)
end = ", end frame <dir>/canvas.png" if pins else ""
@@ -73,6 +76,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
"state": state,
"facing": facing,
**({"handed": [vars(h) for h in handed]} if handed else {}),
+ **({"body_plan": [vars(b) for b in body_plan]} if body_plan else {}),
"model": model,
"prompt": prompt,
"duration": duration,
@@ -94,7 +98,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
if mid_step:
record["start_still"] = {
"why": "a front or back walk films from its still redrawn mid-step; from a standing still the clip model walks askew",
- "prompt": batch_mod.walk_start_prompt(direction, key, handed),
+ "prompt": batch_mod.walk_start_prompt(direction, key, handed, body_plan),
"command": "sprite-gen gen --ref <still.png> --prompt-file <start-prompt.txt> --out <dir>/walk-start.png --report <dir>/walk-start.report.json",
}
return record
@@ -105,6 +109,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--state", required=True, help="motion state (idle/walk/run/jump/attack/...)")
parser.add_argument("--facing", choices=FACINGS, default="right", help="side or diagonal view: which way it faces (default right)")
parser.add_argument("--handed", action="append", default=[], metavar="ITEM=SIDE [PART]", help="an asymmetric item on one of the character's own sides, e.g. 'the black smartwatch=left wrist' (repeatable): the prompt says where it is in this view")
+ parser.add_argument("--body-plan", action="append", default=[], metavar="PLAN | FIGURE=PLAN", help="what the character stands on: biped (default), quadruped or legless; a scene of several figures names each, e.g. 'the man=biped' 'the horse=quadruped' (repeatable), as video-set --body-plan")
parser.add_argument("--character", help="short subject phrase used in the prompt (e.g. 'The armored knight')")
parser.add_argument("--motion", help="the caller's own motion paragraph in place of the state's sentence (build_prompt(motion=...))")
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"clip model the prompt is for (default {DEFAULT_MODEL}); a Lite model calms a walk")
@@ -123,6 +128,7 @@ def run(**kwargs: object) -> int:
unpinned=bool(kwargs.get("unpinned")), duration=(int(kwargs["duration"]) if kwargs.get("duration") else None), # type: ignore[arg-type]
key=str(kwargs.get("key") or "green"),
handed=handed_mod.parse_all(list(kwargs.get("handed") or [])) or None, # type: ignore[arg-type]
+ body_plan=body_mod.parse_all(list(kwargs.get("body_plan") or [])) or None, # type: ignore[arg-type]
)
for line in record["warnings"]:
print(f"video-prompt: warning: {line}", file=sys.stderr)
diff --git a/tests/video/test_body_plan.py b/tests/video/test_body_plan.py
new file mode 100644
index 0000000..7d64615
--- /dev/null
+++ b/tests/video/test_body_plan.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A body that is not a person is not told a person's walk (`--body-plan`, `sprite_gen.video.body_plan`).
+
+The measured Lite walk calm swung the arms, the Lite back-diagonal head hold moved the arms, the idle
+planted both feet and settled the chest, shoulders and arms, and the front or back walk's mid-step redraw
+put one foot under each hip with the arms swinging: said of a horse, it walks on a person's legs or stands
+up on two. A quadruped, a body without legs, and a scene of a person leading a horse each get prompts
+with no part they lack; no body, or one biped, keeps every prompt byte for byte. Subjects are synthetic.
+"""
+
+from __future__ import annotations
+
+import itertools
+import json
+import re
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.video import batch, body_plan as bp, clip_prompt
+
+LITE, PRO = "grok-imagine-video-1.5-lite", "grok-imagine-video-1.5"
+STATES = ("walk", "run", "idle", "jump")
+QUADRUPED = bp.parse_all(["quadruped"])
+LEGLESS = bp.parse_all(["legless"])
+SCENE = bp.parse_all(["the man=biped", "the horse=quadruped"])
+# Words that name a part only a person has, or count a person's feet.
+PERSON = re.compile(r"\b(arms?|hands?|wrists?|elbows?|shoulders?|chest|hips?|hip-width|knees?|both feet|one foot|the other foot)\b",
+ re.IGNORECASE)
+
+SNAPSHOTS = {
+ 'horse/side/walk/lite': (
+ '2D game sprite animation. A brown horse walks naturally in place, as if on a treadmill, without '
+ 'moving across the screen. It stays on all four legs, as in the image, and never rises onto its hind '
+ 'legs. The character is seen from the exact side, facing right. Stays centered in the frame and does '
+ 'not move across the screen; the body and hair always stay fully inside the frame with margin. Camera'
+ ' completely locked, no zoom, no pan, no reframing. The background stays a perfectly flat, pure '
+ 'chroma-key fill for the whole clip — no shadows, no ground line, no particles, no lighting changes, '
+ 'no effects. Keep the design, colors and proportions exactly as in the image. Consistent, evenly '
+ 'paced motion so the animation loops. A slow, relaxed, unhurried walk: small, low steps with the feet'
+ ' barely leaving the ground and no bounce — never trotting, galloping, running, jogging, skipping or '
+ 'hopping.'
+ ),
+ 'scene/side/walk/lite': (
+ '2D game sprite animation. A man leading a brown horse by its reins walks naturally in place, as if '
+ 'on a treadmill, without moving across the screen. Each figure keeps the body it has in the image: '
+ 'the man on two legs; the horse on all four legs, never rising onto its hind legs. The character is '
+ 'seen from the exact side, facing right. Stays centered in the frame and does not move across the '
+ 'screen; the body and hair always stay fully inside the frame with margin. Camera completely locked, '
+ 'no zoom, no pan, no reframing. The background stays a perfectly flat, pure chroma-key fill for the '
+ 'whole clip — no shadows, no ground line, no particles, no lighting changes, no effects. Keep the '
+ 'design, colors and proportions exactly as in the image. Consistent, evenly paced motion so the '
+ 'animation loops. A slow, relaxed, unhurried walk: small, low steps with the feet barely leaving the '
+ 'ground and no bounce — never trotting, galloping, running, jogging, skipping or hopping.'
+ ),
+ 'horse/side/idle': (
+ '2D game sprite animation. A brown horse stays still in a relaxed idle pose, standing or resting on '
+ 'the ground exactly as in the image for the whole clip: slow, gentle breathing that softly rises and '
+ 'falls in the body, a slight settle of loose parts such as hair, a mane, a tail or cloth, and one '
+ 'natural blink if a face has eyes. Whatever it stands or rests on never lifts, steps, shuffles or '
+ 'slides — no walking, no marching in place, no turning. It stays on all four legs, as in the image, '
+ 'and never rises onto its hind legs. The character is seen from the exact side, facing right. Stays '
+ 'centered in the frame and does not move across the screen; the body and hair always stay fully '
+ 'inside the frame with margin. Camera completely locked, no zoom, no pan, no reframing. The '
+ 'background stays a perfectly flat, pure chroma-key fill for the whole clip — no shadows, no ground '
+ 'line, no particles, no lighting changes, no effects. Keep the design, colors and proportions exactly'
+ ' as in the image. The last frame returns to the exact pose of the first frame, so the animation '
+ 'loops seamlessly.'
+ ),
+ 'horse/front/walk-start/green': (
+ 'Redraw the character in the attached image as the same 2D game sprite, keeping the design, outfit, '
+ 'colors, body proportions and art style exactly as they are. Only the pose changes: the character is '
+ 'caught mid-step while walking straight toward the viewer, facing the viewer directly with the body '
+ 'square. One leg is lifted a little while the others stay planted, each under the body where it is in'
+ ' the image, with clear gaps between the legs. It stays on all four legs, as in the image, and never '
+ 'rises onto its hind legs. Full body, centered, seen at eye level, with generous empty margin all '
+ 'around. The entire background is one perfectly flat, uniform pure green chroma-key fill (#00FF00) '
+ 'with no gradient, no texture, no shadow and no ground line.'
+ ),
+ 'scene/back/walk-start/green': (
+ 'Redraw the figures in the attached image as the same 2D game sprite, keeping the design, outfit, '
+ 'colors, hair, body proportions and art style exactly as they are, and keeping the same view: seen '
+ 'directly from behind, the back of every figure toward the viewer. Only the pose changes: every '
+ 'figure is caught mid-step while walking straight away from the viewer, with the body square to the '
+ 'viewer and not turned to either side. Each figure that walks on legs has one leg lifted a little and'
+ ' the others planted, with clear gaps between the legs. Each figure keeps the body it has in the '
+ 'image: the man on two legs; the horse on all four legs, never rising onto its hind legs. Full body, '
+ 'centered, seen at eye level, with generous empty margin all around; all of the hair, mane and tail '
+ 'stay well inside the image. The entire background is one perfectly flat, uniform pure green chroma-'
+ 'key fill (#00FF00) with no gradient, no texture, no shadow and no ground line.'
+ ),
+}
+
+
+def _every_prompt(body_plan, character):
+ """Each clip prompt (built-in and a caller's paragraph, every model) and video-prompt record for the
+ walk, run, idle and jump in every view, and each mid-step redraw."""
+ for view, state, model in itertools.product(batch.VIEW_TEXT, STATES, (None, PRO, LITE)):
+ yield f"{view}/{state}/{model}", batch.build_prompt(view, state, character, model=model, body_plan=body_plan)
+ yield (f"{view}/{state}/{model}/motion",
+ batch.build_prompt(view, state, character, motion="It ambles along, one cycle about 1 s.", model=model,
+ body_plan=body_plan))
+ for view, state in itertools.product(batch.VIEW_TEXT, STATES):
+ record = clip_prompt.plan_prompt(direction=view, state=state, character=character, model=LITE, body_plan=body_plan)
+ yield f"video-prompt/{view}/{state}", record["prompt"]
+ if "start_still" in record:
+ yield f"video-prompt/{view}/{state}/start", record["start_still"]["prompt"]
+
+
[email protected]("body_plan, character", [(QUADRUPED, "A brown horse"), (LEGLESS, "A green slime"),
+ (SCENE, "A man leading a brown horse by its reins")])
+def test_no_walk_run_idle_or_jump_prompt_names_a_part_the_body_lacks(body_plan, character) -> None:
+ named = {name: sorted({m.group(0).lower() for m in PERSON.finditer(text)})
+ for name, text in _every_prompt(body_plan, character)}
+ assert len(named) > 130
+ assert not {name: words for name, words in named.items() if words}
+
+
+def test_without_a_person_the_v2_31_prompts_did_name_a_persons_parts() -> None:
+ """What the report was about: a Lite walk, an idle and the front or back redraw of a horse, as 2.31.0 said it."""
+ assert "arm swing" in batch.build_prompt("side", "walk", "A brown horse", model=LITE)
+ assert "both feet planted flat" in batch.build_prompt("side", "idle", "A brown horse")
+ assert "directly under its own hip" in batch.walk_start_prompt("front", "green")
+
+
[email protected]("name", list(SNAPSHOTS))
+def test_the_prompts_for_a_horse_and_a_man_leading_one(name) -> None:
+ who, view, state, *rest = name.split("/")
+ body_plan, character = {"horse": (QUADRUPED, "A brown horse"),
+ "scene": (SCENE, "A man leading a brown horse by its reins")}[who]
+ if state == "walk-start":
+ drawn = batch.walk_start_prompt(view, rest[0], body_plan=body_plan)
+ else:
+ drawn = batch.build_prompt(view, state, character, model=LITE if rest == ["lite"] else None, body_plan=body_plan)
+ assert drawn == SNAPSHOTS[name]
+
+
+def test_one_biped_or_none_keeps_every_prompt_byte_for_byte() -> None:
+ biped = bp.parse_all(["biped"])
+ for view, state, model in itertools.product(batch.VIEW_TEXT, (*STATES, "attack", "cheer"), (None, PRO, LITE)):
+ plain = batch.build_prompt(view, state, "The knight", model=model)
+ assert batch.build_prompt(view, state, "The knight", model=model, body_plan=biped) == plain
+ assert batch.build_prompt(view, state, "The knight", model=model, body_plan=[]) == plain
+ motion = "It marches with the knees high, one cycle about 1 s."
+ assert (batch.build_prompt(view, state, "The knight", motion=motion, model=model, body_plan=biped)
+ == batch.build_prompt(view, state, "The knight", motion=motion, model=model))
+ for view in batch.WALK_START_TEXT:
+ assert batch.walk_start_prompt(view, "green", body_plan=biped) == batch.walk_start_prompt(view, "green")
+
+
+def test_the_body_plan_says_what_it_stands_on_after_the_motion_and_before_the_view() -> None:
+ horse = batch.build_prompt("front", "run", "A brown horse", body_plan=QUADRUPED)
+ assert horse.index("runs naturally") < horse.index(bp.ONE_TEXT["quadruped"]) < horse.index("is seen from the front")
+ told = batch.build_prompt("side", "walk", "A brown horse", motion="It trots lightly.", body_plan=QUADRUPED)
+ assert told.startswith(f"2D game sprite animation. It trots lightly. {bp.ONE_TEXT['quadruped']} It stays in place")
+
+
+def test_a_body_without_legs_has_no_mid_step_redraw() -> None:
+ assert batch.starts_mid_step("walk", "front", QUADRUPED) and batch.starts_mid_step("walk", "back", SCENE)
+ assert not batch.starts_mid_step("walk", "front", LEGLESS)
+ assert "start_still" not in clip_prompt.plan_prompt(direction="front", state="walk", body_plan=LEGLESS)
+ with pytest.raises(SystemExit, match="no mid-step start still"):
+ batch.walk_start_prompt("front", "green", body_plan=LEGLESS)
+
+
[email protected]("specs, match", [
+ (["horse"], "expected"),
+ (["=quadruped"], "expected"),
+ (["quadruped", "the man=biped"], "names each figure"),
+ (["the horse=quadruped", "The Horse=biped"], "named once"),
+])
+def test_a_body_plan_is_one_plan_or_one_named_plan_per_figure(specs, match) -> None:
+ with pytest.raises(SystemExit, match=match):
+ bp.parse_all(specs)
+ assert bp.parse_all(["Quadruped"]) == [bp.Body("quadruped")]
+ assert bp.parse_all(["the horse = quadruped"]) == [bp.Body("quadruped", "the horse")]
+
+
+def test_video_set_says_the_body_plan_in_the_redraw_and_the_clip(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(batch.frames_mod, "run_frames", lambda clip, out, **kw: {
+ "fps": 24, "frames": 10, "alpha_zero_pct_min": 50, "alpha_zero_pct_max": 60, "keyed_dir": str(out)})
+ monkeypatch.setattr(batch.loop_mod, "run_loop", lambda *a, **kw: {
+ "cycle": {"length": 10, "period_global": 10, "ratio": 0.2}, "resampled_seam_ratio": 0.2, "n_out": 10,
+ "gif": {"file": "loop.gif"}, "webp": {"file": "loop.webp"}, "strip": {"path": "strip.png"}})
+ monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)
+ redraws: list[str] = []
+ clips: dict[str, str] = {}
+
+ def paint(base, prompt, out, report, *, log, provider=None):
+ redraws.append(prompt)
+ out.write_bytes(base.read_bytes())
+ report.write_text(json.dumps({"prompt": prompt, "refs": [str(base)]}))
+ return 0
+
+ def video(image, prompt, out, report, **kw):
+ clips[out.parent.name] = prompt
+ out.write_bytes(b"test-video")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+
+ base = Image.new("RGB", (128, 96), (0, 255, 0))
+ ImageDraw.Draw(base).rectangle((20, 30, 107, 79), fill=(120, 60, 40))
+ base.save(tmp_path / "front.png")
+ result = batch.run_set(bases={"front": tmp_path / "front.png"}, states=["walk"], root=tmp_path / "set",
+ character="A brown horse", duration=3, resolution="720p", key="green", concurrency=1,
+ force=False, gap=0, video_runner=video, redraw_runner=paint, align_cycles="off",
+ body_plan=QUADRUPED)
+ assert result["ok"] == 1 and result["body_plan"] == [{"plan": "quadruped", "figure": ""}]
+ assert redraws == [batch.walk_start_prompt("front", "green", body_plan=QUADRUPED)]
+ assert clips["front-walk"] == batch.build_prompt("front", "walk", "A brown horse", body_plan=QUADRUPED)
+ seen = []
+ monkeypatch.setattr(batch, "run_set", lambda **kw: seen.append(kw) or {"failed": []})
+ assert batch.main(["--base", f"front={tmp_path / 'front.png'}", "--states", "walk", "--out-dir", str(tmp_path / "x"),
+ "--body-plan", "the man=biped", "--body-plan", "the horse=quadruped"]) == 0
+ assert seen[0]["body_plan"] == SCENE
+
+
+def test_video_prompt_takes_the_body_plan() -> None:
+ record = clip_prompt.plan_prompt(direction="front", state="walk", character="A brown horse", body_plan=QUADRUPED)
+ assert record["prompt"] == batch.build_prompt("front", "walk", "A brown horse", model=clip_prompt.DEFAULT_MODEL,
+ body_plan=QUADRUPED)
+ assert record["start_still"]["prompt"] == batch.walk_start_prompt("front", "green", body_plan=QUADRUPED)
+ assert record["body_plan"] == [{"plan": "quadruped", "figure": ""}]