"""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 sees identically 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 @dataclass class 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 rgba