Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix(video): a walk's steps are witnessed on the order its feet are drawn in, the foot drawn nearer changing sides twice a cycle, where the clip shows its two sides of feet are its two legs, never from the side or on a cut the search kept where no two-step cut closes, and video-cycle-align run on its own stops on a loop whose report holds its cut
Soohong Kim6155871e2302
diff --git a/sprite_gen/video/align.py b/sprite_gen/video/align.pyindex b9f1b64..7a4f4d7 100644--- a/sprite_gen/video/align.py+++ b/sprite_gen/video/align.py@@ -66,6 +66,13 @@ again (`video-loop --steps 1`) and aligns the set anew, or says it holds a wholetaken so a held part closes (its strip metadata says `steps: 2`) — returns half way at its secondstep: that return is no suspect (status `steps`), and the loop is aligned as the one cycle it is.+So is a loop whose cut, as the report beside it records (`held_cut`), nothing witnessed whole cycles+(`cycle-unwitnessed`: the step count left its crossings on steps, or the cut witness held the cut — it may be half a+cycle, one or two) or that was cut two cycles long where its strip counts two steps (`cycle-four-steps`): `video-set`+leaves such a loop out of its alignment, and alone this command stops on it the same way, named under `suspects`+(`held`, with the report), before anything is rewritten. Its return half way is no step then. `--cycles <loop>=1` says+it holds one cycle, `=2` takes one out of two; one step is cut again (`video-loop --steps 1`).+Where a loop's view cannot tell its feet apart (`start_foot` null, with `foot_why`), it starts on itslarger strike, and the report names it under `unnamed_feet` with its two strike frames as they nowstand in `cycle/` (`candidates`, the first being the frame it starts on) — for whoever looks, a@@ -103,6 +110,7 @@ from sprite_gen.video import sway as sway_modfrom sprite_gen.video import cadence as cadence_modfrom sprite_gen.video import held as held_modfrom sprite_gen.video import legs as legs_mod+from sprite_gen.video import local_cyclefrom sprite_gen.video import loop as loop_modfrom sprite_gen.video import period as period_modfrom sprite_gen.video import rife as rife_mod@@ -889,14 +897,38 @@ def one_step(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str,"seconds": round(screen["lag"] / float(data["fps"]), 3), "report": str(path)}+def held_cut(loop_dir: Path, meta_path: Path, meta: dict[str, Any]) -> dict[str, Any] | None:+ """A loop whose cut nothing witnessed whole cycles, or that was cut two cycles long where its strip counts two+ steps, as the cut's report records it (`cut_report`; `local_cycle.unwitnessed`, `local_cycle.four_steps`, which+ `video-set` leaves out of its alignment): `reason` (local_cycle.UNWITNESSED or local_cycle.FOUR_STEPS) and the+ `report` it is in. None otherwise — and where no report is found."""+ found = cut_report(loop_dir, meta_path, meta)+ if found is None:+ return None+ path, data = found+ cycle = data.get("cycle") or {}+ reason = (local_cycle.UNWITNESSED if local_cycle.unwitnessed(cycle) else+ local_cycle.FOUR_STEPS if local_cycle.four_steps(cycle) else None)+ return {"reason": reason, "report": str(path)} if reason else None++def _suspect_line(entry: dict[str, Any]) -> str:"""One loop's suspects, in words: where it returns, how, and what that would make it."""+ said = []+ if "held" in entry:+ held = entry["held"]+ said.append(f"nothing witnessed its cut whole cycles ({held['reason']}, in {held['report']}): it may hold half a "+ "cycle, one or two — if it is one step, cut it again with `sprite-gen video-loop … --steps 1`"+ if held["reason"] == local_cycle.UNWITNESSED else+ f"its cut holds four steps ({held['reason']}, in {held['report']}): two cycles where its strip counts "+ "two steps, and aligned as one it would play twice as fast")if "one_step" in entry:step = entry["one_step"]- line = (f"{entry['dir']}: may be one step of a cycle {step['lag']} frames long ({step['seconds']:.3f} s) — it repeats "- f"{step['ratio']:.2f}x as far two lengths on in its clip as one length on; count its steps, and if it is one, cut it "- f"again with `sprite-gen video-loop … --steps 1` (the arguments are in {step['report']}) and align the set anew")- return line + ("; it may also hold " + "; or ".join(_returns_said(entry)) if entry["candidates"] else "")+ said.append(f"may be one step of a cycle {step['lag']} frames long ({step['seconds']:.3f} s) — it repeats "+ f"{step['ratio']:.2f}x as far two lengths on in its clip as one length on; count its steps, and if it is one, cut it "+ f"again with `sprite-gen video-loop … --steps 1` (the arguments are in {step['report']}) and align the set anew")+ if said:+ return f"{entry['dir']}: " + "; ".join(said) + ("; it may also hold " + "; or ".join(_returns_said(entry)) if entry["candidates"] else "")return f"{entry['dir']}: may hold " + "; or ".join(_returns_said(entry))@@ -1228,21 +1260,23 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:cycle_warnings: list[str] = []for i, ((d, meta_path, meta, _), screen) in enumerate(zip(loops, screens)):k = given.get(i)- # A loop counted two steps long (`steps`) returns half way at its second step: not a second cycle.- stepped = [row for row in screen["suspects"] if meta.get("steps") == 2 and row["cycles"] == 2]+ # A loop counted two steps long (`steps`) returns half way at its second step: not a second cycle — unless nothing+ # witnessed its cut whole cycles, or it was cut two cycles long (`held`).+ held = held_cut(d, meta_path, meta)+ stepped = [row for row in screen["suspects"] if meta.get("steps") == 2 and row["cycles"] == 2 and held is None]rows = [row for row in screen["suspects"] if row not in stepped]step = one_step(d, meta_path, meta)- if rows or step or stepped:- status = ("counted" if k is not None else "steps" if not rows and not step+ if rows or step or stepped or held:+ status = ("counted" if k is not None else "steps" if not rows and not step and not heldelse "stopped" if multi_cycle == "fail" else "warned")suspects.append({"dir": str(d), "name": meta_path.name[: -len(".strip.json")], "length": len(sources[i]),"status": status, "cycles_given": k,"candidates": [{key: row[key] for key in ("period", "seconds", "divisor", "cycles", "periodicity", "pose","off_path", "distance", "steps", "follow", "why") if key in row}for row in (rows or stepped)],- **({"one_step": step} if step else {}),+ **({"one_step": step} if step else {}), **({"held": held} if held else {}),**({"steps": meta["steps"]} if stepped else {}),- "settle": [f"--cycles {d}={c}" for c in sorted({1, *(row["cycles"] for row in rows)})]})+ "settle": [f"--cycles {d}={c}" for c in sorted({1, *(row["cycles"] for row in rows), *([2] if held else [])})]})if k is not None and k > 1:if not any(row["cycles"] == k for row in screen["suspects"]):cycle_warnings.append(f"{d}: --cycles {k} given, but the screen found no return at 1/{k} of it; "@@ -1264,6 +1298,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:message = ("video-cycle-align: " + "; ".join(_suspect_line(e) for e in stopped)+ ". Stopped before anything was rewritten: pixels cannot tell two cycles from one cycle whose steps look alike"+ (", nor one step from a cycle" if any("one_step" in e for e in stopped) else "")+ + (", and nothing witnessed some of the cuts whole cycles" if any("held" in e for e in stopped) else "")+ ". Count the cycles in each (look at it, or ask a vision model how often each foot lands), then run, with each count "f"filled in (1: it holds one, aligned as it is; more: one cycle is taken out of it): {command}"" — or add --multi-cycle warn to align the set as it is (docs/loop-repair.md section 4)")@@ -1275,6 +1310,7 @@ def align_set(loop_dirs: list[Path], *, length: int | None = None, interpolate:raise CycleSuspects(message, suspects, command)cycle_warnings += [f"{_suspect_line(e)}; aligned as it is (--multi-cycle warn) — at the set's length it plays "+ ("one step where the rest play two, if it is one" if "one_step" in e else+ "half or twice as fast as the rest, if it is not one cycle" if "held" in e and not e["candidates"] elsef"{max(row['cycles'] for row in e['candidates'])} times as fast as the rest if it does")for e in suspects if e["status"] == "warned"]lengths = [len(f) for f in sources]diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 79efc1a..677fb30 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -888,7 +888,7 @@ def run_item(# cycle or tworesult["loop"][local_cycle.UNWITNESSED] = Trueif local_cycle.four_steps(lp["cycle"]):- # its body rises and falls four times in its cut: two cycles where its strip counts two steps — aligned as one+ # its cut holds four steps (its body or its feet say so): two cycles where its strip counts two steps — aligned as one# cycle, it would play twice as fastresult["loop"][local_cycle.FOUR_STEPS] = Trueif (lp["cycle"].get("step_screen") or {}).get("suspect"):@@ -985,7 +985,8 @@ def left_out_why(reasons: list[str], *, stands: bool = False, one_step: bool = Fwhy = " and ".join([*([f"a take to film again ({', '.join(retake)}){stood}"] if retake else []),*([f"nothing witnesses its cut whole cycles ({local_cycle.UNWITNESSED}): it may hold half a cycle or two"]if local_cycle.UNWITNESSED in reasons else []),- *([f"its body rises and falls four times in its cut ({local_cycle.FOUR_STEPS}): it holds two cycles "+ *([f"its body rises and falls, or its foot drawn nearer changes sides, four times in its cut "+ f"({local_cycle.FOUR_STEPS}): it holds two cycles ""where its strip counts two steps, and aligned as one cycle it would play twice as fast"]if local_cycle.FOUR_STEPS in reasons else [])])return why + ("; its step screen says it may be one step (cut it again with video-loop --steps 1 if it is)" if one_step else "")@@ -1003,8 +1004,9 @@ def align_gaits(results: list[dict[str, Any]], root: Path, mode: str, *, interpoA loop whose take is to be filmed again because the walk starts or stops in it (`retake` reason`start-stop`, loop.stand_retake) loops no two steps and has no cycle to match, a loop whose cut nothingwitnesses whole cycles (`cycle-unwitnessed`, local_cycle.unwitnessed: its crossings left on steps, or- its cut held by the cut witness) may hold half a cycle or two, and a loop its body rises and falls four- times in (`cycle-four-steps`, local_cycle.four_steps) loops two where its strip counts two steps: each+ its cut held by the cut witness) may hold half a cycle or two, and a loop cut four steps long (its body+ rising and falling, or its foot drawn nearer changing sides, four times in it: `cycle-four-steps`,+ local_cycle.four_steps) loops two where its strip counts two steps: eachis left out, its loop kept as cut, the rest aligned without it, and its state names it under`left_out`, with its reasons — no loop is played at twice its speed, and no count of its cycles isasked for. One left out whose step screen suspects it is one step (`step_screen`) is told in itsdiff --git a/sprite_gen/video/legs.py b/sprite_gen/video/legs.pyindex 302d8f9..4d6e2ca 100644--- a/sprite_gen/video/legs.py+++ b/sprite_gen/video/legs.py@@ -79,6 +79,7 @@ FEET_APART = 0.02FEET_APART_SHARE = 0.2SHADE_BAND = 0.15 # the shade cue reads the feet and lower legs: the lowest 15 % of the bodyTONE = 1 / 255 # one 8-bit level of luma (0..1): the step the shade cue's tones are drawn in; the depth cue's is a pixel row+CONTACT = 0.005 # a foot's contact: its solid pixels this far (of the body's height, at least a row) up from its lowest rowdef _longest_runs(solid: np.ndarray) -> np.ndarray:@@ -101,6 +102,19 @@ def _widest_gap(cols: np.ndarray) -> int:return int((np.nonzero(edges == -1)[0] - np.nonzero(edges == 1)[0]).max())+def _gap_at(cols: np.ndarray) -> tuple[int, int] | None:+ """(the first, the last column) of the longest run of False between the first and the last True of `cols`, or None+ where there is none."""+ xs = np.nonzero(cols)[0]+ inner = ~cols[xs[0] : xs[-1] + 1]+ if not inner.any():+ return None+ edges = np.diff(np.pad(inner.astype(np.int8), 1))+ starts, ends = np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0]+ widest = int(np.argmax(ends - starts))+ return int(xs[0] + starts[widest]), int(xs[0] + ends[widest] - 1)++def strike_signals(frames: list[Image.Image]) -> dict[str, list[float]]:"""Per frame, from the solid pixels: `stride`, `reach`, `top`, `gap` (see the module) and`height`, the frame's own body height in pixels. `top` passes over an ear, a hat's point or an@@ -233,6 +247,44 @@ def depth_cue(frame: Image.Image) -> float:return (low[1] - low[0]) / height+def _parts(cols: np.ndarray) -> list[list[int]]:+ """[first, last] column of each run of True in `cols`."""+ edges = np.diff(np.pad(cols.astype(np.int8), 1))+ return [[int(a), int(b) - 1] for a, b in zip(np.nonzero(edges == 1)[0], np.nonzero(edges == -1)[0])]+++def feet_order(frame: Image.Image) -> dict[str, Any]:+ """The order a frame draws its two feet in (`local_cycle.order_word` reads it). `ground`: what stands on its lowest+ row, the [first, last] column of each run of its solid pixels CONTACT of the height (at least a row) up from it;+ `height`, the frame's own body height; `apart`, whether two feet are seen apart: the foot band (the lowest+ FOOT_BAND of the height) parted at its widest empty run, that run FEET_APART of the height or wider, the picture's+ left foot left of it and its right foot right of it. Where they are, `depth`, how many rows lower the right foot's+ lowest solid row is drawn than the left's (from the front, the back or a diagonal the foot nearer the viewer is+ drawn lower); `left` and `right`, the first and the last column of each foot's contact (its solid pixels CONTACT of+ the height up from its own lowest row); and `sway`, how far right of the run's middle the mean column of the upper+ body's solid pixels lies (the first solid row down to the middle of the body)."""+ solid = np.asarray(frame.getchannel("A")) >= LOW_ALPHA+ rows = np.nonzero(solid.any(axis=1))[0]+ if rows.size == 0:+ raise ValueError("a loop frame has no solid body")+ y0, y1 = int(rows[0]), int(rows[-1])+ height = y1 - y0 + 1+ contact = max(1, round(CONTACT * height))+ read: dict[str, Any] = {"ground": _parts(solid[y1 + 1 - contact : y1 + 1].any(axis=0)), "height": height, "apart": False}+ gap = _gap_at(solid[y1 + 1 - max(1, round(height * FOOT_BAND)) : y1 + 1].any(axis=0))+ if gap is None or gap[1] - gap[0] + 1 < FEET_APART * height:+ return read+ feet = {}+ for side, cols in (("left", slice(0, gap[0])), ("right", slice(gap[1] + 1, solid.shape[1]))):+ part = solid[:, cols]+ low = int(np.nonzero(part.any(axis=1))[0][-1])+ xs = np.nonzero(part[low + 1 - contact : low + 1].any(axis=0))[0] + cols.start+ feet[side] = (low, [int(xs[0]), int(xs[-1])])+ upper = np.nonzero(solid[y0 : y0 + height // 2 + 1])[1]+ return {**read, "apart": True, "depth": feet["right"][0] - feet["left"][0], "left": feet["left"][1],+ "right": feet["right"][1], "sway": float(upper.mean() - (gap[0] + gap[1]) / 2)}++def shade_cue(frame: Image.Image, facing: str) -> float:"""How much lighter the front foot is drawn than the back one (mean luma 0..1 of the lowestSHADE_BAND of the body, front half against back half; the front is the side faced)."""diff --git a/sprite_gen/video/local_cycle.py b/sprite_gen/video/local_cycle.pyindex ae36b6f..ca24fe1 100644--- a/sprite_gen/video/local_cycle.py+++ b/sprite_gen/video/local_cycle.py@@ -95,6 +95,29 @@ BEAT_FRAMES = 8 # a rise and fall twice an interval is fitted (`twice_an_intervCUT_LINES = {'screen': 'on the screen', 'feet': 'over its feet'}CUT_WORDS = ('two steps', 'four steps', 'one step', None)SIDE_VIEW = 'side' # from the side the legs a step on are one silhouette, as near as a cycle on: asked only where a pass hides+# The order the feet are drawn in witnesses as the body does (`order_word`), for the step count and the cut alike: from+# the front, the back or a diagonal the foot nearer the viewer is drawn lower (`legs.feet_order`), and the nearer foot+# changes sides twice a cycle, once a step. Where the clip shows the two sides of its foot band are two legs, the+# changes counted over a crossing interval, or over a cut, say how many steps it holds. The view's label is not taken+# for it (a generated walk's label may be wrong): the clip shows it, or nothing is witnessed. Two feet are seen apart+# (`legs.feet_order`) in at least `legs.FEET_APART_SHARE` of the frames; the lower foot's side swings ORDER_ROWS rows+# or more and `legs.REACH_MIN` of the body's height (p10 to p90 of `depth`), a side read where one foot is drawn an+# eighth of that swing (at least a row) lower; no foot planted on the ground passes under the body to the other side,+# as one does seen from the side, the two sides then its front and back, not its two legs — no change of sides whose+# nearer foot's contact before it and the other side's after it share or touch a column, and nothing standing on the+# lowest row slides along it ORDER_TRAVEL of the feet's distance apart or more (`_travel`; a foot seen from the side+# slides the whole of it, one seen from the front or the back stands, or steps toward or away from the viewer); and the+# upper body sways under ORDER_SWAY of what a tilt about the feet would carry it to draw the lower foot so (`sway`, p10+# to p90, against the swing over the feet's distance apart, at ORDER_REACH of the body's height over them): a picture+# rocking on its feet draws one foot lower and then the other. Then the changes' rate over the span, within+# ORDER_SLACK of two, four or one, no two changes further apart than two of their mean, says two steps, four or one;+# from the side (SIDE_VIEW) it is not read.+ORDER_ROWS = 2+ORDER_TRAVEL = 0.8+ORDER_SWAY = 0.5+ORDER_REACH = 0.75+ORDER_SLACK = 0.2+ORDER_WORDS = (('two steps', 2), ('four steps', 4), ('one step', 1))# A loop whose clip one interval on is the same picture, as a walk whose feet meet once a cycle draws it, with nothing# to witness whether they do (`read_cycles`): its crossings stay on steps, so its two steps may be two cycles. Named on# its step count (`cycles.unwitnessed`), and `video-set` leaves it out of its state's cycle alignment under this reason.@@ -102,8 +125,8 @@ SIDE_VIEW = 'side' # from the side the legs a step on are one silhouette, as ne# `_witnessed`; `cut_witness.held`): it may be one step of a walk whose legs are drawn alike, or, the body rising and# falling once in it, a whole cycle of a body that does so once a cycle (`unwitnessed`).UNWITNESSED = 'cycle-unwitnessed'-# A walk's cut its body rises and falls four times in (`cut_word` says four steps, loop `_witnessed`): two cycles, and it-# stands. Its strip still counts the two steps the crossings counted (`steps: 2`), which `video-cycle-align` reads as one+# A walk's cut its body rises and falls four times in, or its foot drawn nearer changes sides four times in (`cut_word`+# says four steps, loop `_witnessed`): two cycles, and it stands. Its strip still counts the two steps the crossings counted (`steps: 2`), which `video-cycle-align` reads as one# cycle, a return half way its second step: aligned so, it would play twice as fast as the rest. `video-set` leaves it# out of its state's cycle alignment under this reason (`four_steps`).FOUR_STEPS = 'cycle-four-steps'@@ -755,7 +778,104 @@ def bob_word(signals, interval, *, feet=False):return {**word, 'says': 'cycles'}-def read_cycles(reading, distances, *, view=None, cue=None, cue_step=None, signals=None):+def _touch(a, b):+ """Whether two contacts ([first, last] column) share or touch a column."""+ return max(a[0], b[0]) <= min(a[1], b[1]) + 1+++def _travel(order):+ """How far, in columns, the furthest anything standing on the lowest row (`ground`) slides along it while it stands+ there: each run there followed from frame to frame while it shares or touches a column with one run, and only one,+ of the next frame (two runs that meet, or one that parts, start afresh: two feet standing side by side), its+ middle's range over the frames it is followed."""+ chains, widest = [], 0.0+ for o in order:+ nxt = []+ for part in o['ground']:+ middle = (part[0]+part[1])/2+ on = [c for c in chains if _touch(c['part'], part)]+ go = on[0] if len(on) == 1 and sum(1 for p in o['ground'] if _touch(on[0]['part'], p)) == 1 else None+ lo, hi = (min(go['lo'], middle), max(go['hi'], middle)) if go else (middle, middle)+ nxt.append({'part': part, 'lo': lo, 'hi': hi})+ widest = max(widest, hi-lo)+ chains = nxt+ return widest+++def order_word(order, span):+ """What the order the feet are drawn in (`order`, per frame: `legs.feet_order`) says of `span` frames — a crossing+ interval (`read_cycles`) or a cut (`cut_word`): `says` `two steps`, `four steps` or `one step` where the clip shows+ its two sides of feet are two legs and the side drawn lower changes at that rate (ORDER_WORDS, within ORDER_SLACK),+ else None with why (module notes before ORDER_ROWS). Returns the record: `apart` (the share of frames whose feet are+ seen apart), `swing` (the depth's p10 to p90, in rows), `floor`, and where read `changes` (frames between which the+ lower side changes), `slides` (those whose contacts touch), `spacing` (the feet's median distance apart) and+ `travel` (`_travel`), in px, `sway` and `tilt` (the sway a tilt would need), `per` (changes per span)."""+ seen = [o for o in order if o['apart']]+ apart = len(seen)/len(order) if order else 0.0+ word = {'apart': round(apart, 3)}+ if apart < legs_mod.FEET_APART_SHARE or len(seen) < 3:+ return {**word, 'says': None, 'why': f'the feet are seen apart in {apart:.0%} of the frames (from '+ f'{legs_mod.FEET_APART_SHARE:.0%}): the order they are drawn in is not read'}+ height = float(np.median([o['height'] for o in seen]))+ depth = np.asarray([o['depth'] for o in seen], dtype=float)+ swing = float(np.percentile(depth, 90) - np.percentile(depth, 10))+ floor = max(ORDER_ROWS, legs_mod.REACH_MIN*height)+ word.update(swing=round(swing, 2), floor=round(floor, 2))+ if swing < floor:+ return {**word, 'says': None, 'why': f'one foot is drawn lower than the other by {swing:.1f} rows either way, under '+ f'{floor:.1f}: the feet are drawn level'}+ least = max(1.0, swing/8)+ sides, last, changes = [], None, []+ for k, o in enumerate(order):+ side = None if not o['apart'] or abs(o['depth']) < least else ('right' if o['depth'] > 0 else 'left')+ if side is not None:+ if last is not None and side != sides[last]:+ changes.append((last, k))+ last = k+ sides.append(side)+ slides = [[a, b] for a, b in changes if _touch(order[a][sides[a]], order[b][sides[b]])]+ spacing = float(np.median([abs(sum(o['right'])-sum(o['left']))/2 for o in seen]))+ travel = _travel(order)+ word.update(changes=[[a, b] for a, b in changes], slides=slides, spacing=round(spacing, 1), travel=round(travel, 1))+ if slides:+ a, b = slides[0]+ return {**word, 'says': None, 'why': f'the foot drawn lower on the {sides[a]} at frame {a} and the one on the '+ f'{sides[b]} at frame {b} touch at the ground ({len(slides)} of '+ f'{len(changes)} changes): one foot slides under the body from one side to '+ 'the other, as seen from the side, and the sides are not two legs'}+ if travel >= ORDER_TRAVEL*spacing:+ return {**word, 'says': None, 'why': f'a foot standing on the lowest row slides {travel:.0f} px along it, '+ f'{travel/spacing:.0%} of the {spacing:.0f} px the feet are apart (from '+ f'{ORDER_TRAVEL:.0%}): a planted foot passes under the body to the other '+ 'side, as seen from the side, and the sides are not two legs'}+ sway = float(np.percentile([o['sway'] for o in seen], 90) - np.percentile([o['sway'] for o in seen], 10))+ tilt = swing*ORDER_REACH*height/max(spacing, 1.0)+ word.update(sway=round(sway, 1), tilt=round(tilt, 1))+ if sway >= ORDER_SWAY*tilt:+ return {**word, 'says': None, 'why': f'its upper body sways {sway:.0f} px, {sway/tilt:.0%} of the {tilt:.0f} px a tilt '+ f'about its feet would carry it to draw one foot {swing:.0f} rows lower than '+ f'the other (from {ORDER_SWAY:.0%}): the picture may rock on its feet'}+ times = [(a+b)/2 for a, b in changes]+ if len(times) < 3:+ return {**word, 'says': None, 'why': f'the foot drawn lower changes sides {len(times)} times: too few to count'}+ mean = (times[-1]-times[0])/(len(times)-1)+ per = span/mean+ word['per'] = round(per, 3)+ widest = max(b-a for a, b in zip(times, times[1:]))+ for says, k in ORDER_WORDS:+ if abs(per/k-1) <= ORDER_SLACK and widest <= 2*mean:+ return {**word, 'says': says}+ return {**word, 'says': None, 'why': f'the foot drawn lower changes sides {per:.2f} times in {span:.1f} frames '+ f'(every {mean:.1f}, at most {widest:g} apart): not within {ORDER_SLACK:.0%} of '+ 'two, four or one, each change at most two of their mean apart'}+++def _order_why(feet):+ """Why the order of the feet (`order_word`) witnesses nothing: its own why, or the word it says instead."""+ return feet.get('why') or f"the foot drawn nearer changes sides {feet['per']:.2f} times: {feet['says']}"+++def read_cycles(reading, distances, *, view=None, cue=None, cue_step=None, signals=None, order=None):"""Whether the crossings the clip shows (`reading`, gap mode) mark its cycles, not its steps, read and kept on thereading (`Reading.mark_cycles`; crossings.py, "Crossings that mark cycles"). The feet need not meet on the screenat every pass: the far foot can pass hidden behind the near one, or a foot step toward or away from the camera and@@ -769,7 +889,9 @@ def read_cycles(reading, distances, *, view=None, cue=None, cue_step=None, signacycles only where a witness that reads no leg says the interval holds two steps — the body's top line (`signals`,`legs.strike_signals` with `legs.body_signals`) rising and falling twice an interval, less its flow and of its own(`bob_word`: the picture drifting, swaying, shaking or zooming up and down as it pleases witnesses nothing, read- against the lowest row and the widths of the upper body; a lowest row on the frame's edge holds the word). The+ against the lowest row and the widths of the upper body; a lowest row on the frame's edge holds the word) — or the+ order the feet are drawn in (`order`, per frame: `legs.feet_order`; `order_word`), the foot drawn nearer changing+ sides twice an interval where the clip shows its two sides of feet are its two legs, not read from the side. Theview's foot cue (`cue`, per frame, drawn in steps of `cue_step`; `cue_word`) only refuses: where it turns over oneinterval on, the other leg leads there, a step. With no witness the crossings stay on steps, as from the side, andthe record names it (`unwitnessed`): where the feet do meet once a cycle, each step counted is a cycle. Returns@@ -796,7 +918,9 @@ def read_cycles(reading, distances, *, view=None, cue=None, cue_step=None, signaf"and as near as two on ({near['two']:.2f}, +{CYCLE_SLACK:g})")word = None if cue is None or view is None else cue_word(cue, d, step=cue_step)bob = None if not signals else bob_word(signals, d)- said.update({**({'cue': word} if word is not None else {}), **({'bob': bob} if bob is not None else {})})+ feet = None if order is None or view == SIDE_VIEW else order_word(order, d)+ said.update({**({'cue': word} if word is not None else {}), **({'bob': bob} if bob is not None else {}),+ **({'order': feet} if feet is not None else {})})if word is not None and word['says'] == 'steps':said.update(cycles=False, why=f"{picture}, but the view's foot cue turns over there ({word['one']:+.2f}, at most "f"{CUE_SWAPPED:+g}): the other leg leads, a step")@@ -807,11 +931,17 @@ def read_cycles(reading, distances, *, view=None, cue=None, cue_step=None, signaf"{bob['body']['beat']:.1f} left against its lowest row and upper body, "f"{bob['body']['share']:.0%}; "f"at least {BOB_OWN:.0%}): two steps an interval, the feet meet once a cycle")+ elif feet is not None and feet['says'] == 'two steps':+ said.update(cycles=True, why=f"{picture}, and the foot drawn nearer changes sides {feet['per']:.2f} times an "+ f"interval, the clip's two sides of feet its two legs (none slides from one to the "+ f"other, the upper body sways {feet['sway']:.0f} px of the {feet['tilt']:.0f} a tilt "+ "would need): two steps an interval, the feet meet once a cycle")else:said.update(cycles=False, unwitnessed=True,why=f"{picture}, but nothing that reads no leg witnesses two steps an interval "- f"({'no top line read' if bob is None else bob['why']}): a step on draws as a cycle on, as from the "- "side, and the crossings mark steps")+ f"({'no top line read' if bob is None else bob['why']}; "+ f"{'the order of the feet is not read from the side' if feet is None else _order_why(feet)}): "+ "a step on draws as a cycle on, as from the side, and the crossings mark steps")reading.mark_cycles(said)return said@@ -845,7 +975,7 @@ def _feet_mark(signals, length, over):return {'over': over, 'feet': feet, 'beat': top} if feet > top else None-def cut_word(signals, length):+def cut_word(signals, length, *, order=None, declined=None):"""The body's word on a walk's cut `length` frames long as it is about to be cut, whichever way it was chosen — thepixel search's, the step count's crossings read or not read (loop `_witnessed`). Legs drawn alike loop as well onone step as on two, and crossings read off feet that slide, or off a shadow under them on a picture that moves, can@@ -865,20 +995,44 @@ def cut_word(signals, length):- None where neither line reads any of these: nothing witnesses the cut whole cycles (`why`, each line's readingon the cut).+ Where neither line says the cut is a cycle or two, the order the feet are drawn in is read on it (`order`, per+ frame: `legs.feet_order`; `order_word`, as the step count reads it, None from the side): two steps or four, where+ the clip shows its two sides of feet are its two legs, and the cut stands on it (`by` ['order']); else the lines'+ word stands, the order's record kept (`order`). The order counts the changes in the cut, not whether its length+ closes them (a cut a sixth short of a cycle still reads two steps): where the cut is the search's, kept because none+ of the clip's two-step cuts closes (`declined`, the step count's record of the best of them), it does not stand on+ the order — a length the closing refused — and the order's word is kept as `read`.+Where the cut stands (two steps or four) and its lowest row rises and falls twice it more than its top line does onthe screen, the word carries a mark (`mark`, `_feet_mark`), and nothing more. Returns {'says', 'by': the lines thatsaid it (where it says), 'lines': each line's own word (`_cut_line`), 'on': the first such line's reading that said- four steps or one step, with its `line` and `interval`, 'why' where None, 'mark' where marked}."""+ four steps or one step, with its `line` and `interval`, 'why' where None, 'mark' where marked, 'order' where+ read}."""if not signals:return {'says': None, 'why': 'no top line read: a frame has no solid body'}lines = {line: _cut_line(signals, length, feet=line == 'feet') for line in CUT_LINES}says = min((word['says'] for word in lines.values()), key=CUT_WORDS.index)+ if says not in ('two steps', 'four steps') and order is not None:+ feet = order_word(order, length)+ if feet['says'] in ('two steps', 'four steps') and declined:+ feet = {**feet, 'says': None, 'read': feet['says'], 'why': (+ f"the foot drawn nearer changes sides {feet['per']:.2f} times in the cut ({feet['says']}), but the cut is "+ f"the search's, kept where none of the clip's two-step cuts closes (the best, {declined['cut'][0]}/"+ f"{declined['cut'][1]}): the order counts its steps, not whether its length closes, and does not stand a "+ "length the closing refused")}+ if feet['says'] in ('two steps', 'four steps'):+ return {'says': feet['says'], 'by': ['order'], 'lines': lines, 'order': feet}+ if says is None:+ return {'says': None, 'lines': lines, 'order': feet,+ 'why': '; '.join([*dict.fromkeys(word['why'] for word in lines.values()), _order_why(feet)])}if says is None:return {'says': None, 'lines': lines, 'why': '; '.join(dict.fromkeys(word['why'] for word in lines.values()))}by = [line for line, word in lines.items() if word['says'] == says]said = {'says': says, 'by': by, 'lines': lines}if says != 'two steps':said['on'] = {'line': by[0], **lines[by[0]]['on']}+ if says == 'one step' and order is not None:+ said['order'] = feetmark = None if says == 'one step' else _feet_mark(signals, length, lines['feet']['bob']['over'])return {**said, **({'mark': mark} if mark else {})}@@ -892,7 +1046,7 @@ def unwitnessed(cycle):def four_steps(cycle):- """Whether a walk's loop is cut two cycles long, its body rising and falling four times in it (FOUR_STEPS:+ """Whether a walk's loop is cut two cycles long, four steps read in it (FOUR_STEPS:`cut_word`, loop `_witnessed`, `cut_witness.says`). It stands; `video-set` leaves it out of its state's cyclealignment, its strip counting two steps."""return (cycle.get('cut_witness') or {}).get('says') == 'four steps'diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.pyindex d2a4544..61bbae3 100644--- a/sprite_gen/video/loop.py+++ b/sprite_gen/video/loop.py@@ -1543,8 +1543,9 @@ def read_steps(frames: list[Image.Image], D: np.ndarray, *, view: str | None = Nsignals: dict[str, list[float]] | None = None) -> crossings_mod.Reading:"""The clip's crossings (`crossings.read`), and whether they mark its cycles (`local_cycle.read_cycles`, on `D`, theclip's distances, the body's bob read off `signals` — the frames' leg signals, read here where not given, with the- body's own (`legs.body_signals`) — and the `view`'s foot cue: `legs.shade_cue` from the side or a diagonal, drawn in- tones of `legs.TONE`, `legs.depth_cue` from the front or back, in pixel rows of the body's median height). Every+ body's own (`legs.body_signals`) — the order its feet are drawn in (`legs.feet_order`), and the `view`'s foot cue:+ `legs.shade_cue` from the side or a diagonal, drawn in tones of `legs.TONE`, `legs.depth_cue` from the front or+ back, in pixel rows of the body's median height). Everycount the clip's steps make is read on it: the search's cut (`_by_steps`), a fixed cut (`fixed_count`) and, carriedto the loop, the loop as it plays (`ring_steps`)."""signals = leg_signals(frames) if signals is None else signals@@ -1559,7 +1560,8 @@ def read_steps(frames: list[Image.Image], D: np.ndarray, *, view: str | None = Nheights = signals["height"] if signals else legs_mod.strike_signals(frames)["height"]step = legs_mod.TONE if lateral else 1.0 / float(np.median(heights))body = {**signals, **legs_mod.body_signals(frames)} if signals else None- local_cycle.read_cycles(reading, D, view=view, cue=cue, cue_step=step, signals=body)+ local_cycle.read_cycles(reading, D, view=view, cue=cue, cue_step=step, signals=body,+ order=[legs_mod.feet_order(f) for f in frames])return reading@@ -1785,12 +1787,14 @@ def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarreturn found-def _witnessed(cycle: dict[str, Any], *, frames: list[Image.Image]) -> dict[str, Any]:+def _witnessed(cycle: dict[str, Any], *, frames: list[Image.Image], view: str | None = None) -> dict[str, Any]:"""The cut a walk's search and step count chose (`_by_steps`), held to one word before it is cut whichever way itwas chosen — the search's, two steps by the clip's crossings, crossings read or not: the body's- (`local_cycle.cut_word`: its top line on the screen and over its feet, the first word either says), recorded- `cut_witness`. Legs drawn alike loop as well on one step as on two, and crossings read off feet that slide, or off- a shadow under them on a picture that moves, count half steps.+ (`local_cycle.cut_word`: its top line on the screen and over its feet, the first word either says), or where it says+ no cycle the order the feet are drawn in (`legs.feet_order`, as the step count reads it; not from the side `view`),+ recorded `cut_witness` — not the order where the cut is the search's, kept because none of the clip's two-step cuts+ closes (`declined`). Legs drawn alike loop as well on one step as on two, and crossings read off feet that slide,+ or off a shadow under them on a picture that moves, count half steps.- Its own rise and fall twice the cut, or four times: the cut is a cycle, or two, and stands. Cut two cycles, itsstrip still counts two steps where the crossings counted them, and `video-set` leaves it out of its state's cycle@@ -1812,8 +1816,10 @@ def _witnessed(cycle: dict[str, Any], *, frames: list[Image.Image]) -> dict[str,cycle["cut_witness"] = {"cut": first, "held": "step count"}return cyclestrike = leg_signals(frames)+ order = None if view == local_cycle.SIDE_VIEW or not strike else [legs_mod.feet_order(f) for f in frames]said = {"cut": first, **local_cycle.cut_word({**strike, **legs_mod.body_signals(frames)} if strike else None,- cycle["length"])}+ cycle["length"], order=order,+ declined=(cycle.get("step_count") or {}).get("declined"))}cycle["cut_witness"] = said if said["says"] in ("two steps", "four steps") else {**said, "held": "unwitnessed"}return cycle@@ -2157,7 +2163,7 @@ def _cut_loop(cycle = _by_steps(cycle, refused, frames=source_frames, analysis=analysis, D=D, trajectory=trajectory,window=window, searched=searched, detect=detect, seam_max=seam_max, cells=cells,view=view, facing=facing)- cycle = _witnessed(cycle, frames=source_frames)+ cycle = _witnessed(cycle, frames=source_frames, view=view)elif cycle_mode == "once":source_frames = [Image.open(f).convert("RGBA") for f in files]cycle = nonloop.select_cut(D, masses, fps=fps, ending=partial(diff --git a/tests/video/test_cycle_align.py b/tests/video/test_cycle_align.pyindex b4158cb..6fb43a0 100644--- a/tests/video/test_cycle_align.py+++ b/tests/video/test_cycle_align.py@@ -211,14 +211,15 @@ def test_the_view_picks_the_signal_so_a_short_legged_walk_starts_on_a_strike(vieassert strike["foot_why"].startswith("no legs to read"), strike-def _cut(tmp_path: Path, name: str, length: int, cycles: int = 1) -> Path:+def _cut(tmp_path: Path, name: str, length: int, cycles: int = 1, report: bool = False) -> Path:keyed = tmp_path / f"{name}-keyed"keyed.mkdir()for k in range(length + 6):_walker(2 * math.pi * cycles * k / length).save(keyed / f"{k:04d}.png")out = tmp_path / nameloop_mod.run_loop(keyed, out, fps=24.0, state="walk", min_len=None, max_len=None, n_out=None, seam_max=1000.0,- name="walk", report_path=None, cycle_mode="fixed", start=0, length=length, anchor="none", repair="off")+ name="walk", report_path=out / "walk.loop.report.json" if report else None, cycle_mode="fixed",+ start=0, length=length, anchor="none", repair="off")return out@@ -399,6 +400,42 @@ def test_video_set_leaves_a_loop_its_body_rises_and_falls_four_times_in_out_of_tassert f"four times in its cut ({local_cycle.FOUR_STEPS})" in capsys.readouterr().err[email protected]("witness, reason", [({"held": "unwitnessed"}, local_cycle.UNWITNESSED),+ ({"says": "four steps", "by": ["order"]}, local_cycle.FOUR_STEPS)])+def test_video_cycle_align_alone_stops_on_a_loop_whose_cut_its_report_holds_and_names_why(tmp_path, witness, reason):+ """`video-cycle-align` run on a set's loops alone, without the rows `video-set` marks, reads the report beside each+ loop (`align.held_cut`): a loop whose cut nothing witnessed whole cycles (`cycle-unwitnessed`) may hold half a+ cycle or two, and one cut two cycles long where its strip counts two steps (`cycle-four-steps`) returns half way at+ its second step, which alone reads as one cycle. Either stops the set before anything is rewritten, named under+ `suspects` with its reason and its report, never aligned as one cycle without a word (the parent engine aligned+ both: the first at its own length, the second at twice the speed of the rest); a count settles it."""+ four = reason == local_cycle.FOUR_STEPS+ dirs = [_cut(tmp_path, n, L, cycles=c, report=n == "N")+ for n, L, c in (("S", 20, 1), ("E", 24, 1), ("N", 40 if four else 28, 2 if four else 1))]+ report = dirs[2] / "walk.loop.report.json"+ data = json.loads(report.read_text())+ report.write_text(json.dumps({**data, "cycle": {**data["cycle"], "cut_witness": witness}}))+ if four:+ strip = dirs[2] / "walk.strip.json"+ strip.write_text(json.dumps({**json.loads(strip.read_text()), "steps": 2}))+ before = [(d / "walk.strip.png").read_bytes() for d in dirs]+ with pytest.raises(align.CycleSuspects) as stop:+ align.align_set(dirs, interpolate=Recorder(), between="rife")+ (entry,) = stop.value.suspects+ assert entry["dir"] == str(dirs[2].resolve()) and entry["status"] == "stopped" and "one_step" not in entry+ assert entry["held"] == {"reason": reason, "report": str(report.resolve())}+ assert entry["settle"] == [f"--cycles {dirs[2].resolve()}={c}" for c in (1, 2)]+ said = str(stop.value)+ assert reason in said and "nothing witnessed some of the cuts whole cycles" in said and ("--steps 1" in said) is (not four)+ assert [(d / "walk.strip.png").read_bytes() for d in dirs] == before+ out = align.align_set(dirs, interpolate=Recorder(), between="rife", multi_cycle="warn")+ assert out["applied"] is True and any(reason in line for line in out["warnings"])+ counted = align.align_set(dirs, interpolate=Recorder(), between="rife", cycles={str(dirs[2]): 2 if four else 1})+ assert counted["applied"] is True and counted["lengths"] == [20, 24, 20 if four else 28]+ assert counted["suspects"][0]["status"] == "counted" and counted["suspects"][0]["held"]["reason"] == reason++def _no_rife(monkeypatch, tmp_path: Path) -> None:monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)# PATH keeps every other tool (img2webp, ffmpeg); only the directories holding a RIFE godiff --git a/tests/video/test_one_step_cut.py b/tests/video/test_one_step_cut.pyindex 4a5ad55..954af67 100644--- a/tests/video/test_one_step_cut.py+++ b/tests/video/test_one_step_cut.py@@ -234,24 +234,30 @@ def _set(root: Path, side: Path) -> list[Path]:@pytest.mark.slowdef test_cycle_align_stops_on_a_loop_that_may_be_one_step_and_names_the_count_that_settles_it(slow, tmp_path):+ """The step screen suspects the side walk's cut; and the walker is carried whole on its legs, so the cut witness+ held both cuts (`cycle-unwitnessed`, as `test_video_set_names_a_loop_that_may_be_one_step_and_its_table_says_so`+ reads): alone, `video-cycle-align` reads both in the reports beside the loops and stops on both, the front walk+ named held and the side walk held and suspected one step."""root, keyed, _ = slowwhole = _keyed(tmp_path / "whole", cycle=25)_cut(tmp_path / "front", whole)dirs = _set(tmp_path, root / "out")with pytest.raises(align.CycleSuspects) as stop:align.align_set(dirs, between="nearest")- (entry,) = stop.value.suspects+ front, entry = stop.value.suspects+ assert [e["held"]["reason"] for e in (front, entry)] == [local_cycle.UNWITNESSED] * 2 and "one_step" not in front+ assert front["dir"] == str(dirs[0].resolve()) and front["status"] == "stopped"assert entry["dir"] == str(dirs[1].resolve()) and entry["status"] == "stopped" and entry["candidates"] == []assert entry["one_step"]["lag"] in (CYCLE - 1, CYCLE, CYCLE + 1) and entry["one_step"]["report"] == str((dirs[1] / "loop.loop.report.json").resolve())- assert entry["settle"] == [f"--cycles {dirs[1].resolve()}=1"]+ assert entry["settle"] == [f"--cycles {dirs[1].resolve()}={c}" for c in (1, 2)]assert "may be one step" in str(stop.value) and "--steps 1" in str(stop.value)# Nothing was rewritten: the side loop is as cut.assert (dirs[1] / "loop.strip.png").read_bytes() == (root / "out" / "loop.strip.png").read_bytes()- # warn aligns it as it is and says so; a count of one cycle settles it.+ # warn aligns it as it is and says so; a count of one cycle in each settles it.out = align.align_set(dirs, between="nearest", multi_cycle="warn")assert out["applied"] is True and any("one step where the rest play two" in line for line in out["warnings"])- out = align.align_set(dirs, between="nearest", cycles={str(dirs[1]): 1})- assert out["applied"] is True and out["suspects"][0]["status"] == "counted"+ out = align.align_set(dirs, between="nearest", cycles={str(d): 1 for d in dirs})+ assert out["applied"] is True and [e["status"] for e in out["suspects"]] == ["counted"] * 2# --- video-set ----------------------------------------------------------------------------@@ -263,7 +269,7 @@ def test_video_set_names_a_loop_that_may_be_one_step_and_its_table_says_so(slow,the front walk's whole cycle and the side walk's step (`cycle-unwitnessed`), and the step screen suspects theside walk's. The set leaves both out of its alignment, named in words true of half a cycle and of two, and tells theside walk what settles the step screen's suspicion (`--steps 1`), as `video-cycle-align` does: run on the items'- loops, it reads the step screen in the report beside the side walk's loop and stops on it."""+ loops, it reads the held cuts and the step screen in the reports beside them and stops on both."""_, keyed, _ = slowrows = []for direction, source in (("front", _keyed(tmp_path / "whole", cycle=25)), ("side", keyed)):@@ -286,7 +292,8 @@ def test_video_set_names_a_loop_that_may_be_one_step_and_its_table_says_so(slow,assert held in front and held in side and settle in side and settle not in front, (front, side)with pytest.raises(align.CycleSuspects) as stop:align.align_set([Path(r["dir"]) / "loop" for r in rows], between="nearest")- (entry,) = stop.value.suspects+ front, entry = stop.value.suspects+ assert [e["held"]["reason"] for e in (front, entry)] == [local_cycle.UNWITNESSED] * 2 and "one_step" not in frontassert entry["one_step"]["report"] == str((tmp_path / "side-walk" / "loop.report.json").resolve())assert "may be one step" in str(stop.value) and "--steps 1" in str(stop.value)table = batch.write_table(rows, tmp_path / "table.md")diff --git a/tests/video/test_walk_steps.py b/tests/video/test_walk_steps.pyindex b4cefcf..fe18967 100644--- a/tests/video/test_walk_steps.py+++ b/tests/video/test_walk_steps.py@@ -31,6 +31,14 @@ of its head (flat, round, a point, two ears' tips) or however its head or a capewhose feet leave the ground, nor a planted foot sliding down the screen. And one the count alone gets wrong, where thesearch's cut stands: a walk on threes whose tail closes on no cut of two steps.+A walk seen from the front whose feet stay apart and meet once a cycle, its body still, is witnessed by the order its+feet are drawn in (`local_cycle.order_word`): the foot drawn nearer, lower, changes sides twice an interval, and the clip+shows its two sides of feet are its legs — no foot planted on the ground slides under the body to the other side, the+upper body does not rock over them — so the crossings mark cycles and the cut stands on the same word; labelled the+side view, the order is not read. A side walk lifting its swing foot draws one foot lower and then the other too, but+its planted foot passes under the body: never read so, whatever its label; nor a picture rocked on its feet, nor feet+drawn level. Nor does the order stand a cut the search kept where none of the clip's two-step cuts closes.+A walk the search already cuts two steps long, joined at the walk's own point, is cut exactly as before; a bodywhose feet cannot be read is cut as before. Synthetic frames only."""@@ -150,6 +158,32 @@ def _outward(k: float, *, cycle: float, bob: int = 3, whole: bool = False, arm:return im+def _apart(k: float, *, cycle: float, rock: float = 0, slide: bool = False) -> Image.Image:+ """A walker seen from the front whose feet stay apart: the foot stepping toward the camera is drawn lower, up to 3 px+ under the ground and the other as far over it, so the foot drawn nearer changes sides once a step; the right foot,+ drawn higher, swings in to meet the left over it and back, so the feet meet on the screen once a cycle, briefly, and+ no foot on the ground slides along it. Its body does not rise and fall, its arms swinging within its sides+ (ARMS_IN): nothing that reads no leg but the order its feet are drawn in tells a step on from a cycle on.+ `rock`: its feet drawn level and still, the whole picture rocked that many degrees either way about its feet once a+ cycle, one foot drawn lower and then the other with no step. `slide`: the right foot swings in to meet the left as+ both stand level on the ground and back as it is drawn lower, planted, sliding along the ground as only a foot seen+ from the side does."""+ ph = 2 * math.pi * k / cycle+ im = Image.new("RGBA", (300, 220))+ d = ImageDraw.Draw(im)+ x, y = 90, 40+ drop = 0 if rock else round(3 * math.sin(ph))+ inward = 0 if rock else 10 * max(0.0, -math.cos(ph)) ** 4 if slide else 10 * max(0.0, math.sin(ph)) ** 2+ swing = ARMS_IN * math.sin(ph)+ d.rectangle((x + 14 - swing - 4, y + 34, x + 14 - swing + 4, y + 72), fill=(150, 150, 150, 255))+ for lx, sole, t in ((x + 6, GROUND + drop, 0), (x + 22 - inward, GROUND - drop, 1)):+ d.rectangle((lx - 5, y + 80, lx + 5, sole), fill=(60 + t, 60 + t, 70 + t, 255))+ d.rectangle((x, y + 30, x + 28, y + 84), fill=(200, 80, 80, 255))+ d.rectangle((x + 2, y, x + 26, y + 28), fill=(230, 200, 170, 255))+ d.rectangle((x + 14 + swing - 4, y + 34, x + 14 + swing + 4, y + 72), fill=(225, 225, 225, 255))+ return im.rotate(rock * math.sin(ph), resample=Image.Resampling.NEAREST, center=(x + 14, GROUND)) if rock else im++def _alike(k: float, *, cycle: float, phase: float = 0, tone: int = 1, lean: float = 0, leg_tone: int | None = None,leg_half: int = 5, lift: int = 0, light: tuple[str, int] | None = None, bob: int = 3, whole: bool = False,air: int = 0, slide: int = 0, limp: int = 0, top: str = "flat", arm: float = 16) -> Image.Image:@@ -499,6 +533,46 @@ def test_a_diagonal_walk_whose_near_foot_steps_out_is_cut_one_cycle_from_its_vieassert said["says"] == "four steps" and local_cycle.four_steps(plain["cycle"]) and plain["cycle"]["steps"]["count"] == 2[email protected]("cycle", [20, 24])+def test_a_walk_whose_feet_stay_apart_and_meet_once_a_cycle_is_cut_one_cycle_on_the_order_its_feet_are_drawn_in(tmp_path, cycle):+ """Seen from the front, the feet apart, the foot stepping toward the camera drawn lower: the feet meet on the screen+ once a cycle, and the body does not rise and fall. The clip shows its two sides of feet are its two legs — seen apart+ most of the time, one drawn lower and then the other by 6 rows either way, no foot planted on the ground sliding+ along it or passing under the body to the other side, the upper body still over them — and the foot drawn nearer+ changes sides twice an interval: the count reads the crossings as cycles, one cycle, `steps: 2`, and the cut stands+ on the same word (the parent engine left the crossings on steps, nothing that reads no leg witnessing them, and cut+ two cycles with a warning). Labelled the side view, the order is not read: two intervals, named."""+ keyed = _keyed(tmp_path, lambda k: _apart(k, cycle=cycle))+ _cut(tmp_path / "front", keyed, "--view", "front")+ said = _one_cycle(tmp_path / "front", cycle)["cycles"]+ assert said["bob"]["says"] is None and said["order"]["says"] == "two steps" and "unwitnessed" not in said+ assert said["order"]["slides"] == [] and said["order"]["travel"] < local_cycle.ORDER_TRAVEL * said["order"]["spacing"]+ assert "the foot drawn nearer changes sides" in said["why"]+ witness = json.loads((tmp_path / "front" / "loop.loop.report.json").read_text())["cycle"]["cut_witness"]+ assert witness["says"] == "two steps" and witness["by"] == ["order"] and "held" not in witness+ side = _cut(tmp_path / "side", keyed, "--view", "side")+ assert abs(side["cycle"]["length"] - 2 * cycle) <= 1.5 and local_cycle.unwitnessed(side["cycle"])+ assert "order" not in (side["cycle"]["step_count"].get("cycles") or {}) and "order" not in side["cycle"]["cut_witness"]++[email protected]("view", [None, "front", "front_diagonal", "back", "back_diagonal"])+def test_a_side_walk_whose_swing_foot_lifts_is_never_cut_on_the_order_its_feet_are_drawn_in_whatever_its_label(tmp_path, view):+ """The side walker with its legs drawn alike, the leg swinging forward lifted 6 px at its pass: one foot is drawn+ higher and then the other, and its label, where given, says a view the order is read from. The planted foot slides+ along the ground under the body from one side to the other, as only a foot seen from the side does: the clip's two+ sides of feet are its front and its back, not its two legs, and the order witnesses nothing — two steps, 46 frames,+ never one interval read as two steps on a wrong label."""+ report = _cut(tmp_path / "out", _keyed(tmp_path, lambda k: _alike(k, cycle=46, phase=13, tone=4, lean=1, leg_tone=0, lift=6)),+ *(("--view", view) if view else ()))+ _two_steps(report, 46)+ said = report["cycle"]["step_count"].get("cycles")+ if said is not None:+ assert said["cycles"] is False and said["order"]["says"] is None and "under the body" in said["order"]["why"]+ assert report["cycle"]["cut_witness"].get("by") != ["order"]++@pytest.mark.slow@pytest.mark.parametrize("tone, lean", [(1, 0), (4, 1)])def test_a_side_walk_whose_two_steps_look_alike_is_cut_two_steps_however_near_a_step_on(tmp_path, tone, lean):@@ -1411,6 +1485,49 @@ def test_a_cut_is_witnessed_by_how_often_the_body_rises_and_falls_in_it(beat, saassert word["on"]["says"] == "cycles" and word["on"]["interval"] == {"four steps": 8, "one step": 32}[says][email protected]("span, says", [(30, "two steps"), (60, "four steps"), (15, "one step"), (22, None)])+def test_the_order_the_feet_are_drawn_in_says_how_many_steps_a_span_holds(span, says):+ """`order_word` on the walker whose feet stay apart, a cycle 30 frames: the foot drawn nearer changes sides every 15+ frames, twice in 30 — two steps; four times in 60, two cycles; once in 15, one step; in 22, none of those. No foot+ on the ground slides along it, and its upper body is still."""+ word = local_cycle.order_word([legs.feet_order(_apart(k, cycle=30)) for k in range(FRAMES)], span)+ assert word["says"] == says and word["apart"] >= legs.FEET_APART_SHARE and word["swing"] >= word["floor"]+ assert word["slides"] == [] and word["travel"] < local_cycle.ORDER_TRAVEL * word["spacing"]+ assert word["sway"] < local_cycle.ORDER_SWAY * word["tilt"] and word["per"] == pytest.approx(span / 15, rel=0.05)+++def test_the_order_does_not_stand_a_cut_the_search_kept_where_none_of_the_two_step_cuts_closes():+ """The walker whose feet stay apart, its body still, cut 20 frames, a cycle (loop `_witnessed`): the order says two+ steps and the cut stands on it. Where the step count read the clip but none of its two-step cuts closed, and the+ search's cut was kept (`declined`), the order counts the same steps but does not stand a length the closing refused:+ the cut is held, named, the order's word kept as `read`."""+ frames = [_apart(k, cycle=20) for k in range(FRAMES)]+ cut = {"start": 4, "length": 20, "step_count": {"readable": True, "chosen_by": "search"}}+ stood = loop._witnessed(json.loads(json.dumps(cut)), frames=frames, view="front")["cut_witness"]+ assert stood["says"] == "two steps" and stood["by"] == ["order"] and "held" not in stood+ cut["step_count"]["declined"] = {"cut": [6, 40], "phase": 0.0, "gated": True, "seam": 2.6}+ held = loop._witnessed(cut, frames=frames, view="front")+ said = held["cut_witness"]+ assert said["says"] is None and said["held"] == "unwitnessed" and local_cycle.unwitnessed(held)+ assert said["order"]["read"] == "two steps" and "does not stand a length the closing refused" in said["why"]++[email protected]("frames, why", [+ (lambda k: _apart(k, cycle=30, rock=10), "may rock on its feet"),+ (lambda k: _apart(k, cycle=30, slide=True), "slides"),+ (lambda k: _alike(k, cycle=46, phase=13, tone=4, lean=1, leg_tone=0, lift=6), "under the body"),+ (lambda k: _alike(k, cycle=46, phase=13, tone=4, lean=1, leg_tone=0, leg_half=10, lift=6), "under the body"),+ (lambda k: _behind(k, cycle=20, hold=2, arm=ARMS_IN), "drawn level"),+])+def test_the_order_the_feet_are_drawn_in_witnesses_nothing_where_the_clip_does_not_show_its_sides_are_two_legs(frames, why):+ """A picture rocked on its feet draws one foot lower and then the other with its upper body swaying as far as the+ tilt carries it; the walker whose feet stay apart, its right foot sliding along the ground planted to meet the left+ and back, and a side walk lifting its swing foot draw one foot lower and then the other with a foot on the ground+ passing under the body; feet drawn level say no order. None says a word, each says why."""+ word = local_cycle.order_word([legs.feet_order(frames(k)) for k in range(FRAMES)], 23)+ assert word["says"] is None and why in word["why"], word++@pytest.mark.parametrize("verdict", ["held_verdict", "step_verdict"])def test_a_cut_held_on_one_step_whose_record_names_no_line_is_refused_by_name(verdict):"""`held_verdict` (a public caller; `step_verdict` says it) names the line a cut held on one step rose and fell