Skip to content

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

fix(video-sway): --read-on-cut takes each cut's crop on the frame as filmed, less where its anchor moved that frame (the body anchor's ramp, the motion anchor's correction), so two cuts at --anchor body or motion pair a frame where it lies; a record that does not give that move, and a strip aligned from its cut, are refused no-match

Soohong Kim99b55e8456ec
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 79ecf81..fbb4e79 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -706,14 +706,19 @@ def body_wrap_offset(frames: list[Image.Image], *, band: float = BODY_ANCHOR_BAN
return min(range(-search, search + 1), key=cost)
+def ramp_offset(wrap_dx: int, k: int, length: int) -> int:
+ """How far across the ramp of a cycle `length` frames long moves its frame k (`ramp_frames`): round(wrap_dx * k / L)."""
+ return int(round(wrap_dx * k / length))
+
+
def ramp_frames(frames: list[Image.Image], wrap_dx: int) -> list[Image.Image]:
- """Shift frame k by round(wrap_dx * k / L) so the cycle's end returns to its start."""
+ """Shift frame k by round(wrap_dx * k / L) (`ramp_offset`) so the cycle's end returns to its start."""
L = len(frames)
if wrap_dx == 0 or L < 2:
return frames
out = []
for k, im in enumerate(frames):
- dx = int(round(wrap_dx * k / L))
+ dx = ramp_offset(wrap_dx, k, L)
if dx == 0:
out.append(im)
continue
diff --git a/sprite_gen/video/motion_anchor.py b/sprite_gen/video/motion_anchor.py
index d22fc72..5bd3651 100644
--- a/sprite_gen/video/motion_anchor.py
+++ b/sprite_gen/video/motion_anchor.py
@@ -222,12 +222,7 @@ def correct_motion(frames: list[Image.Image], regions: list[Box], *, coarse_dx:
left, top = (-np.minimum(shifts.min(axis=0), 0)).tolist()
right, bottom = np.maximum(shifts.max(axis=0), 0).tolist()
width, height = frames[0].size
- corrected = []
- for frame, (dx, dy) in zip(frames, shifts.tolist()):
- canvas = Image.new("RGBA", (width + left + right, height + top + bottom))
- canvas.paste(frame, (left + dx, top + dy))
- corrected.append(canvas)
- return corrected, {
+ record = {
"method": "masked-ncc-boundary-velocity-v1", "regions": [list(b) for b in regions],
"region_weights": list(REGION_WEIGHTS), "search_radius_xy": list(SEARCH_RADIUS),
"coarse_dx_px": coarse_dx, "boundary_measurements": measurements,
@@ -235,3 +230,17 @@ def correct_motion(frames: list[Image.Image], regions: list[Box], *, coarse_dx:
"endpoint_float_xy": endpoint_float.tolist(), "endpoint_xy": endpoint.tolist(),
"shifts_xy": shifts.tolist(), "padding_ltrb": [left, top, right, bottom],
}
+ corrected = []
+ for k, frame in enumerate(frames):
+ canvas = Image.new("RGBA", (width + left + right, height + top + bottom))
+ canvas.paste(frame, laid_at(record, k))
+ corrected.append(canvas)
+ return corrected, record
+
+
+def laid_at(record: dict, k: int) -> tuple[int, int]:
+ """Where `correct_motion` laid frame k of its cycle on the canvas it gives every frame (its `record`): the padding's
+ left and top, and that frame's shift."""
+ left, top = record["padding_ltrb"][:2]
+ dx, dy = record["shifts_xy"][k]
+ return left + dx, top + dy
diff --git a/sprite_gen/video/sway.py b/sprite_gen/video/sway.py
index a40c855..f233876 100644
--- a/sprite_gen/video/sway.py
+++ b/sprite_gen/video/sway.py
@@ -53,8 +53,10 @@ the cut's cell pixel for pixel (a crop or a scale changed, and nothing records h
carry: refused `uncertain`, never carried by the nearest whole cell. Another cut of this loop's own clip,
named by `--read-on-cut STRIP` with its record beside it, is `recut`: paired by the source frame its cell 0
is, its regions and masks moved onto this loop's cell that is that frame by the whole px shift the two
-crops set it apart by (`recut_pair`), never scaled. Any other strip is refused `no-match`. Without
-`--read-on` nothing of this is read or written.
+crops set it apart by on the frame as filmed — each crop less where its cut's anchor moved that frame, as
+its record gives it (`anchor_move`; refused `no-match` where a record does not) — never scaled
+(`recut_pair`). Any other strip is refused `no-match`. Without `--read-on` nothing of this is read or
+written.
`--stretch-floor D` asks every region's move to leave each pixel at least D of its area. The weight's
steepest slope is π/2 over each radius, so a move (ox, oy) leaves 1 − (π/2)·hypot(ox/rx, oy/ry) of it —
@@ -187,6 +189,7 @@ from sprite_gen.frames import folder as folder_mod
from sprite_gen.spec.runio import atomic_write_text
from sprite_gen.util.gif_utils import save_clean_gif
from sprite_gen.video import loop as loop_mod
+from sprite_gen.video import motion_anchor
from sprite_gen.util.console import utf8_streams
VERB = "video-sway"
@@ -216,7 +219,8 @@ SOURCE = loop_mod.FOLLOW_SOURCE
TRANSPORT_POLICY = "cut-reading/whole-cell/1"
# How regions read on another cut of the same clip are paired with this loop's cut (`--read-on` with `--read-on-cut`): by
# the source frame the cut's cell 0 is, onto the cell of this loop's cut that is that frame, moved by the whole px the two
-# crops set that frame's pixels apart; never scaled or grown.
+# crops set that frame's pixels apart, each crop taken on the frame as filmed (less where its cut's anchor moved it); never
+# scaled or grown.
RECUT_POLICY = "same-clip/source-frame/whole-px-shift/1"
RECUT_DRIFT = 1.0 # px: the most a pixel of the one cut may lie off the whole shift from the same pixel of the other
# How `--stretch-floor` reads a region's least area: the cos² weight's closed form, by direction, never above the
@@ -570,14 +574,48 @@ def _clip(cut: dict[str, Any]) -> str:
return str(source.get("sha256", source)) if isinstance(source, dict) else str(source)
+def anchor_move(record: dict[str, Any], cell: int) -> tuple[int, int]:
+ """Where the anchor of a cut moved the frame its cell `cell` is before the cut was cropped, across and down in px of
+ the frame as filmed, read off the cut's record as `video-loop` writes one (`record`; `foot_anchor`, `source_cut`):
+ at --anchor none nothing; at --anchor body the ramp's move of that frame of the cut (`loop.ramp_offset` of
+ `wrap_dx_px`); at --anchor motion and motion-auto where the correction laid it on the canvas it gives every frame
+ (`motion_anchor.laid_at`). A ValueError says what the record does not give, where it does not give it whole."""
+ anchor = record.get("foot_anchor")
+ if anchor == "none":
+ return 0, 0
+ if anchor not in ("body", "motion", "motion-auto"):
+ raise ValueError("it does not say how its frames were anchored (foot_anchor)" if anchor is None else
+ f"its anchor (--anchor {anchor}) keeps no move of each frame")
+ cut = record["source_cut"]
+ start, length = cut.get("start"), cut.get("length")
+ k = int(cut["samples"][cell]) - start if type(start) is int else None # the frame of the cut the cell is
+ if type(length) is not int or k is None or not 0 <= k < length:
+ raise ValueError(f"it names no whole start and length of its cut that hold its cell {cell} (source_cut)")
+ if anchor == "body":
+ wrap = record.get("wrap_dx_px")
+ if type(wrap) is not int:
+ raise ValueError("it was cut at --anchor body and records no whole wrap offset (wrap_dx_px)")
+ return loop_mod.ramp_offset(wrap, k, length), 0
+ motion = record.get("motion_anchor") or {}
+ shifts, padding = motion.get("shifts_xy"), motion.get("padding_ltrb")
+ if not (isinstance(shifts, list) and len(shifts) == length and isinstance(shifts[k], list) and len(shifts[k]) == 2
+ and isinstance(padding, list) and len(padding) == 4 and all(type(v) is int for v in (*padding[:2], *shifts[k]))):
+ raise ValueError(f"it was cut at --anchor {anchor} and records no whole shift of its frame {k} of {length} and no "
+ "padding (motion_anchor)")
+ return motion_anchor.laid_at(motion, k)
+
+
def recut_pair(meta: dict[str, Any], cut: dict[str, Any], read_on: str, size: tuple[int, int], *,
verb: str = VERB) -> dict[str, Any]:
"""How the cut the regions were read on (`cut`: its record, `--read-on-cut`; `read_on` its strip's sha256) pairs with
this loop's cut (`meta`; cells `size`) when both are cut from one source clip (`source_cut`): the source frame the
cut's cell 0 is, the cell of this loop's cut that is that frame, and the whole px across and down a pixel of that
- frame lies from where it lies in the cut (their crops and scales, `source_rect`; a pixel lies at most RECUT_DRIFT px
- off that shift anywhere in the cell). Refused `no-match` where they are not one clip's or the frame is not this
- cut's, saying which; `uncertain` where their crops do not set the frame apart by one whole shift."""
+ frame lies from where it lies in the cut — their crops and scales (`source_rect`) taken on the frame as filmed, each
+ less where its cut's anchor moved that frame before the crop (`anchor_move`); a pixel lies at most RECUT_DRIFT px
+ off that shift anywhere in the cell. Refused `no-match` where they are not one clip's, the frame is not this cut's,
+ a record does not give where its anchor moved the frame, or the strip named is a loop aligned from a cut (its cell 0
+ is not the frame its cut starts on), saying which; `uncertain` where their crops do not set the frame apart by one
+ whole shift."""
then, now = cut.get("source_cut"), meta.get("source_cut")
def no_match(why: str) -> SystemExit:
@@ -587,6 +625,9 @@ def recut_pair(meta: dict[str, Any], cut: dict[str, Any], read_on: str, size: tu
for whose, record in (("the cut's (--read-on-cut)", then), ("this loop's", now)):
if not isinstance(record, dict) or not record.get("samples"):
raise no_match(f"and {whose} record names no source frame its cells are (source_cut)")
+ if cut.get("cycle_align") is not None:
+ raise no_match("but the strip --read-on-cut names is a loop aligned from its cut (cycle_align), whose cells are not "
+ "the cut's frames in order")
if then.get("source") != now.get("source"):
raise no_match(f"of another clip ({_clip(then)}; this loop's is {_clip(now)})")
frame, held = int(then["samples"][0]), [int(f) for f in now["samples"]]
@@ -603,10 +644,18 @@ def recut_pair(meta: dict[str, Any], cut: dict[str, Any], read_on: str, size: tu
rects = cut.get("source_rect"), meta.get("source_rect")
if rects[0] is None or rects[1] is None:
raise uncertain("a cut records no crop (laid by its feet, each frame is placed on its own)")
+ moves = []
+ for whose, record, at in (("the cut's (--read-on-cut)", cut, 0), ("this loop's", meta, cell)):
+ try:
+ moves.append(anchor_move(record, at))
+ except ValueError as exc:
+ raise no_match(f"whose cell 0 is source frame {frame} (this loop's cut's cell {cell}), but where the anchor moved "
+ f"that frame before the crop cannot be read off {whose} record: {exc}") from None
sizes = (int(cut["w"]), int(cut["h"])), size
shift, drift = [], []
for axis in (0, 1):
- (lo0, hi0), (lo1, hi1) = (rects[0][axis], rects[0][axis + 2]), (rects[1][axis], rects[1][axis + 2])
+ # each crop on the frame as filmed: where it lies on the frame its anchor moved, less that move
+ (lo0, hi0), (lo1, hi1) = ((rect[axis] - move[axis], rect[axis + 2] - move[axis]) for rect, move in zip(rects, moves))
per0, per1 = sizes[0][axis] / (hi0 - lo0), sizes[1][axis] / (hi1 - lo1) # cell px a source px, then and now
# where the first and the last pixel of the cut's cell lie in this loop's cell, less where they lay
ends = [(lo0 + (x + 0.5) / per0 - lo1) * per1 - 0.5 - x for x in (0, sizes[0][axis] - 1)]
@@ -614,7 +663,7 @@ def recut_pair(meta: dict[str, Any], cut: dict[str, Any], read_on: str, size: tu
shift.append(whole)
drift.append(round(max(abs(end - whole) for end in ends), 4))
if max(drift) > RECUT_DRIFT:
- raise uncertain(f"their crops and scales set a pixel up to {max(drift):g} px off one whole shift ({shift[0]}, "
+ raise uncertain(f"their crops, scales and anchors set a pixel up to {max(drift):g} px off one whole shift ({shift[0]}, "
f"{shift[1]}) across the cell, more than {RECUT_DRIFT:g}")
return {"pair_policy": RECUT_POLICY, "source_frame": frame, "cut_cell": cell, "shift_px": shift, "drift_px": drift,
"cut": {"sha256": read_on, "source": then.get("source"), "start": then.get("start"), "length": then.get("length"),
@@ -3479,9 +3528,11 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
help="with --read-on: the strip it names (its PNG, its record beside it as video-loop writes one), when "
"it is another cut of this loop's source clip (a cut again from the same clip, not a new take): "
"paired by the source frame its cell 0 is with the cell of this loop's cut that is that frame, the "
- "regions and the region mask moved onto that cell by the whole px the two crops set it apart, pixel "
- "for pixel, and carried from there (relation recut); refused no-match where the clip differs or "
- "this loop's cut does not hold that frame, uncertain where the crops do not set it apart by one "
+ "regions and the region mask moved onto that cell by the whole px the two crops set it apart, each "
+ "taken on the frame as filmed (less where its cut's anchor moved that frame, as its record gives "
+ "it), pixel for pixel, and carried from there (relation recut); refused no-match where the clip "
+ "differs, this loop's cut does not hold that frame, a record does not give its anchor's move of it "
+ "or the strip is a loop aligned from its cut, uncertain where the crops do not set it apart by one "
"whole shift. Off by default")
parser.add_argument("--band", type=parse_band, default=None, metavar=f"PX|{AUTO}",
help="move each region as one mass: 1 over its ellipse grown by --band-margin, falling to 0 (cos²) over PX px "
diff --git a/tests/video/test_sway_read_on_recut.py b/tests/video/test_sway_read_on_recut.py
index 7a436e4..faf689c 100644
--- a/tests/video/test_sway_read_on_recut.py
+++ b/tests/video/test_sway_read_on_recut.py
@@ -4,9 +4,12 @@ A clip cut twice (a cut, and a cut again from the same clip at another start and
source frames in other cells and at other places. The regions read on the first cut's cell 0, with the region mask drawn
there, are paired by the source frame that cell is with the cell of the loop's cut that is that frame, moved onto it by
the whole px the two crops set that frame apart, the mask pixel for pixel, and carried from there; on a loop aligned from
-its cut, through the alignment's record of where each cell is from. A cut whose frame the loop's cut does not hold, a cut
-whose record names no source frame and a cut of another clip are refused no-match, saying which, and leave the loop as
-it was. Synthetic figures only: the read-on test's runner, cut from a clip of two strides at two starts and two crops.
+its cut, through the alignment's record of where each cell is from. Each crop is taken on the frame as filmed: less where
+its cut's anchor moved that frame (the body anchor's ramp, the motion anchor's correction), as its record gives it. A cut
+whose frame the loop's cut does not hold, a cut whose record names no source frame, a cut of another clip, a record that
+does not give where its anchor moved the frame and a loop aligned from its cut are refused no-match, saying which, and
+leave the loop as it was. Synthetic figures only: the read-on test's runner, cut from a clip of two strides at two starts
+and two crops, by hand or by video-loop.
Each case first reads what a sway writes with the new key (its cells, its record, whether it refuses and what it says),
so on a release without it the same input fails on what comes out.
@@ -18,9 +21,9 @@ import numpy as np
import pytest
from PIL import Image
from sprite_gen import cli
-from sprite_gen.video import sway
+from sprite_gen.video import loop, sway
-from tests.video.test_follow_read_on import N, SHIFT, aligned, cells_of, cut, files, meta_of, runner, sha
+from tests.video.test_follow_read_on import H, N, PATCH, SHIFT, W, aligned, cells_of, cut, files, meta_of, runner, sha
from tests.video.test_sway_region import mask_png
CLIP = 2*N # the clip's frames: the runner's stride twice
@@ -40,9 +43,10 @@ def bbox(frames):
return int(xs.min()), int(ys.min()), int(xs.max())+1, int(ys.max())+1
-def cut_of(path, start, rect, *, source='clip-a', record=True, name='run'):
+def cut_of(path, start, rect, *, source='clip-a', record=True, name='run', anchor='none'):
"""A loop directory as video-loop leaves one, cut from the clip at `start` with the crop `rect` at scale 1: its strip,
- and its record with the source frame each cell is (`source_cut`) where `record`."""
+ and its record with how its frames were anchored (`foot_anchor`; None: not said) and the source frame each cell is
+ (`source_cut`) where `record`."""
frames = clip()
x0, y0, x1, y1 = rect
w, h = x1-x0, y1-y0
@@ -51,7 +55,7 @@ def cut_of(path, start, rect, *, source='clip-a', record=True, name='run'):
strip.alpha_composite(frames[(start+k) % CLIP].crop(rect), (k*w, 0))
meta = {'frames': N, 'sample_indices': list(range(N)), 'source_rect': list(rect), 'w': w, 'h': h, 'kind': 'periodic',
'loop': True, 'scale': 1.0, 'delay_ms': round(1000/FPS, 2), 'cycle_frames': N, 'cycle_seconds': N/FPS,
- 'subsampled': False}
+ 'subsampled': False} | ({} if anchor is None else {'foot_anchor': anchor})
if record:
meta['source_cut'] = {'source': {'sha256': source, 'frames': CLIP, 'fps': FPS}, 'start': start, 'length': N,
'samples': [start+k for k in range(N)]}
@@ -78,6 +82,43 @@ def moved(mask, shift, rect):
return out
+def walked(path, step, size):
+ """The clip keyed as `video-frames` leaves it, one PNG a frame: the runner of frame k laid `step` px further (across,
+ down) each frame, on a canvas of `size`."""
+ path.mkdir(parents=True)
+ for k in range(CLIP):
+ frame = Image.new('RGBA', size)
+ frame.paste(runner(k), (step[0]*k, step[1]*k))
+ frame.save(path/f'frame-{k:03d}.png')
+ return path
+
+
+def loop_cut(clip_dir, path, start, anchor, **kw):
+ """`video-loop` on the keyed clip: the cut given (--cycle fixed from `start`, N frames long), anchored by `anchor`."""
+ loop.run_loop(clip_dir, path, fps=FPS, state=None, min_len=None, max_len=None, n_out=None, seam_max=100, name='run',
+ report_path=None, cycle_mode='fixed', start=start, length=N, anchor=anchor, repair='off', size_hold='off',
+ seam_pop_max=None, wrap_blend='off', strip_height=520, **kw)
+ return path
+
+
+def patch_in(loop_dir, cell):
+ """The runner's chest patch, its own colour's pixels, in a cell of a loop's strip as drawn."""
+ return np.all(cells_of(loop_dir)[cell] == PATCH, axis=2)
+
+
+def read_on_cut(a, b):
+ """A region on the chest patch of `a`'s cell 0 and its mask, those pixels, asked on `b` with `--read-on-cut a`: the
+ region, the request's keywords, and the answer solved on `b`'s strip as cut."""
+ drawn = patch_in(a, 0)
+ ys, xs = np.nonzero(drawn)
+ region = (float(xs.mean()), float(ys.mean()), 18.0, 18.0)
+ kw = dict(region_mask=mask_png(a.parent/f'{a.name}-mask.png', drawn), read_on=sha(a/'run.strip.png'),
+ read_on_cut=a/'run.strip.png', **KW)
+ answer = sway.solve(sway.read_request(b, [region], **kw), Image.open(b/'run.strip.png').convert('RGBA'),
+ strip_name='run.strip.png', strip_sha256=sha(b/'run.strip.png'))
+ return region, kw, answer
+
+
@pytest.fixture
def cuts(tmp_path):
"""The first cut (`a`, at frame 4, cropped to the clip's frames) and its region mask on its cell 0, the patch."""
@@ -164,6 +205,76 @@ def test_on_a_loop_aligned_from_the_cut_again_the_pair_is_carried_through_the_al
assert read_on['cut_cell'] == 3 and read_on['base_cell'] == cut_cells.index(3) and read_on['source_frame'] == 4
+# ---------------------------------------------------------------- the frame where each cut's anchor moved it
+
+def test_two_cuts_at_anchor_body_pair_the_frame_where_each_ramp_moved_it(tmp_path):
+ # The runner walking 2 px a frame, cut by video-loop at --anchor body from frame 4 and from frame 1: each cut's ramp
+ # moves its frame k by round(wrap_dx·k/N), so frame 4 — the first cut's cell 0 — is moved by nothing there, and by
+ # round(-24·3/13) = -6 px as the second cut's cell 3. The crops alone set it 6 px apart; on the frames as filmed, none.
+ clip_dir = walked(tmp_path/'clip', (2, 0), (220, 220))
+ a, b = loop_cut(clip_dir, tmp_path/'a', 4, 'body'), loop_cut(clip_dir, tmp_path/'b', 1, 'body')
+ ma, mb = meta_of(a), meta_of(b)
+ assert ma['wrap_dx_px'] == mb['wrap_dx_px'] == -24 and ma['source_cut']['samples'][0] == mb['source_cut']['samples'][3] == 4
+ assert ma['source_rect'][0] - mb['source_rect'][0] == 6 and ma['source_rect'][1] == mb['source_rect'][1]
+ there = patch_in(b, 3) # frame 4's patch where the second cut drew it
+ region, kw, answer = read_on_cut(a, b)
+ pair = answer.read_on
+ assert (pair['relation'], pair['source_frame'], pair['cut_cell'], pair['base_cell']) == ('recut', 4, 3, 3)
+ assert pair['shift_px'] == [0, 0] and pair['drift_px'] == [0.0, 0.0]
+ assert there.sum() == patch_in(a, 0).sum() > 100 and np.array_equal(answer.mask.worn[0], there)
+ record = sway.sway_loop(b, [region], **kw)
+ assert (record['read_on']['relation'], record['read_on']['shift_px']) == ('recut', [0, 0])
+
+
+def test_two_cuts_at_anchor_body_whose_ramp_moves_nothing_pair_by_their_crops_alone(tmp_path):
+ # The runner laid 1 px lower each frame, cut at --anchor body from frame 12 and from frame 5, where the last frame's
+ # head and torso lie over the first's (the across of their sway is the same): both wrap offsets are nothing, the ramp
+ # moves no frame, and frame 12 — the first cut's cell 0, the second's cell 7 — is moved by the crops alone, as ever.
+ clip_dir = walked(tmp_path/'clip', (0, 1), (W, H+CLIP))
+ a, b = loop_cut(clip_dir, tmp_path/'a', 12, 'body'), loop_cut(clip_dir, tmp_path/'b', 5, 'body')
+ ma, mb = meta_of(a), meta_of(b)
+ assert ma['wrap_dx_px'] == mb['wrap_dx_px'] == 0 and ma['source_cut']['samples'][0] == mb['source_cut']['samples'][7] == 12
+ crops = [ma['source_rect'][axis] - mb['source_rect'][axis] for axis in (0, 1)]
+ assert crops[0] == 0 and crops[1] > 0
+ there = patch_in(b, 7)
+ region, kw, answer = read_on_cut(a, b)
+ assert (answer.read_on['cut_cell'], answer.read_on['base_cell'], answer.read_on['shift_px']) == (7, 7, crops)
+ assert there.sum() > 100 and np.array_equal(answer.mask.worn[0], there)
+
+
[email protected]('anchor', ['motion', 'motion-auto'])
+def test_two_cuts_at_anchor_motion_pair_the_frame_where_each_correction_laid_it(tmp_path, anchor):
+ # The runner walking 2 px a frame, cut by video-loop at --anchor motion from frame 4 and from frame 1 on its head and
+ # torso in each cut's first frame: each correction lays its frame k on a canvas padded for every frame, at the padding
+ # plus that frame's shift, so the crops alone do not say where frame 4 lies in the second cut; the corrections do.
+ clip_dir = walked(tmp_path/'clip', (2, 0), (220, 220))
+
+ def regions(start):
+ phase = 2*math.pi*(start+SHIFT)/N
+ x, y = round(3*math.sin(phase)) + 2*start, round(5*math.cos(2*phase))
+ return [(60+x, 12+y, 101+x, 52+y), (46+x, 52+y, 115+x, 136+y)] # head, torso
+
+ a = loop_cut(clip_dir, tmp_path/'a', 4, 'motion', anchor_regions=regions(4))
+ b = loop_cut(clip_dir, tmp_path/'b', 1, 'motion', anchor_regions=regions(1))
+ if anchor == 'motion-auto':
+ # --anchor motion-auto finds its regions and its cut itself (it takes no --cycle fixed), and records its
+ # correction as --anchor motion does, the same `motion_anchor` under its own `foot_anchor`: these two cuts' records.
+ for loop_dir in (a, b):
+ (loop_dir/'run.strip.json').write_text(json.dumps(meta_of(loop_dir) | {'foot_anchor': anchor}, indent=2)+'\n')
+ ma, mb = meta_of(a), meta_of(b)
+ assert ma['foot_anchor'] == mb['foot_anchor'] == anchor and ma['source_cut']['samples'][0] == mb['source_cut']['samples'][3] == 4
+ laid = [m['motion_anchor']['padding_ltrb'][axis] + m['motion_anchor']['shifts_xy'][k][axis]
+ for m, k in ((ma, 0), (mb, 3)) for axis in (0, 1)]
+ crops = [ma['source_rect'][axis] - mb['source_rect'][axis] for axis in (0, 1)]
+ assert laid[:2] != laid[2:] # the two corrections lay frame 4 apart
+ there = patch_in(b, 3)
+ region, kw, answer = read_on_cut(a, b)
+ pair = answer.read_on
+ assert (pair['relation'], pair['cut_cell'], pair['base_cell']) == ('recut', 3, 3)
+ assert pair['shift_px'] == [crops[axis] - laid[axis] + laid[2+axis] for axis in (0, 1)] != crops
+ assert there.sum() == patch_in(a, 0).sum() > 100 and np.array_equal(answer.mask.worn[0], there)
+
+
# ---------------------------------------------------------------- refused, saying why
def test_a_cut_whose_frame_the_loop_does_not_hold_or_that_names_none_is_refused_no_match(cuts, tmp_path):
@@ -184,6 +295,53 @@ def test_a_cut_whose_frame_the_loop_does_not_hold_or_that_names_none_is_refused_
assert files(later) == before
+UNREAD = { # how the cut the regions were read on and this loop's cut are recorded, and what the refusal says of them
+ 'cut-says-no-anchor': (dict(name='walk', anchor=None), {},
+ r"the cut's \(--read-on-cut\) record: it does not say how its frames were anchored \(foot_anchor\)"),
+ 'body-no-wrap': ({}, dict(anchor='body'),
+ r"this loop's record: it was cut at --anchor body and records no whole wrap offset \(wrap_dx_px\)"),
+ 'motion-no-correction': ({}, dict(anchor='motion'),
+ r"this loop's record: it was cut at --anchor motion and records no whole shift of its frame 3 of 13 "
+ r"and no padding \(motion_anchor\)")}
+
+
[email protected]('case', list(UNREAD))
+def test_a_record_that_does_not_give_where_its_anchor_moved_the_frame_is_refused_no_match(cuts, tmp_path, case):
+ a, tight, region, mask = cuts
+ read_kw, loop_kw, said = UNREAD[case]
+ read = cut_of(tmp_path/'read', 4, tight, **read_kw) if read_kw else a
+ loop_dir = cut_of(tmp_path/'b', 1, (tight[0]-3, tight[1]-2, tight[2]+2, tight[3]+1), **loop_kw)
+ strip = next(read.glob('*.strip.png'))
+ before = files(loop_dir)
+ with pytest.raises(SystemExit, match=r"no-match — the regions were read on another cut, whose cell 0 is source frame 4 "
+ r"\(this loop's cut's cell 3\), but where the anchor moved that frame before the crop "
+ r"cannot be read off " + said + r"; locate them again on this strip$"):
+ sway.sway_loop(loop_dir, [region], region_mask=mask, read_on=sha(strip), read_on_cut=strip, **KW)
+ assert files(loop_dir) == before
+
+
+def test_a_loop_aligned_from_its_cut_named_by_read_on_cut_is_refused_no_match(tmp_path):
+ # The cut from frame 1 aligned on its own (video-cycle-align): its record keeps the cut's, source frames 1 to N in
+ # order, but its cell 0 is another of them, so the frame the record's cut starts on is not where the regions were read.
+ o = cut(tmp_path/'o', clip()[1:1+N])
+ (o/'run.strip.json').write_text(json.dumps(meta_of(o) | {'source_cut': {
+ 'source': {'sha256': 'clip-a', 'frames': CLIP, 'fps': FPS}, 'start': 1, 'length': N, 'samples': [1+k for k in range(N)]}},
+ indent=2)+'\n')
+ turned = aligned(o, tmp_path/'turned')
+ assert meta_of(turned)['source_cut']['samples'][0] == 1 and meta_of(turned)['cycle_align']['cells_from'][0]['source'] != 0
+ drawn = patch_in(turned, 0)
+ ys, xs = np.nonzero(drawn)
+ loop_dir = cut_of(tmp_path/'b', 1, bbox(clip()))
+ before = files(loop_dir)
+ with pytest.raises(SystemExit, match=r'no-match — the regions were read on another cut, but the strip --read-on-cut names '
+ r'is a loop aligned from its cut \(cycle_align\), whose cells are not the cut.s frames '
+ r'in order; locate them again on this strip$'):
+ sway.sway_loop(loop_dir, [(float(xs.mean()), float(ys.mean()), 18.0, 18.0)],
+ region_mask=mask_png(tmp_path/'mask.png', drawn), read_on=sha(turned/'run.strip.png'),
+ read_on_cut=turned/'run.strip.png', **KW)
+ assert files(loop_dir) == before
+
+
def test_a_cut_of_another_clip_is_refused_no_match(cuts, tmp_path):
a, tight, region, mask = cuts
other = cut_of(tmp_path/'other', 4, (tight[0]-3, tight[1]-2, tight[2]+2, tight[3]+1), source='clip-b')