Spaces:
Sleeping
Sleeping
AutoSprite: initial app (early checkpoint)
Browse filesFiles changed (21)
- .gitignoreAdded+8
- README.md+49-5
- app.pyAdded+116
- autosprite/__init__.pyAdded+9
- autosprite/features.pyAdded+108
- autosprite/inference.pyAdded+59
- autosprite/model.pyAdded+114
- autosprite/preprocess.pyAdded+159
- autosprite/sheet.pyAdded+116
- autosprite/synth.pyAdded+413
- evaluate.pyAdded+67
- examples/alan/idle.pngAdded
- examples/alan/jump.pngAdded
- examples/alan/walk_1.pngAdded
- examples/alan/walk_2.pngAdded
- examples/alan/walk_3.pngAdded
- export_onnx.pyAdded+52
- requirements.txtAdded+3
- tests/test_pipeline.pyAdded+72
- train.pyAdded+159
- weights/autosprite.onnxAdded+3
12345678.venv/__pycache__/*.pyc.pytest_cache/weights/*.ptplayer1/player1_18/eval_*.png12345678910111213---title: AutoSpriteemoji: 👁colorFrom: purplecolorTo: bluesdk: gradiosdk_version: 6.32.0python_version: '3.13'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657---title: AutoSpriteemoji: 👾colorFrom: indigocolorTo: pinksdk: gradiosdk_version: 6.32.0app_file: app.pypinned: falselicense: mitshort_description: Few pixel-art frames in, full spritesheet out (CPU)---# AutoSpriteUpload as few as one consistent pixel-art frame (16x16 or 18x18 work best, up to 24x24) andAutoSprite fills in the rest of a platformer set — `idle`, `walk_1..3`, `jump` — then packs adownloadable spritesheet, atlas JSON, per-frame PNGs and a walk-cycle GIF.## How it works- **Model:** a 3.5M-parameter U-Net (`autosprite/model.py`) that sees whichever poses you gaveand predicts the missing ones. Its output head is a *palette pointer*: each pixel picks one ofthe colors already in your frames (or transparency), so results stay crisp and on-palette.- **Data:** no scraped sprites. `autosprite/synth.py` procedurally generates unlimited side-viewcharacters (random proportions, palettes, hair, hats, shading, outlines, walk styles) renderedconsistently in all five poses. Training hides random poses and learns to reconstruct them.- **Runtime:** exported to ONNX and run with `onnxruntime` on CPU — about a hundredmilliseconds per sheet, no GPU required.- **Input cleanup:** upscaled art (e.g. 320x320 of an 18x18 sprite) is detected and resampledback to its native grid with nearest-neighbor, flat backgrounds are removed, and near-duplicateshades are merged.## Run locally```bashpip install -r requirements.txt gradiopython app.py```## Train your own```bashpip install torch onnxpython train.py --steps 16000 --out weights/autosprite.ptpython export_onnx.py weights/autosprite.pt weights/autosprite.onnxpython evaluate.py examples/alan --out eval_alan.png```Training uses Apple `mps`, CUDA, or CPU automatically.## Limits- One side-view platformer pose set; sprites larger than 24x24 (e.g. big Mario at 16x32) are notsupported yet.- The model has only ever seen procedural characters, so very stylized art (3/4 views,big silhouette changes between frames) gets approximate frames that are worth touching up.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""AutoSprite Gradio app: upload a few frames, get a full spritesheet back."""
from __future__ import annotations
import reimport tempfilefrom pathlib import Path
import gradio as grimport numpy as np
from autosprite import POSESfrom autosprite.inference import SpriteCompleterfrom autosprite.preprocess import prepare_framesfrom autosprite.sheet import build_bundle
ROOT = Path(__file__).parentMODEL_PATH = ROOT / "weights" / "autosprite.onnx"EXAMPLES = ROOT / "examples"
completer = SpriteCompleter(MODEL_PATH)
LABELS = { "idle": "Idle", "walk_1": "Walk 1", "walk_2": "Walk 2", "walk_3": "Walk 3", "jump": "Jump",}
CSS = """img { image-rendering: pixelated; image-rendering: crisp-edges; }.sprite-input img { width: 100% !important; height: 100% !important; object-fit: contain; }#title { text-align: center; }"""
def _safe_name(name: str) -> str: cleaned = re.sub(r"[^A-Za-z0-9_-]+", "_", name.strip()).strip("_") return cleaned or "sprite"
def generate(*args): *images, name, scale, fps, sequential = args if all(img is None for img in images): raise gr.Error("Upload at least one frame (Idle is the best single frame to start from).") try: frames = prepare_frames([None if img is None else np.asarray(img) for img in images]) except ValueError as err: raise gr.Error(str(err)) from err
completed = completer.complete(frames, sequential=sequential) out_dir = Path(tempfile.mkdtemp(prefix="autosprite_")) paths = build_bundle(completed, out_dir, _safe_name(name), int(scale), int(fps))
h, w = completed[0].shape[:2] made = [LABELS[p] for p, f in zip(POSES, frames) if f is None] kept = [LABELS[p] for p, f in zip(POSES, frames) if f is not None] summary = ( f"**{w}x{h}** sprite. You gave: {', '.join(kept)}. " + (f"AI generated: {', '.join(made)}." if made else "Nothing to generate; all poses were provided.") ) return str(paths["sheet"]), str(paths["gif"]), str(paths["zip"]), summary
def _example(folder: str, poses: tuple[str, ...]) -> list: return [str(EXAMPLES / folder / f"{p}.png") if p in poses else None for p in POSES]
with gr.Blocks(title="AutoSprite") as demo: gr.Markdown( "# AutoSprite\n" "Drop in as few as **one** pixel-art frame (16x16 or 18x18 work best, up to 24x24, upscaled " "art is detected automatically) and a small CPU model fills in the rest of the " "idle / walk / jump set using only your sprite's own colors.", elem_id="title", ) with gr.Row(): inputs = [ gr.Image( label=LABELS[p], type="numpy", image_mode="RGBA", sources=["upload", "clipboard"], height=180, elem_classes="sprite-input", ) for p in POSES ] with gr.Row(): name = gr.Textbox(value="player", label="Name", scale=2) scale = gr.Slider(1, 16, value=8, step=1, label="Export scale") fps = gr.Slider(2, 20, value=8, step=1, label="Walk GIF FPS") sequential = gr.Checkbox(value=True, label="Generate one frame at a time (more consistent)") button = gr.Button("Generate spritesheet", variant="primary") summary = gr.Markdown() with gr.Row(): sheet = gr.Image(label="Spritesheet", type="filepath", interactive=False, scale=3) gif = gr.Image(label="Walk cycle", type="filepath", interactive=False, scale=1) download = gr.File(label="Download (sheet PNGs, atlas JSON, frames, GIF)")
gr.Examples( examples=[ _example("alan", ("idle",)), _example("alan", ("idle", "walk_1")), _example("alan", ("idle", "walk_1", "jump")), ], inputs=inputs, label="Examples (Alan from AlanPark, 18x18)", )
button.click(generate, [*inputs, name, scale, fps, sequential], [sheet, gif, download, summary])
if __name__ == "__main__": demo.launch(css=CSS)123456789"""AutoSprite: turn a few consistent pixel-art frames into a full spritesheet."""
POSES: tuple[str, ...] = ("idle", "walk_1", "walk_2", "walk_3", "jump")NUM_POSES = len(POSES)
# Every sprite is placed on a fixed square canvas (bottom-aligned, horizontally centered)# before it goes through the network, so sprites up to CANVAS x CANVAS are supported.CANVAS = 24MAX_PALETTE = 32123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Turn a partial set of RGBA frames into the network's input tensors (numpy only).
The same code path is used for training and inference so the model always seesidentically prepared inputs."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from . import CANVAS, MAX_PALETTE, NUM_POSES
IN_CHANNELS = NUM_POSES * 4 + NUM_POSES + 3
@dataclassclass Encoded: x: np.ndarray # (IN_CHANNELS, CANVAS, CANVAS) float32 palmask: np.ndarray # (MAX_PALETTE, CANVAS, CANVAS) float32 palrgb: np.ndarray # (MAX_PALETTE, 3) float32 in [0, 1] palvalid: np.ndarray # (MAX_PALETTE,) float32, 1 for real palette slots palette: np.ndarray # (n, 3) uint8, the colors behind the valid slots width: int height: int top: int left: int
def canvas_offset(width: int, height: int) -> tuple[int, int]: """Sprites sit bottom-aligned and horizontally centered on the canvas.""" return CANVAS - height, (CANVAS - width) // 2
def extract_palette(frames: list[np.ndarray | None]) -> np.ndarray: """Opaque colors used by the given frames, most frequent first, capped at MAX_PALETTE.""" pixels = [f[f[..., 3] > 0][:, :3] for f in frames if f is not None] if not pixels or sum(len(p) for p in pixels) == 0: return np.zeros((0, 3), np.uint8) colors, counts = np.unique(np.concatenate(pixels), axis=0, return_counts=True) return colors[np.argsort(-counts, kind="stable")][:MAX_PALETTE].astype(np.uint8)
def nearest_palette_index(rgb: np.ndarray, palette: np.ndarray) -> np.ndarray: d = ((rgb[..., None, :].astype(np.int32) - palette[None].astype(np.int32)) ** 2).sum(-1) return d.argmin(-1)
def encode(frames: list[np.ndarray | None]) -> Encoded: """Encode up to NUM_POSES frames (None for missing poses); all given frames share a size.""" given = [f for f in frames if f is not None] if not given: raise ValueError("At least one frame is required.") height, width = given[0].shape[:2] if width > CANVAS or height > CANVAS: raise ValueError(f"Sprites must be at most {CANVAS}x{CANVAS} pixels, got {width}x{height}.") top, left = canvas_offset(width, height) region = (slice(top, top + height), slice(left, left + width))
palette = extract_palette(frames) n = len(palette) x = np.zeros((IN_CHANNELS, CANVAS, CANVAS), np.float32) palmask = np.zeros((MAX_PALETTE, CANVAS, CANVAS), np.float32)
for k, frame in enumerate(frames): if frame is None: continue alpha = (frame[..., 3] > 0).astype(np.float32) x[k * 4 : k * 4 + 3][(slice(None), *region)] = frame[..., :3].transpose(2, 0, 1) / 255.0 * alpha x[k * 4 + 3][region] = alpha x[NUM_POSES * 4 + k] = 1.0 if n: idx = nearest_palette_index(frame[..., :3], palette) for p in range(n): palmask[p][region] += (idx == p) & (alpha > 0)
palmask /= len(given) ys, xs = np.mgrid[0:CANVAS, 0:CANVAS].astype(np.float32) / (CANVAS - 1) base = NUM_POSES * 5 x[base], x[base + 1] = ys, xs x[base + 2][region] = 1.0
palrgb = np.zeros((MAX_PALETTE, 3), np.float32) palrgb[:n] = palette / 255.0 palvalid = np.zeros(MAX_PALETTE, np.float32) palvalid[:n] = 1.0 return Encoded(x, palmask, palrgb, palvalid, palette, width, height, top, left)
def labels_for(frame: np.ndarray, enc: Encoded) -> np.ndarray: """Per-canvas-pixel class targets: 0 = transparent, 1 + i = palette[i].""" out = np.zeros((CANVAS, CANVAS), np.int64) alpha = frame[..., 3] > 0 if len(enc.palette): idx = nearest_palette_index(frame[..., :3], enc.palette) + 1 out[enc.top : enc.top + enc.height, enc.left : enc.left + enc.width] = np.where(alpha, idx, 0) return out
def decode(classes: np.ndarray, enc: Encoded) -> np.ndarray: """Turn a (CANVAS, CANVAS) class map back into an RGBA sprite of the original size.""" crop = classes[enc.top : enc.top + enc.height, enc.left : enc.left + enc.width] rgba = np.zeros((enc.height, enc.width, 4), np.uint8) opaque = crop > 0 rgba[opaque, :3] = enc.palette[crop[opaque] - 1] rgba[opaque, 3] = 255 return rgba1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""CPU inference with onnxruntime: fill in the missing poses of a sprite set."""
from __future__ import annotations
from pathlib import Path
import numpy as npimport onnxruntime as ort
from . import NUM_POSESfrom .features import decode, encode
class SpriteCompleter: def __init__(self, model_path: str | Path, threads: int = 2): options = ort.SessionOptions() options.intra_op_num_threads = threads options.inter_op_num_threads = 1 self.session = ort.InferenceSession(str(model_path), options, providers=["CPUExecutionProvider"])
def _logits(self, frames: list[np.ndarray | None]): enc = encode(frames) feeds = { "x": enc.x[None], "palmask": enc.palmask[None], "palrgb": enc.palrgb[None], "palvalid": enc.palvalid[None], } return self.session.run(None, feeds)[0][0], enc
def complete(self, frames: list[np.ndarray | None], sequential: bool = True) -> list[np.ndarray]: """Return all poses; provided frames pass through untouched.
With ``sequential`` the missing poses are generated one at a time and each new frame is fed back as an input, which keeps generated frames consistent with each other instead of only with the uploads. """ if len(frames) != NUM_POSES: raise ValueError(f"Expected {NUM_POSES} slots, got {len(frames)}.") result = list(frames) missing = [k for k, f in enumerate(frames) if f is None] if not missing: return result if not sequential: logits, enc = self._logits(result) for k in missing: result[k] = decode(logits[k].argmax(0), enc) return result
while missing: logits, enc = self._logits(result) # Commit the pose the model is most confident about first. probs = np.exp(logits - logits.max(1, keepdims=True)) probs /= probs.sum(1, keepdims=True) confidence = {k: float(probs[k].max(0).mean()) for k in missing} k = max(confidence, key=confidence.get) result[k] = decode(logits[k].argmax(0), enc) missing.remove(k) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""The AutoSprite network: a small U-Net with a palette-pointer output head.
Instead of regressing RGB values (which blurs pixel art), every output pixel picks oneof the colors already present in the input frames, or transparency. Palette entriesare embedded from their RGB value plus the encoder features pooled over the pixelswhere that color appears, so the network can tell "hair brown" from "shoe brown"."""
from __future__ import annotations
import torchfrom torch import nnfrom torch.nn import functional as F
from . import NUM_POSESfrom .features import IN_CHANNELS
def _norm(channels: int) -> nn.GroupNorm: return nn.GroupNorm(8, channels)
class ResBlock(nn.Module): def __init__(self, channels: int, dilation: int = 1): super().__init__() self.body = nn.Sequential( _norm(channels), nn.SiLU(), nn.Conv2d(channels, channels, 3, padding=dilation, dilation=dilation), _norm(channels), nn.SiLU(), nn.Conv2d(channels, channels, 3, padding=1), )
def forward(self, x: torch.Tensor) -> torch.Tensor: return x + self.body(x)
class GlobalContext(nn.Module): """Mixes a spatially pooled summary back into every position."""
def __init__(self, channels: int): super().__init__() self.proj = nn.Conv2d(channels * 2, channels, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor: pooled = x.mean(dim=(2, 3), keepdim=True).expand_as(x) return x + self.proj(torch.cat([x, pooled], dim=1))
class AutoSpriteNet(nn.Module): def __init__(self, width: int = 48, embed: int = 32): super().__init__() c1, c2, c3 = width, width * 2, width * 4 self.embed = embed self.stem = nn.Conv2d(IN_CHANNELS, c1, 3, padding=1) self.enc1 = nn.Sequential(ResBlock(c1), ResBlock(c1, 2)) self.down1 = nn.Conv2d(c1, c2, 3, stride=2, padding=1) self.enc2 = nn.Sequential(ResBlock(c2), ResBlock(c2, 2)) self.down2 = nn.Conv2d(c2, c3, 3, stride=2, padding=1) self.mid = nn.Sequential(ResBlock(c3), GlobalContext(c3), ResBlock(c3), GlobalContext(c3), ResBlock(c3)) self.up2 = nn.Conv2d(c3 + c2, c2, 3, padding=1) self.dec2 = nn.Sequential(ResBlock(c2), ResBlock(c2)) self.up1 = nn.Conv2d(c2 + c1, c1, 3, padding=1) self.dec1 = nn.Sequential(ResBlock(c1), ResBlock(c1)) self.pixel_head = nn.Sequential(_norm(c1), nn.SiLU(), nn.Conv2d(c1, NUM_POSES * embed, 1))
self.palette_mlp = nn.Sequential( nn.Linear(c1 + c1 + 3 + 3, 128), nn.SiLU(), nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, embed + 1), ) self.transparent = nn.Parameter(torch.zeros(embed + 1))
def forward( self, x: torch.Tensor, palmask: torch.Tensor, palrgb: torch.Tensor, palvalid: torch.Tensor, ) -> torch.Tensor: """Return logits of shape (B, NUM_POSES, 1 + P, H, W); class 0 is transparent.""" b, _, h, w = x.shape s1 = self.enc1(self.stem(x)) s2 = self.enc2(self.down1(s1)) m = self.mid(self.down2(s2)) u2 = F.interpolate(m, size=s2.shape[-2:], mode="nearest") d2 = self.dec2(self.up2(torch.cat([u2, s2], dim=1))) u1 = F.interpolate(d2, size=s1.shape[-2:], mode="nearest") d1 = self.dec1(self.up1(torch.cat([u1, s1], dim=1)))
pix = self.pixel_head(d1).view(b, NUM_POSES, self.embed, h, w)
area = palmask.sum(dim=(2, 3)) denom = area.clamp(min=1e-3).unsqueeze(-1) enc_feat = torch.einsum("bchw,bphw->bpc", s1, palmask) / denom dec_feat = torch.einsum("bchw,bphw->bpc", d1, palmask) / denom ys = x[:, -3] xs = x[:, -2] mean_y = torch.einsum("bhw,bphw->bp", ys, palmask) / denom.squeeze(-1) mean_x = torch.einsum("bhw,bphw->bp", xs, palmask) / denom.squeeze(-1) stats = torch.stack([mean_y, mean_x, area / (h * w)], dim=-1) pal = self.palette_mlp(torch.cat([enc_feat, dec_feat, palrgb, stats], dim=-1))
trans = self.transparent.view(1, 1, -1).expand(b, 1, -1) table = torch.cat([trans, pal], dim=1) # (B, 1 + P, embed + 1) vec, bias = table[..., : self.embed], table[..., self.embed]
logits = torch.einsum("bkdhw,bpd->bkphw", pix, vec) / (self.embed**0.5) logits = logits + bias.view(b, 1, -1, 1, 1) valid = torch.cat([torch.ones_like(palvalid[:, :1]), palvalid], dim=1) return logits.masked_fill(valid.view(b, 1, -1, 1, 1) < 0.5, -1e4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Clean up user-uploaded sprites so they match what the model was trained on."""
from __future__ import annotations
from collections import deque
import numpy as npfrom PIL import Image
from . import CANVAS
ALPHA_THRESHOLD = 128COLOR_MERGE_DISTANCE = 14.0MAX_NATIVE = 64
def to_rgba_array(image: Image.Image | np.ndarray) -> np.ndarray: if isinstance(image, np.ndarray): image = Image.fromarray(image) arr = np.array(image.convert("RGBA"), dtype=np.uint8) arr[..., 3] = np.where(arr[..., 3] >= ALPHA_THRESHOLD, 255, 0) arr[arr[..., 3] == 0] = 0 return arr
def remove_flat_background(arr: np.ndarray, tolerance: int = 12) -> np.ndarray: """If the image has no transparency, flood-fill the border color away.""" if (arr[..., 3] == 0).any(): return arr h, w = arr.shape[:2] corners = np.array([arr[0, 0], arr[0, -1], arr[-1, 0], arr[-1, -1]])[:, :3].astype(int) values, counts = np.unique(corners, axis=0, return_counts=True) bg = values[counts.argmax()] close = np.abs(arr[..., :3].astype(int) - bg).max(-1) <= tolerance
seen = np.zeros((h, w), bool) queue = deque((y, x) for y in range(h) for x in (0, w - 1)) + deque((y, x) for x in range(w) for y in (0, h - 1)) out = arr.copy() while queue: y, x = queue.popleft() if seen[y, x] or not close[y, x]: continue seen[y, x] = True out[y, x] = 0 for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)): if 0 <= ny < h and 0 <= nx < w and not seen[ny, nx]: queue.append((ny, nx)) return out
def _sample_grid(arr: np.ndarray, rows: int, cols: int) -> np.ndarray: h, w = arr.shape[:2] ys = ((np.arange(rows) + 0.5) * h / rows).astype(int) xs = ((np.arange(cols) + 0.5) * w / cols).astype(int) return arr[ys][:, xs]
def _grid_error(arr: np.ndarray, rows: int, cols: int) -> float: small = _sample_grid(arr, rows, cols) h, w = arr.shape[:2] ys = np.minimum((np.arange(h) * rows / h).astype(int), rows - 1) xs = np.minimum((np.arange(w) * cols / w).astype(int), cols - 1) back = small[ys][:, xs].astype(int) diff = np.abs(back - arr.astype(int)).max(-1) > 24 return float(diff.mean())
def detect_native_size(arr: np.ndarray) -> tuple[int, int]: """Find the smallest pixel grid that reproduces an upscaled sprite (e.g. 320x320 -> 18x18).""" h, w = arr.shape[:2] if max(h, w) <= CANVAS: return h, w aspect = w / h best = (h, w) for rows in range(8, min(h, MAX_NATIVE) + 1): cols = max(1, round(rows * aspect)) if abs(cols / rows - aspect) > 0.08: continue # Non-integer scale factors (320 / 18 = 17.8) leave thin seams, so allow a little error. if _grid_error(arr, rows, cols) < 0.02: best = (rows, cols) break return best
def to_native(arr: np.ndarray) -> np.ndarray: rows, cols = detect_native_size(arr) if (rows, cols) == arr.shape[:2]: return arr return _sample_grid(arr, rows, cols)
def merge_similar_colors(frames: list[np.ndarray], distance: float = COLOR_MERGE_DISTANCE) -> list[np.ndarray]: """Snap near-identical shades (e.g. 255,170,116 vs 254,173,115) to one color across all frames.""" opaque = np.concatenate([f[f[..., 3] > 0][:, :3] for f in frames]) if frames else np.zeros((0, 3)) if len(opaque) == 0: return frames colors, counts = np.unique(opaque, axis=0, return_counts=True) order = np.argsort(-counts, kind="stable") reps: list[np.ndarray] = [] mapping: dict[tuple[int, ...], np.ndarray] = {} for i in order: c = colors[i].astype(float) match = next((r for r in reps if np.linalg.norm(r - c) <= distance), None) if match is None: reps.append(c) match = c mapping[tuple(colors[i])] = match.astype(np.uint8)
out = [] for f in frames: g = f.copy() mask = g[..., 3] > 0 g[mask, :3] = np.array([mapping[tuple(p)] for p in g[mask, :3]], np.uint8).reshape(-1, 3) out.append(g) return out
def crop_to_content(arr: np.ndarray) -> np.ndarray: ys, xs = np.nonzero(arr[..., 3]) if len(ys) == 0: return arr return arr[ys.min() : ys.max() + 1, xs.min() : xs.max() + 1]
def pad_to(arr: np.ndarray, height: int, width: int) -> np.ndarray: """Pad bottom-aligned and horizontally centered, matching how sprites sit on the canvas.""" h, w = arr.shape[:2] out = np.zeros((height, width, 4), np.uint8) top, left = height - h, (width - w) // 2 out[top : top + h, left : left + w] = arr return out
def prepare_frames(images: list[Image.Image | np.ndarray | None]) -> list[np.ndarray | None]: """Normalize uploaded frames into same-size, palette-merged RGBA arrays (None stays None).""" cleaned: list[np.ndarray | None] = [] for image in images: if image is None: cleaned.append(None) continue arr = remove_flat_background(to_rgba_array(image)) arr = to_native(arr) if max(arr.shape[:2]) > CANVAS: arr = crop_to_content(arr) if max(arr.shape[:2]) > CANVAS: raise ValueError( f"A frame is {arr.shape[1]}x{arr.shape[0]} after cleanup; AutoSprite supports up to " f"{CANVAS}x{CANVAS} (16x16 and 18x18 sprites are the sweet spot)." ) cleaned.append(arr)
given = [f for f in cleaned if f is not None] if not given: raise ValueError("Upload at least one frame.") height = max(f.shape[0] for f in given) width = max(f.shape[1] for f in given) merged = iter(merge_similar_colors([pad_to(f, height, width) for f in given])) return [None if f is None else next(merged) for f in cleaned]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Pack frames into a spritesheet plus the files a game engine needs."""
from __future__ import annotations
import ioimport jsonimport zipfilefrom pathlib import Path
import numpy as npfrom PIL import Image
from . import POSES
ANIMATIONS = {"idle": ["idle"], "walk": ["walk_1", "walk_2", "walk_3"], "jump": ["jump"]}
def pack_strip(frames: list[np.ndarray], gap: int = 0) -> np.ndarray: h, w = frames[0].shape[:2] sheet = np.zeros((h, len(frames) * w + (len(frames) - 1) * gap, 4), np.uint8) for i, f in enumerate(frames): x = i * (w + gap) sheet[:, x : x + w] = f return sheet
def upscale(arr: np.ndarray, scale: int) -> Image.Image: img = Image.fromarray(arr, "RGBA") return img.resize((img.width * scale, img.height * scale), Image.Resampling.NEAREST)
def atlas_json(width: int, height: int, image_name: str) -> dict: """TexturePacker "hash" layout, readable by Phaser, PixiJS, Godot importers and friends.""" return { "frames": { pose: { "frame": {"x": i * width, "y": 0, "w": width, "h": height}, "rotated": False, "trimmed": False, "spriteSourceSize": {"x": 0, "y": 0, "w": width, "h": height}, "sourceSize": {"w": width, "h": height}, } for i, pose in enumerate(POSES) }, "animations": ANIMATIONS, "meta": { "app": "AutoSprite", "image": image_name, "format": "RGBA8888", "size": {"w": width * len(POSES), "h": height}, "scale": "1", }, }
def animated_gif(frames: list[np.ndarray], scale: int, fps: int) -> bytes: """Transparent looping GIF; index 0 of the shared palette is transparency.""" colors = np.unique(np.concatenate([f[f[..., 3] > 0][:, :3] for f in frames]), axis=0)[:255] lookup = {tuple(c): i + 1 for i, c in enumerate(colors)} flat_palette = [0, 0, 0] + colors.flatten().tolist() images = [] for f in frames: idx = np.zeros(f.shape[:2], np.uint8) for (y, x) in zip(*np.nonzero(f[..., 3])): idx[y, x] = lookup.get(tuple(f[y, x, :3]), 1) img = Image.fromarray(idx, "P") img.putpalette(flat_palette) images.append(img.resize((img.width * scale, img.height * scale), Image.Resampling.NEAREST)) buf = io.BytesIO() images[0].save( buf, format="GIF", save_all=True, append_images=images[1:], duration=max(20, round(1000 / fps)), loop=0, transparency=0, disposal=2, ) return buf.getvalue()
def _png(img: Image.Image) -> bytes: buf = io.BytesIO() img.save(buf, format="PNG") return buf.getvalue()
def build_bundle(frames: list[np.ndarray], out_dir: Path, name: str, scale: int, fps: int) -> dict[str, Path]: """Write sheet PNGs, per-frame PNGs, a walk GIF, an atlas JSON, and a zip of everything.""" out_dir.mkdir(parents=True, exist_ok=True) h, w = frames[0].shape[:2] strip = pack_strip(frames) by_pose = dict(zip(POSES, frames)) walk = [by_pose[p] for p in ANIMATIONS["walk"]]
files: dict[str, bytes] = { f"{name}_sheet.png": _png(Image.fromarray(strip, "RGBA")), f"{name}_sheet@{scale}x.png": _png(upscale(strip, scale)), f"{name}_sheet.json": json.dumps(atlas_json(w, h, f"{name}_sheet.png"), indent=2).encode(), f"{name}_walk@{scale}x.gif": animated_gif(walk, scale, fps), } for pose, frame in by_pose.items(): files[f"frames/{pose}.png"] = _png(Image.fromarray(frame, "RGBA"))
zip_path = out_dir / f"{name}_autosprite.zip" with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for arcname, data in files.items(): zf.writestr(arcname, data)
paths = {"zip": zip_path} for key, arcname in (("sheet", f"{name}_sheet@{scale}x.png"), ("gif", f"{name}_walk@{scale}x.gif")): path = out_dir / arcname path.write_bytes(files[arcname]) paths[key] = path return paths123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413"""Procedural side-view pixel-art characters with a consistent 5-pose animation set.
Each character is sampled once (proportions, colors, hair, accessories, animationstyle) and then rendered in every pose from those same parameters, so the frames ofone character are consistent with each other the way hand-drawn sprites are.The generator is the only source of training data for the model."""
from __future__ import annotations
import colorsysimport mathfrom dataclasses import dataclass, field
import numpy as np
from . import POSES
# Part ids used while drawing; each one is mapped to a color per character.EMPTY = 0HAIR = 1SKIN = 2SKIN_DARK = 3SHIRT = 4SHIRT_DARK = 5PANTS = 6PANTS_DARK = 7SHOES = 8SHOES_DARK = 9EYE = 10ACCENT = 11OUTLINE = 12HAT = 13NUM_PARTS = 14
@dataclassclass Limb: """Horizontal offset of the limb's tip relative to its root and how far it is lifted."""
dx: int = 0 lift: int = 0 style: str = "hang"
@dataclassclass PoseSpec: body_dy: int = 0 front_leg: Limb = field(default_factory=Limb) back_leg: Limb = field(default_factory=Limb) front_arm: Limb = field(default_factory=Limb) back_arm: Limb = field(default_factory=Limb)
@dataclassclass Character: width: int height: int colors: np.ndarray # (NUM_PARTS, 3) uint8 cx: int ground: int head_w: int head_h: int head_fwd: int neck_overlap: int torso_w: int torso_h: int leg_len: int leg_w: int leg_gap: int foot_h: int toe: int arm_len: int arm_w: int arm_off: int sleeve_len: int shoulder_drop: int hair_top: int hair_back: int hair_back_len: int tufts: np.ndarray fringe: np.ndarray round_top: bool round_bottom: bool hat_h: int brim: int eye_back: int eye_drop: int eye_h: int second_eye_gap: int nose: bool mouth: bool ear: bool torso_shade: bool belt: bool overalls: bool dark_back_limbs: bool outline: bool poses: dict[str, PoseSpec]
def _hsv(h: float, s: float, v: float) -> np.ndarray: r, g, b = colorsys.hsv_to_rgb(h % 1.0, min(max(s, 0.0), 1.0), min(max(v, 0.0), 1.0)) return np.array([r * 255, g * 255, b * 255]).round().astype(np.uint8)
def _darker(rgb: np.ndarray, rng: np.random.Generator) -> np.ndarray: h, s, v = colorsys.rgb_to_hsv(*(rgb / 255.0)) # Pixel artists usually hue-shift shadows toward red/purple rather than just darkening. return _hsv(h + rng.uniform(-0.04, 0.02), s * rng.uniform(1.0, 1.25) + 0.05, v * rng.uniform(0.55, 0.8))
def _random_color(rng: np.random.Generator, v_range=(0.25, 0.95), s_range=(0.3, 0.9)) -> np.ndarray: return _hsv(rng.random(), rng.uniform(*s_range), rng.uniform(*v_range))
def _sample_colors(rng: np.random.Generator) -> np.ndarray: c = np.zeros((NUM_PARTS, 3), np.uint8) if rng.random() < 0.85: c[SKIN] = _hsv(rng.uniform(0.03, 0.1), rng.uniform(0.25, 0.6), rng.uniform(0.45, 1.0)) else: c[SKIN] = _random_color(rng, (0.5, 0.95)) c[HAIR] = _random_color(rng, (0.15, 0.9)) c[SHIRT] = _random_color(rng) c[PANTS] = _random_color(rng) c[SHOES] = _random_color(rng, (0.15, 0.8)) c[HAT] = _random_color(rng) c[ACCENT] = _random_color(rng) c[EYE] = _hsv(rng.random(), rng.uniform(0.2, 0.8), rng.uniform(0.03, 0.3)) c[OUTLINE] = _hsv(rng.random(), rng.uniform(0.2, 0.7), rng.uniform(0.02, 0.2))
# Real sprites reuse colors across parts all the time (SMB1 Mario: cap = shirt, hair = shoes). if rng.random() < 0.25: c[PANTS] = c[SHIRT] if rng.random() < 0.3: c[SHOES] = c[HAIR] if rng.random() < 0.4: c[HAT] = c[SHIRT] if rng.random() < 0.2: c[EYE] = c[HAIR]
c[SKIN_DARK] = _darker(c[SKIN], rng) c[SHIRT_DARK] = _darker(c[SHIRT], rng) c[PANTS_DARK] = _darker(c[PANTS], rng) c[SHOES_DARK] = _darker(c[SHOES], rng) return c
def _walk_pose(i: int, phase: float, stride: int, lift: int, bob: int, swing: int) -> PoseSpec: theta = 2 * math.pi * (phase + i / 3) cos, sin = math.cos(theta), math.sin(theta) leg_dx = round(stride * cos) arm_dx = round(swing * cos) return PoseSpec( body_dy=-round(bob * (1 - abs(cos))), front_leg=Limb(leg_dx, round(lift * max(0.0, sin))), back_leg=Limb(-leg_dx, round(lift * max(0.0, -sin))), front_arm=Limb(-arm_dx), back_arm=Limb(arm_dx), )
def _sample_poses(rng: np.random.Generator, leg_len: int, leg_w: int) -> dict[str, PoseSpec]: stride = int(rng.integers(1, min(3, leg_w + 1) + 1)) lift = int(rng.integers(0, min(2, leg_len) + 1)) bob = int(rng.integers(0, 2)) swing = int(rng.integers(1, 3)) phase = float(rng.choice([0.0, 1 / 6, 1 / 4])) spread = int(rng.choice([0, 0, 1]))
poses = { "idle": PoseSpec(front_leg=Limb(spread), back_leg=Limb(-spread)), } for i in range(3): poses[f"walk_{i + 1}"] = _walk_pose(i, phase, stride, lift, bob, swing)
front_arm_style = rng.choice(["up", "up", "up", "forward", "swing"]) back_arm_style = rng.choice(["back", "hang"]) poses["jump"] = PoseSpec( body_dy=-int(rng.integers(0, 3)), front_leg=Limb(int(rng.integers(1, 3)), int(rng.integers(1, min(2, leg_len) + 1))), back_leg=Limb(-int(rng.integers(0, 3)), int(rng.integers(0, 2))), front_arm=Limb(2 if front_arm_style == "swing" else 0, style=str(front_arm_style)), back_arm=Limb(-2 if back_arm_style == "hang" else 0, style=str(back_arm_style)), ) return poses
def sample_character(rng: np.random.Generator, width: int, height: int) -> Character: """Sample proportions, palette and animation style for one character.""" bottom_margin = int(rng.integers(0, 2)) top_margin = int(rng.integers(1, 3)) avail = height - top_margin - bottom_margin
head_h = int(np.clip(round(avail * rng.uniform(0.36, 0.55)), 4, 11)) rest = avail - head_h leg_part = int(np.clip(round(rest * rng.uniform(0.35, 0.55)), 2, rest - 2)) foot_h = 2 if (leg_part >= 4 and rng.random() < 0.35) else 1 leg_len = max(1, leg_part - foot_h) neck_overlap = int(rng.integers(0, 2)) torso_h = max(2, rest - leg_len - foot_h + neck_overlap)
head_w = int(np.clip(round(head_h * rng.uniform(0.9, 1.4)), 5, width - 3)) torso_w = int(np.clip(round(head_w * rng.uniform(0.5, 1.05)), 3, width - 4)) leg_w = 2 if torso_w < 7 else int(rng.integers(2, 4)) arm_w = 1 if torso_w < 6 else int(rng.integers(1, 3)) arm_len = int(np.clip(torso_h + rng.integers(-1, 2), 2, 5))
hair_top = int(rng.integers(1, max(2, head_h // 2))) hat = rng.random() < 0.3
return Character( width=width, height=height, colors=_sample_colors(rng), cx=width // 2 + int(rng.integers(-1, 2)), ground=height - 1 - bottom_margin, head_w=head_w, head_h=head_h, head_fwd=int(rng.integers(0, 2)), neck_overlap=neck_overlap, torso_w=torso_w, torso_h=torso_h, leg_len=leg_len, leg_w=leg_w, leg_gap=int(rng.integers(0, 2)), foot_h=foot_h, toe=int(rng.integers(0, 3)), arm_len=arm_len, arm_w=arm_w, arm_off=int(rng.integers(0, max(1, torso_w // 2 + 1))), sleeve_len=int(rng.integers(0, 3)), shoulder_drop=int(rng.integers(0, 2)), hair_top=hair_top, hair_back=int(rng.integers(0, max(1, head_w // 2))), hair_back_len=int(rng.integers(hair_top, head_h)), tufts=rng.random(head_w) < (0.35 if rng.random() < 0.5 else 0.0), fringe=rng.random(head_w) < rng.uniform(0.0, 0.5), round_top=rng.random() < 0.7, round_bottom=rng.random() < 0.5, hat_h=int(rng.integers(1, 3)) if hat else 0, brim=int(rng.integers(1, 4)) if hat else 0, eye_back=int(rng.integers(1, 4)), eye_drop=int(rng.integers(0, 2)), eye_h=int(rng.integers(1, 3)), second_eye_gap=int(rng.integers(2, 5)) if rng.random() < 0.4 else 0, nose=rng.random() < 0.5, mouth=rng.random() < 0.4, ear=rng.random() < 0.5, torso_shade=rng.random() < 0.5, belt=rng.random() < 0.3, overalls=rng.random() < 0.2, dark_back_limbs=rng.random() < 0.7, outline=rng.random() < 0.15, poses=_sample_poses(rng, leg_len, leg_w), )
class _Canvas: def __init__(self, width: int, height: int): self.g = np.zeros((height, width), np.uint8)
def rect(self, x: int, y: int, w: int, h: int, part: int) -> None: H, W = self.g.shape x0, y0, x1, y1 = max(x, 0), max(y, 0), min(x + w, W), min(y + h, H) if x0 < x1 and y0 < y1: self.g[y0:y1, x0:x1] = part
def px(self, x: int, y: int, part: int) -> None: self.rect(x, y, 1, 1, part)
def clear(self, x: int, y: int) -> None: self.rect(x, y, 1, 1, EMPTY)
def _draw_leg(cv: _Canvas, ch: Character, hip_x: int, hip_y: int, limb: Limb, back: bool) -> None: pants = PANTS_DARK if (back and ch.dark_back_limbs) else PANTS shoes = SHOES_DARK if (back and ch.dark_back_limbs) else SHOES rows = max(0, ch.leg_len - limb.lift) for r in range(rows): cv.rect(hip_x + round(limb.dx * (r + 1) / rows), hip_y + r, ch.leg_w, 1, pants) cv.rect(hip_x + limb.dx, hip_y + rows, ch.leg_w + ch.toe, ch.foot_h, shoes)
def _draw_arm(cv: _Canvas, ch: Character, sx: int, sy: int, limb: Limb, back: bool) -> None: sleeve = SHIRT_DARK if (back and ch.dark_back_limbs) else SHIRT skin = SKIN_DARK if (back and ch.dark_back_limbs) else SKIN n = ch.arm_len
def part(r: int) -> int: return sleeve if (r < ch.sleeve_len and r < n - 1) else skin
if limb.style == "up": for r in range(n): cv.rect(sx + 1 + r // 2, sy - 1 - r, ch.arm_w, 1, part(r)) elif limb.style in ("forward", "back"): direction = 1 if limb.style == "forward" else -1 for r in range(n): x = sx + direction * (r + 1) if direction > 0 else sx - r - 1 cv.rect(x, sy, 1, ch.arm_w, part(r)) else: for r in range(n): cv.rect(sx + round(limb.dx * (r + 1) / n), sy + r, ch.arm_w, 1, part(r))
def _draw_head(cv: _Canvas, ch: Character, hx: int, hy: int) -> None: w, h = ch.head_w, ch.head_h cv.rect(hx, hy, w, h, SKIN) top = max(ch.hair_top, ch.hat_h) cv.rect(hx, hy, w, ch.hair_top, HAIR) cv.rect(hx, hy, ch.hair_back, ch.hair_back_len, HAIR) for i in range(w): if ch.tufts[i] and ch.hat_h == 0: cv.px(hx + i, hy - 1, HAIR) if ch.fringe[i] and i >= ch.hair_back: cv.px(hx + i, hy + ch.hair_top, HAIR) if ch.hat_h: cv.rect(hx, hy, w, ch.hat_h, HAT) cv.rect(hx + w, hy + ch.hat_h - 1, ch.brim, 1, HAT)
ex = hx + w - 1 - ch.eye_back ey = hy + top + 1 + ch.eye_drop cv.rect(ex, ey, 1, ch.eye_h, EYE) if ch.second_eye_gap: cv.rect(ex - ch.second_eye_gap, ey, 1, ch.eye_h, EYE) if ch.nose: cv.px(hx + w, ey + ch.eye_h, SKIN) if ch.mouth and ey + ch.eye_h + 1 < hy + h: cv.rect(ex - 1, ey + ch.eye_h + 1, 2, 1, EYE) if ch.ear: cv.px(hx + max(ch.hair_back, 1), ey + 1, SKIN_DARK)
if ch.round_top: cv.clear(hx, hy) cv.clear(hx + w - 1, hy) if ch.round_bottom: cv.clear(hx, hy + h - 1) cv.clear(hx + w - 1, hy + h - 1)
def _draw_torso(cv: _Canvas, ch: Character, tx: int, ty: int) -> None: cv.rect(tx, ty, ch.torso_w, ch.torso_h, SHIRT) if ch.torso_shade: cv.rect(tx, ty, 1, ch.torso_h, SHIRT_DARK) if ch.overalls: low = max(1, ch.torso_h // 2) cv.rect(tx, ty + ch.torso_h - low, ch.torso_w, low, PANTS) cv.rect(tx + 1, ty, 1, ch.torso_h, PANTS) cv.rect(tx + ch.torso_w - 2, ty, 1, ch.torso_h, PANTS) if ch.belt: cv.rect(tx, ty + ch.torso_h - 1, ch.torso_w, 1, ACCENT)
def _add_outline(g: np.ndarray) -> np.ndarray: filled = g != EMPTY grown = filled.copy() grown[1:] |= filled[:-1] grown[:-1] |= filled[1:] grown[:, 1:] |= filled[:, :-1] grown[:, :-1] |= filled[:, 1:] out = g.copy() out[grown & ~filled] = OUTLINE return out
def render_pose(ch: Character, pose: str) -> np.ndarray: """Render one pose as a (height, width) array of part ids.""" spec = ch.poses[pose] cv = _Canvas(ch.width, ch.height)
feet_top = ch.ground - ch.foot_h + 1 hip_y = feet_top - ch.leg_len + spec.body_dy torso_y = hip_y - ch.torso_h head_y = torso_y - ch.head_h + ch.neck_overlap torso_x = ch.cx - ch.torso_w // 2 head_x = ch.cx - ch.head_w // 2 + ch.head_fwd shoulder_y = torso_y + ch.shoulder_drop front_arm_x = ch.cx + ch.arm_off back_arm_x = ch.cx - ch.arm_off - ch.arm_w front_hip_x = ch.cx + ch.leg_gap back_hip_x = ch.cx - ch.leg_w
_draw_arm(cv, ch, back_arm_x, shoulder_y, spec.back_arm, back=True) _draw_leg(cv, ch, back_hip_x, hip_y, spec.back_leg, back=True) _draw_leg(cv, ch, front_hip_x, hip_y, spec.front_leg, back=False) _draw_torso(cv, ch, torso_x, torso_y) _draw_head(cv, ch, head_x, head_y) _draw_arm(cv, ch, front_arm_x, shoulder_y, spec.front_arm, back=False)
return _add_outline(cv.g) if ch.outline else cv.g
def render_rgba(ch: Character) -> np.ndarray: """Render all poses as a (num_poses, height, width, 4) uint8 RGBA stack.""" frames = np.zeros((len(POSES), ch.height, ch.width, 4), np.uint8) for k, pose in enumerate(POSES): parts = render_pose(ch, pose) mask = parts != EMPTY frames[k, mask, :3] = ch.colors[parts[mask]] frames[k, mask, 3] = 255 return frames
def random_sprite_set(rng: np.random.Generator, width: int | None = None, height: int | None = None) -> np.ndarray: """Sample a character and return its RGBA frames for every pose.""" if width is None: width = int(rng.choice([16, 16, 18, 18, 14, 20, 22, 24, 17, 19])) if height is None: height = width if rng.random() < 0.7 else int(rng.integers(14, 25)) frames = render_rgba(sample_character(rng, width, height)) if rng.random() < 0.5: frames = frames[:, :, ::-1].copy() return frames12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Score the exported model on real sprite sets by hiding frames and comparing.
python evaluate.py examples/alan --out eval_alan.png"""
from __future__ import annotations
import argparsefrom pathlib import Path
import numpy as npfrom PIL import Image
from autosprite import POSESfrom autosprite.inference import SpriteCompleterfrom autosprite.preprocess import prepare_frames
SCENARIOS = { "idle only": ("idle",), "idle + walk_1": ("idle", "walk_1"), "idle + walk_1 + jump": ("idle", "walk_1", "jump"),}
def pixel_scores(pred: np.ndarray, truth: np.ndarray) -> tuple[float, float]: """Exact-pixel accuracy over the union of both silhouettes, and silhouette IoU.""" p, t = pred[..., 3] > 0, truth[..., 3] > 0 union = p | t same = union & p & t & (pred[..., :3] == truth[..., :3]).all(-1) return same.sum() / max(1, union.sum()), (p & t).sum() / max(1, union.sum())
def render(rows: list[list[np.ndarray]], scale: int = 8) -> Image.Image: h, w = rows[0][0].shape[:2] pad = 4 sheet = Image.new("RGBA", (len(rows[0]) * (w * scale + pad), len(rows) * (h * scale + pad)), (225, 225, 225, 255)) for r, row in enumerate(rows): for c, frame in enumerate(row): img = Image.fromarray(frame, "RGBA").resize((w * scale, h * scale), Image.Resampling.NEAREST) sheet.alpha_composite(img, (c * (w * scale + pad), r * (h * scale + pad))) return sheet
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("folder", type=Path) parser.add_argument("--model", type=Path, default=Path("weights/autosprite.onnx")) parser.add_argument("--out", type=Path) args = parser.parse_args()
truth = prepare_frames([Image.open(args.folder / f"{p}.png") for p in POSES]) completer = SpriteCompleter(args.model) rows = [truth] for label, given in SCENARIOS.items(): frames = [f if p in given else None for p, f in zip(POSES, truth)] pred = completer.complete(frames) scores = [pixel_scores(pr, tr) for p, pr, tr in zip(POSES, pred, truth) if p not in given] acc, iou = np.mean(scores, axis=0) print(f"{label:24s} pixel acc {acc:.3f} silhouette IoU {iou:.3f}") rows.append(pred) if args.out: render(rows).save(args.out) print(f"saved {args.out} (top row = ground truth)")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Export a trained checkpoint to ONNX so the app only needs onnxruntime on CPU.
python export_onnx.py weights/autosprite.pt weights/autosprite.onnx"""
from __future__ import annotations
import sysfrom pathlib import Path
import numpy as npimport onnxruntime as ortimport torch
from autosprite import CANVAS, MAX_PALETTEfrom autosprite.features import IN_CHANNELSfrom autosprite.model import AutoSpriteNet
def main(src: Path, dst: Path) -> None: ckpt = torch.load(src, map_location="cpu") model = AutoSpriteNet(width=ckpt["width"]).eval() model.load_state_dict(ckpt["model"])
inputs = ( torch.zeros(1, IN_CHANNELS, CANVAS, CANVAS), torch.zeros(1, MAX_PALETTE, CANVAS, CANVAS), torch.zeros(1, MAX_PALETTE, 3), torch.ones(1, MAX_PALETTE), ) dst.parent.mkdir(parents=True, exist_ok=True) torch.onnx.export( model, inputs, str(dst), input_names=["x", "palmask", "palrgb", "palvalid"], output_names=["logits"], opset_version=17, dynamo=False, )
rng = np.random.default_rng(0) feeds = [rng.random(t.shape, dtype=np.float32) for t in inputs] with torch.no_grad(): expected = model(*map(torch.from_numpy, feeds)).numpy() session = ort.InferenceSession(str(dst), providers=["CPUExecutionProvider"]) got = session.run(None, dict(zip(["x", "palmask", "palrgb", "palvalid"], feeds)))[0] print(f"exported {dst} ({dst.stat().st_size / 1e6:.1f} MB), max abs diff {np.abs(got - expected).max():.2e}")
if __name__ == "__main__": main(Path(sys.argv[1]), Path(sys.argv[2]))123numpypillowonnxruntime123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import jsonimport zipfile
import numpy as npfrom PIL import Image
from autosprite import CANVAS, NUM_POSESfrom autosprite.features import decode, encode, labels_forfrom autosprite.preprocess import detect_native_size, merge_similar_colors, prepare_frames, remove_flat_backgroundfrom autosprite.sheet import build_bundlefrom autosprite.synth import random_sprite_set
def _frames(seed: int = 0, size: int = 18) -> np.ndarray: return random_sprite_set(np.random.default_rng(seed), size, size)
def test_synthetic_set_shares_one_palette_across_poses(): frames = _frames() assert frames.shape == (NUM_POSES, 18, 18, 4) head_colors = [set(map(tuple, f[f[..., 3] > 0][:, :3])) for f in frames] assert len(set.union(*head_colors)) <= len(head_colors[0]) + 4
def test_encode_decode_roundtrip_reproduces_frame(): frames = list(_frames(3, 16)) enc = encode(frames) for frame in frames: assert np.array_equal(decode(labels_for(frame, enc), enc), frame)
def test_encode_places_sprite_bottom_centered(): enc = encode([_frames(1, 16)[0], None, None, None, None]) assert (enc.top, enc.left) == (CANVAS - 16, (CANVAS - 16) // 2) assert enc.x.shape[1:] == (CANVAS, CANVAS)
def test_detects_non_integer_upscale(): sprite = _frames(2, 18)[0] big = np.array(Image.fromarray(sprite).resize((320, 320), Image.Resampling.NEAREST)) assert detect_native_size(big) == (18, 18) restored = prepare_frames([big])[0] assert np.array_equal(restored[..., 3] > 0, sprite[..., 3] > 0)
def test_flat_background_is_removed_but_interior_kept(): arr = np.full((10, 10, 4), 255, np.uint8) arr[3:7, 3:7, :3] = (200, 0, 0) arr[4:6, 4:6, :3] = 255 # white enclosed by red must survive out = remove_flat_background(arr) assert out[0, 0, 3] == 0 and out[4, 4, 3] == 255 and out[3, 3, 3] == 255
def test_near_duplicate_colors_merge(): a = np.zeros((2, 2, 4), np.uint8) a[..., 3] = 255 a[0, :, :3] = (255, 170, 116) a[1, 0, :3] = (254, 173, 115) a[1, 1, :3] = (20, 20, 20) out = merge_similar_colors([a])[0] assert len(np.unique(out.reshape(-1, 4), axis=0)) == 2
def test_bundle_contains_engine_files(tmp_path): frames = list(_frames(4)) paths = build_bundle(frames, tmp_path, "hero", 4, 8) with zipfile.ZipFile(paths["zip"]) as zf: names = set(zf.namelist()) atlas = json.loads(zf.read("hero_sheet.json")) assert {"hero_sheet.png", "hero_sheet@4x.png", "hero_walk@4x.gif", "frames/jump.png"} <= names assert atlas["frames"]["walk_2"]["frame"] == {"x": 36, "y": 0, "w": 18, "h": 18} assert Image.open(paths["sheet"]).size == (18 * 5 * 4, 18 * 4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Train AutoSpriteNet on procedurally generated characters.
Every step draws fresh characters, hides a random subset of their poses, and asks thenetwork to reconstruct the hidden frames from the visible ones.
python train.py --steps 20000 --out weights/autosprite.pt"""
from __future__ import annotations
import argparseimport mathimport timefrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as Ffrom torch.utils.data import DataLoader, IterableDataset, get_worker_info
from autosprite import NUM_POSESfrom autosprite.features import encode, labels_forfrom autosprite.model import AutoSpriteNetfrom autosprite.synth import random_sprite_set
IGNORE = -100
def sample_visible(rng: np.random.Generator) -> np.ndarray: """Which poses the user "provided"; skewed toward very few frames, usually including idle.""" count = int(rng.choice([1, 2, 3, 4], p=[0.4, 0.3, 0.18, 0.12])) visible = np.zeros(NUM_POSES, bool) if rng.random() < 0.7: visible[0] = True count -= 1 hidden = np.flatnonzero(~visible) visible[rng.choice(hidden, size=count, replace=False)] = True return visible
def make_example(rng: np.random.Generator) -> dict[str, np.ndarray]: frames = random_sprite_set(rng) visible = sample_visible(rng) enc = encode([f if v else None for f, v in zip(frames, visible)]) labels = np.stack([labels_for(f, enc) for f in frames]) labels[visible] = IGNORE return { "x": enc.x, "palmask": enc.palmask, "palrgb": enc.palrgb, "palvalid": enc.palvalid, "labels": labels, }
class SyntheticSprites(IterableDataset): def __init__(self, seed: int): self.seed = seed
def __iter__(self): info = get_worker_info() worker = info.id if info else 0 rng = np.random.default_rng([self.seed, worker, int(time.time() * 1000) % 2**31]) while True: yield make_example(rng)
def fixed_batch(seed: int, n: int) -> dict[str, torch.Tensor]: rng = np.random.default_rng(seed) items = [make_example(rng) for _ in range(n)] return {k: torch.from_numpy(np.stack([it[k] for it in items])) for k in items[0]}
def loss_and_metrics(model: AutoSpriteNet, batch: dict[str, torch.Tensor]): logits = model(batch["x"], batch["palmask"], batch["palrgb"], batch["palvalid"]) labels = batch["labels"] b, k, c, h, w = logits.shape flat = logits.permute(0, 1, 3, 4, 2).reshape(-1, c) target = labels.reshape(-1) loss = F.cross_entropy(flat, target, ignore_index=IGNORE) with torch.no_grad(): pred = flat.argmax(-1) scored = target != IGNORE fg = scored & (target > 0) acc_fg = (pred[fg] == target[fg]).float().mean() union = scored & ((target > 0) | (pred > 0)) acc_union = (pred[union] == target[union]).float().mean() return loss, {"acc_fg": acc_fg.item(), "acc_union": acc_union.item()}
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--steps", type=int, default=20000) parser.add_argument("--batch", type=int, default=128) parser.add_argument("--lr", type=float, default=2e-3) parser.add_argument("--width", type=int, default=48) parser.add_argument("--workers", type=int, default=8) parser.add_argument("--out", type=Path, default=Path("weights/autosprite.pt")) parser.add_argument("--resume", type=Path) args = parser.parse_args()
device = torch.device("mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu") model = AutoSpriteNet(width=args.width).to(device) if args.resume: model.load_state_dict(torch.load(args.resume, map_location=device)["model"]) print(f"device={device} params={sum(p.numel() for p in model.parameters()) / 1e6:.2f}M", flush=True)
opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4) warmup = 500
def lr_at(step: int) -> float: if step < warmup: return args.lr * (step + 1) / warmup t = (step - warmup) / max(1, args.steps - warmup) return args.lr * (0.02 + 0.98 * 0.5 * (1 + math.cos(math.pi * t)))
loader = DataLoader( SyntheticSprites(seed=0), batch_size=args.batch, num_workers=args.workers, persistent_workers=args.workers > 0, prefetch_factor=4 if args.workers else None, ) val = {k: v.to(device) for k, v in fixed_batch(12345, 512).items()} args.out.parent.mkdir(parents=True, exist_ok=True)
start = time.time() model.train() for step, batch in enumerate(loader): if step >= args.steps: break for group in opt.param_groups: group["lr"] = lr_at(step) batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()} loss, metrics = loss_and_metrics(model, batch) opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step()
if step % 250 == 0 or step == args.steps - 1: model.eval() with torch.no_grad(): val_loss, val_metrics = loss_and_metrics(model, val) model.train() print( f"step {step:6d} loss {loss.item():.4f} fg {metrics['acc_fg']:.3f} | " f"val loss {val_loss.item():.4f} fg {val_metrics['acc_fg']:.3f} " f"union {val_metrics['acc_union']:.3f} | {time.time() - start:.0f}s", flush=True, ) if step % 2000 == 0 or step == args.steps - 1: torch.save({"model": model.state_dict(), "width": args.width, "step": step}, args.out)
print("done", flush=True)
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:b6eaa04d58f99ca9d6865169123ab172649ff25bf31c73e96786fcf4109f30bdsize 14253424.gitignoreAdded+8
README.md+49-5
app.pyAdded+116
autosprite/__init__.pyAdded+9
autosprite/features.pyAdded+108
autosprite/inference.pyAdded+59
autosprite/model.pyAdded+114
autosprite/preprocess.pyAdded+159
autosprite/sheet.pyAdded+116
autosprite/synth.pyAdded+413
evaluate.pyAdded+67
examples/alan/idle.pngAdded
examples/alan/jump.pngAdded
examples/alan/walk_1.pngAdded
examples/alan/walk_2.pngAdded
examples/alan/walk_3.pngAdded
export_onnx.pyAdded+52
requirements.txtAdded+3
tests/test_pipeline.pyAdded+72
train.pyAdded+159
weights/autosprite.onnxAdded+3