Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video): a clip made by a video MCP on the agent (ZCRE) becomes a loop — video-prompt out, the mp4 into video-frames
Soohong Kim59bd8657dd87
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a8fa3b..7a9cc48 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased - A clip made by a video MCP on your agent (ZCRE) becomes a loop: the prompt comes out, the mp4 goes in++- **New `sprite-gen video-prompt`** prints the clip prompt `video-set` sends for one (direction, state) — `build_prompt` with `--character`, `--motion` and `--model` — so an agent that makes the clip itself, with a video MCP connected to it, sends the same sentence. `--json` adds the duration (the state's own), whether the clip ends on the canvas (`last_frame`), the loop cut (`cycle`), the canvas, clip, frames and loop steps with placeholders, and for a front or back walk the mid-step redraw (`start_still`). sprite-gen never calls the MCP: the agent uploads the `video-canvas` still, quotes, asks the user, generates and saves the mp4, and `video-frames` and `video-loop` take it from there. [docs/video-pipeline.md](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre).+- **ZCRE (지크) is that route's first source**: its remote MCP, signed in with your own ZCRE account and credits, has `grok-imagine-video-1.5` (Grok Imagine Pro) for image-to-video, with no end frame and no Lite model. `--no-last-frame` refuses what `video-set` films pinned — idle, attack, a walk or run in a diagonal — and `--unpinned` films one anyway with a warning (the loop is searched instead of cut whole and may not close). Walk, run and jump from the side, front and back are supported.+- **`video-frames` reads the picture of a clip that carries more**: it takes the first video stream that is not a cover image (`attached_pic`, `stream_index`), and records `codec`, `pix_fmt`, `audio_streams` and `cover_streams`. A ZCRE clip always has an AAC track and an mjpeg cover; the audio is never extracted and the loop outputs carry no sound.+- Measured once end to end: one side walk, 720p 3 s, 52 credits, 33.6 s to generate; the clip was 960×960 H.264 `yuv420p` with an AAC track and a cover, and it cut to a periodic 20-frame loop.+## v2.20.0 - A keyed picture is scaled without a light rim or a green tint at the edge wherever the engine scales one: a row frame, a sliced sheet, a scene layer- **The places that scaled a keyed picture with LANCZOS now use the loop's resample** (`resize_cell`, now in `sprite_gen/util/resample.py`): a row frame shrunk into its cell (`extract`, `fit.resample: lanczos`, the default), the plain and original-quality twins beside a pixel-unfake frame (`.plain.png`, `orig/`), a sliced sheet's figures (`slice-sheet`) and a scene's layers (`scene-render`). Each used LANCZOS over premultiplied RGBA and drew the same lighter rim and key tint at the edge as the loop's strip did before 2.19.0. On the synthetic outlined figure (`tests/keyed_figure.py`), LANCZOS left 137 pixels at 0.2x, 543 at 0.5x, 978 at 0.75x and 7,315 at 2x with a colour none of the source pixels under them had; none are left at any of them. `fit.resample: lanczos` keeps its name and stays the smooth shrink (coverage is still LANCZOS); `nearest`, `kcentroid` and pixel-unfake frames are unchanged, and a picture at its own size is copied as it is. Colour is no longer sharpened, so a scaled scene layer with no transparency (a painted background) is a little softer than LANCZOS drew it. A tween's scale (`normalize_tween_scale`) is left on LANCZOS: it scales an opaque canvas before the key is removed, where there is no coverage to divide by. [docs/video-pipeline.md](docs/video-pipeline.md), [docs/pixel-unfake.md](docs/pixel-unfake.md), [docs/sheet-slicing.md](docs/sheet-slicing.md), [docs/scene.md](docs/scene.md).diff --git a/README.es.md b/README.es.mdindex 73046d2..3480833 100644--- a/README.es.md+++ b/README.es.md@@ -112,6 +112,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# por elemento: video-canvas → video → video-frames → video-loop; set/table.md nombra cada resultado```+¿Generas clips con un MCP de vídeo conectado a tu agente? Con el de ZCRE (지크), el agente crea el clip con tu propia cuenta de ZCRE y sprite-gen lo recorta: `sprite-gen video-prompt --direction side --state walk --no-last-frame` imprime el prompt, y `video-frames` y `video-loop` reciben el mp4. Solo caminar, correr y saltar, porque Grok Imagine 1.5 de ZCRE no tiene fotograma final ([cómo](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+**C · utilidades** — cada una funciona por su cuenta.```bashdiff --git a/README.fr.md b/README.fr.mdindex 8875a6f..29dd3a7 100644--- a/README.fr.md+++ b/README.fr.md@@ -112,6 +112,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# par élément : video-canvas → video → video-frames → video-loop ; set/table.md nomme chaque résultat```+Vous générez vos clips avec un MCP vidéo connecté à votre agent ? Avec celui de ZCRE (지크), l'agent crée le clip sur votre propre compte ZCRE et sprite-gen le découpe : `sprite-gen video-prompt --direction side --state walk --no-last-frame` affiche le prompt, puis `video-frames` et `video-loop` prennent le mp4. Marche, course et saut uniquement, car Grok Imagine 1.5 de ZCRE n'a pas d'image de fin ([comment](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+**C · utilitaires** — chacun est autonome.```bashdiff --git a/README.ja.md b/README.ja.mdindex 24d83bf..44d2294 100644--- a/README.ja.md+++ b/README.ja.md@@ -112,6 +112,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# 項目ごとに: video-canvas → video → video-frames → video-loop; set/table.md が全結果に名前を付ける```+エージェントに接続した動画 MCP でクリップを作る場合: ZCRE(지크)の MCP なら、エージェントがあなた自身の ZCRE アカウントでクリップを作り、sprite-gen がそれを切り出します。`sprite-gen video-prompt --direction side --state walk --no-last-frame` がプロンプトを出し、`video-frames` と `video-loop` が mp4 を受け取ります。ZCRE の Grok Imagine 1.5 には終了フレームがないため、歩き・走り・ジャンプのみです([手順](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre))。+**C · ユーティリティ** — それぞれ単独で動作します。```bashdiff --git a/README.ko.md b/README.ko.mdindex a89192c..a104869 100644--- a/README.ko.md+++ b/README.ko.md@@ -120,6 +120,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# 항목별로: video-canvas → video → video-frames → video-loop; set/table.md 가 모든 결과의 이름을 담는다```+에이전트에 연결된 영상 MCP 로 클립을 만든다면: 지크(ZCRE) MCP 로 에이전트가 사용자 본인의 ZCRE 계정에서 클립을 만들고 sprite-gen 이 그 클립을 자른다. `sprite-gen video-prompt --direction side --state walk --no-last-frame` 가 프롬프트를 내고, 받은 mp4 는 `video-frames`·`video-loop` 가 받는다. ZCRE 의 Grok Imagine 1.5 에는 끝 프레임이 없어 걷기·달리기·점프만 된다([방법](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+**C · 유틸리티** — 각각 독립적으로 쓴다.```bashdiff --git a/README.md b/README.mdindex edca905..f9565dd 100644--- a/README.md+++ b/README.md@@ -127,6 +127,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# per item: video-canvas → video → video-frames → video-loop; set/table.md names every result```+Making clips through a video MCP connected to your agent? With ZCRE's (지크), the agent makes the clip on your own ZCRE account and sprite-gen cuts it: `sprite-gen video-prompt --direction side --state walk --no-last-frame` prints the prompt, then `video-frames` and `video-loop` take the mp4. Walk, run and jump only, because ZCRE's Grok Imagine 1.5 has no end frame ([how](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre)).+**C · utilities** — each stands alone.```bashdiff --git a/README.zh-Hans.md b/README.zh-Hans.mdindex 19e94ce..f7a669c 100644--- a/README.zh-Hans.md+++ b/README.zh-Hans.md@@ -112,6 +112,8 @@ sprite-gen video-set --base side=still.png --states idle,walk,run,jump,attack --# 每项依次:video-canvas → video → video-frames → video-loop;set/table.md 列出每个结果的名称```+通过连接到智能体的视频 MCP 生成片段?使用 ZCRE(지크)的 MCP 时,智能体用你自己的 ZCRE 账户生成片段,sprite-gen 负责切割:`sprite-gen video-prompt --direction side --state walk --no-last-frame` 输出提示词,`video-frames` 和 `video-loop` 接收 mp4。ZCRE 的 Grok Imagine 1.5 没有结束帧,因此仅支持行走、奔跑和跳跃([方法](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre))。+**C · 实用工具** —— 每个都可独立使用。```bashdiff --git a/SKILL.md b/SKILL.mdindex 9a6d24f..5ab5a1d 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,7 +1,7 @@---name: sprite-genversion: 2.20.0-description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘, first/last frame, reference-to-video, 영상 이어붙이기, 영상 편집, extend/edit a clip), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers, engine exports, repeating backgrounds, projected shadows, motion/contact inspection and optional scene composition from existing assets."+description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘, first/last frame, reference-to-video, 영상 이어붙이기, 영상 편집, extend/edit a clip), clips from a video MCP on the agent (ZCRE, 지크 MCP), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers, engine exports, repeating backgrounds, projected shadows, motion/contact inspection and optional scene composition from existing assets."license: Apache-2.0depends_on:required_bins:@@ -92,6 +92,7 @@ front-facing observations also remain unchanged. Mirroring does not preserve lef| Standalone video / animate a still, pin a last frame, reference images | `video` (`--image`, `--last-frame`, `--reference`) | [video](docs/video.md) || Continue or edit an existing clip | `video-extend`, `video-edit` | [video](docs/video.md) || Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) |+| Video sprites from a clip your agent makes with a connected video MCP (ZCRE, 지크) | `video-canvas`, `video-prompt --no-last-frame`, the agent's own MCP tools (quote, user approval, generate, save the mp4), then `video-frames`, `video-loop`. sprite-gen never calls the MCP. Walk, run and jump only: ZCRE's `grok-imagine-video-1.5` has no end frame, so idle, attack and diagonal walks are refused unless `--unpinned` | [video-pipeline](docs/video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) || Ordinary image or edit | `gen --provider codex` or `gen --provider grok` (subscription routes) | [gen](docs/gen.md) || Image generation with no login available (server, container, SaaS) | `gen --provider openai` — server/SaaS route on `OPENAI_API_KEY`, **billed per call**, never a default or a fallback | [gen](docs/gen.md#subscription-first--openai-is-named-or-it-does-not-run) || Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) |diff --git a/docs/README.md b/docs/README.mdindex 6ee53cc..8288745 100644--- a/docs/README.md+++ b/docs/README.md@@ -38,7 +38,7 @@ flowchart LR| Pipeline / tool group / workflow | Entry doc | Verbs ||---|---|---|| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |-| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` → `video-frames` → `video-loop`, `video-set`, `video-cycle-align` |+| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align` || **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` || **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` || **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex 8e69206..26b5037 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -11,13 +11,15 @@ ones that survived that day.```still ──video-canvas──▶ canvas.png ──video──▶ clip.mp4 ──video-frames──▶ keyed/*.png ──video-loop──▶ strip · gif · webp- └── video-set runs all four per (direction, state)+ │ ▲ └── video-set runs all four per (direction, state)+ └──video-prompt──▶ your agent's video MCP (ZCRE)```| Verb | Module | In → out ||---|---|---|| `sprite-gen video-canvas` | `sprite_gen/video/canvas.py` | still → padded still (state canvas) + report || `sprite-gen video` | `sprite_gen/gen/video.py` ([gen](video.md)) | still + prompt → mp4 + report |+| `sprite-gen video-prompt` | `sprite_gen/video/clip_prompt.py` | (direction, state) → the prompt `video-set` sends, for a clip made by a video MCP on your agent ([below](#a-clip-from-a-video-mcp-on-your-agent--zcre)) || `sprite-gen video-frames` | `sprite_gen/video/frames.py` | mp4 → `raw/`, `keyed/` RGBA frames + report || `sprite-gen video-loop` | `sprite_gen/video/loop.py` | keyed frames → `cycle/`, `<name>.strip.png` + `.strip.json`, `<name>.gif`, `<name>.webp` + report || `sprite-gen video-set` | `sprite_gen/video/batch.py` | bases × states → one folder per item, `set.report.json`, `table.md` |@@ -233,6 +235,47 @@ back walk, on the base's own key, kept as `walk-start.png` with its report and rprompt and base are the same; a base on no chroma key is refused with `--walk-start as-given`, whichfilms from the base itself. Side and diagonal walks, and every other state, film from the base.+### 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+remote MCP (`https://mcp.zcre.ai/mcp`, signed in with your own ZCRE account, paid from your own+credits, under ZCRE's terms) — the agent makes the clip with that MCP's tools and sprite-gen does the+rest: `video-prompt` prints the prompt `video-set` would send, and `video-frames` and `video-loop` read+the mp4 the agent saved. What crosses the boundary is a PNG, a prompt and an mp4.++```bash+sprite-gen video-canvas --still still.png --state walk --facing right --out item/canvas.png --report item/canvas.report.json+sprite-gen video-prompt --direction side --state walk --facing right --no-last-frame --json > item/prompt.json+# the agent, with its ZCRE tools and grok-imagine-video-1.5: prepare_upload for item/canvas.png and the+# transfer it describes, query_zcre upload to confirm it, query_zcre quote with prompt.json's prompt and+# duration, the credits shown to the user and approved, create_generation with that quote, query_zcre+# status until it succeeds, the output saved as item/clip.mp4+sprite-gen video-frames --clip item/clip.mp4 --out-dir item/frames --spill auto --reference item/canvas.png+sprite-gen video-loop --frames-dir item/frames/keyed --out-dir item/loop --fps 24 --state walk --cycle auto --facing right --name side-walk+```++`video-prompt --json` also gives the duration (the state's own, as `video-set`), whether the clip+ends on the canvas (`last_frame`), the loop cut (`cycle`) and these 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). `--character`, `--motion` and `--model` reach the+prompt as they reach `build_prompt`. What the ZCRE route supports:++| | Through ZCRE's MCP |+|---|---|+| Model | `grok-imagine-video-1.5` (Grok Imagine Pro), image-to-video only. There is no Lite model there, so `LITE_WALK_TEXT` never applies. |+| End frame | None. `--no-last-frame` refuses what `video-set` films pinned — idle, attack, a walk or run in a diagonal (`pins_last_frame`). `--unpinned` films one anyway, with a warning: the prompt asks for an evenly paced repeat (an attack for one strike), the loop is searched instead of cut whole, and it may not close. Walk, run and jump from the side, front and back are the route. |+| Resolution | 480p, 720p, 1080p. The clip keeps the canvas's ratio (a 1024² canvas came back 544² at 480p and 960² at 720p). |+| Audio | Always an AAC track; there is no option to leave it out. `video-frames` reads the picture alone, records `audio_streams`, and the loop outputs carry no sound. |+| Cover image | The mp4 also holds a one-frame mjpeg cover (`attached_pic`); `video-frames` skips it (`cover_streams`) and reads the first video stream that is not one (`stream_index`). |+| Picture | H.264 `yuv420p` (4:2:0), 24 fps, as a `sprite-gen video` clip; the frames report records `codec` and `pix_fmt`. |+| Side facing | `video-set`'s facing observation is not run on this route; check the still faces `--facing`. |++Measured 2026-10-04, one side walk end to end on that route: a 1024² still, `video-canvas` (square,+1.8 s), 720p 3 s, quoted and charged 52 credits, 33.6 s from submission to `succeeded`; the clip was+960×960, 24 fps, 73 frames, H.264 `yuv420p` with an AAC track and a cover image; `video-frames` kept+73 frames and no edge contact, and `video-loop --cycle auto` cut a periodic 20-frame walk (seam 0.72)+with three frames remade by RIFE and a jolt warning (index 0.85), as a Pro walk can carry.+## 3. Frames — extract, key, check the edges`ffmpeg` extracts every frame; the clip's real fps is recorded (never assumed). Eachdiff --git a/docs/video.md b/docs/video.mdindex 6ac5f05..ec603d1 100644--- a/docs/video.md+++ b/docs/video.md@@ -218,4 +218,5 @@ printed or written** — only the download host (`vidgen.x.ai`).## Related+- [video-pipeline.md](video-pipeline.md#a-clip-from-a-video-mcp-on-your-agent--zcre) — a clip your agent makes with a video MCP (ZCRE) instead of this command- [docs/README.md](README.md) — documentation indexdiff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex 9147adc..bb93bb1 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -27,6 +27,7 @@ MODULE_DOMAIN = {'batch': 'video','align': 'video','rife_install': 'video',+ 'clip_prompt': 'video','prepare': 'gen','extract': 'frames','cutout': 'frames',@@ -88,8 +89,8 @@ DOMAIN_TITLE = dict(DOMAINS)PIPELINES: list[dict[str, object]] = [{"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],"chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},- {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-frames", "video-loop", "video-set", "video-cycle-align"],- "chain": "video-canvas → video → video-frames → video-loop, or video-set; video-cycle-align across a set", "doc": "docs/video-pipeline.md"},+ {"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-prompt", "video-frames", "video-loop", "video-set", "video-cycle-align"],+ "chain": "video-canvas → video (or video-prompt + a video MCP) → video-frames → video-loop, or video-set; video-cycle-align across a set", "doc": "docs/video-pipeline.md"},]TOOL_GROUPS: list[dict[str, object]] = [diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex 54b00d7..47dcd6c 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -18,6 +18,7 @@ from sprite_gen.video import batch as video_batchfrom sprite_gen.video import canvas as video_canvasfrom sprite_gen.video import frames as video_framesfrom sprite_gen.video import loop as video_loop+from sprite_gen.video import clip_prompt as video_promptfrom sprite_gen.video import align as video_alignfrom sprite_gen.video import rife_installfrom sprite_gen.effects import recolor, shadow@@ -334,6 +335,12 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callabvideo_canvas.add_arguments,video_canvas.run,),+ # The prompt alone, for a clip made by a video MCP on the user's agent (ZCRE); the engine never calls it.+ "video-prompt": (+ "Print the clip prompt video-set would send for one (direction, state), for a clip made elsewhere (a video MCP such as ZCRE); --json adds the duration, end-frame pin and loop cut.",+ video_prompt.add_arguments,+ video_prompt.run,+ ),"video-frames": ("Extract a clip's frames and key the chroma out into RGBA frames (edge-contact checked).",video_frames.add_arguments,diff --git a/sprite_gen/video/clip_prompt.py b/sprite_gen/video/clip_prompt.pynew file mode 100644index 0000000..e97883c--- /dev/null+++ b/sprite_gen/video/clip_prompt.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen video-prompt` — the clip prompt for one (direction, state), for a clip made elsewhere.++`video-set` builds this prompt (`batch.build_prompt`) and sends it to `sprite-gen video` itself.+When the clip is made by another tool instead — a video MCP connected to the user's own agent,+such as ZCRE — the agent asks for the prompt here, sends it with the `video-canvas` still through+that tool, and hands the mp4 back to `video-frames` and `video-loop`. The engine never calls the+other tool: this verb prints text and reads nothing but its arguments.++A clip source that cannot pin an end frame (`--no-last-frame`; ZCRE's `grok-imagine-video-1.5` has+image-to-video only) cannot film what `video-set` films pinned (`pins_last_frame`: idle, attack, a+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.+"""++from __future__ import annotations++import argparse+import json+import sys+from typing import Any++from sprite_gen.gen.facing import FACINGS+from sprite_gen.video import batch as batch_mod++DEFAULT_MODEL = "grok-imagine-video-1.5"+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") -> dict[str, Any]:+ """The prompt `video-set` would send for (direction, state), and how its clip is to be cut."""+ 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)")+ wants_pin = batch_mod.pins_last_frame(state, direction)+ warnings: list[str] = []+ pinned: bool | None = None+ if wants_pin and not last_frame:+ if not unpinned:+ raise SystemExit(+ f"video-prompt: a {direction} {state} is filmed ending on its first frame (the canvas pinned as the end "+ "frame), and this clip source has no end frame (--no-last-frame). Leave the state out, or pass --unpinned "+ "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")+ pins = wants_pin and last_frame+ prompt = batch_mod.build_prompt(direction, state, character, facing=facing, motion=motion, pinned=pinned, model=model)+ cycle = "pinned" if pins and state in batch_mod.PINNED_LOOP_STATES else "auto"+ # as video-set places and cuts: a diagonal's canvas takes the facing, its loop does not+ canvas_facing = facing if direction not in ("front", "back") else "right"+ loop_facing = facing if direction == "side" else "right"+ mid_step = batch_mod.starts_mid_step(state, direction)+ 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 ""+ record: dict[str, Any] = {+ "kind": "sprite-gen-video-prompt",+ "direction": direction,+ "state": state,+ "facing": facing,+ "model": model,+ "prompt": prompt,+ "duration": duration,+ "last_frame": "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",+ "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}",+ },+ "warnings": warnings,+ }+ 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),+ "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+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--direction", required=True, choices=sorted(batch_mod.VIEW_TEXT), help="view of the still")+ parser.add_argument("--state", required=True, help="motion state (idle/walk/run/jump/attack/...)")+ parser.add_argument("--facing", choices=FACINGS, default="right", help="side view: which way it faces (default right)")+ 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")+ parser.add_argument("--duration", type=int, help="seconds to ask for (default: the state's own, as video-set)")+ parser.add_argument("--no-last-frame", action="store_true", help="the clip source cannot pin an end frame (ZCRE's grok-imagine-video-1.5): states filmed pinned are refused")+ parser.add_argument("--unpinned", action="store_true", help="with --no-last-frame: film a pinned state without the pin, with a warning, instead of refusing it")+ parser.add_argument("--key", choices=START_STILL_KEYS, default="green", help="the still's chroma key, for a front or back walk's mid-step redraw sentence (default green)")+ parser.add_argument("--json", action="store_true", help="print the whole record (prompt, duration, end-frame pin, loop cut, commands) instead of the prompt alone")+++def run(**kwargs: object) -> int:+ record = plan_prompt(+ 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"),+ 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"),+ )+ for line in record["warnings"]:+ print(f"video-prompt: warning: {line}", file=sys.stderr)+ print(json.dumps(record, ensure_ascii=False, indent=2) if kwargs.get("json") else record["prompt"])+ return 0+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="sprite-gen video-prompt", description=__doc__)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex c4a7683..d61978e 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -81,29 +81,44 @@ def _require(binary: str) -> str:def probe(clip: Path) -> dict[str, Any]:+ """The clip's moving picture and what else it carries.++ A clip can hold more than the picture: an audio track (a clip from a video MCP such as+ ZCRE always has one, and so does `sprite-gen video` unless `--no-audio`) and a cover image,+ a one-frame mjpeg stream marked `attached_pic`. The frames come from the first video stream+ that is not a cover (`stream_index`); the audio is counted and never extracted."""ffprobe = _require("ffprobe")proc = subprocess.run(- [ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate,nb_frames",- "-show_entries", "format=duration", "-of", "json", str(clip)],+ [ffprobe, "-v", "error", "-show_entries", "stream=index,codec_type,codec_name,pix_fmt,width,height,r_frame_rate,nb_frames",+ "-show_entries", "stream_disposition=attached_pic", "-show_entries", "format=duration", "-of", "json", str(clip)],capture_output=True, text=True,)if proc.returncode != 0:raise SystemExit(f"video-frames: ffprobe failed on {clip}: {proc.stderr.strip()[:300]}")data = json.loads(proc.stdout)- stream = (data.get("streams") or [{}])[0]+ streams = data.get("streams") or []+ pictures = [s for s in streams if s.get("codec_type") == "video" and not (s.get("disposition") or {}).get("attached_pic")]+ if not pictures:+ raise SystemExit(f"video-frames: {clip} has no video stream (only {', '.join(sorted({str(s.get('codec_type')) for s in streams})) or 'nothing'})")+ stream = pictures[0]num, den = (stream.get("r_frame_rate") or "24/1").split("/")fps = float(num) / float(den or 1)return {"width": stream.get("width"), "height": stream.get("height"), "fps": fps,"nb_frames": int(stream["nb_frames"]) if str(stream.get("nb_frames", "")).isdigit() else None,- "duration": float(data.get("format", {}).get("duration") or 0)}+ "duration": float(data.get("format", {}).get("duration") or 0),+ "stream_index": stream.get("index"), "codec": stream.get("codec_name"), "pix_fmt": stream.get("pix_fmt"),+ "audio_streams": sum(1 for s in streams if s.get("codec_type") == "audio"),+ "cover_streams": sum(1 for s in streams if s.get("codec_type") == "video" and (s.get("disposition") or {}).get("attached_pic"))}-def extract(clip: Path, raw_dir: Path) -> list[Path]:+def extract(clip: Path, raw_dir: Path, stream_index: int | None = None) -> list[Path]:+ """Every frame of the clip's picture as PNG; `stream_index` names that stream (`probe`)."""ffmpeg = _require("ffmpeg")raw_dir.mkdir(parents=True, exist_ok=True)for old in raw_dir.glob("frame-*.png"):old.unlink()- proc = subprocess.run([ffmpeg, "-v", "error", "-y", "-i", str(clip), str(raw_dir / "frame-%04d.png")], capture_output=True, text=True)+ pick = ["-map", f"0:{stream_index}"] if stream_index is not None else []+ proc = subprocess.run([ffmpeg, "-v", "error", "-y", "-i", str(clip), *pick, str(raw_dir / "frame-%04d.png")], capture_output=True, text=True)if proc.returncode != 0:raise SystemExit(f"video-frames: ffmpeg failed on {clip}: {proc.stderr.strip()[:300]}")files = sorted(raw_dir.glob("frame-*.png"))@@ -347,7 +362,7 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,raw_dir = out_dir / "raw"keyed_dir = out_dir / "keyed"decision = decide_spill(Path(reference).expanduser().resolve(), key) if spill == "auto" else {"mode": spill, "reason": "explicit"}- files = extract(clip, raw_dir)+ files = extract(clip, raw_dir, meta["stream_index"])report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"], allow_subject=allow_subject_edge_contact, decontam=decontam)payload = {"kind": "sprite-gen-video-frames-report", "clip": str(clip), "out_dir": str(out_dir), "raw_dir": str(raw_dir), "keyed_dir": str(keyed_dir), "key": key, "spill": decision, **meta, **report}target = (report_path or (out_dir / "frames.report.json")).expanduser().resolve()@@ -357,7 +372,7 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,def add_arguments(parser: argparse.ArgumentParser) -> None:- parser.add_argument("--clip", required=True, type=Path, help="mp4 from `sprite-gen video`")+ parser.add_argument("--clip", required=True, type=Path, help="mp4 from `sprite-gen video`, or one made elsewhere from a `video-canvas` still (a video MCP such as ZCRE); an audio track and a cover image are left out")parser.add_argument("--out-dir", required=True, type=Path, help="writes raw/ and keyed/ here")parser.add_argument("--key", choices=("auto", "green", "magenta", "white"), default="auto", help="background key (auto reads the corners)")parser.add_argument("--allow-edge-contact", action="store_true", help="accept any opaque pixel at the top/left/right edge (subject and leftover key background alike)")@@ -374,7 +389,7 @@ def run(**kwargs: object) -> int:spill=str(kwargs.get("spill") or "small"), reference=kwargs.get("reference"), # type: ignore[arg-type]allow_subject_edge_contact=bool(kwargs.get("allow_subject_edge_contact")),decontam=str(kwargs.get("decontam") or "off"))- summary = {k: payload[k] for k in ("clip", "keyed_dir", "fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "edge_policy", "spill", "report")}+ summary = {k: payload[k] for k in ("clip", "keyed_dir", "width", "height", "fps", "frames", "codec", "pix_fmt", "audio_streams", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "edge_policy", "spill", "report")}print(json.dumps(summary, ensure_ascii=False, indent=2))return 0diff --git a/tests/video/test_clip_prompt.py b/tests/video/test_clip_prompt.pynew file mode 100644index 0000000..204f827--- /dev/null+++ b/tests/video/test_clip_prompt.py@@ -0,0 +1,128 @@+# SPDX-License-Identifier: Apache-2.0+"""A clip made elsewhere (a video MCP on the user's agent, such as ZCRE) enters the loop pipeline+through `video-prompt` and `video-frames`: the prompt is the one `video-set` sends, a source with no+end frame cannot film a pinned state unless asked to film it unpinned, and a clip's audio track and+cover image are recorded and left out of the frames."""++from __future__ import annotations++import json+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+from PIL import Image++from sprite_gen.video import batch as batch_mod+from sprite_gen.video import clip_prompt+from sprite_gen.video import frames as frames_mod++HAS_FFMPEG = shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not None++[email protected]("direction,state", [("side", "walk"), ("front", "walk"), ("back", "run"), ("side", "jump")])+def test_the_prompt_is_the_one_video_set_sends(direction, state) -> None:+ record = clip_prompt.plan_prompt(direction=direction, state=state, facing="left", character="The knight",+ last_frame=False)+ assert record["prompt"] == batch_mod.build_prompt(direction, state, "The knight", facing="left",+ model=clip_prompt.DEFAULT_MODEL)+ assert record["duration"] == batch_mod.duration_for(state, None)+ assert record["last_frame"] is None and record["cycle"] == "auto" and record["warnings"] == []+++def test_a_callers_motion_and_a_lite_model_reach_the_prompt() -> None:+ record = clip_prompt.plan_prompt(direction="side", state="walk", motion="It marches proudly.",+ model="grok-imagine-video-1.5-lite")+ assert record["prompt"] == batch_mod.build_prompt("side", "walk", None, motion="It marches proudly.",+ model="grok-imagine-video-1.5-lite")+ assert "It marches proudly." in record["prompt"]++[email protected]("direction,state", [("side", "idle"), ("side", "attack"), ("front_diagonal", "walk"), ("back_diagonal", "run")])+def test_no_end_frame_refuses_a_pinned_state(direction, state) -> None:+ assert batch_mod.pins_last_frame(state, direction)+ with pytest.raises(SystemExit, match="no end frame"):+ clip_prompt.plan_prompt(direction=direction, state=state, last_frame=False)+++def test_unpinned_films_a_pinned_state_as_a_searched_loop_with_a_warning() -> None:+ record = clip_prompt.plan_prompt(direction="side", state="idle", last_frame=False, unpinned=True)+ assert record["prompt"] == batch_mod.build_prompt("side", "idle", None, pinned=False, model=clip_prompt.DEFAULT_MODEL)+ assert "evenly paced" in record["prompt"] and "returns to the exact pose of the first frame" not in record["prompt"]+ assert record["last_frame"] is None and record["cycle"] == "auto"+ assert record["warnings"] and "end-frame pin" in record["warnings"][0]+ with pytest.raises(SystemExit, match="goes with --no-last-frame"):+ clip_prompt.plan_prompt(direction="side", state="idle", unpinned=True)+++def test_a_source_with_an_end_frame_films_pinned_states_as_video_set_does() -> None:+ idle = clip_prompt.plan_prompt(direction="side", state="idle")+ assert idle["last_frame"] == "canvas" and idle["cycle"] == "pinned"+ assert idle["prompt"] == batch_mod.build_prompt("side", "idle", None, model=clip_prompt.DEFAULT_MODEL)+ assert "end frame <dir>/canvas.png" in idle["commands"]["clip"]+ diagonal = clip_prompt.plan_prompt(direction="back_diagonal", state="walk")+ assert diagonal["last_frame"] == "canvas" and diagonal["cycle"] == "auto" # a pinned gait is still searched+++def test_a_front_walk_carries_its_mid_step_redraw() -> None:+ record = clip_prompt.plan_prompt(direction="front", state="walk", last_frame=False, key="magenta")+ assert record["start_still"]["prompt"] == batch_mod.walk_start_prompt("front", "magenta")+ assert "--still <dir>/walk-start.png" in record["commands"]["canvas"]+ assert "start_still" not in clip_prompt.plan_prompt(direction="side", state="walk", last_frame=False)+++def test_the_cli_prints_the_prompt_alone_or_the_record() -> None:+ args = [sys.executable, "-m", "sprite_gen.cli", "video-prompt", "--direction", "side", "--state", "walk", "--no-last-frame"]+ plain = subprocess.run(args, capture_output=True, text=True)+ assert plain.returncode == 0, plain.stderr+ assert plain.stdout.strip() == batch_mod.build_prompt("side", "walk", None, model=clip_prompt.DEFAULT_MODEL)+ record = json.loads(subprocess.run([*args, "--json"], capture_output=True, text=True, check=True).stdout)+ assert record["kind"] == "sprite-gen-video-prompt" and record["state"] == "walk"+ refused = subprocess.run([*args[:-3], "attack", "--no-last-frame"], capture_output=True, text=True)+ assert refused.returncode != 0 and "--unpinned" in refused.stderr and not refused.stdout+++def test_probe_reads_the_picture_past_a_cover_image(monkeypatch) -> None:+ """A cover image (`attached_pic`) is not the clip, wherever it sits; the audio is counted."""+ streams = [+ {"index": 0, "codec_type": "video", "codec_name": "mjpeg", "width": 64, "height": 64, "r_frame_rate": "90000/1", "disposition": {"attached_pic": 1}},+ {"index": 1, "codec_type": "audio", "codec_name": "aac", "disposition": {"attached_pic": 0}},+ {"index": 2, "codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p", "width": 960, "height": 960, "r_frame_rate": "24/1", "nb_frames": "73", "disposition": {"attached_pic": 0}},+ ]+ out = json.dumps({"streams": streams, "format": {"duration": "3.041667"}})+ monkeypatch.setattr(frames_mod, "_require", lambda binary: binary)+ monkeypatch.setattr(frames_mod.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0, out, ""))+ meta = frames_mod.probe(Path("clip.mp4"))+ assert meta["stream_index"] == 2 and (meta["width"], meta["height"], meta["fps"], meta["nb_frames"]) == (960, 960, 24.0, 73)+ assert (meta["codec"], meta["pix_fmt"], meta["audio_streams"], meta["cover_streams"]) == ("h264", "yuv420p", 1, 1)+ only_cover = json.dumps({"streams": streams[:2], "format": {}})+ monkeypatch.setattr(frames_mod.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0, only_cover, ""))+ with pytest.raises(SystemExit, match="no video stream"):+ frames_mod.probe(Path("clip.mp4"))++[email protected](not HAS_FFMPEG, reason="ffmpeg/ffprobe not installed")+def test_frames_of_a_clip_with_audio_and_a_cover_are_the_pictures_frames(tmp_path: Path) -> None:+ """The shape a ZCRE clip comes in: H.264 4:2:0, an AAC track and an mjpeg cover image."""+ src = tmp_path / "src"+ src.mkdir()+ for i in range(12):+ im = Image.new("RGB", (64, 64), (0, 255, 0))+ for y in range(20, 50):+ for x in range(20 + i, 34 + i):+ im.putpixel((x, y), (200, 40, 40))+ im.save(src / f"f-{i:04d}.png")+ Image.new("RGB", (64, 64), (10, 10, 200)).save(tmp_path / "cover.png")+ plain = tmp_path / "plain.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-framerate", "24", "-i", str(src / "f-%04d.png"), "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono",+ "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "12", "-c:a", "aac", "-t", "0.5", str(plain)], check=True)+ clip = tmp_path / "clip.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(tmp_path / "cover.png"), "-i", str(plain), "-map", "0", "-map", "1", "-c", "copy",+ "-c:v:0", "mjpeg", "-disposition:v:0", "attached_pic", str(clip)], check=True)+ report = frames_mod.run_frames(clip, tmp_path / "frames", key="green", allow_edge_contact=False, report_path=None)+ assert report["frames"] == 12 and len(list((tmp_path / "frames" / "raw").glob("frame-*.png"))) == 12+ assert (report["codec"], report["pix_fmt"], report["audio_streams"], report["cover_streams"]) == ("h264", "yuv420p", 1, 1)+ saved = json.loads((tmp_path / "frames" / "frames.report.json").read_text(encoding="utf-8"))+ assert saved["audio_streams"] == 1 and saved["stream_index"] == report["stream_index"]