Spaces:
Sleeping

File size: 4,033 Bytes
22938ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""AutoSprite Gradio app: upload a few frames, get a full spritesheet back."""

from __future__ import annotations

import re
import tempfile
from pathlib import Path

import gradio as gr
import numpy as np

from autosprite import POSES
from autosprite.inference import SpriteCompleter
from autosprite.preprocess import prepare_frames
from autosprite.sheet import build_bundle

ROOT = Path(__file__).parent
MODEL_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)