Spaces:
Sleeping
Sleeping
Download autosprite/preprocess.py from neonforestmist/AutoSprite: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/spaces/neonforestmist/AutoSprite/resolve/main/autosprite/preprocess.py
- Command line
-
hf download hf://spaces/neonforestmist/AutoSprite/autosprite/preprocess.py
-
curl -L -o preprocess.py https://huggingface.co/spaces/neonforestmist/AutoSprite/resolve/main/autosprite/preprocess.py
5.85 kB
| """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 np | |
| from PIL import Image | |
| from . import CANVAS | |
| ALPHA_THRESHOLD = 128 | |
| COLOR_MERGE_DISTANCE = 14.0 | |
| MAX_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] | |