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): tight framing for a fixed body height, measured on the clip's first frame

Soohong Kim5c6e52b71683
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d871b1c..afb8b8e 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`.
+## v2.8.0 - Tight framing for a fixed body height
+
+- `video-canvas --fit tight` frames a still with no room for the motion: it drops the empty rows above and below the subject (keeping headroom of 4 % of the subject's height), keeps the still's width, and pads to the nearest framing the video model returns (9:16, 1:1, 16:9). The subject is never scaled or cut. A long, low subject in a square still becomes a 16:9 frame it fills, so a `--body-height` target is reached at a low clip resolution by scaling down rather than up. A motion that leaves the frame is clipped. The default `--fit state` is unchanged, and the report now says which `fit` framed it.
+- `video-frames --allow-subject-edge-contact` accepts the subject at the frame edge and still refuses leftover key background there. The report's `edge_policy` names the rule that applied.
+- `video-set --fit tight` frames every item that way and lets its subject reach the edge. It refuses `--shape`, and a cached canvas framed with another fit is not reused.
+- `--body-height` measures the standing height on the clip's first frame, the base still's pose that every clip starts from. The tallest grounded frame, used before, is an attack's windup with the weapon overhead, and scaling that to the target made the character smaller in its attack than in its walk. The strip sidecar records `body_ref`, `body_src_h` (the standing height as filmed) and `scale`, so a strip whose cells were upscaled says so. Without a target nothing changes.
+
## v2.7.0 - Timed attack clips pinned to their start
- Attack clips are timed strikes pinned to their start. `MOTION_TEXT["attack"]` asks for the same attack twice, each a windup, one strike in front, a held impact pose and a recovery to the exact starting stance with approximate times, keeps what the subject holds in the hand nearest the viewer, and forbids turning. The attack template drops the "evenly paced" line, keeps what the subject holds inside the frame and asks for crisp frames. `video-set` asks attack clips for 4 s by default (other states keep 3 s; `--duration` still sets one length for all) and passes the canvas as `--last-frame`, so the clip ends where it began. The item report records the clip's `duration` and `last_frame`.
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index 6cb2c5f..42d2ac1 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -47,6 +47,18 @@ height; wide canvases grow both dimensions to preserve their ratio without shrin
the still. A still whose corners are not one flat colour
is refused — a non-flat background cannot be extended without guessing.
+**`--fit tight` adds no room.** It is the framing for a fixed body height at a low
+clip resolution: the room above makes the subject a small part of the clip, and a
+`--body-height` target then has to upscale it. Tight drops the empty rows above and
+below the subject (keeping headroom of 4 % of the subject's height), keeps the still's full width,
+and pads to the nearest framing the video model returns — 9:16, 1:1 or 16:9, with the
+midpoints at 3:4 and 4:3 — by adding height above or width on both sides. The subject is never
+scaled or cut, a long, low subject in a square still becomes a 16:9 frame it fills,
+and an upright one keeps its square. A motion that leaves the frame is clipped: pair it
+with `video-frames --allow-subject-edge-contact`. Tight picks its own shape, so it
+refuses `--shape` / `--headroom` / `--lead` / `--trail`; the report says `fit` and
+the `tight` rows it kept.
+
**The canvas owns key normalization.** Image models paint "`#00FF00`" a little
differently every run — (8, 166, 25) on 2026-09-11 — and the video model reproduces
the input colour almost exactly (a pure-key input came back as (16, 239, 11)). So when
@@ -142,7 +154,11 @@ tight and points at a taller/wider canvas. When both occur the message names bot
`residual` can also be reported on the antialiased fringe where a subject genuinely
touches the edge (a key-tinted blend pixel with low alpha), so a "framed too tight"
message with a small residual count is still a framing problem, not a key problem.
-`--allow-edge-contact` accepts the clipping on purpose.
+`--allow-edge-contact` turns the whole check off. `--allow-subject-edge-contact`
+accepts only the subject at the edge — the clipping a `--fit tight` canvas chooses —
+and still fails on leftover key background, which is a keying defect whatever the
+framing. Contacts stay in the report either way, with `edge_policy` saying which rule
+applied (`refuse`, `subject-allowed`, `off`).
## 3a. Spill — key colour the model painted into the subject
@@ -309,7 +325,11 @@ Outputs:
and then over-scales it by ~22 %, 2026-09-09). Scale a jump strip — whose cells include
air room — by `body_h`, not `h`, and it reads the same size as a walk strip;
`--body-height N` does that scaling in the pipeline so every state comes out at the same
- character size (`--strip-height` stays the cap). `delay_ms = cycle_seconds / frames`, so a
+ character size (`--strip-height` stays the cap). With a target, the standing height is
+ measured on the **clip's first frame** instead — the base still's pose, which every clip
+ starts from — because the tallest grounded frame of an attack is its windup with the weapon
+ overhead, and scaling that to N shrank the character against its walk. The sidecar says
+ which (`body_ref`: `first-frame` or `tallest-grounded`) and records `body_src_h` and `scale`. `delay_ms = cycle_seconds / frames`, so a
24 fps clip yields 41.67 ms cells; render at 24 fps to keep one cell per frame
(a 30 fps render of 24 fps cells is a 5:4 pulldown and judders).
- `<name>.gif` — `n_out` frames evenly across the cycle, 1-bit alpha, disposal 2, `loop=0`.
@@ -331,7 +351,9 @@ staggered (`--start-gap 2`) and a 429 gets a bounded, logged retry (15 s, 30 s).
is each state's own default (3 s, attack 4 s) unless `--duration` sets one for all, and an
attack clip is pinned to end on its canvas. States use differently shaped canvases (square, tall, wide),
so the same character films at different pixel heights; `--body-height N` gives every state's loop the
-same standing-height target and keeps the character one size across the set. Items
+same standing-height target and keeps the character one size across the set. At a low
+`--resolution`, `--fit tight` frames every item without room so that target is reached by
+scaling down rather than up, and lets the subject reach the frame edge. Items
are idempotent (an existing clip is reused unless `--force`); one failure stops only
its item and is listed in `table.md` with its stage and error. Exit code is non-zero
when any item failed.
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index 7ad03b5..2c79476 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -154,6 +154,7 @@ def run_item(
facing_fix: str = "none",
prepare_side: Callable[[Path], tuple[Path, dict]] | None = None,
body_height: int | None = None,
+ fit: str = "state",
) -> dict[str, Any]:
if anchor == "motion-auto" and not loop_mod.profile_for(state).gait:
raise SystemExit("video-set: --anchor motion-auto requires walk/run states")
@@ -187,6 +188,8 @@ def run_item(
raise ValueError("missing canvas")
if not all(key in canvas_report for key in ("shape", "canvas", "offset")):
raise ValueError("incomplete canvas report")
+ if canvas_report.get("fit", "state") != fit:
+ raise ValueError("cached canvas was framed with another --fit")
if direction == "side":
prior = canvas_report.get("facing_check") or {}
if not isinstance(prior, dict):
@@ -205,11 +208,11 @@ def run_item(
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)
+ 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)
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")
- result["canvas"] = {k: canvas_report[k] for k in ("shape", "canvas", "offset")}
+ result["canvas"] = {k: canvas_report[k] for k in ("fit", "shape", "canvas", "offset") if k in canvas_report}
if "facing_check" in canvas_report:
result["facing"] = canvas_report["facing_check"]
@@ -233,7 +236,8 @@ def run_item(
if attempts[-1] != 0 or not clip.exists():
raise SystemExit(f"clip generation failed after {len(attempts)} attempt(s); see {item_dir / 'clip.log'}")
- 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)
+ # a tight frame is clipped on purpose; leftover key background still fails
+ 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")
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)
@@ -284,6 +288,7 @@ def run_set(
facing: str = "right",
facing_fix: str = "none",
body_height: int | None = None,
+ fit: str = "state",
) -> dict[str, Any]:
if anchor == "motion-auto" and any(not loop_mod.profile_for(state).gait for state in states):
raise SystemExit("video-set: --anchor motion-auto requires walk/run states")
@@ -292,6 +297,8 @@ def run_set(
validate_facing(facing, facing_fix)
if facing_fix not in facing_mod.FIXES:
raise SystemExit("video-set: --facing-fix must be mirror or none")
+ if fit == "tight" and shape is not None:
+ raise SystemExit("video-set: --fit tight picks each canvas's shape itself; drop --shape")
root = root.expanduser().resolve()
root.mkdir(parents=True, exist_ok=True)
for direction, base in bases.items():
@@ -313,7 +320,7 @@ def run_set(
return prepared[base]
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:
- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=facing, facing_fix=facing_fix, prepare_side=prepare_side, body_height=body_height): i for i, d, s in items}
+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill, facing=facing, facing_fix=facing_fix, prepare_side=prepare_side, body_height=body_height, fit=fit): i for i, d, s in items}
for fut in as_completed(futures):
r = fut.result()
results.append(r)
@@ -356,6 +363,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--shape", choices=canvas_mod.SHAPES, help="force one canvas shape for every state (e.g. wide for a costume or arms that leave a 1:1 frame)")
parser.add_argument("--anchor", choices=tuple(a for a in loop_mod.ANCHOR_MODES if a != "motion"), default="none", help="motion-auto: automatic regions, local period and XY correction (walk/run only); feet: remove in-canvas drift")
parser.add_argument("--spill", choices=frames_mod.SPILL_MODES, default="auto", help="auto: judge key reflections from each item's canvas still (default); small / full: force")
+ parser.add_argument("--fit", choices=canvas_mod.FITS, default="state", help="state: each state's room for the motion (default); tight: no room, the subject fills the frame and a motion that leaves it is clipped (use with --body-height at a low --resolution)")
parser.add_argument("--body-height", type=int, default=None, help="scale every state's loop so the standing height is this many px (video-loop --body-height): one value for the whole set keeps the character the same size across states")
parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")
@@ -369,7 +377,7 @@ def run(**kwargs: object) -> int:
concurrency=int(kwargs.get("concurrency") or 3), force=bool(kwargs.get("force")), gap=float(kwargs.get("start_gap") or START_GAP_SECONDS),
facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") or "none"),
shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),
- body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None),
+ body_height=(int(kwargs["body_height"]) if kwargs.get("body_height") else None), fit=str(kwargs.get("fit") or "state"),
)
return 0 if not payload["failed"] else 1
diff --git a/sprite_gen/video/canvas.py b/sprite_gen/video/canvas.py
index 5972abe..edacf6f 100644
--- a/sprite_gen/video/canvas.py
+++ b/sprite_gen/video/canvas.py
@@ -8,6 +8,13 @@ attack needs room above and in front, a projectile needs room in front (wide), e
The state -> canvas table below is the single owner of that rule; `--shape`
overrides it per call.
+`--fit tight` is the other way to frame: no room is added for the motion. The
+empty rows above and below the subject are dropped (a little headroom stays),
+the still's width is kept, and the result is padded to the nearest framing the
+video model returns (9:16, 1:1, 16:9). The subject then fills as much of the
+clip's height as it can, which is what keeps a fixed body height from being
+upscaled at a low clip resolution; a motion that leaves that frame is clipped.
+
The padding is filled with the chroma key so the clip stays keyable end to end.
A still whose corners disagree is refused — a non-flat background cannot be
extended without guessing.
@@ -25,6 +32,7 @@ from __future__ import annotations
import argparse
import json
+import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -71,6 +79,11 @@ SHAPE_DEFAULTS: dict[str, CanvasProfile] = {
SHAPE_WIDE: STATE_CANVAS["attack"],
}
CORNER_TOLERANCE = 24 # max per-channel spread across the four corners for a "flat" background
+FITS = ("state", "tight") # state: the table's room for the motion; tight: none
+# The framings Grok returns for an input image, width / height. A tight canvas snaps to
+# the nearest one so the clip keeps the proportions the subject was cut to.
+TIGHT_RATIOS = {SHAPE_TALL: 9 / 16, SHAPE_SQUARE: 1.0, SHAPE_WIDE: 16 / 9}
+TIGHT_HEADROOM = 0.04 # of the subject's own height, kept above it so the head is not flush with the edge
KEYS = ("auto", "green", "magenta", "white") # auto: the corners decide; white: no chroma key, pad with the corner colour
@@ -155,6 +168,49 @@ def normalize_key(image: Image.Image, kind: str) -> tuple[Image.Image, dict[str,
return Image.fromarray(data, "RGB"), report
+def subject_rows(image: Image.Image, fill: tuple[int, int, int], tolerance: int) -> tuple[int, int]:
+ """First and one-past-last row holding a pixel that is not the background `fill`."""
+ data = np.asarray(image.convert("RGB"), dtype=np.int16)
+ diff = np.abs(data - np.array(fill, dtype=np.int16)).max(axis=2)
+ rows = np.flatnonzero((diff > tolerance).any(axis=1))
+ if rows.size == 0:
+ raise SystemExit("video-canvas: --fit tight found no subject on the still's background")
+ return int(rows[0]), int(rows[-1]) + 1
+
+
+def tight_canvas(src: Image.Image, fill: tuple[int, int, int], *, tolerance: int) -> tuple[Image.Image, dict[str, Any]]:
+ """Drop the empty rows above and below the subject, keep the width, pad to the nearest framing.
+
+ Never scales the subject and never cuts a column of it. Extra height goes above
+ the subject (it stands on the bottom edge, as on every canvas); extra width is
+ split evenly, because a tight frame adds no room in front on purpose.
+ """
+ w, h = src.size
+ top, bottom = subject_rows(src, fill, tolerance)
+ head = round((bottom - top) * TIGHT_HEADROOM)
+ kept_top = max(0, top - head)
+ band = src.crop((0, kept_top, w, bottom))
+ bw, bh = band.size
+ shape = min(TIGHT_RATIOS, key=lambda name: abs(math.log((bw / bh) / TIGHT_RATIOS[name])))
+ ratio = TIGHT_RATIOS[shape]
+ if bw / bh >= ratio:
+ canvas_w, canvas_h = bw, max(bh, round(bw / ratio))
+ else:
+ canvas_w, canvas_h = max(bw, round(bh * ratio)), bh
+ x, y = (canvas_w - bw) // 2, canvas_h - bh
+ canvas = Image.new("RGB", (canvas_w, canvas_h), fill)
+ canvas.paste(band, (x, y))
+ report = {
+ "shape": shape,
+ "ratio": round(canvas_w / canvas_h, 4),
+ "canvas": [canvas_w, canvas_h],
+ "still": [w, h],
+ "offset": [x, y],
+ "tight": {"subject_rows": [top, bottom], "kept_rows": [kept_top, bottom], "headroom_px": top - kept_top},
+ }
+ return canvas, report
+
+
def pad_canvas(
image: Image.Image,
profile: CanvasProfile,
@@ -164,6 +220,7 @@ def pad_canvas(
lead: float | None = None,
trail: float | None = None,
key: str = "auto",
+ fit: str = "state",
) -> tuple[Image.Image, dict[str, Any]]:
"""Return (padded RGB image, placement report). Never downsizes the still.
@@ -177,6 +234,25 @@ def pad_canvas(
else:
src, key_report = normalize_key(image, kind)
fill = KEY_TARGETS[kind]
+ if fit not in FITS:
+ raise SystemExit(f"video-canvas: unknown --fit {fit!r}; expected one of {', '.join(FITS)}")
+ if fit == "tight":
+ # A normalized key background is the exact key, so any other value is the subject;
+ # a white/ivory base only has its corner colour to go by.
+ canvas, placed = tight_canvas(src, tuple(fill), tolerance=0 if kind is not None else CORNER_TOLERANCE) # type: ignore[arg-type]
+ report = {
+ "fit": "tight",
+ **placed,
+ "headroom": 0.0,
+ "lead": 0.0,
+ "trail": 0.0,
+ "facing": facing,
+ "key_rgb": list(fill),
+ "corner_rgb": list(corner),
+ **key_report,
+ "why": "tight: no room for the motion; the subject fills the frame and a motion that leaves it is clipped",
+ }
+ return canvas, report
w, h = src.size
head = profile.headroom if headroom is None else headroom
front = profile.lead if lead is None else lead
@@ -203,6 +279,7 @@ def pad_canvas(
canvas = Image.new("RGB", (canvas_w, canvas_h), fill)
canvas.paste(src, (x, y))
report = {
+ "fit": "state",
"shape": profile.shape,
"ratio": round(canvas_w / canvas_h, 4),
"canvas": [canvas_w, canvas_h],
@@ -232,12 +309,15 @@ def run_canvas(
report_path: Path | None,
key: str = "auto",
trail: float | None = None,
+ fit: str = "state",
) -> dict[str, Any]:
still = still.expanduser().resolve()
if not still.is_file():
raise SystemExit(f"video-canvas: still not found: {still}")
+ if fit == "tight" and (shape is not None or headroom is not None or lead is not None or trail is not None):
+ raise SystemExit("video-canvas: --fit tight picks its own shape and adds no room; drop --shape/--headroom/--lead/--trail")
profile = profile_for(state, shape)
- canvas, report = pad_canvas(Image.open(still), profile, facing=facing, headroom=headroom, lead=lead, trail=trail, key=key)
+ canvas, report = pad_canvas(Image.open(still), profile, facing=facing, headroom=headroom, lead=lead, trail=trail, key=key, fit=fit)
out = out.expanduser().resolve()
out.parent.mkdir(parents=True, exist_ok=True)
tmp = out.with_name(out.name + ".part")
@@ -259,6 +339,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--lead", type=float, help="wide: empty fraction in front of the subject (default from the profile)")
parser.add_argument("--trail", type=float, help="wide: empty fraction behind the subject, for a weapon drawn back (default from the profile)")
parser.add_argument("--key", choices=KEYS, default="auto", help="chroma key of the still (auto reads the corners; green/magenta are normalized to the exact key; white pads with the corner colour)")
+ parser.add_argument("--fit", choices=FITS, default="state", help="state: the state's room for the motion (default); tight: drop the empty rows around the subject and add no room, so it fills the frame and a motion that leaves it is clipped")
parser.add_argument("--report", type=Path, help="write the canvas report JSON here")
@@ -267,7 +348,7 @@ def run(**kwargs: object) -> int:
Path(str(kwargs["still"])), Path(str(kwargs["out"])),
state=kwargs.get("state"), shape=kwargs.get("shape"), facing=str(kwargs.get("facing") or "right"), # type: ignore[arg-type]
headroom=kwargs.get("headroom"), lead=kwargs.get("lead"), trail=kwargs.get("trail"), report_path=kwargs.get("report"), # type: ignore[arg-type]
- key=str(kwargs.get("key") or "auto"),
+ key=str(kwargs.get("key") or "auto"), fit=str(kwargs.get("fit") or "state"),
)
print(json.dumps(payload, ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.py
index 8862e7f..8f5f7ad 100644
--- a/sprite_gen/video/frames.py
+++ b/sprite_gen/video/frames.py
@@ -18,6 +18,10 @@ the border rule: an edge pixel is border evidence) is **residual background**,
anything else is the **subject** — and the two fail
with different messages: residual points at `video-canvas` normalization of the
base still, subject contact at a taller/wider canvas.
+
+`--allow-subject-edge-contact` accepts the second and keeps the first: a clip made
+from a `video-canvas --fit tight` frame is clipped on purpose, but leftover key
+background at the edge is still a keying defect. The contacts stay in the report.
"""
from __future__ import annotations
@@ -156,6 +160,7 @@ def key_frames(
key: str = "auto",
check_edges: bool = True,
spill: str = "small",
+ allow_subject: bool = False,
) -> dict[str, Any]:
if spill not in ("small", "full"):
raise SystemExit(f"video-frames: key_frames takes a resolved spill mode (small|full), got {spill!r}")
@@ -190,27 +195,41 @@ def key_frames(
"alpha_zero_pct_min": min(r["alpha_zero_pct"] for r in rows),
"alpha_zero_pct_max": max(r["alpha_zero_pct"] for r in rows),
"edge_contacts": contacts,
+ "edge_policy": "off" if not check_edges else ("subject-allowed" if allow_subject else "refuse"),
"rows": rows,
}
if contacts and check_edges:
- raise SystemExit(_edge_contact_message(contacts))
+ if not allow_subject:
+ raise SystemExit(_edge_contact_message(contacts))
+ residual = [c for c in contacts if c["residual"] > 0]
+ if residual:
+ raise SystemExit(_residual_message(residual))
return report
+def _worst(contacts: list[dict[str, Any]]) -> tuple[dict[str, Any], str]:
+ worst = max(contacts, key=lambda c: c["top"] + c["left"] + c["right"])
+ return worst, f"(worst {worst['frame']}: top {worst['top']} / left {worst['left']} / right {worst['right']} px)"
+
+
+def _residual_message(contacts: list[dict[str, Any]]) -> str:
+ worst, where = _worst(contacts)
+ painted = tuple(worst["key_painted"]) if worst.get("key_painted") else None
+ return (
+ f"video-frames: leftover chroma background reaches the frame edge in {len(contacts)} frame(s) {where} — "
+ f"the key survived the matte (painted background {painted}); this is background, not the subject: "
+ "normalize the base still with `sprite-gen video-canvas` (repaints the flat background to the exact key) "
+ "and regenerate the clip"
+ )
+
+
def _edge_contact_message(contacts: list[dict[str, Any]]) -> str:
"""Residual background and a clipped subject are different defects with different fixes."""
- worst = max(contacts, key=lambda c: c["top"] + c["left"] + c["right"])
- where = f"(worst {worst['frame']}: top {worst['top']} / left {worst['left']} / right {worst['right']} px)"
+ worst, where = _worst(contacts)
subject_frames = [c for c in contacts if c["subject"] > 0]
residual_frames = [c for c in contacts if c["residual"] > 0]
if not subject_frames:
- painted = tuple(worst["key_painted"]) if worst.get("key_painted") else None
- return (
- f"video-frames: leftover chroma background reaches the frame edge in {len(contacts)} frame(s) {where} — "
- f"the key survived the matte (painted background {painted}); this is background, not the subject: "
- "normalize the base still with `sprite-gen video-canvas` (repaints the flat background to the exact key) "
- "and regenerate the clip"
- )
+ return _residual_message(contacts)
message = (
f"video-frames: the subject touches the frame edge in {len(subject_frames)} frame(s) {where} — "
"the clip was framed too tight; regenerate from a taller/wider canvas (`sprite-gen video-canvas`) "
@@ -221,7 +240,7 @@ def _edge_contact_message(contacts: list[dict[str, Any]]) -> str:
return message
-def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None, spill: str = "small", reference: Path | None = None) -> dict[str, Any]:
+def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None, spill: str = "small", reference: Path | None = None, allow_subject_edge_contact: bool = False) -> dict[str, Any]:
if spill not in SPILL_MODES:
raise SystemExit(f"video-frames: unknown --spill {spill!r}; expected one of {', '.join(SPILL_MODES)}")
if spill == "auto" and reference is None:
@@ -235,7 +254,7 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,
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)
- report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"])
+ report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"], allow_subject=allow_subject_edge_contact)
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()
atomic_write_text(target, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
@@ -247,7 +266,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--clip", required=True, type=Path, help="mp4 from `sprite-gen video`")
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 frames whose subject touches the top/left/right edge")
+ 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)")
+ parser.add_argument("--allow-subject-edge-contact", action="store_true", help="accept the subject touching the top/left/right edge (a `video-canvas --fit tight` clip) but still refuse leftover key background there")
parser.add_argument("--report", type=Path, help="report JSON (default <out-dir>/frames.report.json)")
parser.add_argument("--spill", choices=SPILL_MODES, default="small", help="small: correct only small key-tinted clusters (default); full: every key tint in the subject is spill; auto: decide from --reference")
parser.add_argument("--reference", type=Path, help="the still the clip was made from (required by --spill auto)")
@@ -256,8 +276,9 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
def run(**kwargs: object) -> int:
payload = run_frames(Path(str(kwargs["clip"])), Path(str(kwargs["out_dir"])), key=str(kwargs.get("key") or "auto"),
allow_edge_contact=bool(kwargs.get("allow_edge_contact")), report_path=kwargs.get("report"), # type: ignore[arg-type]
- spill=str(kwargs.get("spill") or "small"), reference=kwargs.get("reference")) # type: ignore[arg-type]
- summary = {k: payload[k] for k in ("clip", "keyed_dir", "fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "spill", "report")}
+ 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")))
+ 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")}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index ec19a49..5f09f9a 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -553,7 +553,20 @@ def ramp_frames(frames: list[Image.Image], wrap_dx: int) -> list[Image.Image]:
return out
-def build_strip(frames: list[Image.Image], *, max_cells: int = STRIP_MAX_CELLS, max_height: int = STRIP_MAX_HEIGHT, max_width: int = STRIP_MAX_WIDTH, cycle_seconds: float, body_height: int | None = None, anchor: str = "none", kind: str = "periodic") -> tuple[Image.Image, dict[str, Any]]:
+def first_frame_height(path: Path) -> int:
+ """The subject's height in the clip's first frame: the base still's pose as filmed.
+
+ Every clip starts from its still (image-to-video), so this is the same pose in every
+ state of one character — which is what one `--body-height` across states has to measure
+ to give that character one size.
+ """
+ box = Image.open(path).convert("RGBA").getchannel("A").point(lambda v: 255 if v >= 8 else 0).getbbox()
+ if box is None:
+ raise SystemExit(f"video-loop: {path.name}, the clip's first frame, has no subject to measure the standing height on (--body-height)")
+ return box[3] - box[1]
+
+
+def build_strip(frames: list[Image.Image], *, max_cells: int = STRIP_MAX_CELLS, max_height: int = STRIP_MAX_HEIGHT, max_width: int = STRIP_MAX_WIDTH, cycle_seconds: float, body_height: int | None = None, anchor: str = "none", kind: str = "periodic", standing_src: int | None = None) -> tuple[Image.Image, dict[str, Any]]:
"""Union-crop (no bottom pad so feet meet the floor), scale, bottom-align, tile horizontally.
The cell count is capped by the strip's PIXEL width (`max_width`) as well as by
@@ -573,7 +586,10 @@ def build_strip(frames: list[Image.Image], *, max_cells: int = STRIP_MAX_CELLS,
# over-scales it — the 2026-09-09 hero read 22 % taller than the walk beside it.
floor = max(b[3] for b in boxes)
grounded = [b[3] - b[1] for b in boxes if b[3] >= floor - 4] or [b[3] - b[1] for b in boxes]
- body_src = max(grounded)
+ # `standing_src` is the caller's own measurement of the standing pose (run_loop: the clip's
+ # first frame). The tallest grounded frame counts whatever is raised overhead — an attack's
+ # windup lifts the weapon above the head — and would shrink that state against the others.
+ body_src = standing_src if standing_src is not None else max(grounded)
# max_height is a ceiling on the CELL; an explicit body_height is a target for the BODY.
# Without one, nothing is ever scaled up. With one, a state whose source body is SHORTER
# than the request has to grow — clamping to 1.0 first made the option a downward clamp
@@ -622,6 +638,9 @@ def build_strip(frames: list[Image.Image], *, max_cells: int = STRIP_MAX_CELLS,
"kind": kind,
"loop": kind != "one-shot",
"body_h": round(body_src * scale),
+ "body_src_h": body_src, # the standing height as filmed; body_h / body_src_h > 1 means the cells were upscaled
+ "body_ref": "first-frame" if standing_src is not None else "tallest-grounded",
+ "scale": round(scale, 4),
"delay_ms": round(1000 * cycle_seconds / len(cells), 2),
"cycle_frames": L,
"cycle_seconds": round(cycle_seconds, 4),
@@ -866,7 +885,8 @@ def run_loop(
old.unlink()
for k, im in enumerate(frames):
im.save(cycle_dir / f"frame-{k:03d}.png")
- strip, strip_meta = build_strip(frames, max_height=strip_height, cycle_seconds=cycle_seconds, body_height=body_height, anchor="feet" if anchor == "feet" else "none", kind=str(cycle.get("kind") or "periodic"))
+ strip, strip_meta = build_strip(frames, max_height=strip_height, cycle_seconds=cycle_seconds, body_height=body_height, anchor="feet" if anchor == "feet" else "none", kind=str(cycle.get("kind") or "periodic"),
+ standing_src=first_frame_height(files[0]) if body_height is not None else None)
if motion is not None:
strip_meta["foot_anchor"] = anchor
strip_meta["motion_anchor"] = motion
@@ -968,7 +988,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
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")
- parser.add_argument("--body-height", type=int, help="scale so the STANDING height (tallest floor-contact frame) is this many px — the same value across states gives the same character size; --strip-height stays the cap")
+ parser.add_argument("--body-height", type=int, help="scale so the STANDING height (the subject in the clip's first frame, i.e. the base still's pose) is this many px — the same value across states gives the same character size; --strip-height stays the cap")
parser.add_argument("--anchor", choices=ANCHOR_MODES, default=None, help="motion-auto: automatic stable regions, local repeat selection and XY ramp (walk/run); motion: fixed cut with explicit regions; body (default for walk/run): measure the last-to-first head-and-torso offset once and spread it as a ramp over the cycle; feet: remove in-canvas drift (a straight-line trend) so every cell stands on the mean foot line; none: leave placement as filmed (default for other states)")
parser.add_argument("--anchor-region", type=motion_anchor.parse_region, action="append", help="motion anchor only: repeat twice with head then torso x0,y0,x1,y1 in the first selected frame; requires --cycle fixed and at least 6 frames")
parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")
diff --git a/tests/video/test_attack_motion.py b/tests/video/test_attack_motion.py
index d3ac667..0e3ef20 100644
--- a/tests/video/test_attack_motion.py
+++ b/tests/video/test_attack_motion.py
@@ -86,7 +86,7 @@ def test_video_set_gives_every_state_the_same_body_height(tmp_path: Path, monkey
from PIL import Image
seen: list = []
- def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path):
+ def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path, fit="state"):
Image.new("RGB", (32, 32), (0, 255, 0)).save(out)
return {"shape": "square", "canvas": [32, 32], "offset": [0, 0]}
diff --git a/tests/video/test_fit_tight.py b/tests/video/test_fit_tight.py
new file mode 100644
index 0000000..ffad90c
--- /dev/null
+++ b/tests/video/test_fit_tight.py
@@ -0,0 +1,208 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`video-canvas --fit tight` drops the empty rows around the subject and adds no room;
+`video-frames --allow-subject-edge-contact` accepts the clipping that follows but still
+refuses leftover key background at the edge."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.video import batch as batch_mod
+from sprite_gen.video import canvas as canvas_mod
+from sprite_gen.video import frames as frames_mod
+from tests.video.test_canvas_key_normalize import _frames
+
+GREEN = (0, 255, 0)
+IVORY = (248, 247, 242)
+SUBJECT = (200, 40, 40)
+
+
+def _still(tmp_path: Path, size: tuple[int, int], box: tuple[int, int, int, int], bg=GREEN, name="still.png") -> Path:
+ im = Image.new("RGB", size, bg)
+ x0, y0, x1, y1 = box
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ # a gradient, so a scaled or shifted subject would not compare equal
+ im.putpixel((x, y), (SUBJECT[0] - (x - x0), SUBJECT[1] + (y - y0) % 50, SUBJECT[2]))
+ path = tmp_path / name
+ im.save(path)
+ return path
+
+
+def _tight(tmp_path: Path, still: Path, **kw) -> tuple[Image.Image, dict]:
+ out = tmp_path / "canvas.png"
+ report = canvas_mod.run_canvas(still, out, state="attack", shape=None, facing="right", headroom=None, lead=None, report_path=None, fit="tight", **kw)
+ return Image.open(out).convert("RGB"), report
+
+
+def _subject_box(canvas: Image.Image, bg=GREEN) -> tuple[int, int, int, int]:
+ data = np.asarray(canvas, dtype=np.int16)
+ mask = np.abs(data - np.array(bg, dtype=np.int16)).max(axis=2) > 0
+ ys, xs = np.nonzero(mask)
+ return int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1
+
+
+def test_a_long_low_subject_in_a_square_still_becomes_a_wide_frame_it_fills(tmp_path: Path) -> None:
+ box = (10, 50, 190, 130) # 180 x 80 inside a 200 x 200 still: most of the height is empty
+ canvas, report = _tight(tmp_path, _still(tmp_path, (200, 200), box))
+ assert report["fit"] == "tight" and report["shape"] == "wide"
+ assert canvas.size == (200, round(200 / (16 / 9)))
+ x0, y0, x1, y1 = _subject_box(canvas)
+ assert (x1 - x0, y1 - y0) == (180, 80) # never scaled
+ assert y1 == canvas.height # stands on the bottom edge
+ assert (y1 - y0) / canvas.height > 0.7 # the subject fills the height; it was 0.4 of the still
+ assert report["tight"]["subject_rows"] == [50, 130]
+
+
+def test_an_upright_subject_in_a_square_still_keeps_the_square(tmp_path: Path) -> None:
+ box = (70, 20, 130, 190) # 60 x 170: already fills the height
+ canvas, report = _tight(tmp_path, _still(tmp_path, (200, 200), box))
+ assert report["shape"] == "square" and canvas.size == (200, 200)
+ x0, y0, x1, y1 = _subject_box(canvas)
+ assert (x0, x1, y1) == (70, 130, 200) # width kept as drawn, moved down onto the bottom edge
+
+
+def test_the_subject_pixels_are_the_stills_own(tmp_path: Path) -> None:
+ box = (10, 50, 190, 130)
+ still = _still(tmp_path, (200, 200), box)
+ canvas, report = _tight(tmp_path, still)
+ x0, y0, x1, y1 = _subject_box(canvas)
+ original = np.asarray(Image.open(still).convert("RGB").crop(box))
+ assert np.array_equal(np.asarray(canvas.crop((x0, y0, x1, y1))), original)
+
+
+def test_headroom_is_a_small_share_of_the_subject(tmp_path: Path) -> None:
+ box = (10, 50, 190, 130)
+ _, report = _tight(tmp_path, _still(tmp_path, (200, 200), box))
+ assert report["tight"]["headroom_px"] == round(80 * canvas_mod.TIGHT_HEADROOM)
+ assert report["tight"]["kept_rows"] == [50 - report["tight"]["headroom_px"], 130]
+
+
+def test_a_narrow_band_snaps_to_the_nearest_framing_by_adding_width(tmp_path: Path) -> None:
+ box = (10, 5, 50, 195) # 60 x 200 still, 40 x 190 subject: taller than 9:16
+ canvas, report = _tight(tmp_path, _still(tmp_path, (60, 200), box))
+ assert report["shape"] == "tall"
+ kept = report["tight"]["kept_rows"]
+ band_h = kept[1] - kept[0]
+ assert canvas.size == (round(band_h * 9 / 16), band_h)
+ # the still's full width is kept and centred; the subject keeps its place inside it
+ assert _subject_box(canvas)[0] == (canvas.width - 60) // 2 + 10
+
+
[email protected]("size,bottom,shape", [
+ ((200, 200), 152, "square"), # band 200/152 = 1.32, under the 1:1 / 16:9 midpoint (4:3)
+ ((200, 200), 148, "wide"), # 200/148 = 1.35, over it
+ ((60, 100), 79, "square"), # 60/79 = 0.76, over the 9:16 / 1:1 midpoint (3:4)
+ ((60, 100), 81, "tall"), # 60/81 = 0.74, under it
+])
+def test_the_framing_is_the_nearest_ratio_either_side_of_the_midpoints(tmp_path: Path, size, bottom, shape) -> None:
+ # a subject from the top row has no headroom to add, so the band is exactly `bottom` rows
+ _, report = _tight(tmp_path, _still(tmp_path, size, (5, 0, 20, bottom)))
+ assert report["tight"]["kept_rows"] == [0, bottom]
+ assert report["shape"] == shape
+
+
+def test_a_white_base_is_trimmed_by_its_corner_colour(tmp_path: Path) -> None:
+ box = (10, 50, 190, 130)
+ canvas, report = _tight(tmp_path, _still(tmp_path, (200, 200), box, bg=IVORY), key="white")
+ assert report["shape"] == "wide" and report["key"] is None
+ assert _subject_box(canvas, IVORY)[3] == canvas.height
+
+
+def test_tight_refuses_the_state_room_flags(tmp_path: Path) -> None:
+ still = _still(tmp_path, (200, 200), (10, 50, 190, 130))
+ for extra in ({"shape": "wide"}, {"headroom": 0.2}, {"lead": 0.1}, {"trail": 0.1}):
+ kw = {"shape": None, "headroom": None, "lead": None, **extra}
+ with pytest.raises(SystemExit, match="--fit tight"):
+ canvas_mod.run_canvas(still, tmp_path / "c.png", state="attack", facing="right", report_path=None, fit="tight", **kw)
+
+
+def test_a_still_with_no_subject_is_refused(tmp_path: Path) -> None:
+ empty = tmp_path / "empty.png"
+ Image.new("RGB", (64, 64), GREEN).save(empty)
+ with pytest.raises(SystemExit, match="no subject"):
+ _tight(tmp_path, empty)
+
+
+def test_the_state_fit_is_unchanged_and_says_so(tmp_path: Path) -> None:
+ still = _still(tmp_path, (200, 200), (70, 20, 130, 190))
+ report = canvas_mod.run_canvas(still, tmp_path / "c.png", state="attack", shape=None, facing="right", headroom=None, lead=None, report_path=None)
+ assert report["fit"] == "state" and report["shape"] == "wide" and "tight" not in report
+
+
+# --- frames: the subject may leave a tight frame, leftover background may not ---------
+
+
+def test_subject_contact_passes_when_allowed_and_stays_in_the_report(tmp_path: Path) -> None:
+ files = _frames(tmp_path, residual=False, touch_top=True)
+ report = frames_mod.key_frames(files, tmp_path / "keyed", key="green", allow_subject=True)
+ assert report["edge_policy"] == "subject-allowed"
+ assert report["edge_contacts"] and all(c["subject"] > 0 for c in report["edge_contacts"])
+
+
+def test_leftover_background_still_fails_when_the_subject_is_allowed(tmp_path: Path) -> None:
+ files = _frames(tmp_path, residual=True, touch_top=True)
+ with pytest.raises(SystemExit, match="leftover chroma background") as info:
+ frames_mod.key_frames(files, tmp_path / "keyed", key="green", allow_subject=True)
+ assert "framed too tight" not in str(info.value)
+
+
+def test_the_default_policy_is_unchanged(tmp_path: Path) -> None:
+ files = _frames(tmp_path, residual=False, touch_top=True)
+ with pytest.raises(SystemExit, match="framed too tight"):
+ frames_mod.key_frames(files, tmp_path / "keyed", key="green")
+ assert frames_mod.key_frames(files, tmp_path / "keyed2", key="green", check_edges=False)["edge_policy"] == "off"
+
+
+def test_the_cli_takes_the_new_flags() -> None:
+ import argparse
+
+ frames_parser = argparse.ArgumentParser()
+ frames_mod.add_arguments(frames_parser)
+ assert frames_parser.parse_args(["--clip", "c", "--out-dir", "o", "--allow-subject-edge-contact"]).allow_subject_edge_contact is True
+ canvas_parser = argparse.ArgumentParser()
+ canvas_mod.add_arguments(canvas_parser)
+ assert canvas_parser.parse_args(["--still", "s", "--out", "o"]).fit == "state"
+ assert canvas_parser.parse_args(["--still", "s", "--out", "o", "--fit", "tight"]).fit == "tight"
+ set_parser = argparse.ArgumentParser()
+ batch_mod.add_arguments(set_parser)
+ assert set_parser.parse_args(["--out-dir", "x", "--fit", "tight"]).fit == "tight"
+
+
+# --- video-set: tight frames every item and lets its subject reach the edge ----------
+
+
+def test_video_set_fit_tight_reaches_canvas_and_frames(tmp_path: Path, monkeypatch) -> None:
+ seen: dict[str, object] = {}
+
+ def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path, fit="state"):
+ seen["fit"] = fit
+ Image.new("RGB", (32, 18), GREEN).save(out)
+ return {"fit": fit, "shape": "wide", "canvas": [32, 18], "offset": [0, 0]}
+
+ def fake_frames(clip, out_dir, **kw):
+ seen["allow_subject"] = kw.get("allow_subject_edge_contact")
+ raise SystemExit("stop after frames")
+
+ def video(image, prompt, out, report, **kw):
+ Path(out).write_bytes(b"x")
+ Path(report).write_text("{}")
+ Path(kw["log"]).write_text("")
+ return 0
+
+ monkeypatch.setattr(batch_mod.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
+ monkeypatch.setattr(batch_mod.canvas_mod, "run_canvas", fake_canvas)
+ monkeypatch.setattr(batch_mod.frames_mod, "run_frames", fake_frames)
+ base = tmp_path / "base.png"
+ Image.new("RGB", (32, 32), GREEN).save(base)
+ payload = batch_mod.run_set(bases={"side": base}, states=["attack"], root=tmp_path / "set", character=None, duration=None,
+ resolution="480p", key="green", concurrency=1, force=False, gap=0.0, video_runner=video, fit="tight")
+ assert seen == {"fit": "tight", "allow_subject": True}
+ assert payload["failed"]
+ with pytest.raises(SystemExit, match="--fit tight"):
+ batch_mod.run_set(bases={"side": base}, states=["attack"], root=tmp_path / "set2", character=None, duration=None,
+ resolution="480p", key="green", concurrency=1, force=False, gap=0.0, video_runner=video, fit="tight", shape="wide")
diff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.py
index f875abf..4e8ddc0 100644
--- a/tests/video/test_gait_guard_anchor_wide.py
+++ b/tests/video/test_gait_guard_anchor_wide.py
@@ -199,12 +199,12 @@ def test_raised_limb_states_get_a_wide_canvas() -> None:
def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch, state, anchor) -> None:
seen: dict[str, object] = {}
- def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path):
+ def fake_canvas(base, out, *, state, shape, facing, headroom, lead, report_path, fit="state"):
seen["shape"] = shape
Image.new("RGB", (32, 32), (0, 255, 0)).save(out)
return {"shape": shape or "square", "canvas": [32, 32], "offset": [0, 0]}
- def fake_frames(clip, out_dir, *, key, allow_edge_contact, report_path, spill, reference):
+ def fake_frames(clip, out_dir, *, key, allow_edge_contact, report_path, spill, reference, allow_subject_edge_contact=False):
seen["spill"] = (spill, Path(reference).name)
keyed = Path(out_dir) / "keyed"
keyed.mkdir(parents=True, exist_ok=True)
diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.py
index cc9458a..42c8241 100644
--- a/tests/video/test_video_pipeline.py
+++ b/tests/video/test_video_pipeline.py
@@ -409,6 +409,30 @@ def test_body_h_is_the_standing_height_not_the_cycle_median() -> None:
assert meta3["h"] <= 40, "--strip-height stays the cap"
+def test_body_height_measures_the_clips_first_frame_not_a_raised_weapon(tmp_path: Path) -> None:
+ """Every clip starts from its still, so the first frame is the one pose all of a
+ character's states share. An attack's tallest grounded frame is its windup with the
+ weapon overhead; scaled to the target, it made the attacking character smaller than
+ the walking one."""
+ files = _gait_frames(tmp_path, period=12, n=72)
+ for path in files[1:]: # from the second frame on, something is held up above the head
+ im = Image.open(path)
+ for y in range(2, 10):
+ im.putpixel((36, y), (120, 120, 120, 255))
+ im.save(path)
+ rep = loop_mod.run_loop(tmp_path / "keyed", tmp_path / "out", fps=24.0, state="walk", min_len=None, max_len=None,
+ n_out=8, seam_max=9.0, name="w", report_path=None, body_height=48)
+ meta = json.loads((tmp_path / "out" / "w.strip.json").read_text())
+ assert meta["body_ref"] == "first-frame"
+ assert (meta["body_src_h"], meta["scale"], meta["body_h"]) == (48, 1.0, 48) # the raised frames are 56 tall
+ assert rep["strip"]["body_h"] == 48
+ # without a target nothing changes: the tallest grounded frame, never scaled up
+ loop_mod.run_loop(tmp_path / "keyed", tmp_path / "plain", fps=24.0, state="walk", min_len=None, max_len=None,
+ n_out=8, seam_max=9.0, name="w", report_path=None)
+ plain = json.loads((tmp_path / "plain" / "w.strip.json").read_text())
+ assert plain["body_ref"] == "tallest-grounded" and plain["body_src_h"] == 56
+
+
def test_body_height_is_a_target_across_states_not_a_downward_clamp() -> None:
"""`--body-height` exists so the same number across states gives one character size.
That only holds if a state whose source body is SHORTER than the request scales UP:
@@ -427,6 +451,9 @@ def test_body_height_is_a_target_across_states_not_a_downward_clamp() -> None:
_, short_meta = loop_mod.build_strip(short, cycle_seconds=4 / 24, body_height=60)
_, tall_meta = loop_mod.build_strip(tall, cycle_seconds=4 / 24, body_height=60)
assert short_meta["body_h"] == tall_meta["body_h"] == 60
+ # the sidecar says which one was filmed small: the short body was upscaled, the tall one was not
+ assert (short_meta["body_src_h"], short_meta["scale"]) == (40, 1.5)
+ assert (tall_meta["body_src_h"], tall_meta["scale"]) == (80, 0.75)
# No body_height still never scales up: that is what --strip-height is for.
_, plain = loop_mod.build_strip(short, cycle_seconds=4 / 24)