Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(sway, breathe): the Sway layer on a cycle's frames at their own size, on the breath, with a flat share and a gain across, seams with three regions, and a Breathe beat chosen to miss the hands (red)
Soohong Kim61bbd2a9c494
diff --git a/tests/effects/test_breath_beat.py b/tests/effects/test_breath_beat.pynew file mode 100644index 0000000..dbd25e2--- /dev/null+++ b/tests/effects/test_breath_beat.py@@ -0,0 +1,148 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen breathe --avoid-region` — 손을 비키는 숨 박자.++손이 가슴 앞을 오르내리는 idle 에서 숨 박자(숨 수 또는 들숨 꼭대기 칸)를 칸에서 고른다: 손과 그 위 몸을 따라가+손의 제 오름을 읽고, 들숨 꼭대기에서 가슴이 손 위에 있는 박자 가운데 숨이 손을 따라가지 않고 몸과 같이 가는 것을+고른다. 꼭대기를 민 박자는 문턱(MARGIN)보다 더 나을 때만. 고른 박자와 후보는 breathe.json `beat` 에 남고, 그 파일을+받는 Sway 레이어가 같은 박자로 흔든다. 합성 흉상(질감 있는 몸, 다른 질감의 손)으로 본다.+"""++from __future__ import annotations++import json+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen import cli+from sprite_gen.effects import breath_beat, breathe++from tests.effects.test_breathe_smooth import _bust++H, N, FPS = 160, 48, 12 # 4 초 루프 — 숨 하나(4 초) 또는 둘(2 초)이 한 숨 1.5~4 초에 든다+HANDS = (0.33, 0.74, 0.67, 0.89) # 손 상자 (그림 비율) — 가슴 아래 앞+HAND_ROWS, HAND_COLS = (122, 141), (45, 84)+LIFT_DEPTH = 0.025+FILES = [f"frame-{k:03d}.png" for k in range(N)]+++def _figure(hand_rise: int = 0, body_rise: int = 0) -> Image.Image:+ """질감 있는 흉상과 그 앞의 손 — 손은 몸에 대해 `hand_rise` px, 그림 전체는 `body_rise` px 오른다(위 양수)."""+ a = np.asarray(_bust(H)).copy()+ body = a[..., 3] > 0+ a[..., 1][body] = np.clip(a[..., 1][body].astype(int)+ + np.random.default_rng(5).integers(-25, 26, a.shape[:2])[body], 0, 255).astype(np.uint8)+ y0, y1 = HAND_ROWS[0] - hand_rise, HAND_ROWS[1] - hand_rise+ hand = np.random.default_rng(9).integers(0, 256, (y1 - y0, HAND_COLS[1] - HAND_COLS[0], 3)).astype(np.uint8)+ a[y0:y1, HAND_COLS[0]:HAND_COLS[1], :3] = hand+ a[y0:y1, HAND_COLS[0]:HAND_COLS[1], 3] = 255+ if body_rise:+ a = np.concatenate([a[body_rise:], np.repeat(a[-1:], body_rise, axis=0)]) # 아래 변에 닿은 채로 오른다+ return Image.fromarray(a, "RGBA")+++def _loop(folder: Path, hands: list[int], body: list[int] | None = None) -> Path:+ folder.mkdir(parents=True)+ for k, name in enumerate(FILES):+ _figure(hands[k], 0 if body is None else body[k]).save(folder / name)+ return folder+++def _wave(cfg: dict) -> np.ndarray:+ return np.asarray([breathe.smooth_wave(p) for p in breathe.fit_breathe_pattern(N, {"mode": "smooth", **cfg})])+++def _peaks(w: np.ndarray) -> list[int]:+ return [i for i in range(N) if w[i] > 0.9 and w[i] >= w[i - 1] and w[i] >= w[(i + 1) % N]]+++def _bake(src: Path, out: Path, *extra: str) -> dict:+ assert cli.main(["breathe", str(src), str(out), "--mode", "smooth", "--depth", str(LIFT_DEPTH), *extra]) == 0+ return json.loads((out / "breathe.json").read_text(encoding="utf-8"))+++def _avoid(src: Path, out: Path, *extra: str) -> dict:+ return _bake(src, out, "--avoid-region", ",".join(f"{v:g}" for v in HANDS), "--fps", str(FPS), *extra)+++BUMP = [round(5 * max(0.0, 1 - abs(k - 34) / 5)) for k in range(N)] # 손이 34 칸 둘레에서 5 px 오른다+++def test_the_in_breath_peaks_miss_the_hands_big_rise(tmp_path) -> None:+ report = _avoid(_loop(tmp_path / "loop", BUMP), tmp_path / "out")+ beat = report["beat"]+ assert max(abs(a - b) for a, b in zip(beat["hands_rise_px"], BUMP)) <= 1, "손을 따라가지 못했다"+ rows = {row["breaths"]: row for row in beat["candidates"]}+ assert set(rows) == {1, 2} and rows[2]["keeps"] is False and rows[1]["keeps"] is True # 숨 둘은 34 칸 꼭대기가 손 밑+ chosen = beat["chosen"]+ assert report["config"]["breath_peaks" if "breath_peaks" in chosen else "breaths"] == next(iter(chosen.values()))+ assert report["phases"] == breathe.fit_breathe_pattern(N, report["config"])+ peaks = _peaks(_wave(chosen))+ assert peaks and all(not 34 - 5 - breath_beat.NEAR <= p <= 34 + 5 + breath_beat.NEAR for p in peaks)+ lift = beat["lift_px"]+ assert all(lift * _wave(chosen)[p] >= max(BUMP[(p + j) % N] for j in range(-2, 3)) for p in peaks)+++def test_hands_that_move_against_the_breath_keep_the_evenly_spaced_breaths(tmp_path) -> None:+ against = [round(4 * (1 - w)) for w in _wave({"breaths": 2})]+ beat = _avoid(_loop(tmp_path / "loop", against), tmp_path / "out")["beat"]+ assert beat["chosen"] == {"breaths": 2}+ rows = {row["breaths"]: row for row in beat["candidates"]}+ assert rows[2]["corr_hands"] < -0.9 and rows[2]["score"] > rows[1]["score"]+ assert beat["nudged_best"]["score"] <= rows[2]["score"] + breath_beat.MARGIN+++def test_the_hands_own_rise_is_read_against_the_band_just_above_them(tmp_path) -> None:+ """몸 상자를 주지 않으면 손 상자와 같은 열, 바로 위 띠 — 몸이 숨과 같이 오르내리면 손의 제 오름은 0 이고 숨은 몸을 따른다."""+ with_body = [round(2 * w) for w in _wave({"breaths": 2})]+ beat = _avoid(_loop(tmp_path / "loop", [0] * N, with_body), tmp_path / "out")["beat"]+ band = breath_beat.anchor_band(HANDS)+ assert beat["avoid_anchor"] == list(band)+ x0, y0, x1, y1 = HANDS+ assert band[0] == x0 and band[2] == x1 and band[3] < y0 and band[3] - band[1] == pytest.approx(0.65 * (y1 - y0) - 0.02)+ assert max(abs(v) for v in beat["hands_rise_px"]) <= 1+ assert max(abs(a - b) for a, b in zip(beat["body_rise_px"], with_body)) <= 1+ assert beat["chosen"] == {"breaths": 2}+++def test_a_nudged_peak_is_taken_only_when_it_is_more_than_the_margin_better() -> None:+ evenly = [{"breaths": 1, "score": 0.5, "keeps": True, "margin_px": 1.0},+ {"breaths": 2, "score": 0.9, "keeps": False, "margin_px": -1.0}]++ def nudged(score: float, keeps: bool = True) -> list[dict]:+ return [{"breath_peaks": [16], "score": score, "keeps": keeps, "margin_px": 1.0 if keeps else -1.0}]++ assert breath_beat.pick(evenly, []) is evenly[0] # 가슴이 손 밑으로 묻히는 숨 둘은 아니다+ assert breath_beat.pick(evenly, nudged(0.5 + breath_beat.MARGIN)) is evenly[0]+ assert breath_beat.pick(evenly, nudged(0.5 + breath_beat.MARGIN + 1e-9))["breath_peaks"] == [16]+ assert breath_beat.pick(evenly, nudged(2.0, keeps=False)) is evenly[0]+ with pytest.raises(SystemExit, match="가슴이 손 위에 있지 않다"):+ breath_beat.pick([evenly[1]], [])+++def test_what_the_beat_choice_refuses_and_what_it_leaves_alone(tmp_path) -> None:+ src = _loop(tmp_path / "loop", BUMP)+ region = ",".join(f"{v:g}" for v in HANDS)+ for extra, why in ((["--breaths", "2"], "--breaths"), (["--breath-peaks", "10,30"], "--breaths"),+ (["--depth", "0.02", "--mode", "pixel"], "smooth 의 것")):+ with pytest.raises(SystemExit, match=why):+ cli.main(["breathe", str(src), str(tmp_path / "x"), "--avoid-region", region, "--fps", "12",+ *([] if "--mode" in extra else ["--mode", "smooth"]), *extra])+ with pytest.raises(SystemExit, match="--fps 를 주라"):+ cli.main(["breathe", str(src), str(tmp_path / "x"), "--mode", "smooth", "--avoid-region", region])+ for extra in (["--fps", "12"], ["--avoid-anchor", region]):+ with pytest.raises(SystemExit, match="--avoid-region 의 것"):+ cli.main(["breathe", str(src), str(tmp_path / "x"), "--mode", "smooth", *extra])+ assert not (tmp_path / "x").exists()+ assert "beat" not in _bake(src, tmp_path / "plain", "--breaths", "2")+++def test_the_sway_layer_sways_on_the_beat_chosen(tmp_path) -> None:+ out = tmp_path / "out"+ report = _avoid(_loop(tmp_path / "loop", BUMP), out)+ assert cli.main(["video-sway", "--frames", str(out), "--out", str(tmp_path / "swayed"), "--breathe", str(out / "breathe.json"),+ "--region", "64,95,30,18"]) == 0+ drive = json.loads((tmp_path / "swayed" / "sway.json").read_text())["drive"]+ assert {k: drive[k] for k in report["beat"]["chosen"]} == report["beat"]["chosen"]diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.pyindex b9d2ba8..dee4bb0 100644--- a/tests/video/test_follow_inspect.py+++ b/tests/video/test_follow_inspect.py@@ -434,8 +434,9 @@ def test_the_command_takes_what_video_follow_takes(tmp_path, capsys):cli.COMMANDS[cli.VERB_ALIASES['video-follow'][0]][1](parsers[0])add_arguments(parsers[1])followed, inspected = vars(parsers[0].parse_args(asked)), vars(parsers[1].parse_args([*asked, '--out-dir', str(out)]))- assert set(inspected)-set(followed) == {'out_dir', 'scale', 'columns'} and set(followed)-set(inspected) == {'board'}- assert {key: inspected[key] for key in followed if key != 'board'} == {key: value for key, value in followed.items() if key != 'board'}+ own = {'board', 'frames', 'out', 'fps'} # video-sway's own: its board, and the frames path beside the loop directory+ assert set(inspected)-set(followed) == {'out_dir', 'scale', 'columns'} and set(followed)-set(inspected) == own+ assert {key: inspected[key] for key in followed if key not in own} == {key: value for key, value in followed.items() if key not in own}capsys.readouterr()assert cli.main(['video-follow-inspect', *asked, '--out-dir', str(out), '--columns', '6']) == 0printed, said = capsys.readouterr()diff --git a/tests/video/test_follow_stretch_floor.py b/tests/video/test_follow_stretch_floor.pyindex d2fc097..47e1f3f 100644--- a/tests/video/test_follow_stretch_floor.py+++ b/tests/video/test_follow_stretch_floor.py@@ -164,7 +164,7 @@ def test_the_floor_is_read_between_0_and_1(probes, tmp_path):def test_q1_the_bend_is_the_moves_steepest_tilt_and_a_lowered_region_moves_just_under_45_degrees(probes, tmp_path):_, region = X1record = follow_inspect.inspect_loop(probes['X1'], [region], tmp_path/'out', on_fold='lower')- assert record['schema_version'] == 2+ assert record['schema_version'] == 3radius = min(region[2:])for cell in record['cells']:entry = cell['regions'][0]diff --git a/tests/video/test_sway_breath.py b/tests/video/test_sway_breath.pynew file mode 100644index 0000000..3569e23--- /dev/null+++ b/tests/video/test_sway_breath.py@@ -0,0 +1,187 @@+"""`video-sway --breathe <breathe.json>`: the Sway layer on the breath, not the body's outline.++A breathing idle's head stays where it is and its body moves a pixel or two, so the damped mass on the outline answers+whole-pixel steps, not the breath. On the breath the part follows the chest's rise late: the chest rises lift x w, the+part as far late by --lag of a breath (the time warp of the Breathe layer's shoulders), and it lies the difference behind.+The first cell, every rest and the loop's close are 0, so a cell there is the breathed cell byte for byte. On a+synthetic bust breathed by `sprite-gen breathe` (smooth, two breaths in 48 cells).+"""+import hashlib+import json+import math++import numpy as np+import pytest+from PIL import Image+from sprite_gen import cli+from sprite_gen.effects import breathe+from sprite_gen.video import sway, sway_inspect++from tests.effects.test_breathe_smooth import _bust++N, BREATHS, DEPTH = 48, 2, 0.025+CHEST = (48.0, 80.0, 30.0, 20.0) # over the bust's chest, in frame pixels+FILES = [f'frame-{k:03d}.png' for k in range(N)]++[email protected](scope='module')+def breathed(tmp_path_factory):+ """A still bust, 48 frames, and those frames breathed: `plain/`, `breathed/` (with breathe.json)."""+ root = tmp_path_factory.mktemp('breath')+ plain = root/'plain'+ plain.mkdir()+ for name in FILES:+ _bust().save(plain/name)+ assert cli.main(['breathe', str(plain), str(root/'breathed'), '--mode', 'smooth', '--depth', str(DEPTH),+ '--breaths', str(BREATHS)]) == 0+ return root+++def rgba(path):+ with Image.open(path) as im:+ return np.asarray(im.convert('RGBA'))+++def lift(record):+ """The chest's rise at the top of an in-breath, px: depth times the body below the neck, as the record says it."""+ anatomy = record['resolved']['anatomy']+ return record['config']['depth']*(anatomy['height']-anatomy['basis_row'])+++def answer(breathed, **kw):+ cells = [Image.fromarray(rgba(breathed/'breathed'/name)) for name in FILES]+ return sway.solve_cells(sway.read_ask([CHEST], breathe=breathed/'breathed'/'breathe.json', **kw), cells, None)+++def region(values=CHEST):+ return ','.join(f'{v:g}' for v in values)+++def test_the_first_cell_every_rest_and_the_close_are_the_breathed_cells(breathed, tmp_path):+ out = tmp_path/'swayed'+ src = breathed/'breathed'+ assert cli.main(['video-sway', '--frames', str(src), '--out', str(out), '--breathe', str(src/'breathe.json'),+ '--region', region(), '--gain', '3']) == 0+ record = json.loads((out/'sway.json').read_text())+ rests = [k for k in range(N) if (k*BREATHS) % N == 0]+ assert rests == [0, N//BREATHS]+ for k in rests:+ assert record['dy_px'][k] == record['dx_px'][k] == 0+ assert np.array_equal(rgba(out/FILES[k]), rgba(src/FILES[k])), k+ assert sum(not np.array_equal(rgba(out/name), rgba(src/name)) for name in FILES) > N//2+ dy = np.asarray(record['dy_px'])+ assert abs(dy[0]-dy[-1]) <= np.abs(np.diff(dy)).max() / 4, 'the loop does not close at rest'+ report = json.loads((src/'breathe.json').read_text())+ assert record['drive'] == {'kind': 'breath', 'breathe_sha256': hashlib.sha256((src/'breathe.json').read_bytes()).hexdigest(),+ 'lag': sway.LAG_DEFAULT, 'lift_px': round(lift(report), 4), 'heading_deg': 0.0, 'breaths': BREATHS}+ assert 'freq_hz' not in record and record['frame_ms'] is None+++def late_peak(lag, inhale=breathe.INHALE):+ """Where in a breath the part peaks: the phase t whose warped time t - lag sin(pi t) is the chest's peak."""+ t = inhale+ for _ in range(60):+ t = inhale + lag*math.sin(math.pi*t)+ return t++[email protected]('lag', [0.1, 0.15, 0.2])+def test_the_part_peaks_late_by_the_lag_and_reaches_gain_times_the_lift(breathed, lag):+ report = json.loads((breathed/'breathed'/'breathe.json').read_text())+ got = answer(breathed, lag=lag, gain=1.0)+ w = np.asarray([breathe.smooth_wave(p) for p in report['phases']])+ rise = lift(report)+ part = w - got.dy/rise # the part's own rise, as a share of the chest's+ per = N//BREATHS+ assert int(np.argmax(w[:per])) == round(breathe.INHALE*per)+ assert int(np.argmax(part[:per])) == round(late_peak(lag)*per)+ late = np.asarray([breathe.smooth_shoulder_wave(p, lag) for p in report['phases']])+ assert np.allclose(part, late, atol=1e-12)+ for gain in (1.0, 2.5):+ assert answer(breathed, lag=lag, gain=gain).reach == pytest.approx(gain*rise*float(np.max(np.abs(w-late))), rel=1e-12)+ assert np.all(got.dx == 0) and got.dy[0] == 0+++def test_a_heading_moves_the_part_against_the_way_the_chest_rises(breathed, tmp_path):+ plain = breathed/'plain'+ assert cli.main(['breathe', str(plain), str(tmp_path/'turned'), '--mode', 'smooth', '--depth', str(DEPTH),+ '--breaths', str(BREATHS), '--chest-dir', '-30']) == 0+ cells = [Image.fromarray(rgba(tmp_path/'turned'/name)) for name in FILES]+ got = sway.solve_cells(sway.read_ask([CHEST], breathe=tmp_path/'turned'/'breathe.json'), cells, None)+ k = int(np.argmax(got.dy))+ assert got.dy[k] > 0 and got.dx[k] > 0 # the chest rises up and to the left; the part lies behind, down and right+ assert math.degrees(math.atan2(got.dx[k], got.dy[k])) == pytest.approx(30)+++def test_a_record_that_does_not_say_the_breath_is_refused(breathed, tmp_path):+ src = breathed/'breathed'+ report = json.loads((src/'breathe.json').read_text())+ cases = {+ 'changed': report | {'phases': [0.0, *report['phases'][1:-1], 0.5]},+ 'counted': report | {'frames': N-1},+ 'pixel': report | {'config': {k: v for k, v in report['config'].items() if k != 'mode'} | {'mode': 'pixel'}},+ 'not one': {'phases': report['phases']},+ }+ whys = {'changed': 'changed after it was written', 'counted': f'says {N-1} frames', 'pixel': 'a pixel breath',+ 'not one': "not a Breathe layer's record"}+ for name, bad in cases.items():+ path = tmp_path/f'{name}.json'+ path.write_text(json.dumps(bad))+ with pytest.raises(SystemExit, match=whys[name]):+ cli.main(['video-sway', '--frames', str(src), '--out', str(tmp_path/name), '--breathe', str(path), '--region', region()])+ assert not (tmp_path/name).exists()+ fewer = tmp_path/'fewer'+ fewer.mkdir()+ for name in FILES[:-1]:+ (fewer/name).write_bytes((src/name).read_bytes())+ with pytest.raises(SystemExit, match=f'breathes {N} cells and there are {N-1} to sway'):+ cli.main(['video-sway', '--frames', str(fewer), '--out', str(tmp_path/'f'), '--breathe', str(src/'breathe.json'),+ '--region', region()])+++def test_what_belongs_to_one_drive_is_refused_on_the_other(breathed, tmp_path):+ src = breathed/'breathed'+ asked = ['video-sway', '--frames', str(src), '--out', str(tmp_path/'out'), '--region', region()]+ on_breath = [*asked, '--breathe', str(src/'breathe.json')]+ for extra, why in ((['--freq', '1'], '--freq and --zeta'), (['--zeta', '0.5'], '--freq and --zeta'),+ (['--fps', '24'], '--fps is the damped mass'), (['--lag', '0.4'], 'under 1/π'), (['--lag', '0'], 'above 0')):+ with pytest.raises(SystemExit, match=why):+ cli.main([*on_breath, *extra])+ with pytest.raises(SystemExit, match='--lag .* needs --breathe'):+ cli.main([*asked, '--fps', '24', '--lag', '0.1'])+ assert not (tmp_path/'out').exists()+++def test_the_inspection_records_the_drive_and_its_way_by_name(breathed, tmp_path):+ src = breathed/'breathed'+ cells = [rgba(src/name) for name in FILES]+ h, w = cells[0].shape[:2]+ loop_dir = tmp_path/'loop'+ loop_dir.mkdir()+ Image.fromarray(np.concatenate(cells, axis=1)).save(loop_dir/'idle.strip.png')+ (loop_dir/'idle.strip.json').write_text(json.dumps({'kind': 'periodic', 'frames': N, 'w': w, 'h': h, 'delay_ms': 41.67}))+ record = sway_inspect.inspect_loop(loop_dir, [CHEST], tmp_path/'out', breathe=src/'breathe.json')+ digest = hashlib.sha256((src/'breathe.json').read_bytes()).hexdigest()+ assert record['follow']['drive']['kind'] == 'breath' and record['follow']['drive']['breathe_sha256'] == digest+ assert record['inputs']['policy']['name'] == sway.BREATH_POLICY != sway.POLICY+ assert record['inputs']['settings'] | {} == {'gain': sway.BREATH_GAIN_DEFAULT, 'on_fold': 'refuse', 'freq_hz': None, 'zeta': None,+ 'read_on': None, 'stretch_floor': None, 'breathe_sha256': digest,+ 'lag': sway.LAG_DEFAULT}+ assert record['cells'][0]['changed_px'] == 0 and any(cell['changed_px'] for cell in record['cells'])+ on_body = sway_inspect.inspect_loop(loop_dir, [CHEST], tmp_path/'body')+ assert on_body['inputs']['policy']['name'] == sway.POLICY and 'drive' not in on_body['follow']+ assert on_body['input_id'] != record['input_id']+++def test_a_cell_no_region_moves_is_the_cell_as_it_was():+ """A move of nothing keeps even the colour under a clear pixel, which a move clears (the WebP check refuses it)."""+ cell = np.zeros((40, 40, 4), np.uint8)+ cell[..., :3] = np.random.default_rng(1).integers(0, 256, (40, 40, 3))+ cell[10:30, 10:30, 3] = 255+ picture = Image.fromarray(cell)+ still = sway.move_regions(picture, [([(20.0, 20.0, 15.0, 15.0)], (0.0, 0.0))], (2.0, 1.0))+ assert still.tobytes() == picture.tobytes()+ moved = np.asarray(sway.move_regions(picture, [([(20.0, 20.0, 15.0, 15.0)], (0.5, 0.0))], (2.0, 1.0)))+ yy, xx = np.mgrid[0:40, 0:40]+ clear_inside = (((xx-22)/15)**2+((yy-21)/15)**2 < 1) & (cell[..., 3] == 0) & (moved[..., 3] == 0)+ assert cell[clear_inside][:, :3].any() and not moved[clear_inside][:, :3].any()diff --git a/tests/video/test_sway_flat_across.py b/tests/video/test_sway_flat_across.pynew file mode 100644index 0000000..b45f6bf--- /dev/null+++ b/tests/video/test_sway_flat_across.py@@ -0,0 +1,113 @@+"""Two of the Sway layer's gaps: a region moved whole, and across apart from down.++A region's weight is 1 at its centre and falls to 0 at its rim, so a large region moves its middle and presses the rest+in. Its fifth number, flat, is the share of the way from its centre to its rim that moves in full — the Breathe layer's+chest weight, one formula — and the fold rule and the floor read it by the radius left. `--gain-across` moves across by+a gain of its own; a gain lowered for a region lowers both alike. Neither changes anything when left out. On the+synthetic figure of the inspection's tests, which sways once and bobs twice a cycle.+"""+import json+import math+import shutil++import numpy as np+import pytest+from sprite_gen import cli+from sprite_gen.effects import breathe+from sprite_gen.video import sway, sway_inspect++from tests.video.test_follow_inspect import CHEST, strip_dir++LOOP_FILES = ('walk.strip.png', 'walk.strip.json', 'walk.gif', 'walk.webp')+++def files(directory):+ return {name: (directory/name).read_bytes() for name in LOOP_FILES}+++def swayed(tmp_path, name, *args):+ directory = strip_dir(tmp_path/name)+ assert cli.main(['video-sway', '--loop-dir', str(directory), *args]) == 0+ return directory, json.loads((directory/'walk.strip.json').read_text())['follow']+++def text(region):+ return ','.join(f'{v:g}' for v in region)+++def test_a_flat_share_of_0_is_the_region_of_four_numbers(tmp_path):+ four, four_record = swayed(tmp_path, 'four', '--region', text(CHEST))+ five, five_record = swayed(tmp_path, 'five', '--region', text(CHEST) + ',0')+ assert files(four) == files(five) and five_record['regions'] == [list(CHEST)]+ inspected = [sway_inspect.inspect_loop(strip_dir(tmp_path/f'loop-{name}'), [region], tmp_path/f'out-{name}')+ for name, region in (('four', CHEST), ('five', (*CHEST, 0.0)))]+ assert inspected[0] == inspected[1]+++def test_a_flat_region_moves_its_middle_whole():+ region = (60.0, 72.0, 24.0, 20.0, 0.6)+ yy, xx = np.mgrid[0:160, 0:120].astype(np.float32)+ inside, move_x, move_y = sway.move_field(xx, yy, [([region], (2.0, 3.0))], (1.0, -2.0))+ r = np.hypot((xx-61)/24, (yy-70)/20)+ assert np.all(move_x[r <= 0.59] == 2.0) and np.all(move_y[r <= 0.59] == 3.0)+ falling = (r > 0.61) & (r < 1)+ weight = breathe.flat_cos2(r.astype(np.float64), 0.6)+ assert np.allclose(move_y[falling], 3.0*weight[falling], atol=1e-5) and not inside[r >= 1.001].any() # the rim, read in float32+ assert np.all(move_y[falling] < 3.0) and np.all(np.diff(move_y[70, 61:85]) <= 0)+++def test_the_fold_and_the_floor_read_a_flat_region_by_the_radius_left_and_stay_under_the_numbers(tmp_path):+ flat = 0.5+ region = (*CHEST, flat)+ record = sway_inspect.inspect_loop(strip_dir(tmp_path/'loop'), [region], tmp_path/'out', gain=1.0, on_fold='lower')+ radius = min(CHEST[2:])*(1-flat)+ assert record['follow']['fold']['regions'][0]['radius_px'] == radius+ for cell in record['cells']:+ entry = cell['regions'][0]+ ox, oy = entry['offset_px']+ assert entry['ellipse'][4] == flat+ assert entry['bend'] == pytest.approx(math.hypot(ox, oy)*math.pi/(2*radius), abs=2e-4)+ closed = 1-(math.pi/2)/(1-flat)*math.hypot(ox/CHEST[2], oy/CHEST[3]) # the floor's least area for this move+ assert closed <= entry['jacobian_min'] + 1e-4, cell['index']+ floored = sway_inspect.inspect_loop(strip_dir(tmp_path/'loop2'), [region], tmp_path/'out2', gain=1.0, on_fold='lower',+ stretch_floor=0.0)+ least = floored['follow']['stretch']['regions'][0]['least_area']+ assert least <= min(cell['regions'][0]['jacobian_min'] for cell in floored['cells']) + 1e-4+ unflat = sway_inspect.inspect_loop(strip_dir(tmp_path/'loop3'), [CHEST], tmp_path/'out3', gain=1.0, on_fold='lower',+ stretch_floor=0.0)+ assert least < unflat['follow']['stretch']['regions'][0]['least_area'] # the same move, the steeper fall+++def test_a_flat_share_out_of_the_breathe_layers_range_is_refused(tmp_path):+ directory = strip_dir(tmp_path/'loop')+ for bad in ('0.95', '-0.1', 'nan'):+ with pytest.raises(SystemExit):+ cli.main(['video-sway', '--loop-dir', str(directory), '--region', f'{text(CHEST)},{bad}'])+ with pytest.raises(SystemExit, match='flat is the share'):+ sway.sway_loop(directory, [(*CHEST, 0.95)])+++def test_gain_across_left_out_or_equal_to_the_gain_moves_as_ever(tmp_path):+ ever, ever_record = swayed(tmp_path, 'ever', '--region', text(CHEST), '--gain', '2')+ equal, equal_record = swayed(tmp_path, 'equal', '--region', text(CHEST), '--gain', '2', '--gain-across', '2')+ assert files(ever)['walk.strip.png'] == files(equal)['walk.strip.png']+ assert 'gain_across' not in ever_record and (equal_record['gain_across'], equal_record['gain_across_requested']) == (2.0, 2.0)+ assert {k: v for k, v in equal_record.items() if not k.startswith('gain_across')} == ever_record+++def test_gain_across_moves_across_by_its_own_gain(tmp_path):+ _, ever = swayed(tmp_path, 'ever', '--region', text(CHEST), '--gain', '2')+ _, apart = swayed(tmp_path, 'apart', '--region', text(CHEST), '--gain', '2', '--gain-across', '0.5')+ assert apart['dy_px'] == ever['dy_px'] and any(ever['dx_px'])+ assert np.allclose(apart['dx_px'], np.asarray(ever['dx_px'])/4, atol=0.007)+ with pytest.raises(SystemExit, match='--gain 0 leaves the cells as they were'):+ sway.sway_loop(strip_dir(tmp_path/'zero'), [CHEST], gain=0, gain_across=1)+++def test_a_gain_lowered_for_a_region_lowers_across_in_proportion(tmp_path):+ small = (60.0, 72.0, 10.0, 10.0)+ _, record = swayed(tmp_path, 'lowered', '--region', text(small), '--gain', '40', '--gain-across', '20', '--on-fold', 'lower')+ assert record['fold']['lowered'] is True and record['gain'] < 40+ assert record['gain_across'] == round(record['gain']/2, 4) and record['gain_across_requested'] == 20+ unit = sway.read_ask([small], gain=1.0, gain_across=0.5)+ assert unit.across == 0.5diff --git a/tests/video/test_sway_frames.py b/tests/video/test_sway_frames.pynew file mode 100644index 0000000..d2a5719--- /dev/null+++ b/tests/video/test_sway_frames.py@@ -0,0 +1,167 @@+"""`video-sway --frames <folder> --out <new folder>`: the Sway layer on a cycle's frames at their own size and count.++A strip holds 64 cells and 32,000 px across at most, so a cycle of large frames is cut down to fit it. The frames path+sways the cycle's frames themselves. It is the strip's sway cell for cell: a strip cut from the same frames at scale 1+with none left out, its regions moved by its crop origin, at the frame time its meta writes, moves its cells as the+frames are moved. On a synthetic body that bobs and sways, textured, with colour under its clear pixels.+"""+import json+import math++import numpy as np+import pytest+from PIL import Image, ImageDraw+from sprite_gen import cli+from sprite_gen.video import loop, sway++N, SIZE = 24, 200+TORSO = (100.0, 125.0, 30.0, 40.0) # the region, in frame pixels: over the torso in frame 0+FILES = [f'frame-{k:03d}.png' for k in range(N)]+++def frame(k, n=N):+ """A body that bobs twice a cycle and sways once, an arm swinging: noise-textured everywhere, colour under the clear+ pixels too, so a move shows and a clear pixel's colour is there to keep or lose."""+ texture = (np.random.default_rng(7).integers(0, 60, (SIZE, SIZE, 1)) + np.array([150, 110, 90])).clip(0, 255)+ t = 2*math.pi*k/n+ dy, dx = round(6*(0.5-0.5*math.cos(2*t))), round(3*math.sin(t))+ mask = Image.new('L', (SIZE, SIZE), 0)+ d = ImageDraw.Draw(mask)+ d.ellipse((60+dx, 70+dy, 140+dx, 180+dy), fill=255) # torso+ d.ellipse((78+dx, 30+dy, 122+dx, 74+dy), fill=255) # head+ d.line((130+dx, 100+dy, 160+dx, 150+dy+15*math.sin(t)), fill=255, width=9) # an arm+ return Image.fromarray(np.dstack([np.roll(texture, (dy, dx), (0, 1)), np.asarray(mask)]).astype(np.uint8), 'RGBA')+++def frames_dir(path, n=N):+ path.mkdir(parents=True)+ for k in range(n):+ frame(k, n).save(path/f'frame-{k:03d}.png')+ return path+++def rgba(path):+ with Image.open(path) as im:+ return np.asarray(im.convert('RGBA'))+++def as_strip_cell(image, rect):+ """A frame as the strip holds it at scale 1: cropped at its source rect and laid on a clear cell (build_strip)."""+ cell = Image.new('RGBA', (rect[2]-rect[0], rect[3]-rect[1]), (0, 0, 0, 0))+ cell.alpha_composite(image.crop(tuple(rect)))+ return np.asarray(cell)+++def cut(tmp_path, frames):+ """A loop directory holding the frames cut as video-loop cuts them, at scale 1, none left out."""+ strip, meta = loop.build_strip(frames, cycle_seconds=1.0, max_height=520)+ assert meta['scale'] == 1 and meta['frames'] == len(frames) and meta['delay_ms'] == 41.67+ directory = tmp_path/'loop'+ directory.mkdir()+ strip.save(directory/'walk.strip.png')+ (directory/'walk.strip.json').write_text(json.dumps(meta))+ return directory, meta+++def test_the_frames_are_swayed_as_the_strip_cut_from_them_at_scale_1(tmp_path):+ src = frames_dir(tmp_path/'cycle-frames')+ frames = [frame(k) for k in range(N)]+ loop_dir, meta = cut(tmp_path, frames)+ left, top = meta['source_rect'][:2]+ in_strip = (TORSO[0]-left, TORSO[1]-top, TORSO[2], TORSO[3])+ strip_record = sway.sway_loop(loop_dir, [in_strip], on_fold='lower')+ out = tmp_path/'swayed'+ assert cli.main(['video-sway', '--frames', str(src), '--out', str(out), '--region', ','.join(f'{v:g}' for v in TORSO),+ '--fps', '24', '--on-fold', 'lower']) == 0+ assert sorted(p.name for p in out.iterdir()) == sorted([*FILES, 'sway.json'])+ record = json.loads((out/'sway.json').read_text())+ for key in ('gain', 'dx_px', 'dy_px', 'reach_px', 'body_bob_px', 'fold', 'freq_hz', 'zeta'):+ assert record[key] == strip_record[key], key+ assert record['regions'] == [list(TORSO)] and record['frames'] == N and record['frame_ms'] == 41.67+ strip = rgba(loop_dir/'walk.strip.png')+ w = meta['w']+ moved = 0+ for k, name in enumerate(FILES):+ with Image.open(out/name) as im:+ cell = as_strip_cell(im.convert('RGBA'), meta['source_rect'])+ assert np.array_equal(cell, strip[:, k*w:(k+1)*w]), f'cell {k} differs from the strip path'+ moved += not np.array_equal(rgba(out/name), rgba(src/name))+ assert moved > N//2, 'the frames path moved nothing'+++def test_the_frame_time_is_the_one_a_strip_meta_writes(tmp_path):+ """--fps 24 is read as the strip meta writes 24 frames a second, 41.67 ms: the exact 1000/24 ms is another sway."""+ src = frames_dir(tmp_path/'cycle-frames')+ out = tmp_path/'swayed'+ assert cli.main(['video-sway', '--frames', str(src), '--out', str(out), '--region', ','.join(f'{v:g}' for v in TORSO),+ '--fps', '24', '--on-fold', 'lower']) == 0+ frames = [frame(k) for k in range(N)]+ ask = sway.read_ask([TORSO], on_fold='lower')+ rounded, exact = sway.solve_cells(ask, frames, 41.67), sway.solve_cells(ask, frames, 1000/24)+ written = [rgba(out/name) for name in FILES]+ assert all(np.array_equal(np.asarray(rounded.moved(k)), written[k]) for k in range(N))+ assert any(not np.array_equal(np.asarray(exact.moved(k)), written[k]) for k in range(N))+++def test_a_loops_cycle_folder_carries_its_own_frame_time(tmp_path):+ loop_dir, _ = cut(tmp_path, [frame(k) for k in range(N)])+ meta = json.loads((loop_dir/'walk.strip.json').read_text())+ assert (meta['cycle_frames'], meta['cycle_seconds']) == (N, 1.0)+ cycle = frames_dir(loop_dir/'cycle')+ region = ','.join(f'{v:g}' for v in TORSO)+ assert cli.main(['video-sway', '--frames', str(cycle), '--out', str(tmp_path/'a'), '--region', region, '--on-fold', 'lower']) == 0+ assert cli.main(['video-sway', '--frames', str(cycle), '--out', str(tmp_path/'b'), '--region', region, '--on-fold', 'lower',+ '--fps', '24']) == 0+ assert all((tmp_path/'a'/name).read_bytes() == (tmp_path/'b'/name).read_bytes() for name in FILES)+ assert json.loads((tmp_path/'a'/'sway.json').read_text())['frame_ms'] == 41.67+ with pytest.raises(SystemExit, match=r'--fps 30 is a frame of 33\.33 ms.*41\.67 ms'):+ cli.main(['video-sway', '--frames', str(cycle), '--out', str(tmp_path/'c'), '--region', region, '--fps', '30'])+ assert not (tmp_path/'c').exists()+++def test_the_old_name_sways_frames_alike(tmp_path):+ src = frames_dir(tmp_path/'cycle-frames')+ region = ','.join(f'{v:g}' for v in TORSO)+ for verb in ('video-sway', 'video-follow'):+ assert cli.main([verb, '--frames', str(src), '--out', str(tmp_path/verb), '--region', region, '--fps', '24',+ '--on-fold', 'lower']) == 0+ for name in (*FILES, 'sway.json'):+ assert (tmp_path/'video-sway'/name).read_bytes() == (tmp_path/'video-follow'/name).read_bytes(), name+++def snapshot(path):+ return {str(p.relative_to(path)): p.read_bytes() if p.is_file() else None for p in sorted(path.rglob('*'))}+++def test_what_the_frames_path_refuses_it_refuses_before_writing_anything(tmp_path):+ src = frames_dir(tmp_path/'cycle-frames')+ region = ','.join(f'{v:g}' for v in TORSO)+ full = tmp_path/'full'+ full.mkdir()+ (full/'note.txt').write_text('mine\n')+ cases = [+ (['--out', str(src/'out'), '--fps', '24'], 'out 이 frames 안'),+ (['--out', str(tmp_path), '--fps', '24'], 'frames 가 out 안'),+ (['--out', str(full), '--fps', '24'], '비어 있지 않다'),+ (['--out', str(tmp_path/'new')], '--fps'), # the damped mass needs the frames' time+ (['--out', str(tmp_path/'new'), '--fps', '24', '--read-on', 'a'*64], '--read-on'),+ (['--fps', '24'], '--frames needs --out'),+ (['--out', str(tmp_path/'new'), '--fps', '24', '--region', '250,100,10,10'], 'outside the 200x200 cell'),+ ]+ before = snapshot(tmp_path)+ for extra, why in cases:+ asked = ['--region', region] if '--region' not in extra else []+ with pytest.raises(SystemExit, match=why):+ cli.main(['video-sway', '--frames', str(src), *asked, *extra])+ assert snapshot(tmp_path) == before, f'refused ({why}) and something changed'+ loop_dir = tmp_path/'loop'+ with pytest.raises(SystemExit, match='--out goes with --frames'):+ cli.main(['video-sway', '--loop-dir', str(loop_dir), '--region', region, '--out', str(tmp_path/'new')])+++def test_frames_of_two_sizes_are_refused(tmp_path):+ src = frames_dir(tmp_path/'cycle-frames')+ frame(3).resize((SIZE, SIZE+2)).save(src/FILES[3])+ with pytest.raises(SystemExit, match='프레임 크기가 서로 다르다'):+ cli.main(['video-sway', '--frames', str(src), '--out', str(tmp_path/'out'), '--region', '100,125,30,40', '--fps', '24'])+ assert not (tmp_path/'out').exists()diff --git a/tests/video/test_sway_seams.py b/tests/video/test_sway_seams.pynew file mode 100644index 0000000..def392e--- /dev/null+++ b/tests/video/test_sway_seams.py@@ -0,0 +1,60 @@+"""`video-sway-inspect` seams with three regions: a point where a third region moves more than the pair is no seam.++`video-sway` moves a pixel by the largest of every region's weighted move. Where two regions meet, the move's gradient+jumps from one's to the other's and a line bends — unless a third region moves that pixel more than both: then neither+of the two moves it, and the curve where they are equal is no seam there. Counted two at a time, a pair's seam was read+under a third region that covers it. On the synthetic figure of the inspection's tests.+"""+import math++from sprite_gen.video import sway_inspect++from tests.video.test_follow_inspect import strip_dir++A, B = (52.0, 72.0, 12.0, 12.0), (68.0, 72.0, 12.0, 12.0) # side by side: they meet down x = 60, carried+++def weight(x, y, ellipse):+ cx, cy, rx, ry = ellipse+ r = math.hypot((x-cx)/rx, (y-cy)/ry)+ return math.cos(r*math.pi/2)**2 if r < 1 else 0.0+++def carried(cell, i):+ return tuple(cell['regions'][i]['ellipse'])+++def inspect(tmp_path, name, regions):+ return sway_inspect.inspect_loop(strip_dir(tmp_path/f'loop-{name}'), regions, tmp_path/f'out-{name}', gain=1.0, on_fold='lower')+++def pair_seams(record, pair):+ return [(cell, seam) for cell in record['cells'] for seam in cell['seams'] if seam['regions'] == pair]+++def test_two_regions_meet_where_their_weights_cross(tmp_path):+ record = inspect(tmp_path, 'two', [A, B])+ assert record['schema_version'] == 3+ found = pair_seams(record, [0, 1])+ assert found and record['seams'] and record['seams'][0]['regions'] == [0, 1]+++def test_a_third_region_over_the_whole_curve_leaves_the_pair_no_seam(tmp_path):+ over = (60.0, 72.0, 26.0, 26.0) # at every point of x = 60 inside both, its weight is the larger+ record = inspect(tmp_path, 'covered', [A, B, over])+ assert pair_seams(record, [0, 1]) == []+ assert all(entry['regions'] != [0, 1] for entry in record['seams'])+ assert record['seams'], 'the third region meets the two, and those seams are kept'+++def test_a_third_region_over_part_of_the_curve_leaves_the_rest(tmp_path):+ top = (60.0, 66.0, 5.0, 5.0) # over the top of x = 60 only+ record = inspect(tmp_path, 'part', [A, B, top])+ found = pair_seams(record, [0, 1])+ assert found+ for cell, seam in found:+ x, y = seam['at']+ assert weight(x, y, carried(cell, 2)) <= max(weight(x, y, carried(cell, 0)), weight(x, y, carried(cell, 1))) + 1e-6+ alone = inspect(tmp_path, 'alone', [A, B])+ # The largest seam of the two alone is under the top region's reach in no cell where it is kept here.+ assert max(seam['jump'] for _, seam in found) <= max(seam['jump'] for _, seam in pair_seams(alone, [0, 1])) + 1e-9