Skip to content

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

feat(video): measured walk defaults — Lite walks calmed, Lite back-diagonal holds its head, front and back walks start mid-step

Soohong Kim17f28fe71c40
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 26b0220..7c9c5fb 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -190,6 +190,33 @@ out, only `PINNED_LOOP_STATES` do. A caller that retries a walk pinned after no
says True; two such front-walk clips closed on their first frame (seam 0.12 and 0.24 of an
ordinary step).
+`build_prompt(..., model=...)` names the clip model. **A Lite walk is calmed**: for
+`grok-imagine-video-1.5-lite` (`LITE_VIDEO_MODELS`) the built-in walk sentence is followed by
+`LITE_WALK_TEXT` — a slow, relaxed walk, small low steps, a gentle arm swing close to the body, no
+bounce, never running. Lite read "walks naturally" bigger than Pro: long, bouncy steps and a wide
+arm swing, a run more than a walk (2026-10-03, one SD character in five views, two takes each);
+with the clause every view walked. A caller's own walk paragraph is left as written. **A Lite
+back-diagonal walk also holds its head** (`LITE_HEAD_TEXT`, after the calm clause): its head swayed
+2.7–3.8 % of the body height side to side against Pro's 0.88 %, and with the sentence four takes
+swayed 1.7–3.1 % (best 1.84 %). It was measured in that view only, so it is said in that view only.
+The measured sentence ended "only the legs, arms and the end of the ponytail move"; the engine's
+says "the ends of the hair", since most characters have no ponytail. Pro prompts are unchanged.
+
+**A front or back walk starts mid-step.** From a standing still the clip model makes the first
+step itself and walks askew — the feet drawn to one line under the body, or the body turned
+three-quarters: 1 of 14 front clips walked straight from a standing still, 14 of 16 from the same
+characters redrawn mid-step (2026-10-02, four characters, blind judged; three rewordings of the walk
+sentence kept 0 of 14 from a standing SD still). `WALK_START_TEXT[direction]` is the redraw sentence for the front and the
+back — the same 2D sprite, same design, caught mid-step with one foot planted under its hip and
+the other lifted a little under its own, hips and shoulders square, arms swinging gently — and
+`walk_start_prompt(direction, key)` adds the background line for a green or magenta key
+(`starts_mid_step(state, direction)` says which clips need it). The design is the reference
+image's to keep: the sentence is drawn with the base still attached. `video-set` does this before
+the canvas (`--walk-start redraw`, the default): one `sprite-gen gen --ref <base>` call per front or
+back walk, on the base's own key, kept as `walk-start.png` with its report and reused while the
+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.
+
## 3. Frames — extract, key, check the edges
`ffmpeg` extracts every frame; the clip's real fps is recorded (never assumed). Each
@@ -495,7 +522,9 @@ are idempotent (an existing clip is reused unless `--force`); one failure stops
its item and is listed in `table.md` with its stage and error. Exit code is non-zero
when any item failed.
-After the loops are cut, every walk or run filmed in two or more directions is given one cycle
+A front or back walk films from its base redrawn mid-step (`--walk-start redraw`, default; one
+image generation each, `--still-provider` picks the provider; see §2). After the loops are cut,
+every walk or run filmed in two or more directions is given one cycle
length: each loop is resampled to the set's median length (only the frames that fall between two
source frames are made, by RIFE) and turned to start on a foot strike (`--align-cycles auto`, the
default; `off` keeps each loop's own length). The same step stands alone as
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 13d64e2..74e35b2 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -22,6 +22,8 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Callable
+from PIL import Image
+
from sprite_gen.spec.runio import atomic_write_text
from sprite_gen.gen.facing import FACINGS, validate as validate_facing
from sprite_gen.video import facing as facing_mod
@@ -190,6 +192,28 @@ VIEW_MOTION_TEXT = {
PINNED_GAIT_VIEWS = DIAGONAL_VIEWS
+# Clip models that read a walk sentence bigger than it is written. The lower-priced Lite model took
+# "walks naturally" as long, bouncy steps and a wide arm swing — it ran (2026-10-03, an SD girl in
+# five views, two takes each); a calming clause after the walk sentence brought it back to a walk.
+LITE_VIDEO_MODELS = frozenset({"grok-imagine-video-1.5-lite"})
+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."
+)
+# 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 = {
+ "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 the legs, arms and the ends of the hair move."
+ ),
+}
+
+
+def is_lite(model: str | None) -> bool:
+ return model in LITE_VIDEO_MODELS
+
+
def pins_last_frame(state: str, direction: str) -> bool:
"""Whether the clip of (state, direction) is filmed ending on its first frame."""
return state in PIN_LAST_FRAME_STATES or (state in GAIT_STATES and direction in PINNED_GAIT_VIEWS)
@@ -235,7 +259,7 @@ 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) -> str:
+ pinned: bool | None = None, model: str | None = None) -> str:
"""The clip prompt for one (direction, state).
`motion` replaces the built-in state sentence with the caller's own description of the
@@ -248,6 +272,10 @@ def build_prompt(direction: str, state: str, character: str | None, facing: str
for the return to the first pose instead of an evenly paced repeat (`PINNED_LOOP_TEXT`). None
leaves it to the state and view (`PINNED_LOOP_STATES`, a walk or run in `PINNED_GAIT_VIEWS`);
a caller that pins any other walk or run says True.
+
+ `model` is the clip model the prompt is for. A Lite walk (`LITE_VIDEO_MODELS`) gets the calming
+ 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`.
"""
validate_facing(facing)
view = VIEW_TEXT.get(direction, f"seen from the {direction}").format(facing=facing)
@@ -267,11 +295,72 @@ def build_prompt(direction: str, state: str, character: str | None, facing: str
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"
- return f"2D game sprite animation. {motion}{hold}{repeat} {subject} is {view}." + template[len(head):]
+ return f"2D game sprite animation. {motion}{hold}{repeat} {subject} is {view}." + template[len(head):] + _lite_text(state, direction, model, built_in=False)
built_in = VIEW_MOTION_TEXT.get((state, direction)) or MOTION_TEXT.get(
state, f"performs the '{state}' action in place, repeating at an even rhythm.")
text = template.format(motion=built_in, view=view)
- return text.replace("The character", character, 1) if character else text
+ return (text.replace("The character", character, 1) if character else text) + _lite_text(state, direction, model, built_in=True)
+
+
+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."""
+ 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]}"
+ return text
+
+
+# A walk seen from the front or from behind starts from a still redrawn mid-step. From a standing
+# still the clip model makes the first step itself and walks askew — the feet drawn to one line, or
+# the body turned three-quarters — 1 of 14 front clips straight; from a mid-step still, 14 of 16
+# (2026-10-02, four characters, blind judged). The sentence redraws the base still with a reference;
+# the design is the reference's to keep, the background the caller's to say (`walk_start_prompt`).
+WALK_START_TEXT = {
+ "front": (
+ "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 hips and shoulders square. One foot is "
+ "planted flat directly under its own hip; the other foot is lifted a little with the knee slightly bent, directly "
+ "under its own hip, so the feet stay hip-width apart with a clear gap between the legs. The arms swing gently "
+ "opposite to the legs, hands as in the image. Full body, centered, seen at eye level, with generous empty margin "
+ "above the head and below the feet."
+ ),
+ "back": (
+ "Redraw the character 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 the character toward the viewer. Only the pose changes: the character is caught mid-step while walking straight "
+ "away from the viewer, with the hips and shoulders square to the viewer and the body not turned to either side. One "
+ "foot is planted flat directly under its own hip; the other foot is lifted a little with the knee slightly bent, "
+ "directly under its own hip, so the feet stay hip-width apart with a clear gap between the legs. The arms swing "
+ "gently opposite to the legs, hands as in the image. Full body, centered, seen at eye level, with generous empty "
+ "margin above the head and below the feet; all of the hair stays well inside the image."
+ ),
+}
+WALK_START_MODES = ("redraw", "as-given")
+KEY_BACKGROUND_TEXT = {
+ "green": ("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."),
+ "magenta": ("The entire background is one perfectly flat, uniform pure magenta chroma-key fill (#FF00FF) with no "
+ "gradient, no texture, no shadow and no ground line."),
+}
+
+
+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 walk_start_prompt(direction: str, key: str | None = None) -> str:
+ """The redraw sentence for a walk's mid-step start still; with `key` (green / magenta) the background line."""
+ 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)})")
+ if key is None:
+ return WALK_START_TEXT[direction]
+ 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}")
+ return f"{WALK_START_TEXT[direction]} {KEY_BACKGROUND_TEXT[key]}"
def run_video_cli(image: Path, prompt: str, out: Path, report: Path, *, duration: int, resolution: str, log: Path, last_frame: Path | None = None) -> int:
@@ -282,6 +371,40 @@ def run_video_cli(image: Path, prompt: str, out: Path, report: Path, *, duration
return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode
+def run_redraw_cli(base: Path, prompt: str, out: Path, report: Path, *, log: Path, provider: str | None = None) -> int:
+ """`sprite-gen gen` with the base still as the reference: one redrawn still, its report beside it."""
+ cmd = [sys.executable, "-m", "sprite_gen.cli", "gen", "--ref", str(base), "--prompt", prompt, "--out", str(out), "--report", str(report)]
+ if provider:
+ cmd += ["--provider", provider]
+ with log.open("w", encoding="utf-8") as fh:
+ return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode
+
+
+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) -> 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.
+
+ Reused when the same prompt already drew it from the same base (unless `force`)."""
+ with Image.open(base) as im:
+ kind = canvas_mod.resolve_key(canvas_mod.corner_key(im.convert("RGB")), key)
+ 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)
+ 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:
+ prior = json.loads(report.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ prior = {}
+ if prior.get("prompt") == prompt and [str(Path(r).resolve()) for r in prior.get("refs") or []] == [str(base.resolve())]:
+ return out, {"redrawn": True, "reused": True, "still": str(out), "key": kind}
+ rc = runner(base, prompt, out, report, log=item_dir / "walk-start.log", provider=provider)
+ if rc != 0 or not out.is_file():
+ raise SystemExit(f"the mid-step start still for the {direction} walk was not drawn; see {item_dir / 'walk-start.log'}")
+ return out, {"redrawn": True, "reused": False, "still": str(out), "key": kind, "report": str(report)}
+
+
def run_item(
*,
item: str,
@@ -305,7 +428,12 @@ def run_item(
body_height: int | None = None,
fit: str = "state",
decontam: str = "off",
+ walk_start: str = "redraw",
+ redraw_runner: Callable[..., int] = run_redraw_cli,
+ still_provider: str | 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)}")
if anchor == "motion-auto" and not loop_mod.profile_for(state).gait:
raise SystemExit("video-set: --anchor motion-auto requires walk/run states")
if anchor == "motion":
@@ -352,6 +480,9 @@ def run_item(
else:
still = base
facing_report = None
+ if starts_mid_step(state, direction) 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)
if direction == "side":
if prepare_side is not None:
still, facing_report = prepare_side(base)
@@ -477,6 +608,9 @@ def run_set(
decontam: str = "off",
align_cycles: str = "auto",
interpolate: Any = None,
+ walk_start: str = "redraw",
+ redraw_runner: Callable[..., int] = run_redraw_cli,
+ still_provider: str | None = None,
) -> dict[str, Any]:
if align_cycles not in ALIGN_MODES:
raise SystemExit(f"video-set: --align-cycles must be one of {', '.join(ALIGN_MODES)}")
@@ -510,7 +644,7 @@ def run_set(
return prepared[base]
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], 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=facing, facing_fix=facing_fix, prepare_side=prepare_side, body_height=body_height, fit=fit, decontam=decontam): i for i, d, s in items}
+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], 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=facing, facing_fix=facing_fix, prepare_side=prepare_side, body_height=body_height, fit=fit, decontam=decontam, walk_start=walk_start, redraw_runner=redraw_runner, still_provider=still_provider): i for i, d, s in items}
for fut in as_completed(futures):
r = fut.result()
results.append(r)
@@ -558,6 +692,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--fit", choices=canvas_mod.FITS, default="state", help="state: each state's room for the motion (default); tight: no room, the subject fills the frame and a motion that leaves it is clipped (use with --body-height at a low --resolution)")
parser.add_argument("--body-height", type=int, default=None, help="scale every state's loop so the standing height is this many px (video-loop --body-height): one value for the whole set keeps the character the same size across states")
parser.add_argument("--decontam", choices=frames_mod.DECONTAM_MODES, default="off", help="passed to video-frames: palette re-explains key-tinted edges with the subject's own colours (default off)")
+ parser.add_argument("--walk-start", choices=WALK_START_MODES, default="redraw", help="redraw (default): a front or back walk films from its base still redrawn mid-step (one image generation, `sprite-gen gen --ref base`, kept as walk-start.png) — from a standing still the clip model walks askew; as-given: film from the base still itself")
+ parser.add_argument("--still-provider", help="image provider for the mid-step redraw (default: sprite-gen gen's own default)")
parser.add_argument("--align-cycles", choices=ALIGN_MODES, default="auto", help="auto (default): after the loops are cut, every walk/run filmed in two or more directions is resampled to the set's median cycle length and turned to start on a foot strike (video-cycle-align; RIFE makes only the frames between source frames); off: each loop keeps its own length")
parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")
@@ -573,6 +709,7 @@ def run(**kwargs: object) -> int:
shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),
body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None), fit=str(kwargs.get("fit") or "state"),
decontam=str(kwargs.get("decontam") or "off"), align_cycles=str(kwargs.get("align_cycles") or "auto"),
+ walk_start=str(kwargs.get("walk_start") or "redraw"), still_provider=kwargs.get("still_provider"), # type: ignore[arg-type]
)
return 0 if not payload["failed"] else 1
diff --git a/tests/video/test_walk_defaults.py b/tests/video/test_walk_defaults.py
new file mode 100644
index 0000000..419df43
--- /dev/null
+++ b/tests/video/test_walk_defaults.py
@@ -0,0 +1,96 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Two measured walk defaults (2026-10-02/03): a Lite walk gets a calming clause after the walk
+sentence, and a head-steady one in the back-diagonal view; a front or back walk films from its
+base still redrawn mid-step. Pro prompts and every other state stay byte-for-byte as they were."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.video import batch
+
+LITE, PRO = "grok-imagine-video-1.5-lite", "grok-imagine-video-1.5"
+
+
+def test_a_lite_walk_is_calmed_and_nothing_else_changes():
+ for direction in ("side", "front", "back", "front_diagonal"):
+ plain = batch.build_prompt(direction, "walk", "The knight")
+ assert batch.build_prompt(direction, "walk", "The knight", model=PRO) == plain
+ assert batch.build_prompt(direction, "walk", "The knight", model=LITE) == f"{plain} {batch.LITE_WALK_TEXT}"
+ for state in ("run", "idle", "attack", "jump"):
+ assert batch.build_prompt("side", state, "The knight", model=LITE) == batch.build_prompt("side", state, "The knight")
+
+
+def test_a_lite_back_diagonal_walk_also_holds_its_head_after_the_calm_clause():
+ plain = batch.build_prompt("back_diagonal", "walk", "The knight")
+ lite = batch.build_prompt("back_diagonal", "walk", "The knight", model=LITE)
+ assert lite == f"{plain} {batch.LITE_WALK_TEXT} {batch.LITE_HEAD_TEXT['back_diagonal']}"
+ assert "ponytail" not in lite # the measured sentence named the test character's ponytail; the engine's names hair
+
+
+def test_a_callers_own_walk_is_not_calmed_but_the_head_still_holds():
+ own = "The knight marches briskly in place, knees high."
+ plain = batch.build_prompt("back_diagonal", "walk", "The knight", motion=own)
+ lite = batch.build_prompt("back_diagonal", "walk", "The knight", motion=own, model=LITE)
+ assert lite == f"{plain} {batch.LITE_HEAD_TEXT['back_diagonal']}"
+ assert batch.build_prompt("side", "walk", "The knight", motion=own, model=LITE) == batch.build_prompt("side", "walk", "The knight", motion=own)
+
+
+def test_only_a_front_or_back_walk_starts_mid_step():
+ assert batch.starts_mid_step("walk", "front") and batch.starts_mid_step("walk", "back")
+ for state, direction in (("walk", "side"), ("walk", "front_diagonal"), ("walk", "back_diagonal"), ("run", "front"), ("idle", "front")):
+ assert not batch.starts_mid_step(state, direction)
+ assert batch.walk_start_prompt("front", "green").endswith(batch.KEY_BACKGROUND_TEXT["green"])
+ assert "caught mid-step while walking straight away from the viewer" in batch.walk_start_prompt("back")
+ with pytest.raises(SystemExit, match="green or magenta"):
+ batch.walk_start_prompt("front", "white")
+
+
+def _still(path: Path, background: tuple[int, int, int]) -> Path:
+ im = Image.new("RGB", (96, 128), background)
+ for y in range(20, 110):
+ for x in range(36, 60):
+ im.putpixel((x, y), (120, 60, 40))
+ im.save(path)
+ return path
+
+
+class Painter:
+ def __init__(self):
+ self.calls: list[str] = []
+
+ def __call__(self, base, prompt, out, report, *, log, provider=None):
+ self.calls.append(prompt)
+ Image.open(base).save(out)
+ report.write_text(json.dumps({"prompt": prompt, "refs": [str(base)], "provider": provider or "stub"}))
+ return 0
+
+
+def test_the_start_still_is_redrawn_once_on_the_bases_key_and_reused(tmp_path):
+ base = _still(tmp_path / "front.png", (0, 255, 0))
+ item = tmp_path / "front-walk"
+ item.mkdir()
+ paint = Painter()
+ still, record = batch.walk_start_still(base, "front", item, key="auto", force=False, runner=paint)
+ assert still == item / "walk-start.png" and record["key"] == "green" and record["reused"] is False
+ assert paint.calls == [batch.walk_start_prompt("front", "green")]
+ _, again = batch.walk_start_still(base, "front", item, key="auto", force=False, runner=paint)
+ assert again["reused"] is True and len(paint.calls) == 1
+ batch.walk_start_still(base, "front", item, key="auto", force=True, runner=paint)
+ assert len(paint.calls) == 2
+
+
+def test_a_base_on_no_chroma_key_is_refused_naming_as_given(tmp_path):
+ base = _still(tmp_path / "front.png", (255, 255, 255))
+ with pytest.raises(SystemExit, match="--walk-start as-given"):
+ batch.walk_start_still(base, "front", tmp_path, key="auto", force=False, runner=Painter())
+
+
+def test_a_failed_redraw_stops_the_item(tmp_path):
+ base = _still(tmp_path / "back.png", (255, 0, 255))
+ with pytest.raises(SystemExit, match="mid-step start still for the back walk was not drawn"):
+ batch.walk_start_still(base, "back", tmp_path, key="auto", force=False, runner=lambda *a, **k: 1)