Skip to content

The agent that grows with you

refactor(agent/runtime): pet — shared flood/placement helpers in atlas, provider resolution loop, dead helpers removed

Teknium2ad284b47379
diff --git a/agent/pet/constants.py b/agent/pet/constants.py
index a7e816c4012..5a3fafb291f 100644
--- a/agent/pet/constants.py
+++ b/agent/pet/constants.py
@@ -140,8 +140,7 @@ STATE_ALIASES: dict[str, tuple[str, ...]] = {
def state_aliases_for(state: "PetState | str") -> tuple[str, ...]:
"""Return accepted row-name aliases for *state* (always non-empty)."""
value = state.value if isinstance(state, PetState) else str(state)
- aliases = STATE_ALIASES.get(value)
- return aliases if aliases else (value,)
+ return STATE_ALIASES.get(value) or (value,)
def state_rows_for_grid(row_count: int | None) -> list[str]:
@@ -150,10 +149,7 @@ def state_rows_for_grid(row_count: int | None) -> list[str]:
rows = int(row_count or 0)
except (TypeError, ValueError):
rows = 0
-
- if rows >= len(CODEX_STATE_ROWS):
- return CODEX_STATE_ROWS
- return LEGACY_STATE_ROWS
+ return CODEX_STATE_ROWS if rows >= len(CODEX_STATE_ROWS) else LEGACY_STATE_ROWS
def state_row_index(state: "PetState | str", row_count: int | None = None) -> int:
diff --git a/agent/pet/generate/atlas.py b/agent/pet/generate/atlas.py
index b631d79f359..7049bd6cd09 100644
--- a/agent/pet/generate/atlas.py
+++ b/agent/pet/generate/atlas.py
@@ -1,31 +1,20 @@
"""Deterministic spritesheet assembly — generated row strips → Hermes atlas.
-Image-generation models are good at *drawing* a row of poses but bad at exact
-grid geometry, so the model never owns the atlas layout: it produces one loose
-horizontal strip per state, and these deterministic ops slice that strip into
-clean, centered, transparent ``192x208`` cells and pack them into the sheet our
-renderer reads.
-
-The atlas follows the **petdex/Codex standard**: 8 columns x 9 rows of
-``192x208`` cells (``1536x1872``), with the row order + per-row frame counts
-from OpenAI's ``hatch-pet`` skill. Our renderer (:mod:`agent.pet.render`) keys
-frames as ``rows = states, cols = frames`` via
-:data:`agent.pet.constants.CODEX_STATE_ROWS`, and a pet built here is a valid
-``petdex submit`` spritesheet. Rows shorter than 8 columns leave the trailing
-cells fully transparent.
-
-Note ``running`` is the *working* state (in-place processing), NOT locomotion —
-``running-right`` / ``running-left`` are the actual directional walk cycles.
-
-The frame-segmentation, fit-to-cell, and transparency-residue logic is adapted
-from OpenAI's ``hatch-pet`` skill (openai/skills, Apache-2.0).
+Image models draw a row of poses well but can't do exact grid geometry, so the
+model never owns the layout: it emits one loose horizontal strip per state and
+these ops slice it into centered transparent ``192x208`` cells packed into the
+petdex/Codex atlas (8 columns x 9 rows, ``1536x1872``) that
+:mod:`agent.pet.render` reads via :data:`agent.pet.constants.CODEX_STATE_ROWS`.
+``running`` is the in-place *working* state; ``running-right``/``-left`` are the
+directional walk cycles. Segmentation/fit/residue logic is adapted from
+OpenAI's ``hatch-pet`` skill (openai/skills, Apache-2.0).
"""
from __future__ import annotations
-import io
import logging
import math
+from collections import deque
from pathlib import Path
from agent.pet.constants import FRAME_H, FRAME_W
@@ -36,10 +25,8 @@ CELL_WIDTH = FRAME_W
CELL_HEIGHT = FRAME_H
# (state, row index, frame count). Order/row indices MUST match
-# ``constants.CODEX_STATE_ROWS`` so the renderer crops the right row for each
-# driven state, and the per-row frame counts mirror the petdex/Codex
-# ``hatch-pet`` ``animation-rows`` spec. The renderer trims trailing blank
-# columns, so rows shorter than ``COLUMNS`` (8) just leave the tail transparent.
+# ``constants.CODEX_STATE_ROWS``; frame counts mirror the petdex ``hatch-pet``
+# spec. Rows shorter than 8 leave their tail transparent (renderer trims it).
ROW_SPECS: list[tuple[str, int, int]] = [
("idle", 0, 6),
("running-right", 1, 8),
@@ -57,42 +44,112 @@ COLUMNS = max(count for _, _, count in ROW_SPECS)
ATLAS_WIDTH = COLUMNS * CELL_WIDTH
ATLAS_HEIGHT = ROWS * CELL_HEIGHT
-FRAME_COUNTS: dict[str, int] = {state: count for state, _, count in ROW_SPECS}
-
-# Alpha at/below which a pixel is "background" for component detection.
-_ALPHA_FLOOR = 16
-# Cell padding kept around a fitted sprite so poses never touch the edge.
-_CELL_PAD = 10
-# Margin for the normalized pass — small, to fill the cell like real petdex pets
-# (they sit ~5px from the edges); the width clamp, not the pad, prevents clipping.
+_ALPHA_FLOOR = 16 # alpha at/below which a pixel is "background"
+_CELL_PAD = 10 # padding kept around a fitted sprite
+# Small margin for the normalized pass so cells fill like real petdex pets
+# (~5px from the edges); the width clamp, not the pad, prevents clipping.
_NORMALIZE_PAD = 14
-# Side-lobe cutoff for fitted frames. Adjacent-pose bleed usually appears as a
-# small separated horizontal lobe beside the real subject; keep sizeable lobes so
-# we don't punish a legitimate wide pose.
+# Side-lobe cutoff: adjacent-pose bleed shows as a small separated lobe; keep
+# sizeable lobes so a legitimate wide pose isn't punished.
_SIDE_LOBE_RATIO = 0.18
+_NEIGHBOURS = ((1, 0), (-1, 0), (0, 1), (0, -1))
-# ───────────────────────── background removal ─────────────────────────
+def _median(values) -> int:
+ ordered = sorted(values)
+ return ordered[len(ordered) // 2]
+
+
+def _blank(size=(CELL_WIDTH, CELL_HEIGHT)):
+ from PIL import Image
+
+ return Image.new("RGBA", size, (0, 0, 0, 0))
+
+
+def _place(sprite, size: tuple[int, int], offset: tuple[int, int] = (0, 0)):
+ """*sprite* alpha-composited at *offset* onto a new transparent canvas of *size*."""
+ canvas = _blank(size)
+ canvas.alpha_composite(sprite, offset)
+ return canvas
+
+
+def _clear_region(image, box: tuple[int, int, int, int]) -> None:
+ """Make the ``(left, top, right, bottom)`` region of *image* fully transparent, in place."""
+ image.paste(_blank((box[2] - box[0], box[3] - box[1])), (box[0], box[1]))
+
+
+def _load_rgba(image):
+ """Open a path (or take an image) as RGBA."""
+ from PIL import Image
+
+ if isinstance(image, (str, Path)):
+ with Image.open(image) as opened:
+ return opened.convert("RGBA")
+ return image.convert("RGBA")
+
+
+def _border_coords(w: int, h: int):
+ """Every border pixel: top/bottom rows column-wise, then left/right columns."""
+ for x in range(w):
+ for y in (0, h - 1):
+ yield x, y
+ for y in range(h):
+ for x in (0, w - 1):
+ yield x, y
+
+
+def _flood(w: int, h: int, visited: bytearray, seeds, accept) -> list[tuple[int, int]]:
+ """4-connected BFS from *seeds* over pixels passing *accept*; returns the visited pixels."""
+ queue = deque(seeds)
+ pixels: list[tuple[int, int]] = []
+ while queue:
+ x, y = queue.popleft()
+ pixels.append((x, y))
+ for dx, dy in _NEIGHBOURS:
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < w and 0 <= ny < h:
+ idx = ny * w + nx
+ if not visited[idx]:
+ visited[idx] = 1
+ if accept(nx, ny):
+ queue.append((nx, ny))
+ return pixels
+
+
+def _border_flood(w: int, h: int, visited: bytearray, accept) -> list[tuple[int, int]]:
+ """Flood from every border pixel passing *accept* (edge-connected region only)."""
+ seeds: list[tuple[int, int]] = []
+ for x, y in _border_coords(w, h):
+ if not visited[y * w + x] and accept(x, y):
+ visited[y * w + x] = 1
+ seeds.append((x, y))
+ return _flood(w, h, visited, seeds, accept)
+
+
+def _unvisited_components(w: int, h: int, visited: bytearray, accept):
+ """Yield each 4-connected component of not-yet-visited pixels passing *accept*, in scan order."""
+ for start in range(w * h):
+ if visited[start]:
+ continue
+ visited[start] = 1
+ x, y = start % w, start // w
+ if accept(x, y):
+ yield _flood(w, h, visited, [(x, y)], accept)
-def _color_distance(r: int, g: int, b: int, key: tuple[int, int, int]) -> float:
- return math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2)
+# ───────────────────────── background removal ─────────────────────────
def _has_transparency(image) -> bool:
"""True if the strip already carries a real alpha background."""
- extrema = image.getchannel("A").getextrema()
- # Min alpha 0 somewhere and a meaningful share of fully-transparent pixels.
- if extrema[0] > _ALPHA_FLOOR:
+ if image.getchannel("A").getextrema()[0] > _ALPHA_FLOOR:
return False
- hist = image.getchannel("A").histogram()
- transparent = sum(hist[: _ALPHA_FLOOR + 1])
- total = image.width * image.height
- return transparent > total * 0.05
+ transparent = sum(image.getchannel("A").histogram()[: _ALPHA_FLOOR + 1])
+ return transparent > image.width * image.height * 0.05
def _dominant_corner_color(image) -> tuple[int, int, int]:
- """Sample the four corners and return the most common opaque color."""
+ """Most common opaque color among the four corners."""
from collections import Counter
w, h = image.width, image.height
@@ -102,17 +159,14 @@ def _dominant_corner_color(image) -> tuple[int, int, int]:
r, g, b, a = px[x, y]
if a > _ALPHA_FLOOR:
counter[(r, g, b)] += 1
- if not counter:
- return (0, 255, 0)
- return counter.most_common(1)[0][0]
+ return counter.most_common(1)[0][0] if counter else (0, 255, 0)
def _near_key_mask(image, key: tuple[int, int, int], tol: int = 48):
- """An ``L`` mask, 255 where a pixel is within *tol* per-channel of *key*.
+ """``L`` mask, 255 where a pixel is within *tol* per-channel of *key*.
- Tight on purpose: it only marks near-pure backdrop so trapped chroma pockets
- seed the flood, while chroma-*tinted* character pixels stay outside it. Built
- with channel point-ops (fast C), no per-pixel Python.
+ Tight on purpose: marks only near-pure backdrop so trapped chroma pockets
+ seed the flood while chroma-tinted character pixels stay outside it.
"""
from PIL import ImageChops
@@ -127,36 +181,26 @@ def _near_key_mask(image, key: tuple[int, int, int], tol: int = 48):
)
-def _defringe(rgba):
- """Shave the 1px antialiased edge ring left after keying.
+def _remove_masked(rgba, mask):
+ """Clear the pixels *mask* (``L``, 255 = remove) selects, then erode alpha by 1px (3x3 min).
- Chroma keying can't catch the antialiased band where the sprite meets the
- backdrop — those pixels are a key/sprite blend, too far from the key to be
- removed, so they ring the cutout in magenta/green. Erode the alpha by one
- pixel (a 3x3 min filter) to drop that contaminated ring; the sprite's own
- thick dark outline keeps the silhouette intact. Built on a C-level filter, no
- per-pixel Python.
+ The erosion drops the antialiased key/sprite blend ring (too far from the key to
+ match); the sprite's own thick outline keeps the silhouette intact.
"""
- from PIL import ImageFilter
+ from PIL import Image, ImageFilter
- rgba.putalpha(rgba.getchannel("A").filter(ImageFilter.MinFilter(3)))
- return rgba
+ out = Image.composite(_blank(rgba.size), rgba, mask)
+ out.putalpha(out.getchannel("A").filter(ImageFilter.MinFilter(3)))
+ return out
def remove_background(image, *, chroma_key: tuple[int, int, int] | None = None, threshold: float = 90.0):
"""Return *image* (RGBA) with its flat background keyed out to transparent.
- If the strip already has a transparent background we leave it alone; else we
- key out *chroma_key* (or the dominant corner color when not given) via a
- **border flood-fill**: only background-coloured pixels *connected to an edge*
- are removed. A global color match (the old approach) punched holes in the pet
- wherever an interior highlight happened to match the backdrop — e.g. a pug's
- light belly against a near-white background — which then showed through as the
- window behind. Flood-fill keeps those interior pixels because they aren't
- reachable from the border without crossing the (non-background) pet.
+ Already-transparent strips are left alone (holes repaired). Otherwise key out
+ *chroma_key* (or the dominant corner color) via a border flood-fill: a global
+ color match punched holes wherever an interior highlight matched the backdrop.
"""
- from collections import deque
-
from PIL import Image, ImageChops
rgba = image.convert("RGBA")
@@ -169,77 +213,31 @@ def remove_background(image, *, chroma_key: tuple[int, int, int] | None = None,
def _is_bg(x: int, y: int) -> bool:
r, g, b, a = px[x, y]
- return a > _ALPHA_FLOOR and _color_distance(r, g, b, key) <= threshold
+ return a > _ALPHA_FLOOR and math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2) <= threshold
- # Fast path for strongly-saturated chroma keys (our normal sprite prompts use
- # hot magenta): remove all near-key opaque pixels with C-level channel ops.
- # This clears both border-connected backdrop and enclosed triangular pockets
- # between connected limbs/capes, without a Python flood over ~1.5M pixels.
+ # Fast path for saturated chroma keys (our prompts use hot magenta): C-level
+ # channel ops clear border backdrop and enclosed pockets alike, no Python flood.
if max(key) - min(key) >= 120:
- near = _near_key_mask(rgba, key) # L mask, 255 where near key
opaque = rgba.getchannel("A").point(lambda a: 255 if a > _ALPHA_FLOOR else 0)
- remove_mask = ImageChops.darker(near, opaque)
- keyed = Image.composite(Image.new("RGBA", rgba.size, (0, 0, 0, 0)), rgba, remove_mask)
- return _defringe(keyed)
+ return _remove_masked(rgba, ImageChops.darker(_near_key_mask(rgba, key), opaque))
- visited = bytearray(w * h)
- # Mark removals in a flat mask and apply them in one C composite at the end —
- # writing `px[x, y] = (0,0,0,0)` per pixel was ~3M PixelAccess calls (84% of
- # the whole pipeline) and pegged a core in pure Python, stalling the gateway.
+ # Border-only flood on purpose: a desaturated near-white/gray key must never
+ # seed from the character's interior (that is the hole-punching case).
+ # Mark removals in a flat mask and composite once in C — per-pixel writes
+ # were ~3M PixelAccess calls and stalled the gateway.
remove = bytearray(w * h)
- queue: deque[tuple[int, int]] = deque()
-
- # Seed from every border pixel that looks like background.
- for x in range(w):
- for y in (0, h - 1):
- if _is_bg(x, y) and not visited[y * w + x]:
- visited[y * w + x] = 1
- queue.append((x, y))
- for y in range(h):
- for x in (0, w - 1):
- if _is_bg(x, y) and not visited[y * w + x]:
- visited[y * w + x] = 1
- queue.append((x, y))
-
- # Trapped pockets: background enclosed by the character (the magenta between
- # an arm and the body) isn't border-reachable, so also seed the flood from
- # interior near-key pixels. Gated to a *saturated* key (our magenta backdrop)
- # so we never seed from a character sharing a desaturated near-white/gray key
- # — that's the hole-punching the border-only flood exists to avoid.
- if max(key) - min(key) >= 120:
- for i, near in enumerate(_near_key_mask(rgba, key).getdata()):
- if near and not visited[i]:
- visited[i] = 1
- queue.append((i % w, i // w))
-
- while queue:
- x, y = queue.popleft()
+ for x, y in _border_flood(w, h, bytearray(w * h), _is_bg):
remove[y * w + x] = 1
- for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
- if 0 <= nx < w and 0 <= ny < h:
- idx = ny * w + nx
- if not visited[idx]:
- visited[idx] = 1
- if _is_bg(nx, ny):
- queue.append((nx, ny))
-
- # One C-level composite instead of millions of per-pixel writes: paint the
- # flooded pixels to (0,0,0,0) wherever the mask is set.
- mask = Image.frombytes("L", (w, h), bytes(remove)).point(lambda v: 255 if v else 0)
- return _defringe(Image.composite(Image.new("RGBA", rgba.size, (0, 0, 0, 0)), rgba, mask))
+ return _remove_masked(rgba, Image.frombytes("L", (w, h), bytes(remove)).point(lambda v: 255 if v else 0))
def _repair_internal_alpha_holes(image):
"""Fill transparent islands fully enclosed by opaque sprite pixels.
Some providers return "transparent" PNGs with swiss-cheese alpha inside the
- character. Border flood-fill cannot see those because there is no opaque
- backdrop to key, so repair the alpha mask itself: transparent components that
- touch an image edge remain background; transparent components enclosed by
- the sprite are filled with the average color of their opaque neighbours.
+ character. Edge-connected transparent components stay background; enclosed
+ ones are filled with the average color of their opaque neighbours.
"""
- from collections import deque
-
rgba = image.convert("RGBA")
w, h = rgba.size
px = rgba.load()
@@ -248,69 +246,24 @@ def _repair_internal_alpha_holes(image):
def _is_transparent(x: int, y: int) -> bool:
return px[x, y][3] <= _ALPHA_FLOOR
- def _mark_border_component(sx: int, sy: int) -> None:
- queue: deque[tuple[int, int]] = deque([(sx, sy)])
- visited[sy * w + sx] = 1
- while queue:
- x, y = queue.popleft()
- for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
- if 0 <= nx < w and 0 <= ny < h:
- idx = ny * w + nx
- if not visited[idx] and _is_transparent(nx, ny):
- visited[idx] = 1
- queue.append((nx, ny))
-
- # First mark true background: all transparent pixels reachable from the edge.
- for x in range(w):
- for y in (0, h - 1):
- if _is_transparent(x, y) and not visited[y * w + x]:
- _mark_border_component(x, y)
- for y in range(h):
- for x in (0, w - 1):
- if _is_transparent(x, y) and not visited[y * w + x]:
- _mark_border_component(x, y)
-
- def _collect_hole(sx: int, sy: int) -> list[tuple[int, int]]:
- queue: deque[tuple[int, int]] = deque([(sx, sy)])
- visited[sy * w + sx] = 1
- pixels: list[tuple[int, int]] = []
- while queue:
- x, y = queue.popleft()
- pixels.append((x, y))
- for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
- if 0 <= nx < w and 0 <= ny < h:
- idx = ny * w + nx
- if not visited[idx] and _is_transparent(nx, ny):
- visited[idx] = 1
- queue.append((nx, ny))
- return pixels
+ _border_flood(w, h, visited, _is_transparent) # edge-connected transparency = background
def _fill_color(hole: list[tuple[int, int]]) -> tuple[int, int, int, int]:
samples: list[tuple[int, int, int]] = []
seen = set(hole)
for x, y in hole:
- for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
+ for dx, dy in _NEIGHBOURS:
+ nx, ny = x + dx, y + dy
if 0 <= nx < w and 0 <= ny < h and (nx, ny) not in seen:
r, g, b, a = px[nx, ny]
if a > _ALPHA_FLOOR:
samples.append((r, g, b))
if not samples:
return (0, 0, 0, 255)
- return (
- round(sum(c[0] for c in samples) / len(samples)),
- round(sum(c[1] for c in samples) / len(samples)),
- round(sum(c[2] for c in samples) / len(samples)),
- 255,
- )
+ r, g, b = (round(sum(c[i] for c in samples) / len(samples)) for i in range(3))
+ return (r, g, b, 255)
- for start, _ in enumerate(visited):
- if visited[start]:
- continue
- x = start % w
- y = start // w
- if not _is_transparent(x, y):
- continue
- hole = _collect_hole(x, y)
+ for hole in _unvisited_components(w, h, visited, _is_transparent):
color = _fill_color(hole)
for hx, hy in hole:
px[hx, hy] = color
@@ -324,128 +277,84 @@ def _fit_to_cell(image):
"""Crop to content, scale to fit a padded cell, and center on transparent."""
from PIL import Image
- target = Image.new("RGBA", (CELL_WIDTH, CELL_HEIGHT), (0, 0, 0, 0))
image = _drop_side_bleed(image)
bbox = image.getbbox()
if bbox is None:
- return target
+ return _blank()
sprite = image.crop(bbox)
- max_w = CELL_WIDTH - _CELL_PAD
- max_h = CELL_HEIGHT - _CELL_PAD
- scale = min(max_w / sprite.width, max_h / sprite.height, 1.0)
+ scale = min((CELL_WIDTH - _CELL_PAD) / sprite.width, (CELL_HEIGHT - _CELL_PAD) / sprite.height, 1.0)
if scale != 1.0:
- # NEAREST, not LANCZOS: the generated "pixel art" has hard edges, and any
- # interpolating resample anti-aliases them into a blurry, washed-out
- # sprite once the renderer upscales the cell. Crisp blocky downscale reads
- # as real pixel art.
+ # NEAREST: interpolating resamples blur the hard pixel-art edges.
sprite = sprite.resize(
(max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale))),
Image.Resampling.NEAREST,
)
- left = (CELL_WIDTH - sprite.width) // 2
- top = (CELL_HEIGHT - sprite.height) // 2
- target.alpha_composite(sprite, (left, top))
- return target
+ return _place(sprite, (CELL_WIDTH, CELL_HEIGHT), ((CELL_WIDTH - sprite.width) // 2, (CELL_HEIGHT - sprite.height) // 2))
def _drop_side_bleed(image):
- """Remove tiny separated left/right lobes before fitting a frame.
-
- Frogger showed the failure mode: a good centered pose plus a thin vertical
- sliver from the neighbouring pose. By the time it reaches a cell, that sliver
- may be close enough to the subject that component extraction already grouped
- it. A horizontal alpha projection still reveals it as a small side lobe with
- a low mass compared to the main silhouette. Drop only those low-mass lobes;
- keep large lobes so wide poses and real limbs survive.
- """
- from PIL import Image
+ """Remove tiny separated left/right lobes (neighbour-pose slivers) before fitting.
+ Component extraction may already have grouped a near sliver with the subject;
+ a horizontal alpha projection still reveals it as a low-mass side lobe. Only
+ those are dropped so wide poses and real limbs survive.
+ """
rgba = image.convert("RGBA")
w, h = rgba.size
- profile = _column_profile(rgba) # mean alpha per column (fast C resize)
-
- runs = _content_runs(profile)
+ runs = _content_runs(_column_profile(rgba))
if len(runs) < 2:
return rgba
- masses = [sum(profile[l:r]) for l, r in runs]
- keep_mass = max(masses) * _SIDE_LOBE_RATIO
- keep = [run for run, m in zip(runs, masses) if m >= keep_mass]
+ keep_mass = max(m for _run, m in runs) * _SIDE_LOBE_RATIO
+ keep = [run for run, m in runs if m >= keep_mass]
if len(keep) == len(runs):
return rgba
- # Zero every column band that isn't a kept segment (box paste, not per-pixel).
rgba = rgba.copy()
- cut, prev = Image.new("RGBA", (w, h), (0, 0, 0, 0)), 0
+ prev = 0
for left, right in keep:
if left > prev:
- rgba.paste(cut.crop((prev, 0, left, h)), (prev, 0))
+ _clear_region(rgba, (prev, 0, left, h))
prev = right
if prev < w:
- rgba.paste(cut.crop((prev, 0, w, h)), (prev, 0))
+ _clear_region(rgba, (prev, 0, w, h))
return rgba
def _erase_long_axis_lines(image):
"""Remove thin slot-spanning guide/floor/divider lines.
- Gemini will sometimes satisfy "baseline" / "cell" language by drawing
- literal horizontal floors or vertical panel dividers. They survive chroma
- keying and connect otherwise clean poses. Drop only *thin* rows/columns that
- span nearly the whole slot; thick sprite body rows are left alone.
+ Models sometimes draw literal floors or panel dividers; they survive keying
+ and connect otherwise clean poses. Only *thin* near-full-span rows/columns go.
"""
- from PIL import Image
-
rgba = image.convert("RGBA").copy()
w, h = rgba.size
alpha = rgba.getchannel("A")
def _thin_groups(indices: list[int]) -> list[tuple[int, int]]:
groups: list[tuple[int, int]] = []
- start: int | None = None
- prev: int | None = None
- for idx in indices:
- if start is None:
- start = prev = idx
- continue
- if prev is not None and idx == prev + 1:
+ start = prev = -2
+ for idx in [*indices, -2]: # -2 sentinel flushes the last run
+ if start >= 0 and idx == prev + 1:
prev = idx
continue
- if start is not None and prev is not None and prev - start + 1 <= 4:
+ if start >= 0 and prev - start + 1 <= 4:
groups.append((start, prev + 1))
start = prev = idx
- if start is not None and prev is not None and prev - start + 1 <= 4:
- groups.append((start, prev + 1))
return groups
- wide_rows = [
- y
- for y in range(h)
- if sum(1 for x in range(w) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= w * 0.85
- ]
- tall_cols = [
- x
- for x in range(w)
- if sum(1 for y in range(h) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= h * 0.85
- ]
-
- clear = Image.new("RGBA", rgba.size, (0, 0, 0, 0))
+ wide_rows = [y for y in range(h) if sum(1 for x in range(w) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= w * 0.85]
+ tall_cols = [x for x in range(w) if sum(1 for y in range(h) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= h * 0.85]
+
for top, bottom in _thin_groups(wide_rows):
- rgba.paste(clear.crop((0, top, w, bottom)), (0, top))
+ _clear_region(rgba, (0, top, w, bottom))
for left, right in _thin_groups(tall_cols):
- rgba.paste(clear.crop((left, 0, right, h)), (left, 0))
+ _clear_region(rgba, (left, 0, right, h))
return rgba
def _component_boxes(image) -> list[tuple[tuple[int, int, int, int], int]]:
- """Connected opaque components as ``[(bbox, mass)]``.
-
- A full ML segmenter would be overkill here: after chroma keying, "the pet" is
- the dominant connected alpha component inside each known slot. Tiny detached
- sparkles, tears, UI dots, and neighbour slivers are separate components.
- """
- from collections import deque
-
+ """Connected opaque components as ``[(bbox, mass)]``."""
rgba = image.convert("RGBA")
bbox = rgba.getbbox()
if bbox is None:
@@ -453,42 +362,20 @@ def _component_boxes(image) -> list[tuple[tuple[int, int, int, int], int]]:
l0, t0, r0, b0 = bbox
w, h = r0 - l0, b0 - t0
alpha = rgba.getchannel("A").load()
- visited = bytearray(w * h)
out: list[tuple[tuple[int, int, int, int], int]] = []
- for start in range(w * h):
- if visited[start]:
- continue
- sx, sy = start % w, start // w
- ax, ay = l0 + sx, t0 + sy
- visited[start] = 1
- if alpha[ax, ay] <= _ALPHA_FLOOR:
- continue
+ def _opaque(x: int, y: int) -> bool:
+ return alpha[l0 + x, t0 + y] > _ALPHA_FLOOR
- queue: deque[tuple[int, int]] = deque([(sx, sy)])
- left = right = sx
- top = bottom = sy
- mass = 0
- while queue:
- x, y = queue.popleft()
- mass += 1
- left, right = min(left, x), max(right, x)
- top, bottom = min(top, y), max(bottom, y)
- for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
- if 0 <= nx < w and 0 <= ny < h:
- idx = ny * w + nx
- if not visited[idx]:
- visited[idx] = 1
- if alpha[l0 + nx, t0 + ny] > _ALPHA_FLOOR:
- queue.append((nx, ny))
- out.append(((l0 + left, t0 + top, l0 + right + 1, t0 + bottom + 1), mass))
+ for pixels in _unvisited_components(w, h, bytearray(w * h), _opaque):
+ xs = [x for x, _ in pixels]
+ ys = [y for _, y in pixels]
+ out.append(((l0 + min(xs), t0 + min(ys), l0 + max(xs) + 1, t0 + max(ys) + 1), len(pixels)))
return out
def _isolate_slot_subject(image):
"""Keep the slot's real subject; drop detached effects/noise."""
- from PIL import Image
-
rgba = _erase_long_axis_lines(image)
comps = _component_boxes(rgba)
if not comps:
@@ -506,42 +393,30 @@ def _isolate_slot_subject(image):
overlap = max(0, min(right, mr) - max(left, ml))
center_x = (left + right) / 2
near_main = (ml - mw * 0.25) <= center_x <= (mr + mw * 0.25)
- # Keep meaningful attached-looking accessories such as halos; drop
- # sparkles/tears/noise that don't overlap the body column.
+ # Keep attached-looking accessories (halos); drop sparkles/tears/noise.
if mass >= max(24, main_mass * 0.035) and (overlap >= mw * 0.3 or near_main):
keep.append(box)
- out = Image.new("RGBA", rgba.size, (0, 0, 0, 0))
+ out = _blank(rgba.size)
for box in keep:
out.alpha_composite(rgba.crop(box), (box[0], box[1]))
return out
-def _has_slot_padding(image) -> bool:
- """True when content has empty room on all four slot edges."""
- bbox = image.getbbox()
- if bbox is None:
- return False
- w, h = image.size
- left, top, right, bottom = bbox
- min_x = max(4, min(12, round(w * 0.025)))
- min_y = max(4, min(16, round(h * 0.02)))
+def _has_margin(size: tuple[int, int], box: tuple[int, int, int, int], fx: float, fy: float) -> bool:
+ """True when *box* leaves empty room on all four edges of an image of *size* (≥4px, ≤12/16px)."""
+ w, h = size
+ left, top, right, bottom = box
+ min_x = max(4, min(12, round(w * fx)))
+ min_y = max(4, min(16, round(h * fy)))
return left >= min_x and top >= min_y and w - right >= min_x and h - bottom >= min_y
-def _slot_bounds(width: int, frame_count: int) -> list[tuple[int, int]]:
- return [
- (round(i * width / frame_count), round((i + 1) * width / frame_count))
- for i in range(frame_count)
- ]
-
-
def _group_component_rows(boxes: list[tuple[int, int, int, int]]) -> list[list[tuple[int, int, int, int]]]:
"""Group component boxes into visual rows, then sort left→right."""
if not boxes:
return []
- heights = sorted(max(1, b[3] - b[1]) for b in boxes)
- row_tol = max(12, heights[len(heights) // 2] * 0.55)
+ row_tol = max(12, _median(max(1, b[3] - b[1]) for b in boxes) * 0.55)
rows: list[list[tuple[int, int, int, int]]] = []
centers: list[float] = []
for box in sorted(boxes, key=lambda b: (b[1] + b[3]) / 2):
@@ -561,12 +436,10 @@ def _group_component_rows(boxes: list[tuple[int, int, int, int]]) -> list[list[t
def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[int, int, int, int]]:
- """Merge disconnected parts that clearly belong to one subject.
+ """Merge disconnected parts of one subject (capes, tails, props) on the same row.
- Capes, tails, horns, and held props sometimes key as separate components.
- Merge components on the same visual row when their vertical spans overlap and
- the horizontal gap is tiny compared with the component size. Do not bridge the
- much larger gaps between separate poses.
+ Merges when vertical spans overlap and the horizontal gap is tiny relative to
+ the component size; never bridges the larger gaps between separate poses.
"""
boxes = list(boxes)
changed = True
@@ -599,21 +472,13 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[i
def _component_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None:
"""Extract frame subjects as connected non-background objects.
- This is the robust path for models that ignore "one horizontal row" and emit a
- 2D sprite grid. We count real opaque subject components, discard tiny
- detached effects, sort in reading order, and return exactly *frame_count*
- frames. Slot slicing is only a fallback when object detection can't satisfy
- the contract.
+ Robust path for models that emit a 2D grid instead of one row: count real
+ subject components, discard tiny effects, sort in reading order, return
+ exactly *frame_count* frames (or ``None`` when the contract can't be met).
"""
- from PIL import Image
def attempt(source) -> list | None:
- comps = _component_boxes(source)
- if not comps:
- return None
-
- max_mass = max(m for _box, m in comps)
- subjects = _merge_related_boxes([box for box, mass in comps if mass >= max(64, max_mass * 0.12)])
+ subjects = _significant_subject_boxes(source, min_mass=64)
if len(subjects) < frame_count:
return None
@@ -622,12 +487,8 @@ def _component_crops(strip, frame_count: int, *, require_padding: bool = False)
if len(ordered) < frame_count:
return None
- if require_padding:
- min_x = max(4, min(12, round(source.width * 0.01)))
- min_y = max(4, min(16, round(source.height * 0.015)))
- for left, top, right, bottom in ordered:
- if left < min_x or top < min_y or source.width - right < min_x or source.height - bottom < min_y:
- return None
+ if require_padding and not all(_has_margin(source.size, box, 0.01, 0.015) for box in ordered):
+ return None
multirow = len(rows) > 1
frames = []
@@ -644,82 +505,73 @@ def _component_crops(strip, frame_count: int, *, require_padding: bool = False)
elif frame_count == 1:
crop_box = (0, 0, source.width, source.height)
else:
- # Preserve vertical motion for true one-row strips (jumping,
- # bobbing) while still narrowing X around the object.
+ # Keep full height for true one-row strips so vertical motion survives.
crop_box = (max(0, left - pad_x), 0, min(source.width, right + pad_x), source.height)
- frame = Image.new("RGBA", (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), (0, 0, 0, 0))
- rel = (left - crop_box[0], top - crop_box[1], right - crop_box[0], bottom - crop_box[1])
- frame.alpha_composite(source.crop((left, top, right, bottom)), (rel[0], rel[1]))
- # The global component pass already chose the subject box. Do not run
- # another component filter here: capes/tails can be legitimate
+ # No second component filter here: capes/tails can be legitimate
# disconnected lobes inside the chosen subject box.
- frames.append(frame)
+ frames.append(
+ _place(
+ source.crop((left, top, right, bottom)),
+ (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]),
+ (left - crop_box[0], top - crop_box[1]),
+ )
+ )
return frames
return attempt(strip) or attempt(_erase_long_axis_lines(strip))
def _sever_expected_gutters(strip, frame_count: int):
- """Cut thin vertical gutters at expected frame boundaries before labeling.
-
- Generated rows often have a shared shadow, glow, motion smear, or 1px bridge
- that connects neighbouring poses. Component detection then sees one giant
- blob and either fails or falls back to slot slicing. We know the requested
- frame count, so cut a very narrow transparent band at each expected boundary
- before connected-component labeling. If a pose truly overlaps the boundary,
- losing a few pixels is better than exporting merged frames.
+ """Cut narrow transparent bands at expected frame boundaries before labeling.
+
+ Shared shadows/smears/1px bridges connect neighbouring poses into one blob;
+ losing a few boundary pixels beats exporting merged frames.
"""
if frame_count <= 1:
return strip
out = strip.copy()
- px = out.load()
+ alpha = out.getchannel("A") # zero alpha only; RGB is left untouched
slot = out.width / frame_count
half = max(3, min(18, round(slot * 0.06)))
for i in range(1, frame_count):
x = round(i * slot)
- left = max(0, x - half)
- right = min(out.width, x + half + 1)
- for gx in range(left, right):
- for gy in range(out.height):
- r, g, b, _a = px[gx, gy]
- px[gx, gy] = (r, g, b, 0)
+ alpha.paste(0, (max(0, x - half), 0, min(out.width, x + half + 1), out.height))
+ out.putalpha(alpha)
return out
+def _clean_slot(image):
+ return _drop_side_bleed(_isolate_slot_subject(image))
+
+
def _slot_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None:
- """Slice *strip* into *frame_count* uniform columns (one coordinate space).
+ """Slice *strip* into *frame_count* uniform, independently cleaned columns.
- Equal-width columns keep every frame in a single shared coordinate frame, so
- a later union-crop + shared placement (:func:`normalize_cells`) preserves the
- row's real motion without the per-frame re-centering that makes a pet visibly
- slide. Each slot is cleaned independently so detached effects, floors,
- dividers, and neighbour slivers do not become "frames".
+ Equal-width columns keep every frame in one shared coordinate frame so
+ :func:`normalize_cells` preserves the row's real motion without sliding.
"""
- h = strip.height
+ w, h = strip.size
frames = []
- for left, right in _slot_bounds(strip.width, frame_count):
- slot = _drop_side_bleed(_isolate_slot_subject(strip.crop((left, 0, right, h))))
- if require_padding and not _has_slot_padding(slot):
+ for i in range(frame_count):
+ slot = _clean_slot(strip.crop((round(i * w / frame_count), 0, round((i + 1) * w / frame_count), h)))
+ bbox = slot.getbbox()
+ if require_padding and (bbox is None or not _has_margin(slot.size, bbox, 0.025, 0.02)):
return None
frames.append(slot)
return frames
-def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[int, int]]:
- """Contiguous column spans whose alpha mass exceeds *threshold*.
-
- A column-projection of the alpha mask: empty (background) columns separate
- one pose from the next, so the runs ARE the candidate frames.
- """
- runs: list[tuple[int, int]] = []
+def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[tuple[int, int], int]]:
+ """``[((left, right), mass)]`` column spans whose alpha exceeds *threshold* (candidate frames)."""
+ runs: list[tuple[tuple[int, int], int]] = []
start: int | None = None
for x, v in enumerate(list(profile) + [0]):
if v > threshold:
if start is None:
start = x
elif start is not None:
- runs.append((start, x))
+ runs.append(((start, x), sum(profile[start:x])))
start = None
return runs
@@ -727,55 +579,46 @@ def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[int,
def _frame_x_ranges(strip, frame_count: int) -> list[tuple[int, int]] | None:
"""Per-frame ``(left, right)`` column ranges from the row's empty gutters.
- The standard sprite-sheet slice — once poses are separated by real gaps
- (which generation now enforces), splitting is just "find the empty columns":
-
- * spans == frames → one span per frame.
- * spans > frames → merge across the smallest gaps. A detached halo/ear sits
- a tiny gap from its body, while the inter-pose gutter is the big gap that
- survives — so over-segmentation (and any over-eager gutter sever) repairs
- itself by collapsing only the small internal gaps.
- * spans < frames → poses are touching; not separable by gutters (the caller
- raises for ``components`` or falls back to even slots for ``auto``).
-
- Ranges span content only; the caller crops full cell height, so tall ears /
- halos are never cut.
+ spans == frames → one per frame; spans > frames → merge across the smallest
+ gaps (a detached halo sits a tiny gap from its body, the inter-pose gutter is
+ the big gap that survives); spans < frames → ``None`` (poses touching).
+ Ranges span X only; the caller crops full height so tall ears/halos survive.
"""
- profile = _column_profile(strip)
- runs = _content_runs(profile)
+ runs = _content_runs(_column_profile(strip))
if not runs:
return None
- # Drop trivial specks so stray noise never counts as a pose.
- masses = [sum(profile[l:r]) for l, r in runs]
- floor = max(masses) * 0.02
- runs = [run for run, m in zip(runs, masses) if m >= floor]
- if len(runs) < frame_count:
+ floor = max(m for _run, m in runs) * 0.02
+ groups = [[l, r] for (l, r), m in runs if m >= floor]
+ if len(groups) < frame_count:
return None
- groups = [[l, r] for l, r in runs]
while len(groups) > frame_count:
gi = min(range(len(groups) - 1), key=lambda i: groups[i + 1][0] - groups[i][1])
groups[gi][1] = groups[gi + 1][1]
del groups[gi + 1]
- return [(l, r) for l, r in groups]
+ return [tuple(g) for g in groups]
-def _significant_subject_boxes(image) -> list[tuple[int, int, int, int]]:
+def _significant_subject_boxes(image, *, min_mass: int = 32) -> list[tuple[int, int, int, int]]:
+ """Merged boxes of components carrying meaningful mass (≥12% of the largest)."""
comps = _component_boxes(image)
if not comps:
return []
max_mass = max(mass for _box, mass in comps)
- return _merge_related_boxes([box for box, mass in comps if mass >= max(32, max_mass * 0.12)])
+ return _merge_related_boxes([box for box, mass in comps if mass >= max(min_mass, max_mass * 0.12)])
+
+
+def _is_multi_pose_outlier(width: int, height: int, med_w: int, med_h: int) -> bool:
+ """A frame several times wider than the median but not proportionally taller."""
+ return width > max(med_w * 3.0, med_w + 96) and height <= med_h * 1.6
def _validate_extracted_frames(frames: list, frame_count: int) -> None:
"""Reject rows where one "frame" is really multiple poses.
- A bad provider roll can collapse a strip into tiny repeated poses. If we let
- that through, normalization sees a huge motion envelope and shrinks the
- entire pet to postage-stamp size. Catch the row here so hatch can regenerate
- it instead of saving a technically non-empty but visually broken atlas.
+ A collapsed strip of tiny repeated poses would make normalization shrink the
+ whole pet to postage-stamp size; catching it here lets hatch regenerate.
"""
if len(frames) != frame_count:
raise ValueError(f"expected {frame_count} frames, got {len(frames)}")
@@ -785,25 +628,17 @@ def _validate_extracted_frames(frames: list, frame_count: int) -> None:
bbox = frame.getbbox()
if bbox is None:
raise ValueError(f"frame {i} is empty")
- subjects = _significant_subject_boxes(frame)
- if len(subjects) >= 3:
+ if len(_significant_subject_boxes(frame)) >= 3:
raise ValueError(f"frame {i} contains multiple separated subjects")
boxes.append(bbox)
if frame_count <= 1:
return
- widths = sorted(b[2] - b[0] for b in boxes)
- heights = sorted(b[3] - b[1] for b in boxes)
- med_w = max(1, widths[len(widths) // 2])
- med_h = max(1, heights[len(heights) // 2])
+ med_w = max(1, _median(b[2] - b[0] for b in boxes))
+ med_h = max(1, _median(b[3] - b[1] for b in boxes))
for i, (left, top, right, bottom) in enumerate(boxes):
- width = right - left
- height = bottom - top
- # A legitimate wing/arm can be wider than the median pose. A frame that is
- # several times wider while not proportionally taller is usually multiple
- # mini-poses packed into one accepted frame.
- if width > max(med_w * 3.0, med_w + 96) and height <= med_h * 1.6:
+ if _is_multi_pose_outlier(right - left, bottom - top, med_w, med_h):
raise ValueError(f"frame {i} is a multi-pose width outlier")
@@ -817,45 +652,21 @@ def extract_strip_frames(
) -> list:
"""Turn one generated row strip into *frame_count* frames.
- The background is keyed out, then strict extraction treats the requested
- frame count as the source of truth: slice known equal slots, isolate the real
- subject in each slot, and require empty padding on X and Y. Empty chroma
- gutters are only a lenient salvage fallback.
-
- Each frame is cropped at full cell height so tall ears / halos are never
- clipped; detached effects and neighbour slivers are dropped per slot. When a
- pose does not have required space around it, ``components`` raises and
- ``auto`` falls back to best-effort slicing.
-
- *fit* (default) fits+centers each frame into a 192x208 cell — the standalone
- contract for callers that don't normalize. Hatching passes ``fit=False`` to
- keep raw, coordinate-aligned columns for :func:`normalize_cells`, which lays
- one shared scale + baseline across the whole pet (no slide, no size pulse).
+ Keys out the background, then treats the frame count as source of truth:
+ isolate padded subjects (component pass, then equal slots). When that fails,
+ ``components`` raises and ``auto`` falls back to lenient salvage (gutters →
+ severed gutters → raw slots). *fit* centers each frame into a 192x208 cell;
+ hatching passes ``fit=False`` so :func:`normalize_cells` can register the
+ whole pet with one shared scale + baseline.
"""
- from PIL import Image
-
- if isinstance(strip, (str, Path)):
- with Image.open(strip) as opened:
- strip = opened.convert("RGBA")
- else:
- strip = strip.convert("RGBA")
+ strip = remove_background(_load_rgba(strip), chroma_key=chroma_key)
- strip = remove_background(strip, chroma_key=chroma_key)
-
- # Strict path: count actual non-background subjects first. This handles both
- # the intended one-row strip and model-cheated 2D grids without ever stacking
- # two visual rows into one frame.
frames = _component_crops(strip, frame_count, require_padding=True)
if frames is None:
frames = _slot_crops(strip, frame_count, require_padding=True)
if frames is None:
if method == "components":
raise ValueError(f"could not segment {frame_count} padded sprites from strip")
-
- # Lenient salvage for the final attempt: prefer real gutters when they
- # exist, then sever expected boundaries, then fall back to raw slots. Still
- # try object extraction first, just without edge-padding enforcement, so
- # cached/borderline model rolls can be inspected without stacking a 2D grid.
frames = _component_crops(strip, frame_count, require_padding=False)
if frames is None:
source = strip
@@ -870,7 +681,7 @@ def extract_strip_frames(
h = source.height
pad = max(2, min(16, round((source.width / max(1, frame_count)) * 0.04)))
frames = [
- _drop_side_bleed(_isolate_slot_subject(source.crop((max(0, left - pad), 0, min(source.width, right + pad), h))))
+ _clean_slot(source.crop((max(0, left - pad), 0, min(source.width, right + pad), h)))
for left, right in ranges
]
_validate_extracted_frames(frames, frame_count)
@@ -878,110 +689,76 @@ def extract_strip_frames(
def _column_profile(image) -> list[int]:
- """Per-column alpha mass — collapse the frame to a 1px-tall strip (fast in C)."""
+ """Per-column alpha mass — collapse to a 1px-tall strip (fast in C)."""
from PIL import Image
return list(image.getchannel("A").resize((image.width, 1), Image.BILINEAR).getdata())
def _best_shift(ref: list[int], prof: list[int], window: int) -> int:
- """Integer dx that best aligns *prof* onto *ref* by cross-correlation.
+ """Integer dx that best aligns *prof* onto *ref* (1-D cross-correlation).
- This is 1-D phase correlation: the body is the dominant mass in the column
- profile, so the peak overlap locks onto the body and a flipping arm/cape (a
- small secondary bump) doesn't move the match. Proven on the jitter case to
- cut body drift from ~9px to ~1px where a centroid/bbox anchor cannot.
+ The body dominates the column profile, so the peak locks onto the body and a
+ flipping arm/cape barely moves the match (~9px drift → ~1px).
"""
n = len(ref)
- best_score: float | None = None
- best = 0
- for d in range(-window, window + 1):
- score = 0
- for x in range(max(0, d), min(n, n + d)):
- score += ref[x] * prof[x - d]
- if best_score is None or score > best_score:
- best_score = score
- best = d
- return best
+
+ def score(d: int) -> int:
+ return sum(ref[x] * prof[x - d] for x in range(max(0, d), min(n, n + d)))
+
+ return max(range(-window, window + 1), key=score) # ties → smallest dx, as before
def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_PAD) -> dict[str, list]:
"""Register every frame into a 192x208 cell — the deterministic anti-jitter math.
- A per-frame "crop→scale→center" pipeline jitters because a moving limb/cape
- shifts the bbox (or even the centroid) and a per-frame scale pulses the size.
- The rigorous fix, matching image-registration practice (phase correlation)
- and AI-sprite pipelines (perfectpixel-studio / sprite-gen):
-
- 1. **Cross-correlate** each frame's column profile against the per-state
- *median* profile to find the integer shift that locks the **body** in
- place — robust to limbs/cape because the body dominates the profile.
- 2. **Union-crop** through one shared state window, then scale every state by a
- single global factor keyed to its median pose height, so the character is
- the same on-screen size in every row while a jump's lift still fits.
+ Per-frame crop→scale→center jitters (bbox shifts with a limb, per-frame scale
+ pulses). Instead: cross-correlate each frame's column profile against the
+ state's median profile to lock the body, union-crop through one shared state
+ window, then scale every state by a single global factor keyed to its median
+ pose height so the character is the same size in every row.
"""
from PIL import Image
- blank = lambda: Image.new("RGBA", (CELL_WIDTH, CELL_HEIGHT), (0, 0, 0, 0))
- med = lambda vs: sorted(vs)[len(vs) // 2] # robust center; ignores a limb/cape outlier
-
out: dict[str, list] = {}
prepared: dict[str, tuple[list, tuple[int, int, int, int], tuple[int, int]]] = {}
- # Fill the cell — real petdex pets sit ~pad from the edges; the K cap below
- # keeps a tall pose (a jump's lift) from clipping.
target_w = CELL_WIDTH - pad
target_h = CELL_HEIGHT - pad
for state, frames in frames_by_state.items():
rgba = [f.convert("RGBA") for f in frames]
if not any(f.getbbox() for f in rgba):
- out[state] = [blank() for _ in frames]
+ out[state] = [_blank() for _ in frames]
continue
# Pad every frame to a common canvas so column profiles are comparable.
w0 = max(f.width for f in rgba)
h0 = max(f.height for f in rgba)
- canvas = []
- for f in rgba:
- if f.size != (w0, h0):
- c = Image.new("RGBA", (w0, h0), (0, 0, 0, 0))
- c.alpha_composite(f, (0, 0))
- f = c
- canvas.append(f)
-
- # Register horizontally: shift each frame to lock the body (xcorr).
+ canvas = [f if f.size == (w0, h0) else _place(f, (w0, h0)) for f in rgba]
+
profiles = [_column_profile(f) for f in canvas]
- ref = [sorted(p[x] for p in profiles)[len(profiles) // 2] for x in range(w0)]
+ ref = [_median(p[x] for p in profiles) for x in range(w0)]
window = max(8, w0 // 5)
margin = window
- aligned = []
- for f, prof in zip(canvas, profiles):
- shifted = Image.new("RGBA", (w0 + 2 * margin, h0), (0, 0, 0, 0))
- shifted.alpha_composite(f, (margin + _best_shift(ref, prof, window), 0))
- aligned.append(shifted)
-
- # Shared window over the registered set; scale is resolved against a
- # common apparent-character target below.
+ aligned = [
+ _place(f, (w0 + 2 * margin, h0), (margin + _best_shift(ref, prof, window), 0))
+ for f, prof in zip(canvas, profiles)
+ ]
+
boxes = [b for b in (a.getbbox() for a in aligned) if b]
- left = min(b[0] for b in boxes)
- top = min(b[1] for b in boxes)
- right = max(b[2] for b in boxes)
- bottom = max(b[3] for b in boxes)
prepared[state] = (
aligned,
- (left, top, right, bottom),
- (med([b[2] - b[0] for b in boxes]), med([b[3] - b[1] for b in boxes])),
+ (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)),
+ (_median(b[2] - b[0] for b in boxes), _median(b[3] - b[1] for b in boxes)),
)
if not prepared:
return out
- # Uniform apparent size: scale each state by K / pose_h, so a row the model
- # drew small renders as big as one it drew large. K is the one global cap that
- # keeps the tallest/widest motion envelope (a jump's lift) inside the cell —
- # for a still row union ≈ pose so its term ≈ target_h (full fill).
+ # K is the one global cap keeping the tallest/widest motion envelope (a
+ # jump's lift) inside the cell; a still row's union ≈ pose so it fills fully.
K = target_h
- for (_aligned, (left, top, right, bottom), (_pose_w, pose_h)) in prepared.values():
+ for _aligned, (left, top, right, bottom), (_pose_w, pose_h) in prepared.values():
uw, uh = right - left, bottom - top
K = min(K, target_h * pose_h / max(1, uh), target_w * pose_h / max(1, uw))
@@ -995,11 +772,8 @@ def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_P
for a in aligned:
crop = a.crop((left, top, right, bottom))
if crop.size != (sw, sh):
- # NEAREST keeps the pixel-art edges crisp; LANCZOS blurred them.
- crop = crop.resize((sw, sh), Image.Resampling.NEAREST)
- cell = blank()
- cell.alpha_composite(crop, (px, py))
- cells.append(cell)
+ crop = crop.resize((sw, sh), Image.Resampling.NEAREST) # keep pixel edges crisp
+ cells.append(_place(crop, (CELL_WIDTH, CELL_HEIGHT), (px, py)))
out[state] = cells
return out
@@ -1008,18 +782,12 @@ def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_P
def single_frame(image, *, fit: bool = True):
- """One frame from a standalone image (e.g. the base look).
+ """One frame from a standalone image (idle fallback so a pet always renders).
- Used as an idle fallback so a pet always renders even if the idle row
- generation failed. *fit* yields a finished 192x208 cell; ``fit=False`` yields
- the raw keyed sprite for :func:`normalize_cells` to place with the rest.
+ *fit* yields a finished cell; ``fit=False`` the raw keyed sprite for
+ :func:`normalize_cells`.
"""
- from PIL import Image
-
- if isinstance(image, (str, Path)):
- with Image.open(image) as opened:
- image = opened.convert("RGBA")
- keyed = remove_background(image)
+ keyed = remove_background(_load_rgba(image))
return _fit_to_cell(keyed) if fit else _drop_side_bleed(keyed)
@@ -1036,12 +804,9 @@ def _clear_transparent_rgb(image):
def mirror_frames(frames: list) -> list:
- """Horizontally flip each frame *in place* (RGBA-safe).
+ """Flip each frame horizontally (per-frame, so order/timing is preserved).
- Used to derive ``running-left`` from an approved ``running-right`` row. The
- flip is per-frame so the leftward loop preserves the rightward loop's frame
- order and timing — this is NOT a whole-strip reverse (which would play the
- animation backwards), matching the petdex/Codex mirror rule.
+ Derives ``running-left`` from ``running-right``; NOT a strip reverse.
"""
from PIL import Image
@@ -1050,14 +815,8 @@ def mirror_frames(frames: list) -> list:
def compose_atlas(frames_by_state: dict[str, list]):
- """Pack per-state frame lists into the Hermes atlas (RGBA, residue-cleared).
-
- Missing/short states leave their trailing cells transparent; extra frames
- beyond a state's spec are dropped.
- """
- from PIL import Image
-
- atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0))
+ """Pack per-state frame lists into the atlas; short states leave trailing cells transparent."""
+ atlas = _blank((ATLAS_WIDTH, ATLAS_HEIGHT))
for state, row, count in ROW_SPECS:
frames = frames_by_state.get(state) or []
for col, frame in enumerate(frames[:count]):
@@ -1068,46 +827,42 @@ def compose_atlas(frames_by_state: dict[str, list]):
return _clear_transparent_rgb(atlas)
-def atlas_to_webp_bytes(atlas) -> bytes:
- """Encode an atlas image to lossless WebP bytes (the on-disk pet format)."""
- buf = io.BytesIO()
- atlas.save(buf, format="WEBP", lossless=True, quality=100, method=6, exact=True)
- return buf.getvalue()
-
-
def validate_atlas(atlas) -> dict:
"""Check geometry, per-cell occupancy, and transparency invariants.
- Returns ``{ok, width, height, errors, warnings, filled_states}``. Errors are
- blockers (wrong size, empty used cell, opaque/dirty transparency); warnings
- are soft (a whole state row blank — generation likely dropped a row).
+ Returns ``{ok, width, height, errors, warnings, filled_states}``; errors are
+ blockers, warnings soft (a whole state row blank).
"""
- from PIL import Image
-
- if isinstance(atlas, (str, Path)):
- with Image.open(atlas) as opened:
- atlas = opened.convert("RGBA")
+ atlas = _load_rgba(atlas)
+ if atlas.size != (ATLAS_WIDTH, ATLAS_HEIGHT):
+ errors: list[str] = [f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}"]
+ warnings: list[str] = []
+ filled_states: list[str] = []
else:
- atlas = atlas.convert("RGBA")
+ errors, warnings, filled_states = _check_atlas_cells(atlas)
+ return {
+ "ok": not errors,
+ "width": atlas.width,
+ "height": atlas.height,
+ "errors": errors,
+ "warnings": warnings,
+ "filled_states": filled_states,
+ }
+
+def _check_atlas_cells(atlas) -> tuple[list[str], list[str], list[str]]:
+ """Occupancy/collapse/residue checks for a correctly-sized atlas → ``(errors, warnings, filled_states)``."""
errors: list[str] = []
warnings: list[str] = []
-
- if atlas.size != (ATLAS_WIDTH, ATLAS_HEIGHT):
- errors.append(f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}")
- return {"ok": False, "width": atlas.width, "height": atlas.height, "errors": errors, "warnings": warnings, "filled_states": []}
-
filled_states: list[str] = []
cell_boxes_by_state: dict[str, list[tuple[int, int, int, int]]] = {}
for state, row, count in ROW_SPECS:
row_pixels = 0
boxes: list[tuple[int, int, int, int]] = []
for col in range(count):
- left = col * CELL_WIDTH
- top = row * CELL_HEIGHT
+ left, top = col * CELL_WIDTH, row * CELL_HEIGHT
cell = atlas.crop((left, top, left + CELL_WIDTH, top + CELL_HEIGHT))
- nonblank = sum(cell.getchannel("A").histogram()[1:])
- row_pixels += nonblank
+ row_pixels += sum(cell.getchannel("A").histogram()[1:])
bbox = cell.getbbox()
if bbox is not None:
boxes.append(bbox)
@@ -1120,64 +875,35 @@ def validate_atlas(atlas) -> dict:
if not filled_states:
errors.append("atlas is empty — no state produced any frames")
- # A visually valid pet must occupy the cell. A single bad row can otherwise
- # poison global normalization and shrink every state to a tiny postage stamp
- # while still passing the old "non-empty cells" check.
- all_widths = sorted(
- right - left
- for boxes in cell_boxes_by_state.values()
- for left, _top, right, _bottom in boxes
- )
- all_heights = sorted(
- bottom - top
- for boxes in cell_boxes_by_state.values()
- for _left, top, _right, bottom in boxes
- )
- global_med_w = 0
- global_med_h = 0
- if all_widths and all_heights:
- global_med_w = all_widths[len(all_widths) // 2]
- median_h = all_heights[len(all_heights) // 2]
- global_med_h = median_h
- min_h = max(56, round(CELL_HEIGHT * 0.28))
- if median_h < min_h:
- errors.append(f"atlas sprites are too small after normalization (median frame height {median_h}px)")
+ # A valid pet must occupy the cell: one bad row can poison global
+ # normalization and shrink every state while still passing "non-empty".
+ all_boxes = [b for boxes in cell_boxes_by_state.values() for b in boxes]
+ global_med_w = global_med_h = 0
+ if all_boxes:
+ global_med_w = _median(r - l for l, _t, r, _b in all_boxes)
+ global_med_h = _median(b - t for _l, t, _r, b in all_boxes)
+ if global_med_h < max(56, round(CELL_HEIGHT * 0.28)):
+ errors.append(f"atlas sprites are too small after normalization (median frame height {global_med_h}px)")
for state, boxes in cell_boxes_by_state.items():
if len(boxes) <= 1:
continue
- widths = sorted(right - left for left, _top, right, _bottom in boxes)
- heights = sorted(bottom - top for _left, top, _right, bottom in boxes)
- med_w = max(1, widths[len(widths) // 2])
- med_h = max(1, heights[len(heights) // 2])
- max_w = widths[-1]
- max_h = heights[-1]
- if max_w > max(med_w * 3.0, med_w + 96) and max_h <= med_h * 1.6:
+ widths = [right - left for left, _top, right, _bottom in boxes]
+ heights = [bottom - top for _left, top, _right, bottom in boxes]
+ med_w, med_h = max(1, _median(widths)), max(1, _median(heights))
+ if _is_multi_pose_outlier(max(widths), max(heights), med_w, med_h):
errors.append(f"state '{state}' contains a multi-pose frame outlier")
- # Per-state collapse guard: one malformed row (tiny slivers / chopped
- # fragments) should not pass because other rows are healthy.
- if global_med_w and global_med_h:
- min_state_w = max(32, round(global_med_w * 0.42))
- min_state_h = max(40, round(global_med_h * 0.50))
- if med_w < min_state_w or med_h < min_state_h:
- errors.append(
- f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)"
- )
+ # Per-state collapse guard: one malformed row must not pass on the
+ # strength of the healthy ones.
+ if (global_med_w and global_med_h) and (
+ med_w < max(32, round(global_med_w * 0.42)) or med_h < max(40, round(global_med_h * 0.50))
+ ):
+ errors.append(
+ f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)"
+ )
- # Transparent pixels must carry zero RGB (no halo residue).
data = atlas.tobytes()
- residue = 0
- for i in range(0, len(data), 4):
- if data[i + 3] == 0 and (data[i] or data[i + 1] or data[i + 2]):
- residue += 1
+ residue = sum(1 for i in range(0, len(data), 4) if data[i + 3] == 0 and (data[i] or data[i + 1] or data[i + 2]))
if residue:
errors.append(f"{residue} transparent pixels retain RGB residue")
-
- return {
- "ok": not errors,
- "width": atlas.width,
- "height": atlas.height,
- "errors": errors,
- "warnings": warnings,
- "filled_states": filled_states,
- }
+ return errors, warnings, filled_states
diff --git a/agent/pet/generate/imagegen.py b/agent/pet/generate/imagegen.py
index 4f5000fd703..65c4630e8ea 100644
--- a/agent/pet/generate/imagegen.py
+++ b/agent/pet/generate/imagegen.py
@@ -37,17 +37,6 @@ _PROVIDER_LABELS: dict[str, str] = {
}
-def _forced_provider_from_env() -> str | None:
- """Optional QA override to force a pet-gen backend.
-
- `HERMES_PET_IMAGE_PROVIDER=<name>` (e.g. `openrouter`) bypasses the normal
- active/default provider resolution for pet generation only. Unknown values are
- ignored so existing users are unaffected.
- """
- forced = os.environ.get("HERMES_PET_IMAGE_PROVIDER", "").strip().lower()
- return forced if forced in _REF_CAPABLE else None
-
-
class GenerationError(RuntimeError):
"""Raised on any image-generation failure (no provider, API error, IO)."""
@@ -70,6 +59,14 @@ def _discover() -> None:
logger.debug("image-gen plugin discovery failed: %s", exc)
+def _available(name: str):
+ """The registered provider *name* if it exists and has credentials, else ``None``."""
+ from agent.image_gen_registry import get_provider
+
+ provider = get_provider(name)
+ return provider if provider is not None and provider.is_available() else None
+
+
def resolve_provider(*, require_references: bool = True, prefer: str | None = None) -> SpriteProvider:
"""Pick the image provider to use for sprite work.
@@ -80,25 +77,17 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = No
prompt-only base drafts).
"""
_discover()
- from agent.image_gen_registry import get_active_provider, get_provider
-
- # QA override: force one provider for pet-gen iteration regardless of the
- # globally active image_gen backend.
- forced = _forced_provider_from_env()
- if forced:
- chosen = get_provider(forced)
- if chosen is not None and chosen.is_available():
- return SpriteProvider(name=forced, provider=chosen, supports_references=True)
-
- # An explicit user pick wins when it's reference-capable and has credentials;
- # otherwise we ignore it and fall through to the normal resolution.
- if prefer:
- chosen = get_provider(prefer)
- if prefer in _REF_CAPABLE and chosen is not None and chosen.is_available():
- return SpriteProvider(name=prefer, provider=chosen, supports_references=True)
+ from agent.image_gen_registry import get_active_provider
+
+ # QA override: ``HERMES_PET_IMAGE_PROVIDER=<name>`` forces one ref-capable backend
+ # for pet-gen only (unknown values ignored). Then an explicit user pick (desktop
+ # picker) wins when ref-capable and configured; otherwise fall through.
+ forced = os.environ.get("HERMES_PET_IMAGE_PROVIDER", "").strip().lower()
+ for name in (forced, prefer):
+ if name in _REF_CAPABLE and (chosen := _available(name)) is not None:
+ return SpriteProvider(name=name, provider=chosen, supports_references=True)
# Configured / active provider first.
- active = None
try:
active = get_active_provider()
except Exception: # noqa: BLE001
@@ -110,8 +99,8 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = No
# Any available reference-capable provider.
for name in _REF_CAPABLE:
- provider = get_provider(name)
- if provider is not None and provider.is_available():
+ provider = _available(name)
+ if provider is not None:
return SpriteProvider(name=name, provider=provider, supports_references=True)
if not require_references and active is not None and active.is_available():
@@ -136,26 +125,15 @@ def list_sprite_providers() -> list[dict]:
yield an empty list.
"""
_discover()
- from agent.image_gen_registry import get_provider
-
try:
default_name = resolve_provider(require_references=True).name
except GenerationError:
default_name = ""
-
- out: list[dict] = []
- for name in _REF_CAPABLE:
- provider = get_provider(name)
- if provider is None or not provider.is_available():
- continue
- out.append(
- {
- "name": name,
- "label": _PROVIDER_LABELS.get(name, name),
- "default": name == default_name,
- }
- )
- return out
+ return [
+ {"name": name, "label": _PROVIDER_LABELS.get(name, name), "default": name == default_name}
+ for name in _REF_CAPABLE
+ if _available(name) is not None
+ ]
def _save_local(image_ref: str, *, prefix: str) -> Path:
diff --git a/agent/pet/generate/orchestrate.py b/agent/pet/generate/orchestrate.py
index 1b267a4de21..344cb9b8978 100644
--- a/agent/pet/generate/orchestrate.py
+++ b/agent/pet/generate/orchestrate.py
@@ -1,16 +1,12 @@
"""Pet generation orchestration — the base-draft → hatch flow.
-Two steps, mirroring the UX across every surface:
+1. :func:`generate_base_drafts` — a few cheap prompt-only "what should this pet
+ look like" variants; the user picks one (or retries).
+2. :func:`hatch_pet` — grounds one row strip per Hermes state on the chosen base,
+ slices frames, composes + validates the atlas, and writes it to the store.
-1. :func:`generate_base_drafts` — a handful of prompt-only "what should this pet
- look like" variants. Cheap; the user picks one (or retries for a fresh set).
-2. :func:`hatch_pet` — takes the chosen base and generates one grounded row
- strip per Hermes state, slices each into frames, composes the atlas, validates
- it, and writes the pet into the store.
-
-Splitting it this way bounds cost (4 cheap base calls per round; the ~6 row
-calls happen once, on the pet you actually keep) and gives each UI a natural
-preview/loading point.
+Splitting bounds cost (4 cheap base calls per round; the ~8 row calls happen
+once, on the pet you keep) and gives each UI a natural preview/loading point.
"""
from __future__ import annotations
@@ -20,7 +16,7 @@ import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
-from typing import Callable
+from typing import Callable, Iterator
from agent.pet.generate import atlas, imagegen, prompts
from agent.pet.generate.imagegen import GenerationError, SpriteProvider
@@ -30,18 +26,30 @@ logger = logging.getLogger(__name__)
# (event, detail) — e.g. ("row", "idle"), ("compose", ""), ("save", "<slug>").
ProgressFn = Callable[[str, str], None]
-# Image generations are independent network calls, so we fan them out instead of
-# blocking on each in turn — a hatch is ~8 row calls that would otherwise run
-# back-to-back and routinely blow past the client's RPC timeout. Capped so we
-# don't hammer the provider's rate limit (one cold call can still be slow).
+# Generations are independent network calls, fanned out so a hatch (~8 rows)
+# doesn't blow the client's RPC timeout; capped to respect provider rate limits.
_MAX_PARALLEL_GENERATIONS = 4
-# How many times to (re)generate a single row before accepting a best-effort
-# slice. Early attempts demand clean per-pose gutters; the last is lenient so a
-# stubborn row still yields frames instead of dropping out entirely.
+# Row (re)generation attempts: early ones demand clean per-pose gutters, the
+# last is lenient so a stubborn row still yields frames instead of dropping out.
_ROW_GEN_ATTEMPTS = 3
_MIN_FILLED_STATES = 6
_REQUIRED_STATES = frozenset({"idle", "running-right", "waving"})
+# (substrings, friendly message), first match wins. Moderation is the big one:
+# image models refuse trademarked characters / real people as an opaque 400.
+_IMAGE_ERROR_HINTS: tuple[tuple[tuple[str, ...], str], ...] = (
+ (
+ ("moderation_blocked", "safety system", "content policy", "content_policy"),
+ "The image provider blocked this prompt — its safety filter rejects "
+ "trademarked characters and real people. Try an original description.",
+ ),
+ (
+ ("api key", "unauthorized", "401", "auth"),
+ "The image provider rejected the request — check your API key in Settings → Providers.",
+ ),
+ (("rate limit", "429"), "The image provider is rate-limiting — wait a moment and try again."),
+)
+
@dataclass(frozen=True)
class HatchResult:
@@ -54,47 +62,60 @@ class HatchResult:
validation: dict
+def _unlink_quietly(path: Path) -> None:
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
def _harden_transparency(path: Path) -> Path:
"""Key out any solid backdrop the provider painted; save as an RGBA PNG.
- ``background=transparent`` is requested on every call, but image models honor
- it inconsistently — some still paint a flat (often near-white) backdrop. We
- run the same chroma-key pass the row extractor uses so every base draft the
- user picks between (and the reference the rows are grounded on) is a clean
- cutout. Best-effort: a decode failure leaves the original untouched.
+ ``background=transparent`` is requested but honored inconsistently, so run the
+ row extractor's chroma-key pass on every base draft. Best-effort: a decode
+ failure leaves the original untouched.
"""
from PIL import Image
try:
with Image.open(path) as opened:
keyed = atlas.remove_background(opened.convert("RGBA"))
- # Zero the RGB of any leftover semi-transparent edge pixels so a keyed
- # draft has no colored halo when composited on the dark UI.
- keyed = atlas._clear_transparent_rgb(keyed)
- # PNG inputs are hardened in place, including mixed-case suffixes like
- # .PNG. with_suffix(".png") would name a different Path string that still
- # resolves to the same file on case-insensitive filesystems (macOS APFS,
- # Windows), and unlinking path after save would delete the hardened output.
- if path.suffix.lower() == ".png":
- out = path
- else:
- out = path.with_suffix(".png")
+ keyed = atlas._clear_transparent_rgb(keyed) # no colored halo on the dark UI
+ # PNGs (any case) are hardened in place: with_suffix(".png") on ".PNG" would
+ # name the same file on case-insensitive filesystems and the unlink below
+ # would delete the hardened output.
+ out = path if path.suffix.lower() == ".png" else path.with_suffix(".png")
keyed.save(out, format="PNG")
if out != path:
- # The hardened PNG stands in for the draft. When the provider handed
- # back a non-PNG file (webp, jpg, gif), out is a different path, so
- # remove the original instead of leaving it behind in cache/images
- # (nothing prunes that directory outside the gateway loop).
- try:
- path.unlink(missing_ok=True)
- except OSError:
- pass
+ # Nothing prunes cache/images outside the gateway loop: drop the
+ # non-PNG original the hardened PNG replaces.
+ _unlink_quietly(path)
return out
except Exception as exc: # noqa: BLE001 - cosmetic; fall back to the raw image
logger.debug("base draft transparency hardening failed for %s: %s", path, exc)
return path
+def _run_parallel(fn, items, *, cancelled, on_cancel_log: str) -> Iterator:
+ """Fan *fn* over *items* in a pool, yielding results in completion order.
+
+ ``as_completed`` runs on the caller's (request) thread, so callbacks fired
+ from the results inherit the request's bound transport, unlike the workers.
+ Once *cancelled* trips, queued work is cancelled and in-flight results dropped.
+ """
+ workers = max(1, min(len(items), _MAX_PARALLEL_GENERATIONS))
+ with ThreadPoolExecutor(max_workers=workers) as pool:
+ futures = [pool.submit(fn, item) for item in items]
+ for fut in as_completed(futures):
+ if cancelled():
+ logger.info(on_cancel_log)
+ for pending in futures:
+ pending.cancel()
+ break
+ yield fut.result()
+
+
def generate_base_drafts(
concept: str,
*,
@@ -107,31 +128,23 @@ def generate_base_drafts(
) -> list[Path]:
"""Generate *n* candidate base looks for *concept*; returns image paths.
- Each draft is hardened to a transparent cutout (see :func:`_harden_transparency`).
- Drafts are generated concurrently and *on_draft(index, path)* fires as each
- one finishes (not at the end) so callers can stream previews to the UI
- instead of leaving it blank until the whole batch is done.
-
- *is_cancelled*, when supplied, is polled cooperatively: a draft that hasn't
- started yet is skipped, and once it trips we stop staging/streaming further
- drafts and cancel any queued work (already-in-flight provider calls can't be
- hard-killed, but their results are dropped).
+ Drafts run concurrently and are hardened to transparent cutouts;
+ *on_draft(index, path)* fires as each finishes so UIs can stream previews.
+ *is_cancelled* is polled cooperatively (unstarted drafts skipped, queued work
+ cancelled, in-flight results dropped).
"""
- # A user reference image (e.g. their own pet) grounds every draft, so it
- # needs a reference-capable provider — same requirement as the row passes.
+ # A user reference image grounds every draft, so it needs a reference-capable provider.
refs = reference_images or None
sprite = provider or imagegen.resolve_provider(require_references=bool(refs))
cancelled = is_cancelled or (lambda: False)
- # Each draft is its own one-shot generation, run concurrently so the user
- # waits for one image, not N. A single draft failing must not sink the set.
- # Each gets a distinct variation nudge so the options aren't near-duplicates.
logger.info("pet generate: drafting %d base looks for %r (style=%s)", n, concept, style)
def _one(index: int) -> tuple[int, Path | None, str | None]:
if cancelled():
return index, None, None
t0 = time.monotonic()
+ # Distinct variation nudge per draft so the options aren't near-duplicates.
variation = prompts.BASE_VARIATIONS[index % len(prompts.BASE_VARIATIONS)]
prompt = prompts.build_base_prompt(concept, style=style, variation=variation)
try:
@@ -145,68 +158,40 @@ def generate_base_drafts(
logger.info("pet generate: draft %d ready in %.1fs", index, time.monotonic() - t0)
return index, _harden_transparency(out[0]), None
- workers = max(1, min(n, _MAX_PARALLEL_GENERATIONS))
results: dict[int, Path] = {}
errors: list[str] = []
- with ThreadPoolExecutor(max_workers=workers) as pool:
- futures = [pool.submit(_one, i) for i in range(n)]
- # as_completed runs in *this* (the caller's) thread, so on_draft — and any
- # gateway event it emits — inherits the request's bound transport, unlike
- # the worker threads above.
- for fut in as_completed(futures):
- if cancelled():
- logger.info("pet generate: cancelled — dropping remaining drafts")
- for pending in futures:
- pending.cancel()
- break
- index, path, err = fut.result()
- if path is None:
- if err:
- errors.append(err)
- continue
- results[index] = path
- if on_draft is not None:
- try:
- on_draft(index, path)
- except Exception as exc: # noqa: BLE001 - progress is best-effort
- logger.debug("on_draft callback failed: %s", exc)
+ for index, path, err in _run_parallel(
+ _one, range(n), cancelled=cancelled, on_cancel_log="pet generate: cancelled — dropping remaining drafts"
+ ):
+ if path is None:
+ if err:
+ errors.append(err)
+ continue
+ results[index] = path
+ if on_draft is not None:
+ try:
+ on_draft(index, path)
+ except Exception as exc: # noqa: BLE001 - progress is best-effort
+ logger.debug("on_draft callback failed: %s", exc)
drafts = [results[i] for i in sorted(results)]
if not drafts and not cancelled():
- # Surface *why* — every draft failed for a reason (a content-policy refusal
- # on a name like "minion", a provider/auth error, …); the most common one
- # is the representative cause. Far more useful than "no usable drafts".
- raise GenerationError(_drafts_failed_reason(errors))
- return drafts
+ # Surface *why*: the most common failure reason is the representative cause.
+ if not errors:
+ raise GenerationError("image generation produced no usable drafts")
+ from collections import Counter
-
-def _drafts_failed_reason(errors: list[str]) -> str:
- """The representative reason a draft round produced nothing, humanized."""
- if not errors:
- return "image generation produced no usable drafts"
- from collections import Counter
-
- return _humanize_image_error(Counter(errors).most_common(1)[0][0])
+ raise GenerationError(_humanize_image_error(Counter(errors).most_common(1)[0][0]))
+ return drafts
def _humanize_image_error(error: str) -> str:
- """Turn a raw provider error into a friendly, actionable sentence.
-
- The big one is moderation: image models refuse trademarked characters and
- real people (e.g. "minion"), which reads as an opaque 400 otherwise.
- """
+ """Turn a raw provider error into a friendly, actionable sentence."""
low = error.lower()
- if any(s in low for s in ("moderation_blocked", "safety system", "content policy", "content_policy")):
- return (
- "The image provider blocked this prompt — its safety filter rejects "
- "trademarked characters and real people. Try an original description."
- )
- if any(s in low for s in ("api key", "unauthorized", "401", "auth")):
- return "The image provider rejected the request — check your API key in Settings → Providers."
- if "rate limit" in low or "429" in low:
- return "The image provider is rate-limiting — wait a moment and try again."
- # Otherwise the first line, trimmed of the noisy provider envelope.
- return error.splitlines()[0].strip()[:200]
+ for needles, message in _IMAGE_ERROR_HINTS:
+ if any(s in low for s in needles):
+ return message
+ return error.splitlines()[0].strip()[:200] # first line, sans provider envelope
def hatch_pet(
@@ -223,14 +208,10 @@ def hatch_pet(
) -> HatchResult:
"""Turn an approved base image into a full, installed Hermes pet.
- Generates a grounded row strip per state, extracts frames, composes +
- validates the atlas, and registers it. The idle row falls back to the base
- look so the pet always renders. Raises :class:`GenerationError` on failure.
-
- *is_cancelled*, when supplied, is polled cooperatively: rows that haven't
- started are skipped, queued rows are cancelled, and once every row is done we
- abort (raising :class:`GenerationError`) before composing/saving so a stopped
- hatch never writes a half-built pet.
+ Idle falls back to the base look so the pet always renders. Raises
+ :class:`GenerationError` on failure. *is_cancelled* is polled cooperatively
+ and, once tripped, aborts before composing/saving so a stopped hatch never
+ writes a half-built pet.
"""
base = Path(base_image)
if not base.is_file():
@@ -245,19 +226,15 @@ def hatch_pet(
total_rows = len(atlas.ROW_SPECS)
logger.info("pet hatch %r: generating %d animation rows", slug, total_rows)
- # Generate every state's row strip concurrently — they're independent
- # grounded calls, so the hatch waits for the slowest row, not their sum. A
- # single row failing is tolerated (idle is guaranteed below).
def _gen_row(spec: tuple[str, int, int]) -> tuple[str, list | None]:
state, _row, count = spec
if cancelled():
return state, None
t0 = time.monotonic()
last_exc: Exception | None = None
- # Self-healing: a model occasionally returns a row whose poses are touching
- # (no clean gutters), which slices badly. We retry such rolls; only the
- # final attempt falls back to lenient ``auto`` slicing so a stubborn row
- # still yields *something* rather than dropping the whole row.
+ # Self-healing: a roll whose poses touch (no gutters) slices badly, so
+ # ``components`` (raises on touching poses) drives regeneration and only
+ # the final attempt uses lenient ``auto`` slicing.
for attempt in range(_ROW_GEN_ATTEMPTS):
if cancelled():
return state, None
@@ -270,14 +247,10 @@ def hatch_pet(
reference_images=[base],
provider=sprite,
prefix=f"pet_row_{state}",
- # Wider canvas → each frame gets real horizontal room, so winged
- # poses keep a full, healthy size and still leave clean gutters.
+ # Wider canvas: each frame gets real horizontal room and clean gutters.
aspect_ratio="landscape",
)
- # ``components`` requires clean per-pose gutters (raises otherwise),
- # so a touching roll is rejected and regenerated; the last attempt
- # uses ``auto`` (equal-slot fallback, never raises). Raw (fit=False)
- # so normalize_cells registers the whole pet at once.
+ # fit=False keeps raw columns so normalize_cells registers the whole pet at once.
method = "components" if strict else "auto"
frames = atlas.extract_strip_frames(strips[0], count, method=method, fit=False)
logger.info(
@@ -292,51 +265,35 @@ def hatch_pet(
slug, state, attempt + 1, _ROW_GEN_ATTEMPTS, exc,
)
finally:
- # The strip is an intermediate. extract_strip_frames has already
- # decoded its frames into memory, so drop the row image after
- # every attempt (success or failure). Nothing prunes
- # cache/images outside the gateway housekeeping loop, so a CLI
- # or desktop hatch would otherwise leave each strip behind for
- # good and grow the cache without bound.
+ # Strips are intermediates already decoded into memory; nothing
+ # prunes cache/images outside the gateway loop, so drop them now.
for strip in strips:
- try:
- Path(strip).unlink(missing_ok=True)
- except OSError:
- pass
+ _unlink_quietly(Path(strip))
logger.warning(
"pet hatch %r: row %r gave up after %.1fs: %s",
slug, state, time.monotonic() - t0, last_exc,
)
return state, None
- # running-left is derived by mirroring running-right (guaranteed-consistent
- # and one fewer generation), so we don't generate it directly.
+ # running-left is mirrored from running-right (consistent, one fewer generation).
generated_specs = [spec for spec in atlas.ROW_SPECS if spec[0] != "running-left"]
-
- workers = max(1, min(len(generated_specs), _MAX_PARALLEL_GENERATIONS))
done = 0
- with ThreadPoolExecutor(max_workers=workers) as pool:
- futures = [pool.submit(_gen_row, spec) for spec in generated_specs]
- # as_completed runs on the caller (request) thread, so progress events
- # emitted here inherit the request transport — unlike the worker threads.
- for fut in as_completed(futures):
- if cancelled():
- logger.info("pet hatch %r: cancelled — dropping remaining rows", slug)
- for pending in futures:
- pending.cancel()
- break
- state, frames = fut.result()
- done += 1
- progress("row", f"{state}:{done}:{total_rows}")
- if frames:
- frames_by_state[state] = frames
+ for state, frames in _run_parallel(
+ _gen_row,
+ generated_specs,
+ cancelled=cancelled,
+ on_cancel_log=f"pet hatch {slug!r}: cancelled — dropping remaining rows",
+ ):
+ done += 1
+ progress("row", f"{state}:{done}:{total_rows}")
+ if frames:
+ frames_by_state[state] = frames
if cancelled():
raise GenerationError("hatch cancelled")
- # Derive running-left from the approved running-right row (per-frame mirror,
- # preserving order/timing). Missing running-right is rejected below; a pet
- # without its canonical walk cycle is a failed hatch, not a shippable mascot.
+ # Per-frame mirror preserves order/timing. A missing running-right is
+ # rejected below: a pet without its canonical walk cycle is a failed hatch.
right = frames_by_state.get("running-right")
if right:
done += 1
@@ -346,15 +303,13 @@ def hatch_pet(
else:
logger.warning("pet hatch %r: no running-right to mirror; left walk left empty", slug)
- # Idle is the resting state the renderer falls back to — guarantee it.
- if not frames_by_state.get("idle"):
+ if not frames_by_state.get("idle"): # the renderer's resting fallback — guarantee it
progress("row", "idle-fallback")
frames_by_state["idle"] = [atlas.single_frame(base, fit=False)]
progress("compose", "")
logger.info("pet hatch %r: composing atlas from %d states", slug, len(frames_by_state))
- # One shared scale + baseline across every state so the pet never slides or
- # pulses size between frames; compose just packs the normalized cells.
+ # One shared scale + baseline across states so the pet never slides or pulses.
sheet = atlas.compose_atlas(atlas.normalize_cells(frames_by_state))
validation = atlas.validate_atlas(sheet)
if not validation["ok"]:
diff --git a/agent/pet/manifest.py b/agent/pet/manifest.py
index 98a0e4a3f7e..9d23a28de6d 100644
--- a/agent/pet/manifest.py
+++ b/agent/pet/manifest.py
@@ -120,7 +120,7 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
"""
global _cache
- if not force and _cache is not None and time.monotonic() - _cache[0] < _MANIFEST_TTL:
+ if not force and _cache_is_warm():
return _cache[1]
try:
@@ -144,14 +144,8 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
if not isinstance(pets, list):
raise ManifestError("petdex manifest had no 'pets' array")
- entries: list[ManifestEntry] = []
- for raw in pets:
- if not isinstance(raw, dict):
- continue
- entry = ManifestEntry.from_dict(raw)
- if entry.slug and entry.spritesheet_url:
- entries.append(entry)
-
+ parsed = (ManifestEntry.from_dict(raw) for raw in pets if isinstance(raw, dict))
+ entries = [entry for entry in parsed if entry.slug and entry.spritesheet_url]
_cache = (time.monotonic(), entries)
return entries
diff --git a/agent/pet/render.py b/agent/pet/render.py
index 6e3ec74fd73..3eb958ff7a3 100644
--- a/agent/pet/render.py
+++ b/agent/pet/render.py
@@ -1,19 +1,11 @@
"""Decode a pet spritesheet and encode frames for a terminal.
-Shared by the base CLI (writes the escape bytes to its own stdout) and the
-TUI (``tui_gateway`` ships the encoded bytes to Ink, which writes them) so the
-decode + capability-detection + protocol-encoding logic exists exactly once.
-
-Supported output modes, in fidelity order:
-
-- ``kitty`` — the kitty graphics protocol (kitty, Ghostty, WezTerm).
-- ``iterm`` — iTerm2 inline images (iTerm2, WezTerm).
-- ``sixel`` — DEC sixel (xterm -ti vt340, foot, mlterm, WezTerm, …).
-- ``unicode`` — 24-bit half-block downscale; works in any truecolor terminal.
-
-Frame decoding requires Pillow (a core Hermes dependency). If Pillow or the
-spritesheet is unavailable the renderer degrades to ``unicode`` text or an
-empty string rather than raising.
+Shared by the base CLI (writes escape bytes to stdout) and the TUI (ships the
+encoded bytes to Ink) so decode + capability detection + protocol encoding
+exist once. Output modes, in fidelity order: ``kitty`` (kitty, Ghostty,
+WezTerm), ``iterm`` (iTerm2, WezTerm), ``sixel`` (xterm -ti vt340, foot,
+mlterm, …), ``unicode`` (24-bit half-blocks; any truecolor terminal). Missing
+Pillow or spritesheet degrades to an empty string rather than raising.
"""
from __future__ import annotations
@@ -41,78 +33,50 @@ logger = logging.getLogger(__name__)
RENDER_MODES = ("auto", "kitty", "iterm", "sixel", "unicode", "off")
-# ─────────────────────────────────────────────────────────────────────────
-# Terminal capability detection
-# ─────────────────────────────────────────────────────────────────────────
+# ───────────────────────── terminal capability detection ─────────────────────────
+
+
+def _is_wezterm() -> bool:
+ return os.environ.get("TERM_PROGRAM", "").lower() == "wezterm" or bool(os.environ.get("WEZTERM_PANE"))
+
def detect_terminal_graphics() -> str:
- """Best-effort detection of the richest graphics protocol available.
+ """Best-effort richest protocol from env vars only (never a DA1 query that could hang a pipe).
- Env-based (non-blocking — we never issue a DA1/terminal query that could
- hang a pipe). Returns one of ``kitty`` / ``iterm`` / ``sixel`` /
- ``unicode``. Conservative: unknown terminals get ``unicode``, which works
- anywhere with truecolor.
+ Returns ``kitty`` / ``iterm`` / ``sixel`` / ``unicode``; unknown terminals get
+ ``unicode``, which works anywhere with truecolor.
"""
term = os.environ.get("TERM", "").lower()
term_program = os.environ.get("TERM_PROGRAM", "").lower()
- # The VS Code / Cursor integrated terminal sets TERM_PROGRAM=vscode
- # authoritatively but does NOT scrub the terminal env vars it inherits when
- # launched from another emulator (ITERM_SESSION_ID, KITTY_WINDOW_ID, …).
- # Trusting those leaks emits an image protocol the embedded xterm.js can't
- # display — you get a blank frame. Inline images there are opt-in
- # (terminal.integrated.enableImages), so default to half-blocks, which
- # always render in its truecolor grid. Users who enabled images can pin
- # display.pet.render_mode explicitly.
+ # VS Code/Cursor set TERM_PROGRAM=vscode but don't scrub inherited
+ # ITERM_SESSION_ID/KITTY_WINDOW_ID; trusting those emits a protocol xterm.js
+ # can't show (blank frame). Inline images there are opt-in, so default to
+ # half-blocks; users who enabled them can pin display.pet.render_mode.
if term_program == "vscode":
return "unicode"
-
- # kitty graphics protocol
- if os.environ.get("KITTY_WINDOW_ID") or "kitty" in term or "ghostty" in term:
+ if os.environ.get("KITTY_WINDOW_ID") or "kitty" in term or "ghostty" in term or term_program == "ghostty":
return "kitty"
- if term_program in {"ghostty"}:
+ if _is_wezterm(): # speaks kitty and iterm; kitty has richer placement
return "kitty"
-
- # WezTerm speaks both kitty and iterm; prefer kitty (richer placement).
- if term_program == "wezterm" or os.environ.get("WEZTERM_PANE"):
- return "kitty"
-
- # iTerm2 inline images
if term_program == "iterm.app" or os.environ.get("ITERM_SESSION_ID"):
return "iterm"
-
- # sixel-capable terminals (env heuristics only)
- if term_program in {"mintty"} or "foot" in term or "mlterm" in term:
- return "sixel"
- if "sixel" in term:
+ if term_program == "mintty" or "foot" in term or "mlterm" in term or "sixel" in term:
return "sixel"
-
return "unicode"
def supports_kitty_placeholders() -> bool:
- """True when the terminal can paint kitty Unicode placeholders (U+10EEEE).
+ """True when the terminal paints kitty Unicode placeholders (U+10EEEE).
- Narrower than ``detect_terminal_graphics() == "kitty"``. WezTerm speaks
- kitty APC transmits but does not implement the placeholder grid, so those
- cells render as tofu. Ghostty and kitty do. VS Code already falls out of
- ``detect_terminal_graphics`` as ``unicode``.
+ Narrower than ``detect_terminal_graphics() == "kitty"``: WezTerm accepts
+ kitty APC transmits but lacks the placeholder grid (cells render as tofu).
"""
- if detect_terminal_graphics() != "kitty":
- return False
- term_program = os.environ.get("TERM_PROGRAM", "").lower()
- if term_program == "wezterm" or os.environ.get("WEZTERM_PANE"):
- return False
- return True
+ return detect_terminal_graphics() == "kitty" and not _is_wezterm()
def resolve_mode(configured: str | None, *, stream=None) -> str:
- """Resolve the effective render mode from config + the environment.
-
- ``configured`` is ``display.pet.render_mode`` (``auto`` → detect). Returns
- ``off`` when not attached to a TTY (no point emitting graphics into a pipe
- or logfile).
- """
+ """Effective render mode from ``display.pet.render_mode`` + env; ``off`` when not a TTY."""
mode = (configured or "auto").strip().lower()
if mode not in RENDER_MODES:
mode = "auto"
@@ -126,56 +90,35 @@ def resolve_mode(configured: str | None, *, stream=None) -> str:
except (ValueError, OSError):
return "off"
- if mode == "auto":
- return detect_terminal_graphics()
- return mode
-
-
-# ─────────────────────────────────────────────────────────────────────────
-# Frame decoding
-# ─────────────────────────────────────────────────────────────────────────
-
-def _open_sheet(path: Path):
- from PIL import Image
+ return detect_terminal_graphics() if mode == "auto" else mode
- img = Image.open(path)
- return img.convert("RGBA")
+# ───────────────────────── frame decoding ─────────────────────────
-# Max alpha at/below which a frame counts as blank padding. petdex sheets are
-# left-packed: a state with fewer real frames than ``FRAMES_PER_STATE`` fills
-# the trailing columns with fully transparent cells. Animating into one flashes
-# the pet blank, so we stop the row at the first such gap.
+# Max alpha at/below which a frame is blank padding. petdex sheets are
+# left-packed, so a state with fewer real frames than FRAMES_PER_STATE has
+# fully transparent trailing cells; animating into one flashes the pet blank.
_BLANK_ALPHA = 8
def _frame_is_blank(frame) -> bool:
- """True if *frame* has no meaningfully opaque pixel (transparent padding)."""
return frame.getchannel("A").getextrema()[1] <= _BLANK_ALPHA
@lru_cache(maxsize=16)
-def _raw_frames(
- sheet_path: str,
- state_value: str,
- frame_w: int,
- frame_h: int,
- frames_per_state: int,
-) -> tuple:
- """Cropped, padding-trimmed RGBA frames for one state row (unscaled).
+def _raw_frames(sheet_path: str, state_value: str, frame_w: int, frame_h: int, frames_per_state: int) -> tuple:
+ """Cropped RGBA frames for one state row, stopping at the first blank column.
- Steps across the row until the first blank column so pets with ragged
- per-state frame counts never animate into empty padding. Cached; returns
- ``()`` on any decode failure.
+ Cached; returns ``()`` on any decode failure.
"""
try:
- sheet = _open_sheet(Path(sheet_path))
+ from PIL import Image
+
+ sheet = Image.open(Path(sheet_path)).convert("RGBA")
cols = max(1, sheet.width // frame_w)
rows = max(1, sheet.height // frame_h)
- row = state_row_index(state_value, rows)
- top = row * frame_h
- # Clamp the row to the sheet (some pets ship fewer rows than the 8 the
- # taxonomy reserves).
+ top = state_row_index(state_value, rows) * frame_h
+ # Clamp to the sheet: some pets ship fewer rows than the taxonomy reserves.
if top + frame_h > sheet.height:
top = max(0, sheet.height - frame_h)
@@ -184,7 +127,7 @@ def _raw_frames(
left = i * frame_w
frame = sheet.crop((left, top, left + frame_w, top + frame_h))
if _frame_is_blank(frame):
- break # trailing transparent padding — real frames end here
+ break
frames.append(frame)
return tuple(frames)
except Exception as exc: # noqa: BLE001 - cosmetic feature, never fatal
@@ -202,11 +145,7 @@ def _frames_for(
scale_w: int,
scale_h: int,
):
- """Return padding-trimmed RGBA frames for one state row, scaled.
-
- Thin scaling layer over :func:`_raw_frames`; both are cached so repeated
- frame requests during animation are free.
- """
+ """Scaled :func:`_raw_frames` (both cached, so animation-time requests are free)."""
raw = _raw_frames(sheet_path, state_value, frame_w, frame_h, frames_per_state)
if not raw or (scale_w, scale_h) == (frame_w, frame_h):
return list(raw)
@@ -222,137 +161,97 @@ def state_frame_counts(
frame_h: int = FRAME_H,
frames_per_state: int = FRAMES_PER_STATE,
) -> dict[str, int]:
- """Map each driven :class:`PetState` → its real (padding-trimmed) frame count.
+ """Each driven :class:`PetState` → its real (padding-trimmed) frame count.
- The single source of truth for "how many frames does this state actually
- have?". The CLI/TUI consume the trimmed frame lists directly; the gateway
- ships this map to the desktop canvas, which steps its own loop.
+ The gateway ships this map to the desktop canvas, which steps its own loop.
"""
return {
- state.value: len(
- _raw_frames(str(sheet_path), state.value, frame_w, frame_h, frames_per_state)
- )
+ state.value: len(_raw_frames(str(sheet_path), state.value, frame_w, frame_h, frames_per_state))
for state in PetState
}
-# ─────────────────────────────────────────────────────────────────────────
-# Encoders
-# ─────────────────────────────────────────────────────────────────────────
+# ───────────────────────── encoders ─────────────────────────
+
-def _png_bytes(frame) -> bytes:
+def _png_b64(frame) -> str:
buf = io.BytesIO()
frame.save(buf, format="PNG")
- return buf.getvalue()
+ return base64.standard_b64encode(buf.getvalue()).decode("ascii")
-def _union_alpha_bbox(frames) -> tuple[int, int, int, int] | None:
- """Union opaque-pixel bbox across *frames* (a stable trim for animation)."""
- left = top = right = bottom = None
+def _crop_frames_to_alpha_union(frames):
+ """Crop every frame to the union opaque bbox (a stable trim across the animation).
+
+ kitty paints the whole transmitted rectangle, transparent margins included,
+ so an untrimmed pet looks small and adrift inside its cell box.
+ """
+ boxes = []
for frame in frames:
try:
bbox = frame.getchannel("A").getbbox()
except Exception: # noqa: BLE001 - cosmetic; fail open
bbox = None
- if not bbox:
- continue
- l, t, r, b = bbox
- left = l if left is None else min(left, l)
- top = t if top is None else min(top, t)
- right = r if right is None else max(right, r)
- bottom = b if bottom is None else max(bottom, b)
- if left is None or top is None or right is None or bottom is None:
- return None
- return (left, top, right, bottom)
-
-
-def _crop_frames_to_alpha_union(frames):
- """Crop every frame to the union opaque bbox so the sprite hugs its box.
-
- kitty paints the whole transmitted rectangle, transparent margins included,
- which makes the visible pet look small and adrift inside a larger cell box.
- Trimming to the visible bounds keeps the pet tight in its corner.
- """
- bbox = _union_alpha_bbox(frames)
- if not bbox:
+ if bbox:
+ boxes.append(bbox)
+ if not boxes:
return frames
- return [f.crop(bbox) for f in frames]
+ union = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))
+ return [f.crop(union) for f in frames]
# Nominal terminal cell size in pixels. kitty fits an image to its cell
-# rectangle preserving aspect, so a frame whose pixel size isn't a whole
-# multiple of the cell rounds up — which makes the terminal clip the bottom row
-# (the "clipped feet") and letterbox a blank row. Snapping each frame to an
-# exact cell multiple avoids that. (See ratatui-image #57: "render in multiples
-# of the font-size, to avoid stale character artifacts.")
+# rectangle preserving aspect, so a frame that isn't a whole cell multiple
+# rounds up, clipping the bottom row ("clipped feet") and letterboxing a blank
+# row. Snapping to an exact multiple avoids that (cf. ratatui-image #57).
_CELL_W = 8
_CELL_H = 16
def _snap_frames_to_cell_grid(frames):
- """Resize frames so width/height are exact multiples of the cell box.
-
- Removes the sub-cell remainder kitty would otherwise round up + clip. All
- frames share the union-cropped size, so they snap to the same cell grid.
- """
+ """Resize frames so width/height are exact multiples of the cell box (all frames share the union-cropped size)."""
if not frames:
return frames
from PIL import Image
w, h = frames[0].size
- cols = max(1, round(w / _CELL_W))
- rows = max(1, round(h / _CELL_H))
- target = (cols * _CELL_W, rows * _CELL_H)
+ target = (max(1, round(w / _CELL_W)) * _CELL_W, max(1, round(h / _CELL_H)) * _CELL_H)
if (w, h) == target:
return frames
return [f.resize(target, Image.LANCZOS) for f in frames]
def _kitty_apc(ctrl: str, data: str) -> str:
- """Emit a kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces."""
- chunk = 4096
- if len(data) <= chunk:
- return f"\x1b_G{ctrl},m=0;{data}\x1b\\"
- out = [f"\x1b_G{ctrl},m=1;{data[:chunk]}\x1b\\"]
- rest = data[chunk:]
- while rest:
- piece, rest = rest[:chunk], rest[chunk:]
- out.append(f"\x1b_Gm={1 if rest else 0};{piece}\x1b\\")
- return "".join(out)
+ """kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces."""
+ pieces = [data[i : i + 4096] for i in range(0, len(data), 4096)] or [""]
+ last = len(pieces) - 1
+ return "".join(
+ f"\x1b_G{ctrl + ',' if i == 0 else ''}m={0 if i == last else 1};{piece}\x1b\\" for i, piece in enumerate(pieces)
+ )
def _encode_kitty(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:
- """Encode one frame via the kitty graphics protocol (transmit + display).
-
- ``a=T`` transmits & displays at the cursor; ``c``/``r`` request a display
- box in terminal cells so successive frames overwrite the same area.
- """
+ """kitty transmit+display at the cursor; ``c``/``r`` pin the cell box so frames overwrite each other."""
ctrl = "f=100,a=T,q=2"
if cell_cols:
ctrl += f",c={cell_cols}"
if cell_rows:
ctrl += f",r={cell_rows}"
- return _kitty_apc(ctrl, base64.standard_b64encode(_png_bytes(frame)).decode("ascii"))
-
-
-# ─────────────────────────────────────────────────────────────────────────
-# kitty Unicode placeholders
-#
-# Ink (the TUI's React-for-terminal layer) owns the screen and measures every
-# cell's width, so it can't host raw kitty image escapes (no width to count,
-# clobbered on the next repaint). kitty's *Unicode placeholder* protocol is the
-# grid-safe path: transmit the image once (q=2, virtual placement U=1), then the
-# host app prints ordinary-width placeholder cells (U+10EEEE + diacritics) whose
-# foreground color encodes the image id. Ink counts those as width-1 text, so
-# layout stays correct and the terminal paints the image underneath.
+ return _kitty_apc(ctrl, _png_b64(frame))
+
+
+# ───────────────────────── kitty Unicode placeholders ─────────────────────────
+# Ink owns the screen and measures every cell's width, so it can't host raw
+# kitty image escapes. The placeholder protocol is the grid-safe path: transmit
+# once as a virtual placement (U=1), then print ordinary-width placeholder cells
+# (U+10EEEE + diacritics) whose foreground color encodes the image id; Ink counts
+# them as width-1 text and the terminal paints the image underneath.
# https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders
-# ─────────────────────────────────────────────────────────────────────────
_KITTY_PLACEHOLDER = "\U0010eeee"
-# Row/column diacritics, in order (index → diacritic). Verbatim from kitty's
-# gen/rowcolumn-diacritics.txt (Unicode 6.0.0, combining class 230). Index i is
-# the diacritic that encodes the number i; we only ever need the row index.
+# Row/column diacritics, index → diacritic, verbatim from kitty's
+# gen/rowcolumn-diacritics.txt. We only ever need the row index.
_ROWCOL_DIACRITICS: tuple[int, ...] = (
0x0305, 0x030D, 0x030E, 0x0310, 0x0312, 0x033D, 0x033E, 0x033F, 0x0346, 0x034A,
0x034B, 0x034C, 0x0350, 0x0351, 0x0352, 0x0357, 0x035B, 0x0363, 0x0364, 0x0365,
@@ -388,13 +287,7 @@ _ROWCOL_DIACRITICS: tuple[int, ...] = (
def kitty_image_id(slug: str) -> int:
- """Stable per-pet image id in ``[1, 0x7FFF]``.
-
- The id is encoded in the placeholder's 24-bit foreground color, so it must
- be non-zero and fit comfortably under ``0xFFFFFF``. A small CRC keeps it
- deterministic per slug (so re-renders reuse the same terminal-side image)
- while making collisions between two different pets unlikely.
- """
+ """Deterministic per-slug image id in ``[1, 0x7FFF]`` (non-zero; encoded in the placeholder fg color) so re-renders reuse the terminal-side image."""
import zlib
return (zlib.crc32(slug.encode("utf-8")) % 0x7FFE) + 1
@@ -406,40 +299,30 @@ def kitty_color_hex(image_id: int) -> str:
def kitty_placeholder_rows(cols: int, rows: int) -> list[str]:
- """Build the placeholder text grid for an *rows*×*cols* image.
+ """Placeholder text grid: first cell carries the row diacritic, the rest auto-increment the column.
- Each line is one row of the grid: the first cell carries the row diacritic
- (column defaults to 0), and the remaining ``cols-1`` bare placeholders let
- the terminal auto-increment the column. The foreground color (the image id)
- is applied by the caller / Ink, not embedded here.
+ The foreground color (image id) is applied by the caller / Ink, not here.
"""
cols = max(1, cols)
out: list[str] = []
for r in range(max(1, rows)):
idx = min(r, len(_ROWCOL_DIACRITICS) - 1)
- first = _KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[idx])
- out.append(first + _KITTY_PLACEHOLDER * (cols - 1))
+ out.append(_KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[idx]) + _KITTY_PLACEHOLDER * (cols - 1))
return out
def _encode_kitty_virtual(frame, *, image_id: int, cols: int, rows: int) -> str:
- """Transmit a frame as a kitty *virtual* placement for Unicode placeholders.
+ """Transmit a frame as a kitty virtual placement (``U=1``; ``q=2`` mutes replies that would corrupt Ink's output).
- ``a=T`` transmits and creates the placement in one shot; ``U=1`` marks it
- virtual (no on-screen output, cursor untouched); ``q=2`` suppresses the
- terminal's OK/error replies that would otherwise corrupt the host app's
- output. Re-sending with the same ``i`` replaces the image, so the static
- placeholder cells animate underneath.
+ Re-sending with the same ``i`` replaces the image, so static placeholder cells animate underneath.
"""
- ctrl = f"a=T,U=1,i={image_id},c={cols},r={rows},f=100,q=2"
- return _kitty_apc(ctrl, base64.standard_b64encode(_png_bytes(frame)).decode("ascii"))
+ return _kitty_apc(f"a=T,U=1,i={image_id},c={cols},r={rows},f=100,q=2", _png_b64(frame))
def _encode_iterm(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:
- """Encode one frame as an iTerm2 inline image (OSC 1337 File)."""
- payload = base64.standard_b64encode(_png_bytes(frame)).decode("ascii")
- size = len(payload)
- args = ["inline=1", f"size={size}", "preserveAspectRatio=1"]
+ """iTerm2 inline image (OSC 1337 File)."""
+ payload = _png_b64(frame)
+ args = ["inline=1", f"size={len(payload)}", "preserveAspectRatio=1"]
if cell_cols:
args.append(f"width={cell_cols}")
if cell_rows:
@@ -448,32 +331,24 @@ def _encode_iterm(frame, *, cell_cols: int | None = None, cell_rows: int | None
def _encode_sixel(frame) -> str:
- """Encode one frame as DEC sixel.
+ """DEC sixel via a compact hand-rolled encoder (Pillow has no sixel writer).
- Quantizes to an adaptive palette (≤255 colors) and emits the sixel band
- stream. Pillow has no sixel writer, so this is a compact hand-rolled
- encoder. Transparent pixels render as background (color register skipped).
+ Quantizes to ≤255 adaptive colors; transparent pixels are skipped (render as background).
"""
from PIL import Image
- rgba = frame
- # Composite onto transparent-as-skip: track alpha to decide background.
- pal = rgba.convert("RGB").quantize(colors=255, method=Image.MEDIANCUT)
+ pal = frame.convert("RGB").quantize(colors=255, method=Image.MEDIANCUT)
palette = pal.getpalette() or []
px = pal.load()
- alpha = rgba.getchannel("A").load()
+ alpha = frame.getchannel("A").load()
w, h = pal.size
out = ["\x1bP0;1;0q", '"1;1;%d;%d' % (w, h)]
- # Color register definitions (sixel uses 0..100 scale).
used = sorted({px[x, y] for y in range(h) for x in range(w)})
- for idx in used:
- r = palette[idx * 3] if idx * 3 < len(palette) else 0
- g = palette[idx * 3 + 1] if idx * 3 + 1 < len(palette) else 0
- b = palette[idx * 3 + 2] if idx * 3 + 2 < len(palette) else 0
+ for idx in used: # color registers on a 0..100 scale
+ r, g, b = (palette[idx * 3 + c] if idx * 3 + c < len(palette) else 0 for c in range(3))
out.append("#%d;2;%d;%d;%d" % (idx, r * 100 // 255, g * 100 // 255, b * 100 // 255))
- # Emit in 6-row bands.
for band in range(0, h, 6):
for color_idx in used:
line = ["#%d" % color_idx]
@@ -484,10 +359,7 @@ def _encode_sixel(frame) -> str:
nonlocal run_char, run_len
if run_char is None:
return
- if run_len > 3:
- line.append("!%d%s" % (run_len, run_char))
- else:
- line.append(run_char * run_len)
+ line.append("!%d%s" % (run_len, run_char) if run_len > 3 else run_char * run_len)
run_char, run_len = None, 0
for x in range(w):
@@ -516,11 +388,9 @@ Cell = tuple[tuple[int, int, int, int], tuple[int, int, int, int]]
def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
- """Downscale a frame to a grid of half-block cells.
+ """Downscale a frame to rows of half-block cells (one terminal row = two pixel rows).
- Each cell pairs a top and bottom pixel so one terminal row encodes two
- pixel rows. Returns rows of ``((tr,tg,tb,ta),(br,bg,bb,ba))`` — the
- framework-neutral representation shared by the ANSI encoder (CLI) and the
+ Framework-neutral representation shared by the ANSI encoder (CLI) and the
structured ``cells`` API (Ink).
"""
from PIL import Image
@@ -528,43 +398,33 @@ def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
target_cols = max(4, target_cols)
aspect = frame.height / max(1, frame.width)
target_rows = max(2, int(round(target_cols * aspect * 0.5)) * 2)
- small = frame.resize((target_cols, target_rows), Image.LANCZOS).convert("RGBA")
- px = small.load()
-
- grid: list[list[Cell]] = []
- for y in range(0, target_rows, 2):
- row: list[Cell] = []
- for x in range(target_cols):
- top = px[x, y]
- bottom = px[x, y + 1] if y + 1 < target_rows else (0, 0, 0, 0)
- row.append((top, bottom))
- grid.append(row)
- return grid
+ px = frame.resize((target_cols, target_rows), Image.LANCZOS).convert("RGBA").load()
+ return [
+ [(px[x, y], px[x, y + 1] if y + 1 < target_rows else (0, 0, 0, 0)) for x in range(target_cols)]
+ for y in range(0, target_rows, 2)
+ ]
def _encode_unicode(frame, *, target_cols: int) -> str:
- """Downscale to truecolor ANSI half-blocks (one char = 2 vertical pixels)."""
+ """Truecolor ANSI half-blocks (one char = 2 vertical pixels)."""
lines: list[str] = []
for row in _downscale_cells(frame, target_cols=target_cols):
- cells: list[str] = []
- for (tr, tg, tb, ta), (br, bg, bb, ba) in row:
- if ta < 32 and ba < 32:
- cells.append("\x1b[0m ") # fully transparent → blank
- continue
- cells.append(f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}")
+ cells = [
+ "\x1b[0m " if ta < 32 and ba < 32 else f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}"
+ for (tr, tg, tb, ta), (br, bg, bb, ba) in row
+ ]
lines.append("".join(cells) + "\x1b[0m")
return "\n".join(lines)
-# ─────────────────────────────────────────────────────────────────────────
-# Public renderer
-# ─────────────────────────────────────────────────────────────────────────
+# ───────────────────────── public renderer ─────────────────────────
+
class PetRenderer:
"""Holds a pet's spritesheet and yields encoded frames per (state, index).
- Construct once per pet, then call :meth:`frame` on an animation timer.
- Cheap to call repeatedly — decoded frames are cached.
+ Construct once per pet, then call :meth:`frame` on an animation timer;
+ decoded frames are cached so repeated calls are cheap.
"""
def __init__(
@@ -594,71 +454,51 @@ class PetRenderer:
return len(self._frames(state))
def _frames(self, state: PetState | str):
- value = state.value if isinstance(state, PetState) else str(state)
- scale_w = max(1, int(self.frame_w * self.scale))
- scale_h = max(1, int(self.frame_h * self.scale))
return _frames_for(
self.spritesheet,
- value,
+ state.value if isinstance(state, PetState) else str(state),
self.frame_w,
self.frame_h,
self.frames_per_state,
- scale_w,
- scale_h,
+ max(1, int(self.frame_w * self.scale)),
+ max(1, int(self.frame_h * self.scale)),
)
def cells(self, state: PetState | str, index: int, *, cols: int | None = None) -> list[list[Cell]]:
- """Return one frame as a half-block cell grid (framework-neutral).
-
- Used by the TUI, which renders the grid with native Ink color props
- instead of raw ANSI. Returns ``[]`` when no frame is available.
- """
+ """One frame as a half-block cell grid for Ink's native color props; ``[]`` when unavailable."""
frames = self._frames(state)
if not frames:
return []
- frame = frames[index % len(frames)]
- return _downscale_cells(frame, target_cols=cols or self.unicode_cols)
+ return _downscale_cells(frames[index % len(frames)], target_cols=cols or self.unicode_cols)
def _cell_box(self, frame) -> tuple[int, int]:
- """Terminal cell box for a scaled frame (~8×16 px per cell).
+ """Terminal cell box (~8×16 px per cell) for a scaled frame.
- Must match :meth:`frame` graphics sizing — kitty stretches the image to
- fill ``c``×``r`` cells, so these must reflect the scaled pixel
- dimensions, not a native-aspect column count (that upscales small pets).
+ kitty stretches the image to fill ``c``×``r`` cells, so this must track
+ the scaled pixel size, not a native-aspect column count (that upscales small pets).
"""
return max(1, frame.width // 8), max(1, frame.height // 16)
def kitty_payload(self, state: PetState | str, *, image_id: int) -> dict | None:
- """Build the kitty Unicode-placeholder payload for one state.
-
- Returns ``{cols, rows, placeholder, frames}`` where ``frames`` is a
- list of transmit escapes (one per animation frame, all reusing
- ``image_id``) and ``placeholder`` is the static text grid Ink paints.
- Placement geometry is derived from the scaled frame pixels (via
- :meth:`_cell_box`), not ``unicode_cols`` — kitty upscales to fill
- ``c``×``r`` cells. ``None`` when no frame is available.
+ """kitty Unicode-placeholder payload ``{cols, rows, placeholder, frames}`` for one state.
+
+ ``frames`` are transmit escapes (all reusing ``image_id``); ``placeholder``
+ is the static text grid Ink paints. ``None`` when no frame is available.
"""
frames = self._frames(state)
if not frames:
return None
- frames = _crop_frames_to_alpha_union(frames)
- frames = _snap_frames_to_cell_grid(frames)
+ frames = _snap_frames_to_cell_grid(_crop_frames_to_alpha_union(frames))
cols, rows = self._cell_box(frames[0])
return {
"cols": cols,
"rows": rows,
"placeholder": kitty_placeholder_rows(cols, rows),
- "frames": [
- _encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames
- ],
+ "frames": [_encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames],
}
def frame(self, state: PetState | str, index: int) -> str:
- """Return the encoded escape string for one frame, or ``""``.
-
- ``index`` is taken modulo the available frame count so callers can pass
- a free-running counter.
- """
+ """Encoded escape string for one frame (``index`` taken modulo the frame count), or ``""``."""
if self.mode == "off":
return ""
frames = self._frames(state)
@@ -688,11 +528,6 @@ def build_renderer(
unicode_cols: int = 20,
stream=None,
) -> PetRenderer:
- """Convenience factory: resolve the mode from config+env, then construct."""
+ """Resolve the mode from config+env, then construct a :class:`PetRenderer`."""
mode = resolve_mode(configured_mode, stream=stream)
- return PetRenderer(
- spritesheet,
- mode=mode,
- scale=scale,
- unicode_cols=unicode_cols,
- )
+ return PetRenderer(spritesheet, mode=mode, scale=scale, unicode_cols=unicode_cols)
diff --git a/agent/pet/state.py b/agent/pet/state.py
index a9ad5afd801..3385098a0ec 100644
--- a/agent/pet/state.py
+++ b/agent/pet/state.py
@@ -64,18 +64,13 @@ def derive_pet_state(
7. ``busy`` → ``RUN`` (turn in flight, unspecified work)
8. otherwise → ``IDLE``
"""
- if error:
- return PetState.FAILED
- if celebrate:
- return PetState.JUMP
- if just_completed:
- return PetState.WAVE
- if awaiting_input:
- return PetState.WAITING
- if tool_running:
- return PetState.RUN
- if reasoning:
- return PetState.REVIEW
- if busy:
- return PetState.RUN
- return PetState.IDLE
+ ranked = (
+ (error, PetState.FAILED),
+ (celebrate, PetState.JUMP),
+ (just_completed, PetState.WAVE),
+ (awaiting_input, PetState.WAITING),
+ (tool_running, PetState.RUN),
+ (reasoning, PetState.REVIEW),
+ (busy, PetState.RUN),
+ )
+ return next((state for flag, state in ranked if flag), PetState.IDLE)
diff --git a/agent/pet/store.py b/agent/pet/store.py
index 42627c1ac81..fd1891ecc88 100644
--- a/agent/pet/store.py
+++ b/agent/pet/store.py
@@ -1,17 +1,10 @@
"""On-disk pet store — install / list / resolve pets.
-Pets live under ``get_hermes_home()/pets/<slug>/`` so every profile gets its
-own set (we deliberately do **not** reuse petdex's ``~/.codex/pets`` default —
-that's owned by the petdex npm CLI and isn't profile-aware). Each installed
-pet directory holds:
-
- pets/<slug>/
- pet.json # {id, displayName, description, spritesheetPath}
- spritesheet.webp # (or .png)
-
-The active pet is resolved from the caller-supplied ``display.pet.slug`` config
-value (falling back to the first installed pet), so this module stays free of
-the config loader.
+Pets live under ``get_hermes_home()/pets/<slug>/`` (profile-scoped; we do NOT
+reuse petdex's ``~/.codex/pets``, which the petdex CLI owns). Each pet dir holds
+``pet.json`` ({id, displayName, description, spritesheetPath}) plus
+``spritesheet.webp`` (or .png). The active pet is resolved from the
+caller-supplied ``display.pet.slug`` so this module stays free of the config loader.
"""
from __future__ import annotations
@@ -27,6 +20,7 @@ from hermes_constants import get_hermes_home
logger = logging.getLogger(__name__)
_DOWNLOAD_TIMEOUT = 60.0
+_HTTP_HEADERS = {"User-Agent": "hermes-agent-petdex"}
class PetStoreError(RuntimeError):
@@ -60,6 +54,13 @@ def pets_dir() -> Path:
return path
+def _thumb_path(slug: str) -> Path:
+ """Cached thumbnail for *slug* (lives OUTSIDE the pet dir, under ``pets/.thumbs/``)."""
+ path = pets_dir() / ".thumbs"
+ path.mkdir(parents=True, exist_ok=True)
+ return path / f"{slug}.png"
+
+
def _read_pet_json(directory: Path) -> dict:
pet_json = directory / "pet.json"
if not pet_json.is_file():
@@ -71,37 +72,28 @@ def _read_pet_json(directory: Path) -> dict:
return {}
-def _resolve_spritesheet(directory: Path, meta: dict) -> Path:
- """Find the spritesheet for a pet dir.
+def _write_pet_json(directory: Path, meta: dict) -> None:
+ (directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
- Honors ``spritesheetPath`` from pet.json, else probes the conventional
- filenames (``spritesheet.{webp,png}`` and petdex R2's ``sprite.webp``).
- """
+
+def _resolve_spritesheet(directory: Path, meta: dict) -> Path:
+ """Honor ``spritesheetPath``, else probe conventional names (incl. petdex R2's ``sprite.webp``)."""
declared = str(meta.get("spritesheetPath", "") or "").strip()
- if declared:
- candidate = directory / declared
- if candidate.is_file():
- return candidate
- for name in ("spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"):
+ for name in ([declared] if declared else []) + ["spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"]:
candidate = directory / name
if candidate.is_file():
return candidate
- # Default expectation even if missing, so callers get a stable path.
- return directory / "spritesheet.webp"
+ return directory / "spritesheet.webp" # stable default even when missing
def _safe_slug(slug: str) -> str:
"""Normalize a slug to a single bare path segment.
- Pet slugs index into ``pets_dir()/<slug>/`` for load/remove, so a value
- carrying path separators (``../``, absolute paths) could escape the pets
- directory. Strip every separator and reject ``.``/``..`` so callers can
- only ever name a direct child of the pets directory.
+ Slugs index ``pets_dir()/<slug>/`` for load/remove, so separators (``../``,
+ absolute paths) must not escape the pets directory; ``.``/``..`` are rejected.
"""
segment = Path(str(slug).strip()).name
- if segment in ("", ".", ".."):
- return ""
- return segment
+ return "" if segment in ("", ".", "..") else segment
def load_pet(slug: str) -> InstalledPet | None:
@@ -123,6 +115,13 @@ def load_pet(slug: str) -> InstalledPet | None:
)
+def _loaded_pet_or_raise(slug: str, error: str) -> InstalledPet:
+ pet = load_pet(slug)
+ if pet is None or not pet.exists:
+ raise PetStoreError(error)
+ return pet
+
+
def installed_pets() -> list[InstalledPet]:
"""Return every installed pet (dirs containing a usable spritesheet)."""
out: list[InstalledPet] = []
@@ -136,11 +135,7 @@ def installed_pets() -> list[InstalledPet]:
def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | None:
- """Resolve which pet to display.
-
- Precedence: the configured slug (``display.pet.slug``) if it's installed,
- otherwise the first installed pet alphabetically, otherwise ``None``.
- """
+ """The configured slug (``display.pet.slug``) if installed, else the first pet alphabetically."""
if configured_slug:
pet = load_pet(configured_slug.strip())
if pet and pet.exists:
@@ -152,9 +147,8 @@ def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | Non
def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TIMEOUT) -> InstalledPet:
"""Download *slug* from the manifest into the pets directory.
- Idempotent: a fully-installed pet is returned as-is unless *force*. Raises
- :class:`PetStoreError` / :class:`~agent.pet.manifest.ManifestError` on
- failure.
+ Idempotent: a fully-installed pet is returned as-is unless *force*. Raises
+ :class:`PetStoreError` / :class:`~agent.pet.manifest.ManifestError` on failure.
"""
from agent.pet.manifest import find_entry
@@ -169,9 +163,8 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TI
if entry is None:
raise PetStoreError(f"pet '{slug}' is not in the petdex manifest")
- # Host-pin every asset URL to petdex. The manifest is trusted (HTTPS from
- # petdex.dev), but pin the asset hosts too so a compromised/spoofed manifest
- # can't redirect the download at an arbitrary host. Matches thumbnail_png.
+ # Host-pin asset URLs so a compromised/spoofed manifest can't redirect the
+ # download to an arbitrary host (matches thumbnail_png).
if not _is_petdex_host(entry.spritesheet_url):
raise PetStoreError(f"refusing non-petdex spritesheet host for '{slug}'")
@@ -180,28 +173,22 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TI
sprite_ext = ".png" if entry.spritesheet_url.lower().split("?")[0].endswith(".png") else ".webp"
sprite_path = directory / f"spritesheet{sprite_ext}"
-
_download(entry.spritesheet_url, sprite_path, timeout=timeout)
- # Fetch the upstream pet.json if present; otherwise synthesize a minimal
- # one so the local layout is self-describing.
+ # Prefer the upstream pet.json; else synthesize one so the layout is self-describing.
meta: dict = {}
if entry.pet_json_url and _is_petdex_host(entry.pet_json_url):
try:
meta = _download_json(entry.pet_json_url, timeout=timeout)
except Exception as exc: # noqa: BLE001 - non-fatal, fall back below
logger.debug("pet.json fetch failed for %s: %s", slug, exc)
- if not isinstance(meta, dict) or not meta:
+ if not meta:
meta = {"id": slug, "displayName": entry.display_name, "description": ""}
meta["spritesheetPath"] = sprite_path.name
meta.setdefault("id", slug)
meta.setdefault("displayName", entry.display_name)
- (directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
-
- pet = load_pet(slug)
- if pet is None or not pet.exists:
- raise PetStoreError(f"install of '{slug}' did not produce a spritesheet")
- return pet
+ _write_pet_json(directory, meta)
+ return _loaded_pet_or_raise(slug, f"install of '{slug}' did not produce a spritesheet")
def slugify(name: str) -> str:
@@ -244,12 +231,11 @@ def register_local_pet(
display_name: str = "",
description: str = "",
) -> InstalledPet:
- """Write a locally-generated pet into the store and return it.
+ """Write a locally-generated pet (PIL image, WebP/PNG bytes, or path) into the store.
- *spritesheet* may be a PIL image, raw WebP/PNG bytes, or a path. The pet
- appears in :func:`installed_pets` immediately, and because :func:`install_pet`
- returns an already-on-disk pet before consulting the manifest, it can be
- adopted (``pet.select`` / ``/pet <slug>``) without a manifest entry.
+ It appears in :func:`installed_pets` immediately and, because :func:`install_pet`
+ returns an on-disk pet before consulting the manifest, can be adopted without
+ a manifest entry.
"""
slug = slugify(slug)
directory = pets_dir() / slug
@@ -260,33 +246,27 @@ def register_local_pet(
except Exception as exc: # noqa: BLE001 - normalize to one error type
raise PetStoreError(f"could not write spritesheet for '{slug}': {exc}") from exc
- meta = {
- "id": slug,
- "displayName": display_name or slug,
- "description": description or "",
- "spritesheetPath": sprite_path.name,
- "createdBy": "generator",
- }
- (directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
-
- pet = load_pet(slug)
- if pet is None or not pet.exists:
- raise PetStoreError(f"register of generated pet '{slug}' did not produce a spritesheet")
- return pet
+ _write_pet_json(
+ directory,
+ {
+ "id": slug,
+ "displayName": display_name or slug,
+ "description": description or "",
+ "spritesheetPath": sprite_path.name,
+ "createdBy": "generator",
+ },
+ )
+ return _loaded_pet_or_raise(slug, f"register of generated pet '{slug}' did not produce a spritesheet")
def export_pet(slug: str) -> tuple[str, bytes]:
- """Zip an installed pet's folder (pet.json + spritesheet) → (filename, bytes).
-
- Dotfiles (cached thumbs, backups) are skipped so the archive is a clean,
- re-importable pet package. Raises :class:`PetStoreError` if not installed.
- """
+ """Zip an installed pet's folder → ``(filename, bytes)``; dotfiles (thumbs, backups) skipped."""
import io
import zipfile
root = pets_dir()
directory = root / slug.strip()
- # Guard against traversal: the target must be a direct child of pets_dir.
+ # Traversal guard: the target must be a direct child of pets_dir.
if directory.resolve().parent != root.resolve() or not directory.is_dir():
raise PetStoreError(f"pet '{slug}' is not installed")
@@ -304,12 +284,6 @@ _THUMB_FRAME_H = 208
_THUMB_W = 96 # rendered ~40px; 2x+ keeps it crisp on HiDPI
-def _thumbs_dir() -> Path:
- path = pets_dir() / ".thumbs"
- path.mkdir(parents=True, exist_ok=True)
- return path
-
-
def _is_petdex_host(url: str) -> bool:
"""True only for petdex.dev hosts — bounds server-side fetch (anti-SSRF)."""
from urllib.parse import urlparse
@@ -322,23 +296,18 @@ def _is_petdex_host(url: str) -> bool:
def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) -> bytes | None:
- """Return a small idle-frame PNG for *slug*, cached on disk.
+ """Small idle-frame (top-left cell) PNG for *slug*, cached on disk.
- Crops the top-left (idle, frame 0) cell of the spritesheet and downsamples
- it to a thumbnail. Source preference: an installed spritesheet on disk, else
- *source_url* — but only when it points at petdex (so the gateway never
- fetches an arbitrary client-supplied URL). Returns ``None`` when there's no
- usable source or Pillow/network fails; callers render a placeholder.
-
- Doing this server-side sidesteps the renderer's CSP / R2 hotlink limits that
- break a direct ``<img src=cdn>`` and lets the result ride the authenticated
- gateway as a same-origin data URL.
+ Source: the installed spritesheet, else *source_url* only when it points at
+ petdex (the gateway never fetches an arbitrary client URL). ``None`` when no
+ usable source or Pillow/network fails. Server-side so the result rides the
+ authenticated gateway as a same-origin data URL, sidestepping CSP/hotlink limits.
"""
slug = slug.strip()
if not slug:
return None
- cache = _thumbs_dir() / f"{slug}.png"
+ cache = _thumb_path(slug)
if cache.is_file():
try:
return cache.read_bytes()
@@ -351,18 +320,13 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
try:
sheet_bytes = pet.spritesheet.read_bytes()
except OSError:
- sheet_bytes = None
+ pass
if sheet_bytes is None and source_url and _is_petdex_host(source_url):
try:
import httpx
- resp = httpx.get(
- source_url,
- timeout=timeout,
- follow_redirects=True,
- headers={"User-Agent": "hermes-agent-petdex"},
- )
+ resp = httpx.get(source_url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)
resp.raise_for_status()
sheet_bytes = resp.content
except Exception as exc: # noqa: BLE001 - cosmetic, degrade to placeholder
@@ -377,11 +341,8 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
from PIL import Image
with Image.open(io.BytesIO(sheet_bytes)) as im:
- frame = im.convert("RGBA").crop(
- (0, 0, min(_THUMB_FRAME_W, im.width), min(_THUMB_FRAME_H, im.height))
- )
- height = round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)
- frame = frame.resize((_THUMB_W, height), Image.NEAREST)
+ frame = im.convert("RGBA").crop((0, 0, min(_THUMB_FRAME_W, im.width), min(_THUMB_FRAME_H, im.height)))
+ frame = frame.resize((_THUMB_W, round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)), Image.NEAREST)
buf = io.BytesIO()
frame.save(buf, format="PNG")
data = buf.getvalue()
@@ -397,18 +358,16 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
def remove_pet(slug: str) -> bool:
- """Delete an installed pet directory. Returns True if anything was removed."""
+ """Delete an installed pet directory. Returns True if anything was removed."""
import shutil
slug = _safe_slug(slug)
if not slug:
return False
- # The cached thumbnail lives in pets/.thumbs/<slug>.png — OUTSIDE the pet
- # dir, so rmtree won't catch it. Drop it too, or a later pet that reuses this
- # slug renders this one's stale thumbnail.
+ # Drop the cached thumb too or a later pet reusing this slug shows the stale one.
try:
- (_thumbs_dir() / f"{slug}.png").unlink(missing_ok=True)
+ _thumb_path(slug).unlink(missing_ok=True)
except OSError:
pass
@@ -422,25 +381,19 @@ def remove_pet(slug: str) -> bool:
def rename_pet(slug: str, display_name: str) -> str | None:
"""Rename a pet's ``displayName`` AND realign its slug/dir to match.
- Generated pets are hatched under a provisional, prompt-derived slug; when
- the user names the pet on the reveal screen we make that name the real
- identity so lists/subtitles show what they typed, not the prompt. The dir is
- renamed to ``slugify(name)`` (and the cached thumbnail moved alongside it)
- whenever that yields a free, different slug — otherwise the slug is left as
- is. Returns the resulting slug on success, or ``None`` on failure.
+ Generated pets hatch under a provisional prompt-derived slug; naming on the
+ reveal screen makes that name the real identity. The dir (and cached thumb)
+ moves to ``slugify(name)`` when that's a free, different slug; otherwise the
+ slug stays. Returns the resulting slug, or ``None`` on failure.
"""
slug = _safe_slug(slug)
display_name = (display_name or "").strip()
if not slug or not display_name:
return None
directory = pets_dir() / slug
- pet_json = directory / "pet.json"
- if not pet_json.is_file():
+ if not (directory / "pet.json").is_file():
return None
- try:
- meta = json.loads(pet_json.read_text(encoding="utf-8"))
- except (OSError, ValueError):
- meta = {}
+ meta = _read_pet_json(directory)
if not isinstance(meta, dict):
meta = {}
meta["displayName"] = display_name
@@ -451,18 +404,17 @@ def rename_pet(slug: str, display_name: str) -> str | None:
try:
directory.rename(pets_dir() / desired)
try:
- (_thumbs_dir() / f"{slug}.png").rename(_thumbs_dir() / f"{desired}.png")
+ _thumb_path(slug).rename(_thumb_path(desired))
except OSError:
pass
directory = pets_dir() / desired
- pet_json = directory / "pet.json"
new_slug = desired
meta["id"] = new_slug
except OSError:
new_slug = slug # keep the provisional slug if the move fails
try:
- pet_json.write_text(json.dumps(meta, indent=2), encoding="utf-8")
+ _write_pet_json(directory, meta)
except OSError:
return None
return new_slug
@@ -472,13 +424,7 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:
import httpx
try:
- with httpx.stream(
- "GET",
- url,
- timeout=timeout,
- follow_redirects=True,
- headers={"User-Agent": "hermes-agent-petdex"},
- ) as resp:
+ with httpx.stream("GET", url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS) as resp:
resp.raise_for_status()
tmp = dest.with_suffix(dest.suffix + ".part")
with tmp.open("wb") as fh:
@@ -492,12 +438,7 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:
def _download_json(url: str, *, timeout: float) -> dict:
import httpx
- resp = httpx.get(
- url,
- timeout=timeout,
- follow_redirects=True,
- headers={"User-Agent": "hermes-agent-petdex"},
- )
+ resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)
resp.raise_for_status()
data = resp.json()
return data if isinstance(data, dict) else {}
diff --git a/tests/agent/test_pet_generate.py b/tests/agent/test_pet_generate.py
index 84d303281c0..34cbe20ea21 100644
--- a/tests/agent/test_pet_generate.py
+++ b/tests/agent/test_pet_generate.py
@@ -291,7 +291,7 @@ def test_hatch_pet_end_to_end(monkeypatch, tmp_path):
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
# Return a synthetic row strip; frame count is inferable from the spec.
state = prefix.replace("pet_row_", "")
- count = atlas_mod.FRAME_COUNTS.get(state, 6)
+ count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
p = tmp_path / f"{prefix}.png"
_strip(count).save(p)
return [p]
@@ -331,7 +331,7 @@ def test_hatch_pet_removes_row_strips_after_extraction(monkeypatch, tmp_path):
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
state = prefix.replace("pet_row_", "")
- count = atlas_mod.FRAME_COUNTS.get(state, 6)
+ count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
p = tmp_path / f"{prefix}.png"
_strip(count).save(p)
produced.append(p)
@@ -359,7 +359,7 @@ def test_hatch_pet_removes_row_strips_after_failed_attempt(monkeypatch, tmp_path
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
attempts[prefix] = attempts.get(prefix, 0) + 1
state = prefix.replace("pet_row_", "")
- count = atlas_mod.FRAME_COUNTS.get(state, 6)
+ count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
path = tmp_path / f"{prefix}_{attempts[prefix]}.png"
_strip(count).save(path)
return [path]
@@ -397,7 +397,7 @@ def test_hatch_pet_idle_fallback_when_row_fails(monkeypatch, tmp_path):
if prefix == "pet_row_idle":
raise GenerationError("boom")
state = prefix.replace("pet_row_", "")
- count = atlas_mod.FRAME_COUNTS.get(state, 6)
+ count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
p = tmp_path / f"{prefix}.png"
_strip(count).save(p)
return [p]