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): a motion plays as its request says — loop, once-return, once-hold or lifetime — and video-set takes a motion text per item

Soohong Kim0c686b469e16
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 643b637..8776762 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -41,6 +41,7 @@ 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
from sprite_gen.video import nonloop
+from sprite_gen.video import play as play_mod
START_GAP_SECONDS = 2.0
# Clip length the batch asks the video model for. 3 s holds two or more cycles of every
@@ -351,9 +352,38 @@ 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."""
+def pins_last_frame(state: str, direction: str, play: str | None = None) -> bool:
+ """Whether the clip of (state, direction) is filmed ending on its first frame — its end-frame pin: a once-return
+ ends on its first pose and an effect on its empty black frame; a once-hold never; a loop as its state is filmed.
+ `play` is the request's play mode (`play.MODES`), None for the state's preset."""
+ mode = play_mod.resolve(state, play)
+ if mode in (play_mod.ONCE_RETURN, play_mod.LIFETIME):
+ return True
+ if mode == play_mod.ONCE_HOLD:
+ return False
return state in PIN_LAST_FRAME_STATES or (state in GAIT_STATES and direction in PINNED_GAIT_VIEWS)
+
+
+def cycle_for(state: str, direction: str, play: str | None = None, *, pinned: bool | None = None) -> str:
+ """The `video-loop --cycle` that cuts the clip of (state, direction): `pinned` says whether that clip was filmed
+ ending on its first frame (None: as `pins_last_frame` films it; False: a source that could not pin it).
+
+ A state with no play mode in the request is cut as its preset: an idle or attack filmed pinned whole
+ (`pinned`), any other loop searched (`auto`, which an action state may fail over to `one-shot`). A play mode the
+ request gives is the cut's: a loop is never failed over to a single play (`periodic`), a once-return is the
+ whole clip pinned to its first frame (`once-return`) or, unpinned, the searched return (`one-shot`), a once-hold
+ is cut at its held pose (`once`) and a lifetime at its empty end (`lifetime`)."""
+ mode = play_mod.resolve(state, play)
+ pins = pins_last_frame(state, direction, play) if pinned is None else pinned
+ if mode == play_mod.LIFETIME:
+ return "lifetime"
+ if mode == play_mod.ONCE_HOLD:
+ return "once"
+ if mode == play_mod.ONCE_RETURN:
+ return "once-return" if pins else "one-shot"
+ if pins and state in PINNED_LOOP_STATES:
+ return "pinned"
+ return "auto" if play is None else "periodic"
COMMON_TEXT = (
"2D game sprite animation. The character {motion} The character is {view}. 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 "
@@ -382,6 +412,15 @@ ACTION_COMMON_TEXT = (
# How many times a caller's own motion paragraph (`build_prompt(motion=...)`) is performed, for
# states that repeat it. An attack is performed once: its pinned clip is the loop.
REPEAT_TEXT: dict[str, str] = {}
+# The sentence of a motion that has none of its own in its play mode — a state the engine does not name, or a named
+# one played another way (`play.own_sentence`): the state's word and how it plays.
+PLAY_TEXT = {
+ play_mod.LOOP: "performs the '{state}' action in place, repeating at an even rhythm.",
+ play_mod.ONCE_RETURN: "performs the '{state}' action once in place, then returns to the exact starting stance.",
+ play_mod.ONCE_HOLD: "performs the '{state}' action once and holds its final pose.",
+}
+# Said after a caller's own motion paragraph played once-return: the clip ends on its first frame.
+RETURN_TEXT = "It does this once, then returns to the exact pose of the first frame."
_start_lock = threading.Lock()
_last_start = [0.0]
@@ -397,15 +436,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,
- body_plan: list[Body] | None = None) -> str:
+ body_plan: list[Body] | None = None, play: str | 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, body_plan=body_plan).text
+ handed=handed, body_plan=body_plan, play=play).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, body_plan: list[Body] | None = None) -> prompt_parts.Prompt:
+ handed: list[Handed] | None = None, body_plan: list[Body] | None = None,
+ play: str | 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).
@@ -431,26 +471,33 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
motion sentence or the caller's paragraph, what it stands on (`body_plan.text`); a walk or run seen from behind
then says it stays square and does not sway (`BACK_GAIT_TEXT_ANY_BODY`).
+ `play` is the request's play mode (`play.MODES`; None, the state's preset). A once-hold takes the terminal
+ template (`nonloop.COMMON_TEXT`), a once-return the one-action template (`ACTION_COMMON_TEXT`) and, after a
+ caller's paragraph, `RETURN_TEXT`, a lifetime the effect's prompt (`effect.prompt`). A state's own sentence is
+ used where it films the mode (`play.own_sentence`); otherwise, without `motion`, the mode's sentence names the
+ state (`PLAY_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.
"""
validate_facing(facing)
- if state == "effect":
+ mode = play_mod.resolve(state, play)
+ if mode == play_mod.LIFETIME:
from . import effect
return prompt_parts.Prompt(effect.prompt(character, motion), caller=f"{character or ''} {motion or ''}", sep=" ")
view = VIEW_TEXT.get(direction, f"seen from the {direction}").format(facing=facing)
turned = facing if direction in handed_mod.LATERAL_VIEWS else None
- if state in nonloop.STATES:
+ if mode == play_mod.ONCE_HOLD:
template = "2D game sprite animation. The character {motion} The character is {view}. " + nonloop.COMMON_TEXT
- elif state in ACTION_TEXT_STATES:
+ elif mode == play_mod.ONCE_RETURN or state in ACTION_TEXT_STATES:
template = ACTION_COMMON_TEXT
elif (state in PINNED_LOOP_STATES or (state in GAIT_STATES and direction in PINNED_GAIT_VIEWS)) if pinned is None else pinned:
template = PINNED_LOOP_TEXT
else:
template = COMMON_TEXT
stands_on = body_mod.text(body_plan)
- if state in nonloop.STATES and body_plan:
+ if mode == play_mod.ONCE_HOLD and body_plan:
stands_on = " ".join((b.figure + ": " if b.figure else "") + nonloop.ANATOMY_TEXT.get(b.plan, "") for b in body_plan).strip()
stands_on = f" {stands_on}" if stands_on else ""
if direction == "back" and state in GAIT_STATES and not body_mod.biped(body_plan):
@@ -465,16 +512,19 @@ def clip_prompt_parts(direction: str, state: str, character: str | None, facing:
if state in GAIT_STATES and direction in GAIT_HOLD_TEXT:
hold += f" {GAIT_HOLD_TEXT[direction].format(facing=facing)}"
repeat = f" {REPEAT_TEXT[state]}" if state in REPEAT_TEXT else ""
+ if mode == play_mod.ONCE_RETURN:
+ repeat += f" {RETURN_TEXT}"
subject = character.strip().rstrip(".") if character else "The character"
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
+ built_in = (PLAY_TEXT[mode].format(state=state) if not play_mod.own_sentence(state, mode)
+ else 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 ATTACK_TEXT_ANY_BODY if state == "attack" and not body_mod.biped(body_plan)
else nonloop.MOTION_TEXT[state] if state in nonloop.STATES
- else MOTION_TEXT.get(state, f"performs the '{state}' action in place, repeating at an even rhythm."))
+ else MOTION_TEXT.get(state, PLAY_TEXT[play_mod.LOOP].format(state=state)))
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, body_plan=body_plan))
@@ -664,10 +714,15 @@ def run_item(
handed: list[Handed] | None = None,
body_plan: list[Body] | None = None,
end_frame: Path | None = None,
+ play: str | None = None,
+ motion: str | None = None,
) -> dict[str, Any]:
- if end_frame is not None and state not in nonloop.STATES:
- raise SystemExit("video-set: --end-frame requires a non-loop state")
- if state in nonloop.STATES and (fit == "tight" or anchor != "none"):
+ """One (direction, state) item, canvas to loop. `play` is the request's play mode for it (`play.MODES`; None, the
+ state's preset) and `motion` the caller's own motion text in place of the state's sentence."""
+ mode = play_mod.resolve(state, play, prog="video-set")
+ if end_frame is not None and mode != play_mod.ONCE_HOLD:
+ raise SystemExit("video-set: --end-frame requires a once-hold item (a non-loop state, or --play once-hold)")
+ if mode == play_mod.ONCE_HOLD and (fit == "tight" or anchor != "none"):
raise SystemExit("video-set: non-loop states need --fit state and --anchor none to preserve the terminal pose")
if walk_start not in WALK_START_MODES:
raise SystemExit(f"video-set: --walk-start must be one of {', '.join(WALK_START_MODES)}")
@@ -682,11 +737,16 @@ def run_item(
duration = duration_for(state, duration)
item_dir = root / item
item_dir.mkdir(parents=True, exist_ok=True)
- result: dict[str, Any] = {"item": item, "direction": direction, "state": state, "dir": str(item_dir)}
+ result: dict[str, Any] = {"item": item, "direction": direction, "state": state, "play": mode, "dir": str(item_dir)}
+ if motion is not None:
+ result["motion"] = motion
+ lifetime = mode == play_mod.LIFETIME
+ pins = pins_last_frame(state, direction, play)
if direction in handed_mod.LATERAL_VIEWS:
result["turned"] = facing
try:
- parts = clip_prompt_parts(direction, state, character, facing=facing, handed=handed, body_plan=body_plan)
+ parts = clip_prompt_parts(direction, state, character, facing=facing, motion=motion, handed=handed,
+ body_plan=body_plan, play=play)
prompt = parts.text
if parts.notes:
result["prompt_notes"] = parts.notes
@@ -703,7 +763,7 @@ def run_item(
previous = json.loads(clip_report.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise SystemExit("cannot verify cached clip prompt; use --force to regenerate") from exc
- if state in nonloop.STATES and isinstance(previous, dict) and previous.get("end_frame_sha256") != end_digest:
+ if mode == play_mod.ONCE_HOLD and isinstance(previous, dict) and previous.get("end_frame_sha256") != end_digest:
raise SystemExit("cached clip end frame differs; use --force to regenerate")
if not isinstance(previous, dict) or previous.get("prompt") != prompt:
raise SystemExit("cached clip prompt differs (including facing); use --force to regenerate")
@@ -718,7 +778,7 @@ def run_item(
raise ValueError("incomplete canvas report")
if canvas_report.get("fit", "state") != fit:
raise ValueError("cached canvas was framed with another --fit")
- if direction == "side" and state != "effect":
+ if direction == "side" and not lifetime:
prior = canvas_report.get("facing_check") or {}
if not isinstance(prior, dict):
raise ValueError("invalid cached facing")
@@ -734,13 +794,14 @@ def run_item(
still, result["walk_start"] = walk_start_still(base, direction, item_dir, key=key, force=force,
runner=redraw_runner, provider=still_provider, handed=handed,
body_plan=body_plan)
- if direction == "side" and state != "effect":
+ if direction == "side" and not lifetime:
if prepare_side is not None:
still, facing_report = prepare_side(base)
else:
still = item_dir / "facing.png"
facing_report = facing_mod.prepare_still(base, still, facing=facing, fix=facing_fix)
- canvas_report = canvas_mod.run_canvas(still, canvas_png, state=state, shape=shape, facing=facing if direction not in ("front", "back") else "right", headroom=None, lead=None, report_path=canvas_report_path, fit=fit)
+ # a lifetime is framed as an effect, whatever its name: on black, its centre kept
+ canvas_report = canvas_mod.run_canvas(still, canvas_png, state="effect" if lifetime else state, shape=shape, facing=facing if direction not in ("front", "back") else "right", headroom=None, lead=None, report_path=canvas_report_path, fit=fit)
if facing_report is not None:
canvas_report["facing_check"] = facing_report
atomic_write_text(canvas_report_path, json.dumps(canvas_report, ensure_ascii=False, indent=2) + "\n")
@@ -754,8 +815,8 @@ def run_item(
# One run of `sprite-gen video`: a 429 is sent again inside it (`gen.retry`), so a second run here
# would be a second retry loop on top of the first, each of its POSTs a request.
_staggered_start(gap)
- pin_frame = Path(canvas_report["end_frame"]) if state == "effect" else canvas_png
- pin = {"last_frame": pin_frame} if pins_last_frame(state, direction) else {}
+ pin_frame = Path(canvas_report["end_frame"]) if lifetime else canvas_png
+ pin = {"last_frame": pin_frame} if pins else {}
if end_frame is not None:
with Image.open(end_frame) as final, Image.open(canvas_png) as initial:
if final.size != initial.size or canvas_mod.corner_key(final) != canvas_mod.corner_key(initial):
@@ -763,7 +824,7 @@ def run_item(
pin = {"last_frame": end_frame}
attempts = [video_runner(canvas_png, prompt, clip, clip_report, duration=duration, resolution=resolution,
log=item_dir / "clip.log", **pin)]
- result["clip"] = {"attempts": attempts, "duration": duration, "last_frame": str(end_frame) if end_frame is not None else pins_last_frame(state, direction)}
+ result["clip"] = {"attempts": attempts, "duration": duration, "last_frame": str(end_frame) if end_frame is not None else pins}
if attempts[-1] != 0 or not clip.exists():
raise SystemExit(f"clip generation failed after {len(attempts)} attempt(s); see {item_dir / 'clip.log'}")
try: # what the clip ran on, as its report says: the Grok login or XAI_API_KEY
@@ -778,13 +839,13 @@ def run_item(
# a tight frame is clipped on purpose; leftover key background still fails. The default
# call keeps its pre-decontam signature, so a stand-in for run_frames still fits
extra = {} if decontam == "off" else {"decontam": decontam}
- if state == "effect":
+ if lifetime:
extra["alpha_mode"] = "brightness"
fr = frames_mod.run_frames(clip, item_dir / "frames", key=key, allow_edge_contact=False, report_path=item_dir / "frames.report.json", spill=spill, reference=canvas_png, allow_subject_edge_contact=fit == "tight", **extra)
result["frames"] = {k: fr[k] for k in ("fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max")}
result["frames"]["spill"] = fr.get("spill", {}).get("mode")
lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor, body_height=body_height,
- cycle_mode="lifetime" if state == "effect" else "once" if state in nonloop.STATES else "pinned" if state in PINNED_LOOP_STATES else "auto",
+ cycle_mode=cycle_for(state, direction, play, pinned=pins),
facing=facing if direction in handed_mod.LATERAL_VIEWS else "right")
result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}
result["loop"]["review_recommended"] = lp["cycle"].get("review_recommended", False)
@@ -1009,12 +1070,17 @@ def run_set(
align_feet: dict[str, str] | None = None,
body_plan: list[Body] | None = None,
end_frames: dict[str, Path] | None = None,
+ play: dict[str, str] | None = None,
+ motion: dict[str, str] | 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
asymmetric item's side into every clip prompt; it refuses `facing_fix` mirror, which would move it.
`align_feet` (`--align-foot`) maps an item of a walk or run filmed in two or more directions to the
- own foot that lands on its loop's first strike (`align_gaits`); any other item is refused up front."""
+ own foot that lands on its loop's first strike (`align_gaits`); any other item is refused up front.
+ `play` (`--play`) and `motion` (`--motion`) map a state of the set — every item of it — or one item to its play
+ mode (`play.MODES`) and to the caller's motion text (`item_values`): a motion the engine has no state for is
+ filmed under its name in that mode, a named state without one plays as its preset."""
if align_cycles not in ALIGN_MODES:
raise SystemExit(f"video-set: --align-cycles must be one of {', '.join(ALIGN_MODES)}")
if anchor == "motion-auto" and any(not loop_mod.profile_for(state).gait for state in states):
@@ -1037,11 +1103,13 @@ def run_set(
raise SystemExit(f"video-set: base still for '{direction}' not found: {base}")
# (item, direction, state, facing, base); a set filmed both ways names a lateral item's facing
items = [(f"{d}-{f}-{s}" if both and f else f"{d}-{s}", d, s, f or facings[0], b) for d, f, b in views for s in states]
+ plays = item_values(play or {}, items, "--play")
+ motions = item_values(motion or {}, items, "--motion")
+ modes = {i: play_mod.resolve(s, plays.get(i), prog="video-set") for i, _, s, _, _ in items}
for item, path in (end_frames or {}).items():
- selected = [state for name, _, state, _, _ in items if name == item]
- if not selected or selected[0] not in nonloop.STATES or not path.is_file():
- raise SystemExit(f"video-set: --end-frame {item} needs a non-loop item and an existing image")
- if any(s in nonloop.STATES for s in states) and (fit == "tight" or anchor != "none"):
+ if item not in modes or modes[item] != play_mod.ONCE_HOLD or not path.is_file():
+ raise SystemExit(f"video-set: --end-frame {item} needs a non-loop item (a once-hold) and an existing image")
+ if play_mod.ONCE_HOLD in modes.values() and (fit == "tight" or anchor != "none"):
raise SystemExit("video-set: non-loop states need --fit state and --anchor none")
aligned_items = [i for i, _, s, _, _ in items if align_cycles == "auto" and loop_mod.profile_for(s).gait
and sum(1 for _, _, s2, _, _ in items if s2 == s) >= 2]
@@ -1066,7 +1134,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, body_plan=body_plan, **({"end_frame": end_frames[i]} if end_frames and i in end_frames else {})): 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, **({"end_frame": end_frames[i]} if end_frames and i in end_frames else {}), **({"play": plays[i]} if i in plays else {}), **({"motion": motions[i]} if i in motions else {})): i for i, d, s, f, b in items}
for fut in as_completed(futures):
r = fut.result()
results.append(r)
@@ -1087,7 +1155,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_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}
+ 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 {}), **({"play": play} if play else {}), **({"motion": motion} if motion 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
@@ -1108,6 +1176,34 @@ def _parse_bases(values: list[str]) -> dict[str, Path]:
return bases
+def item_values(values: dict[str, str], items: list[tuple[str, str, str, str, Path]], flag: str) -> dict[str, str]:
+ """`values` keyed by a state of the set (every item of it) or by one item, as each item's own: an item's key wins
+ over its state's. A key that names neither is refused."""
+ names = {i for i, *_ in items}
+ states = {s for _, _, s, _, _ in items}
+ for key in values:
+ if key not in names and key not in states:
+ raise SystemExit(f"video-set: {flag} {key}=…: {key} is neither a state of the set ({', '.join(sorted(states))}) "
+ f"nor one of its items ({', '.join(sorted(names))})")
+ out = {}
+ for i, _, s, _, _ in items:
+ if i in values or s in values:
+ out[i] = values[i] if i in values else values[s]
+ return out
+
+
+def _parse_keyed(values: list[str], flag: str) -> dict[str, str]:
+ """`--play` / `--motion`: KEY=VALUE, each key once, neither side empty."""
+ result: dict[str, str] = {}
+ for value in values:
+ key, sep, text = value.partition("=")
+ key, text = key.strip(), text.strip()
+ if not sep or not key or not text or key in result:
+ raise SystemExit(f"video-set: {flag} expects each STATE=… or ITEM=… once, neither side empty, got {value!r}")
+ result[key] = text
+ return result
+
+
def _parse_end_frames(values: list[str]) -> dict[str, Path]:
result = {}
for value in values:
@@ -1125,7 +1221,16 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
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("--end-frame", action="append", default=[], metavar="ITEM=PATH", help="non-loop item: terminal-pose canvas with the same size and key as the starting canvas (repeatable)")
- parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states")
+ parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states: a named state (idle, walk, run, jump, attack, death, effect, …) films as its preset; any other word names a motion of your own, filmed with --play and --motion")
+ parser.add_argument("--play", action="append", default=[], metavar="STATE=MODE | ITEM=MODE",
+ help=f"how a state of the set (every view of it) or one item plays: {', '.join(play_mod.MODES)} "
+ "(repeatable; an item's own wins). Without it a named state plays as its preset and any other "
+ "word as a loop; with it the clip's end-frame pin, the prompt's ending, the cut and the strip's "
+ "loop/hold_last/returns follow the mode")
+ parser.add_argument("--motion", action="append", default=[], metavar="STATE=TEXT | ITEM=TEXT",
+ help="your own motion text for a state of the set (every view of it) or one item, in place of the "
+ "state's sentence, written as whole sentences about the subject, e.g. "
+ "'punch=It throws one straight punch with its front fist.' (repeatable; an item's own wins)")
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')")
parser.add_argument("--duration", type=int, default=None, help=f"seconds per clip for every state (default: {DEFAULT_DURATION_SECONDS}, attack {STATE_DURATION_SECONDS['attack']}); a repeating motion holds enough cycles at 3 s and a longer clip only costs more (2026-09-18)")
@@ -1167,6 +1272,8 @@ def run(**kwargs: object) -> int:
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]
+ play=_parse_keyed(list(kwargs.get("play") or []), "--play") or None, # type: ignore[arg-type]
+ motion=_parse_keyed(list(kwargs.get("motion") or []), "--motion") or None, # type: ignore[arg-type]
)
return 0 if not payload["failed"] else 1
diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.py
index eb8453d..531145a 100644
--- a/sprite_gen/video/clip_prompt.py
+++ b/sprite_gen/video/clip_prompt.py
@@ -12,6 +12,9 @@ image-to-video only) cannot film what `video-set` films pinned (`pins_last_frame
walk or run in a diagonal). Those are refused, or with `--unpinned` asked for as an unpinned clip,
with a warning: the prompt then asks for an evenly paced repeat (an attack still asks for one
strike), the loop is searched instead of cut whole, and it may not close.
+
+`--play` gives the play mode as `video-set --play` does (`play.MODES`): a motion of your own, named
+by `--state` and described by `--motion`, is asked for and cut as that mode says.
"""
from __future__ import annotations
@@ -27,7 +30,7 @@ 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 import nonloop
+from sprite_gen.video import play as play_mod
from sprite_gen.video.body_plan import Body
DEFAULT_MODEL = "grok-imagine-video-1.5"
@@ -37,23 +40,27 @@ 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, body_plan: list[Body] | None = None, end_frame: Path | None = None) -> dict[str, Any]:
+ handed: list[Handed] | None = None, body_plan: list[Body] | None = None, end_frame: Path | None = None,
+ play: str | 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;
- `body_plan` (`body_plan.parse_all`) what the subject stands on, as `video-set --body-plan` does."""
+ `body_plan` (`body_plan.parse_all`) what the subject stands on, as `video-set --body-plan` does; `play` the play
+ mode (`play.MODES`; None, the state's preset), as `video-set --play` 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:
raise SystemExit(f"video-prompt: --key must be one of {', '.join(START_STILL_KEYS)}, got {key!r}")
if unpinned and last_frame:
raise SystemExit("video-prompt: --unpinned goes with --no-last-frame (a source that can pin the end frame films it pinned)")
+ mode = play_mod.resolve(state, play, prog="video-prompt")
+ lifetime = mode == play_mod.LIFETIME
if end_frame is not None:
- if state not in nonloop.STATES:
- raise SystemExit("video-prompt: --end-frame requires a non-loop state")
+ if mode != play_mod.ONCE_HOLD:
+ raise SystemExit("video-prompt: --end-frame requires a once-hold motion (a non-loop state, or --play once-hold)")
if not last_frame:
raise SystemExit("video-prompt: this source cannot pin an end frame")
- wants_pin = batch_mod.pins_last_frame(state, direction)
- if state == "effect" and not last_frame:
+ wants_pin = batch_mod.pins_last_frame(state, direction, play)
+ if lifetime and not last_frame:
raise SystemExit("video-prompt: an effect requires an empty black end-frame pin; this source cannot pin it")
warnings: list[str] = []
pinned: bool | None = None
@@ -65,34 +72,37 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
"to film it without the pin: the prompt then asks for an evenly paced repeat (an attack for one strike), "
"the loop is searched instead of cut whole, and it may not close.")
pinned = False
- warnings.append(f"{direction} {state} filmed without its end-frame pin: the loop is searched, not cut whole, and may not close")
+ cut = "loop" if mode == play_mod.LOOP else "return"
+ warnings.append(f"{direction} {state} filmed without its end-frame pin: the {cut} 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, body_plan=body_plan)
+ model=model, handed=handed, body_plan=body_plan, play=play)
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 = "lifetime" if state == "effect" else "once" if state in nonloop.STATES else "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"
+ cycle = batch_mod.cycle_for(state, direction, play, pinned=pins)
# 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, body_plan)
still = "<dir>/walk-start.png" if mid_step else "<still.png>"
duration = batch_mod.duration_for(state, duration)
- end = f", end frame {end_frame}" if end_frame is not None else (", end frame <dir>/canvas.end.png" if state == "effect" else ", end frame <dir>/canvas.png") if pins else ""
+ end = f", end frame {end_frame}" if end_frame is not None else (", end frame <dir>/canvas.end.png" if lifetime else ", end frame <dir>/canvas.png") if pins else ""
record: dict[str, Any] = {
"kind": "sprite-gen-video-prompt",
"direction": direction,
"state": state,
+ "play": mode,
"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,
- "last_frame": str(end_frame) if end_frame is not None else ("black" if state == "effect" else "canvas") if pins else None,
+ "last_frame": str(end_frame) if end_frame is not None else ("black" if lifetime else "canvas") if pins else None,
"cycle": cycle,
"commands": {
- "canvas": f"sprite-gen video-canvas --still {still} --state {state} --facing {canvas_facing} --out <dir>/canvas.png --report <dir>/canvas.report.json",
+ # a lifetime is framed as an effect, whatever its name
+ "canvas": f"sprite-gen video-canvas --still {still} --state {'effect' if lifetime else state} --facing {canvas_facing} --out <dir>/canvas.png --report <dir>/canvas.report.json",
"clip": f"your video tool, not sprite-gen: image-to-video from <dir>/canvas.png with this prompt, {duration} s{end}, saved as <dir>/clip.mp4",
"frames": "sprite-gen video-frames --clip <dir>/clip.mp4 --out-dir <dir>/frames --spill auto --reference <dir>/canvas.png",
"loop": f"sprite-gen video-loop --frames-dir <dir>/frames/keyed --out-dir <dir>/loop --fps <fps in frames.report.json> --state {state} --cycle {cycle} --facing {loop_facing} --name {direction}-{state}",
@@ -100,7 +110,7 @@ def plan_prompt(*, direction: str, state: str, facing: str = "right", character:
"warnings": warnings,
**({"notes": parts.notes} if parts.notes else {}),
}
- if state == "effect":
+ if lifetime:
record["commands"]["frames"] = "sprite-gen video-frames --clip <dir>/clip.mp4 --out-dir <dir>/frames --alpha-mode brightness"
record["blend"] = "add"
needs = handed_mod.first_frame_needs(handed or [], direction, canvas_facing if direction in handed_mod.LATERAL_VIEWS else None,
@@ -124,6 +134,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
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("--play", choices=play_mod.MODES, help="how the motion plays (default: the state's preset; a word that is no named state, a loop): the end-frame pin, the prompt's ending and the video-loop --cycle follow it, as video-set --play")
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"clip model the prompt is for (default {DEFAULT_MODEL}); a Lite model calms a walk")
parser.add_argument("--duration", type=int, help="seconds to ask for (default: the state's own, as video-set)")
parser.add_argument("--end-frame", type=Path, help="non-loop terminal-pose canvas to pin instead of returning to the starting image")
@@ -135,7 +146,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
def run(**kwargs: object) -> int:
record = plan_prompt(
- end_frame=kwargs.get("end_frame"),
+ end_frame=kwargs.get("end_frame"), play=kwargs.get("play"), # type: ignore[arg-type]
direction=str(kwargs["direction"]), state=str(kwargs["state"]), facing=str(kwargs.get("facing") or "right"),
character=kwargs.get("character"), motion=kwargs.get("motion"), # type: ignore[arg-type]
model=str(kwargs.get("model") or DEFAULT_MODEL), last_frame=not kwargs.get("no_last_frame"),
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 3003cbf..a1039dd 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -559,6 +559,24 @@ def pinned_cycle(D: np.ndarray, *, seam_max: float) -> dict[str, Any]:
"pin_tolerance": max(seam_max * inner, PIN_NOISE_MAX), "period_global": None, "periodicity": None}
+def once_return_cycle(D: np.ndarray, *, seam_max: float) -> dict[str, Any]:
+ """The whole clip played once, for a clip pinned to end on its first frame (`--cycle once-return`).
+
+ Every frame is kept, the last too: the strip starts on the first pose and ends on it again, so a game plays it
+ once and goes on from the pose it started in. The gate is the pin, as `pinned_cycle`'s: the last frame is the
+ first again within `seam_max` ordinary steps or the re-render noise. The motion's peak is its largest step,
+ as a `once` cut's (`nonloop.select_cut`).
+ """
+ n = D.shape[0]
+ steps = np.diag(D, 1)
+ inner = float(steps.mean())
+ pin_error = float(D[n - 1, 0])
+ return {"kind": "once-return", "start": 0, "length": n, "end_frame": n - 1, "event_frame": int(np.argmax(steps)) + 1,
+ "seam": pin_error, "inner_mean_adjacent": inner, "pin_error": pin_error,
+ "pin_tolerance": max(seam_max * inner, PIN_NOISE_MAX), "period_global": None, "periodicity": None,
+ "ratio": 0.0, "review_recommended": False}
+
+
def _scrub(image: Image.Image) -> int:
px = image.load()
n = 0
@@ -1305,6 +1323,8 @@ def run_loop(
cycle = _one_shot(D, window, hi, masses)
elif cycle_mode == "pinned":
cycle = pinned_cycle(D, seam_max=seam_max)
+ elif cycle_mode == "once-return":
+ cycle = once_return_cycle(D, seam_max=seam_max)
else:
gait_floor = round(prof.min_seconds * fps) if prof.gait and prof.min_seconds > 0 else None
cycle = detect_cycle(D, min_len=lo, max_len=hi, gait_floor=gait_floor,
@@ -1582,11 +1602,12 @@ def run_loop(
delay_ms = max(20, round(1000 * cycle_seconds / n_out))
gif_path = out_dir / f"{name}.gif"
webp_path = out_dir / f"{name}.webp"
- if cycle["kind"] == "pinned":
+ if cycle["kind"] in ("pinned", "once-return"):
if cycle["pin_error"] > cycle["pin_tolerance"]:
+ what = "the loop does not close" if cycle["kind"] == "pinned" else "it does not return to its first pose"
error = (
- f"video-loop: the pinned clip does not end on its first frame (pin error {cycle['pin_error']:.4f} "
- f"exceeds {cycle['pin_tolerance']:.4f}); the loop does not close — regenerate the clip with "
+ f"video-loop: the {cycle['kind']} clip does not end on its first frame (pin error {cycle['pin_error']:.4f} "
+ f"exceeds {cycle['pin_tolerance']:.4f}); {what} — regenerate the clip with "
"--last-frame set to its first frame"
)
write_loop_report(target, {**report_base, "status": "failed", "error": error, "cycle": cycle,
@@ -1665,7 +1686,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--n-out", type=int, help="frames in the GIF/WebP (default: cycle seconds x --gif-fps)")
parser.add_argument("--gif-fps", type=float, default=GIF_FPS_DEFAULT, help=f"GIF/WebP playback density (default {GIF_FPS_DEFAULT:g}); every state plays at this rate regardless of cycle length")
parser.add_argument("--seam-max", type=float, default=SEAM_RATIO_MAX, help=f"loop seam gate (default {SEAM_RATIO_MAX})")
- parser.add_argument("--cycle", choices=CYCLE_MODES, default="auto", help="once: a performed action ending in a stable held pose, with no return or seam gate; auto: non-loop states use once, otherwise periodic first, one-shot failover for action states (recorded in the report); periodic / one-shot force one detector; fixed cuts exactly --start/--length (no detection, reported as kind=fixed); pinned: the whole clip but its last frame, for a clip pinned to end on its first frame (the gate is that pin)")
+ parser.add_argument("--cycle", choices=CYCLE_MODES, default="auto", help="once: a performed action ending in a stable held pose, with no return or seam gate; auto: non-loop states use once, otherwise periodic first, one-shot failover for action states (recorded in the report); periodic / one-shot force one detector; fixed cuts exactly --start/--length (no detection, reported as kind=fixed); pinned: the whole clip but its last frame, for a clip pinned to end on its first frame (the gate is that pin); once-return: the whole clip with its last frame, played once from its first pose back to it (loop false, returns true), for a clip pinned to end on its first frame (the gate is that pin)")
parser.add_argument("--start", type=int, help="fixed cut: first keyed frame of the cycle (with --cycle fixed)")
parser.add_argument("--length", type=int, help="fixed cut: cycle length in frames (with --cycle fixed)")
parser.add_argument("--strip-height", type=int, default=STRIP_MAX_HEIGHT, help=f"cell/strip/GIF height cap in px (default {STRIP_MAX_HEIGHT}); the cycle is scaled down to fit, and never up unless --body-height asks for it")
diff --git a/sprite_gen/video/nonloop.py b/sprite_gen/video/nonloop.py
index 40f40fb..363c9ff 100644
--- a/sprite_gen/video/nonloop.py
+++ b/sprite_gen/video/nonloop.py
@@ -7,7 +7,9 @@ from typing import Any, Callable
from sprite_gen._deps import np
-KINDS = ("once", "lifetime")
+# Cuts played once: `once` ends held on its terminal pose, `lifetime` on an empty frame, `once-return` back on its
+# first pose (a clip pinned to end on its first frame, kept whole, `loop.once_return_cycle`).
+KINDS = ("once", "lifetime", "once-return")
MOTION_TEXT = {'death': 'collapses directly onto the ground, settles into a completely prone position, and remains '
'lying entirely motionless for the final 0.4 seconds without shifting, rising, or returning '
'to the starting posture.',
@@ -132,8 +134,11 @@ def samples(length: int, count: int) -> list[int]:
def metadata(cycle: dict[str, Any], indices: list[int]) -> dict[str, Any]:
+ """A single play's strip metadata: it plays once (`loop: false`); a `once` cut holds its last cell (`hold_last`),
+ and a `once-return` cut starts and ends on its first pose (`returns`)."""
event = cycle["event_frame"] - cycle["start"]
- return {"loop": False, "hold_last": cycle["kind"] == "once", "end_frame": len(indices) - 1,
+ return {"loop": False, "hold_last": cycle["kind"] == "once", **({"returns": True} if cycle["kind"] == "once-return" else {}),
+ "end_frame": len(indices) - 1,
"events": [{"frame": min(range(len(indices)), key=lambda k: abs(indices[k] - event)),
"name": "motion_peak"}]}
diff --git a/sprite_gen/video/play.py b/sprite_gen/video/play.py
new file mode 100644
index 0000000..4f779b3
--- /dev/null
+++ b/sprite_gen/video/play.py
@@ -0,0 +1,56 @@
+# SPDX-License-Identifier: Apache-2.0
+"""How a motion plays — a request value, not a state's name.
+
+`loop` repeats; `once-return` plays once and ends on its first pose; `once-hold` plays once and holds its last pose;
+`lifetime` is an effect that appears and is gone. A named state is a preset: it plays as `preset` says when the
+request names no mode, and its own sentence, canvas row and cut are the engine's as before. A motion the engine has
+no state for is filmed under the caller's name for it, in the mode the request gives, with the caller's motion text
+or the mode's own sentence (`batch.PLAY_TEXT`). The mode decides whether the clip is pinned to end on its first
+frame (`batch.pins_last_frame`), what the prompt asks of the ending (`batch.clip_prompt_parts`), how the clip is cut
+(`batch.cycle_for`) and what the strip's metadata says (`loop`, `hold_last`, `returns`).
+"""
+
+from __future__ import annotations
+
+from sprite_gen.video import effect, nonloop
+
+LOOP, ONCE_RETURN, ONCE_HOLD, LIFETIME = MODES = ("loop", "once-return", "once-hold", "lifetime")
+# The modes a named state's own sentence films beyond its preset: the attack's — one strike, then a recovery to the
+# exact starting stance, filmed pinned to its first frame — is a once-return as it stands.
+ALSO_FILMS = {"attack": ONCE_RETURN}
+
+
+def fixed(state: str) -> str | None:
+ """The one mode a state plays in by its nature, or None: an effect lives and is gone, a terminal state
+ (`nonloop.STATES`) holds its last pose, and a cyclic one (`nonloop.CYCLIC_STATES`) repeats."""
+ if state == effect.STATE:
+ return LIFETIME
+ if state in nonloop.STATES:
+ return ONCE_HOLD
+ if state in nonloop.CYCLIC_STATES:
+ return LOOP
+ return None
+
+
+def preset(state: str) -> str:
+ """How a state plays when the request names no mode: its fixed mode, otherwise a loop."""
+ return fixed(state) or LOOP
+
+
+def resolve(state: str, play: str | None, *, prog: str = "video") -> str:
+ """The mode `state` is filmed in: `play` when the request gives one, else the state's preset. A mode that is not
+ one of `MODES`, or one a state of a fixed mode cannot play, is refused."""
+ if play is None:
+ return preset(state)
+ if play not in MODES:
+ raise SystemExit(f"{prog}: a play mode is one of {', '.join(MODES)}, got {play!r}")
+ own = fixed(state)
+ if own is not None and play != own:
+ raise SystemExit(f"{prog}: {state} plays {own} only, not {play}; film the other motion under a name of its "
+ f"own with play mode {play}")
+ return play
+
+
+def own_sentence(state: str, mode: str) -> bool:
+ """Whether `state`'s own sentence films `mode`: its preset, or the mode `ALSO_FILMS` names for it."""
+ return mode == preset(state) or ALSO_FILMS.get(state) == mode
diff --git a/tests/video/test_clip_prompt.py b/tests/video/test_clip_prompt.py
index 4ce4a28..625f348 100644
--- a/tests/video/test_clip_prompt.py
+++ b/tests/video/test_clip_prompt.py
@@ -62,6 +62,7 @@ def test_an_item_films_its_play_mode_and_motion_text_once_back_to_its_first_pose
return {"fps": 24.0, "frames": 36, "alpha_zero_pct_min": 0, "alpha_zero_pct_max": 0, "keyed_dir": str(keyed)}
monkeypatch.setattr(batch_mod.frames_mod, "run_frames", frames_stub)
+ monkeypatch.setattr(batch_mod.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
root = tmp_path / "set"
report = batch_mod.run_set(bases={"side": base}, states=["punch"], root=root, character=None, duration=None,
resolution="480p", key="green", concurrency=1, force=False, gap=0, video_runner=video_stub,
diff --git a/tests/video/test_play.py b/tests/video/test_play.py
new file mode 100644
index 0000000..e95fd70
--- /dev/null
+++ b/tests/video/test_play.py
@@ -0,0 +1,239 @@
+# SPDX-License-Identifier: Apache-2.0
+"""How a motion plays is a request value (`video-set --play`, `video-prompt --play`, `sprite_gen.video.play`): a
+named state the request gives no mode plays as its preset, exactly as before; a mode the request gives decides the
+end-frame pin, the prompt's ending, the cut and the strip's metadata, whatever the motion is called. Synthetic
+fixtures only."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from sprite_gen.video import batch, clip_prompt, effect, loop, nonloop, play
+from test_clip_prompt import PUNCH, punch_frames
+
+# state -> (preset, pinned seen from the side, cut): the engine as it was before play modes, by state name alone.
+PRESETS = {
+ "idle": ("loop", True, "pinned"),
+ "walk": ("loop", False, "auto"),
+ "run": ("loop", False, "auto"),
+ "jump": ("loop", False, "auto"),
+ "attack": ("loop", True, "pinned"),
+ "cheer": ("loop", False, "auto"),
+ "wave": ("loop", False, "auto"),
+ "dance": ("loop", False, "auto"),
+ **{state: ("once-hold", False, "once") for state in nonloop.STATES},
+ "effect": ("lifetime", True, "lifetime"),
+}
+
+
[email protected]("state", sorted(PRESETS))
+def test_a_named_state_with_no_mode_plays_as_its_preset(state) -> None:
+ mode, pinned, cut = PRESETS[state]
+ assert play.preset(state) == mode and play.resolve(state, None) == mode
+ assert batch.pins_last_frame(state, "side") is pinned and batch.cycle_for(state, "side") == cut
+ for direction in ("side", "front", "back_diagonal"):
+ assert batch.build_prompt(direction, state, "The knight") == batch.build_prompt(direction, state, "The knight", play=mode)
+ assert (batch.build_prompt(direction, state, None, motion="It moves.")
+ == batch.build_prompt(direction, state, None, motion="It moves.", play=mode))
+ assert batch.pins_last_frame(state, direction) == batch.pins_last_frame(state, direction, mode)
+ # the preset named in the request cuts the same, except that a loop asked for is never failed over to a single play
+ assert batch.cycle_for(state, "side", mode) == ("periodic" if cut == "auto" else cut)
+ record = clip_prompt.plan_prompt(direction="side", state=state)
+ assert record["play"] == mode and record["cycle"] == cut
+
+
+def test_a_pinned_gait_keeps_its_searched_cut() -> None:
+ assert batch.pins_last_frame("walk", "back_diagonal") and batch.cycle_for("walk", "back_diagonal") == "auto"
+ assert batch.cycle_for("walk", "back_diagonal", "loop") == "periodic"
+
+
[email protected]("state,mode", [("effect", "loop"), ("death", "once-return"), ("hurt_hold", "loop"),
+ ("walk", "once-hold"), ("idle", "lifetime"), ("run", "once-return"),
+ ("punch", "bounce"), ("punch", "once")])
+def test_a_mode_a_state_cannot_play_is_refused(state, mode) -> None:
+ with pytest.raises(SystemExit, match="play mode is one of" if mode in ("bounce", "once") else f"{state} plays"):
+ play.resolve(state, mode)
+ with pytest.raises(SystemExit):
+ clip_prompt.plan_prompt(direction="side", state=state, play=mode)
+
+
+def test_once_return_is_asked_for_pinned_and_cut_whole() -> None:
+ record = clip_prompt.plan_prompt(direction="side", state="punch", play="once-return", motion=PUNCH, character="The boxer")
+ assert record["play"] == "once-return" and record["cycle"] == "once-return" and record["last_frame"] == "canvas"
+ assert "end frame <dir>/canvas.png" in record["commands"]["clip"] and "--cycle once-return" in record["commands"]["loop"]
+ prompt = record["prompt"]
+ assert prompt.startswith(f"2D game sprite animation. {PUNCH} {batch.RETURN_TEXT} The boxer is seen from the exact side")
+ assert prompt.endswith("Crisp, clean frames with no motion blur, no smears and no afterimages.")
+ assert "evenly paced" not in prompt and "loops" not in prompt
+ # no text of its own: the mode's sentence names the motion
+ plain = clip_prompt.plan_prompt(direction="side", state="punch", play="once-return")["prompt"]
+ assert "performs the 'punch' action once in place, then returns to the exact starting stance." in plain
+ # a source with no end frame films it only when asked, and then searches the return
+ with pytest.raises(SystemExit, match="no end frame"):
+ clip_prompt.plan_prompt(direction="side", state="punch", play="once-return", last_frame=False)
+ unpinned = clip_prompt.plan_prompt(direction="side", state="punch", play="once-return", last_frame=False, unpinned=True)
+ assert unpinned["cycle"] == "one-shot" and unpinned["last_frame"] is None
+ assert "the return is searched" in unpinned["warnings"][0]
+
+
+def test_an_attack_played_once_return_is_the_attack_it_always_filmed() -> None:
+ for direction in ("side", "front"):
+ assert batch.build_prompt(direction, "attack", None, play="once-return") == batch.build_prompt(direction, "attack", None)
+ assert batch.pins_last_frame("attack", "side", "once-return")
+ assert batch.cycle_for("attack", "side", "once-return") == "once-return" and batch.cycle_for("attack", "side") == "pinned"
+
+
+def test_a_named_state_played_another_way_takes_the_modes_sentence() -> None:
+ cheer = batch.build_prompt("side", "cheer", None, play="once-return")
+ assert "performs the 'cheer' action once in place" in cheer and "repeating" not in cheer
+ assert batch.build_prompt("side", "jump", None, play="once-hold").count("performs the 'jump' action once and holds its final pose.") == 1
+
+
+def test_once_hold_is_cut_at_its_held_pose() -> None:
+ record = clip_prompt.plan_prompt(direction="side", state="block", play="once-hold", motion="It raises its shield and holds it.",
+ end_frame=Path("blocked.png"))
+ assert record["cycle"] == "once" and record["last_frame"] == "blocked.png"
+ assert "It raises its shield and holds it." in record["prompt"] and nonloop.COMMON_TEXT in record["prompt"]
+ assert not batch.pins_last_frame("block", "side", "once-hold")
+ with pytest.raises(SystemExit, match="once-hold"):
+ clip_prompt.plan_prompt(direction="side", state="block", play="once-return", end_frame=Path("blocked.png"))
+
+
+def test_lifetime_is_filmed_as_an_effect_whatever_its_name() -> None:
+ text = "A white crescent arcs from left to right."
+ record = clip_prompt.plan_prompt(direction="front", state="slash", play="lifetime", motion=text, character="A white slash")
+ assert record["prompt"] == effect.prompt("A white slash", text)
+ assert record["cycle"] == "lifetime" and record["last_frame"] == "black" and record["blend"] == "add"
+ assert "--state effect" in record["commands"]["canvas"] and "--alpha-mode brightness" in record["commands"]["frames"]
+ assert "--state slash --cycle lifetime" in record["commands"]["loop"]
+
+
+def test_a_loop_asked_for_is_searched_as_a_loop_with_the_callers_text() -> None:
+ prompt = batch.build_prompt("side", "type_at_desk", None, play="loop", motion="It types at a desk.")
+ assert prompt.startswith("2D game sprite animation. It types at a desk. The character is seen from the exact side")
+ assert prompt.endswith("Consistent, evenly paced motion so the animation loops.")
+ assert batch.cycle_for("type_at_desk", "side", "loop") == "periodic" and batch.cycle_for("type_at_desk", "side") == "auto"
+
+
+def stub_set(tmp_path, monkeypatch, *, bases, states, **kwargs):
+ """`run_set` with every stage but the item's own choices stubbed: what each item asked for, and how it was cut."""
+ seen: dict[str, dict] = {}
+
+ def video_stub(image, prompt, out, report, **kw):
+ seen.setdefault(out.parent.name, {}).update(prompt=prompt, last_frame=kw.get("last_frame"))
+ out.write_bytes(b"clip")
+ report.write_text(json.dumps({"prompt": prompt}))
+ return 0
+
+ def frames_stub(clip, out, **kw):
+ seen.setdefault(clip.parent.name, {})["alpha_mode"] = kw.get("alpha_mode")
+ return {"fps": 24, "frames": 24, "alpha_zero_pct_min": 0, "alpha_zero_pct_max": 0, "keyed_dir": str(out)}
+
+ def loop_stub(frames, out, **kw):
+ seen.setdefault(out.parent.name, {})["cycle"] = kw["cycle_mode"]
+ return {"cycle": {"kind": kw["cycle_mode"], "length": 24, "period_global": None, "ratio": 0},
+ "resampled_seam_ratio": None, "n_out": 24, "gif": {"file": "g"}, "webp": {"file": "w"}, "strip": {"path": "s"}}
+
+ monkeypatch.setattr(batch.frames_mod, "run_frames", frames_stub)
+ monkeypatch.setattr(batch.loop_mod, "run_loop", loop_stub)
+ monkeypatch.setattr(batch.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
+ report = batch.run_set(bases=bases, states=states, root=tmp_path / "set", character=None, duration=None, resolution="480p",
+ key="green", concurrency=1, force=False, gap=0, video_runner=video_stub, align_cycles="off", **kwargs)
+ return report, seen
+
+
+def still(path: Path) -> Path:
+ im = Image.new("RGB", (96, 96), (0, 255, 0))
+ ImageDraw.Draw(im).rectangle((40, 20, 56, 86), fill=(200, 80, 30))
+ im.save(path)
+ return path
+
+
+def test_video_set_takes_a_mode_and_a_text_per_state_or_per_item(tmp_path, monkeypatch) -> None:
+ bases = {"side": still(tmp_path / "side.png"), "front": still(tmp_path / "front.png")}
+ report, seen = stub_set(tmp_path, monkeypatch, bases=bases, states=["punch", "jump", "idle", "slash"],
+ play={"punch": "once-return", "jump": "loop", "slash": "lifetime"},
+ motion={"punch": PUNCH, "front-punch": "It punches straight at the viewer.", "slash": "A slash."})
+ assert report["ok"] == 8, [r.get("error") for r in report["items"]]
+ assert PUNCH in seen["side-punch"]["prompt"] and "straight at the viewer" in seen["front-punch"]["prompt"]
+ assert {item: seen[item]["cycle"] for item in ("side-punch", "side-jump", "side-idle", "side-slash")} == {
+ "side-punch": "once-return", "side-jump": "periodic", "side-idle": "pinned", "side-slash": "lifetime"}
+ assert seen["side-punch"]["last_frame"].name == "canvas.png" and seen["side-jump"]["last_frame"] is None
+ assert seen["side-slash"]["last_frame"].name == "canvas.end.png" and seen["side-slash"]["alpha_mode"] == "brightness"
+ assert seen["side-slash"]["prompt"] == effect.prompt(None, "A slash.")
+ rows = {r["item"]: r for r in report["items"]}
+ assert rows["side-idle"]["play"] == "loop" and "motion" not in rows["side-idle"]
+ assert rows["front-punch"]["motion"] == "It punches straight at the viewer."
+ assert report["play"] == {"punch": "once-return", "jump": "loop", "slash": "lifetime"}
+
+
[email protected]("kwargs,match", [
+ ({"play": {"kick": "loop"}}, "--play kick"),
+ ({"motion": {"side-kick": "It kicks."}}, "--motion side-kick"),
+ ({"play": {"death": "loop"}}, "death plays once-hold only"),
+ ({"play": {"punch": "once-return"}, "anchor": "feet", "end_frames": {"side-punch": Path("x.png")}}, "once-hold"),
+])
+def test_video_set_refuses_a_bad_mode_or_key_before_any_clip(tmp_path, monkeypatch, kwargs, match) -> None:
+ called = []
+ monkeypatch.setattr(batch, "run_item", lambda **kw: called.append(kw))
+ with pytest.raises(SystemExit, match=match):
+ batch.run_set(bases={"side": still(tmp_path / "side.png")}, states=["punch", "death"], root=tmp_path / "set",
+ character=None, duration=None, resolution="480p", key="green", concurrency=1, force=False, gap=0, **kwargs)
+ assert called == []
+
+
[email protected]("values", [["punch"], ["punch="], ["=once-return"], ["punch=loop", "punch=once-return"]])
+def test_keyed_values_are_one_key_and_one_value_each(values) -> None:
+ with pytest.raises(SystemExit, match="--play expects"):
+ batch._parse_keyed(values, "--play")
+ assert batch._parse_keyed(["punch = once-return", "side-punch=It punches = hard."], "--play") == {
+ "punch": "once-return", "side-punch": "It punches = hard."}
+
+
+def cut(tmp_path: Path, frames: Path) -> dict:
+ return loop.run_loop(frames, tmp_path / "out", fps=24, state="punch", min_len=None, max_len=None, n_out=None,
+ seam_max=loop.SEAM_RATIO_MAX, name="punch", report_path=None, cycle_mode="once-return")
+
+
+def test_a_once_return_that_does_not_come_back_is_refused(tmp_path) -> None:
+ frames = punch_frames(tmp_path / "frames", (96, 96))
+ reached = Image.open(frames / "frame-0017.png")
+ for k in range(30, 36):
+ reached.save(frames / f"frame-{k:04d}.png")
+ with pytest.raises(SystemExit, match="does not return to its first pose"):
+ cut(tmp_path, frames)
+ assert json.loads((tmp_path / "out" / "punch.loop.report.json").read_text())["status"] == "failed"
+
+
+def test_a_once_return_cut_keeps_both_ends_and_plays_once(tmp_path) -> None:
+ report = cut(tmp_path, punch_frames(tmp_path / "frames", (96, 96), count=90))
+ meta = report["strip"]
+ assert report["cycle"]["kind"] == "once-return" and report["cycle"]["length"] == 90
+ assert meta["loop"] is False and meta["hold_last"] is False and meta["returns"] is True
+ # subsampled to the cell cap, the strip still starts and ends on the clip's first and last frames
+ assert meta["subsampled"] and meta["source_cut"]["samples"][0] == 0 and meta["source_cut"]["samples"][-1] == 89
+ assert 0 <= meta["events"][0]["frame"] <= meta["end_frame"] == meta["frames"] - 1
+ for suffix, repeat in (("gif", None), ("webp", 1)):
+ with Image.open(tmp_path / "out" / f"punch.{suffix}") as im:
+ assert im.info.get("loop") == repeat
+ with pytest.raises(SystemExit, match="cyclic state walk"):
+ loop.run_loop(tmp_path / "frames" / "keyed", tmp_path / "walk", fps=24, state="walk", min_len=None, max_len=None,
+ n_out=None, seam_max=2, name="walk", report_path=None, cycle_mode="once-return")
+
+
+def test_the_clis_take_the_play_mode(tmp_path) -> None:
+ out = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "video-prompt", "--direction", "side", "--state", "punch",
+ "--play", "once-return", "--motion", PUNCH, "--json"], capture_output=True, text=True)
+ assert out.returncode == 0, out.stderr
+ record = json.loads(out.stdout)
+ assert record["play"] == "once-return" and record["cycle"] == "once-return" and PUNCH in record["prompt"]
+ refused = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "video-set", "--base", f"side={still(tmp_path / 's.png')}",
+ "--states", "death", "--play", "death=loop", "--out-dir", str(tmp_path / "set")],
+ capture_output=True, text=True)
+ assert refused.returncode != 0 and "death plays once-hold only" in refused.stderr