Spaces:
Running on Zero

nyxia's picture
smalt studio medium v1
81aa38e verified
Raw History Blame Contribute Delete
21.3 kB
"""smalt studio: a Hugging Face Space for smalt, the tiny text-to-pixel-art model (MIT).
Explore pre-made sprites (hover to replay how they were painted), type a prompt and watch 16x16 sprites fill in,
remix or recolour the one you like, download PNGs and a sprite sheet. ZeroGPU when available, otherwise CPU.
`/generate` is a plain API endpoint for scripts.
"""
from __future__ import annotations
import base64
import html
import inspect
import io
import json
import math
import os
import random
import tempfile
import time
import zipfile
from pathlib import Path
try: # must come before torch on ZeroGPU
import spaces
except ImportError:
spaces = None
import gradio as gr
import numpy as np
import torch
from PIL import Image
from cards import card, sprite_rgba
from smalt import SmaltPipeline
HERE = Path(__file__).parent
MODEL_DIR = HERE / "model"
ON_ZERO_GPU = bool(os.environ.get("SPACES_ZERO_GPU"))
HAS_GPU = ON_ZERO_GPU or torch.cuda.is_available()
torch.set_num_threads(max(1, min(8, os.cpu_count() or 1)))
PIPE_CPU = SmaltPipeline(MODEL_DIR, device="cpu")
PIPE_GPU = SmaltPipeline(MODEL_DIR, device="cuda") if HAS_GPU else None
G = PIPE_CPU.cfg.grid
N = G * G
PAL = PIPE_CPU.palette # (K, 3) uint8, index 0 = transparent
K = len(PAL)
LAB = np.asarray(json.loads((MODEL_DIR / "palette.json").read_text())["lab"], dtype=np.float64)
PARAMS = sum(p.numel() for p in PIPE_CPU.model.parameters())
MAX = {"gpu": (16, 32), "cpu": (8, 24)} # (sprites shown, steps)
CARD = 240
print(f"[smalt] {PARAMS / 1e6:.1f}M params, gpu={HAS_GPU} zero_gpu={ON_ZERO_GPU}", flush=True)
# per-Space overrides (space.json next to app.py); the defaults below are smalt-small's studio
SPACE = json.loads((HERE / "space.json").read_text()) if (HERE / "space.json").exists() else {}
NAME = SPACE.get("name", "smalt")
CARD_URL = SPACE.get("card", "https://huggingface.co/PixilabAI/smalt-small")
KINDS = {"Object": "", "Creature": "", "Tile": "tile with ", "Effect": "effect ", "UI": "ui ", "Letter": "text "}
PREFIXES = ("tile with ", "fragment of ", "effect ", "ui ", "text ")
IDEAS = {
"Object": ["red health potion", "blue mana potion", "green poison potion", "treasure chest", "silver sword",
"red key", "iron shield", "magic spellbook", "red apple", "wooden bow", "iron axe", "red heart"],
"Creature": ["green dragon", "red dragon", "purple bat", "yellow bat", "purple slime monster", "orange fox",
"knight in silver armor", "skeleton warrior with sword", "green goblin"],
"Tile": ["tile with stone bricks", "tile with blue water", "tile with green grass", "tile with wooden planks",
"tile with orange lava", "tile with yellow sand"],
"Effect": ["effect orange fireball", "effect blue magic sparkle", "effect green poison cloud",
"effect yellow lightning bolt"],
"UI": ["ui wooden button", "ui gold frame", "ui inventory slot"],
"Letter": ["text gold letter "],
}
CHIPS = ["red health potion", "treasure chest", "purple slime monster", "silver sword", "green dragon",
"magic spellbook", "tile with stone bricks", "text gold letter a"]
KINDS = SPACE.get("kinds", KINDS)
IDEAS = SPACE.get("ideas", IDEAS)
CHIPS = SPACE.get("chips", CHIPS)
# ------------------------------------------------------------------------------------------------- pixels
def rgba(tok: np.ndarray) -> np.ndarray:
return sprite_rgba(tok, None, PAL, K, G)
def zip_of(tokens: np.ndarray, prompt: str) -> str:
slug = "".join(c if c.isalnum() else "-" for c in prompt.lower()).strip("-")[:40] or "sprite"
path = Path(tempfile.mkdtemp()) / f"smalt-{slug}.zip"
cols = min(len(tokens), 8)
rows = math.ceil(len(tokens) / cols)
sheet = Image.new("RGBA", (cols * G, rows * G), (0, 0, 0, 0))
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
for i, t in enumerate(tokens):
im = Image.fromarray(rgba(t), "RGBA")
sheet.paste(im, ((i % cols) * G, (i // cols) * G))
for s in (1, 8):
buf = io.BytesIO()
(im if s == 1 else im.resize((G * s, G * s), Image.NEAREST)).save(buf, "PNG")
z.writestr(f"{slug}_{i + 1}{'' if s == 1 else '_8x'}.png", buf.getvalue())
buf = io.BytesIO()
sheet.save(buf, "PNG")
z.writestr(f"{slug}_sheet.png", buf.getvalue())
z.writestr("prompt.txt", prompt + "\n")
return str(path)
def hue_shift(tok: np.ndarray, deg: float) -> np.ndarray:
"""Rotate every saturated colour's OKLab hue by `deg`, snapped to the nearest palette colour; greys stay."""
out = tok.copy()
used = np.unique(tok[(tok > 0) & (tok < K)])
cand = LAB[1:]
rad = math.radians(deg)
for t in used:
L, a, b = LAB[t]
c = math.hypot(a, b)
if c < 0.03:
continue
h = math.atan2(b, a) + rad
target = np.array([L, c * math.cos(h), c * math.sin(h)])
out[tok == t] = 1 + int(((cand - target) ** 2).sum(1).argmin())
return out
def score(tok: np.ndarray, conf: np.ndarray) -> float:
"""How sure the model was of the colours it put down (mean log-prob over opaque pixels)."""
op = tok > 0
return float(np.log(conf[op].clip(1e-6)).mean()) if op.any() else -1e9
# ------------------------------------------------------------------------------------------------- sampling
def _steps(pipe: SmaltPipeline, job: dict):
for st in pipe.stream(job["prompt"], n=job["draw"], seed=job["seed"], canvas=job.get("canvas"),
keep=job.get("keep"), steps=job["steps"], guidance=job["guidance"],
temperature=job["temperature"]):
yield (st.index, st.total, st.tokens.cpu().numpy(), st.preview.cpu().numpy(),
st.confidence.float().cpu().numpy())
def _gpu_duration(job: dict) -> int:
return int(min(30, 6 + 0.01 * job["draw"] * job["steps"]))
def _steps_gpu(job: dict):
yield from _steps(PIPE_GPU, job)
if spaces is not None and ON_ZERO_GPU:
_steps_gpu = spaces.GPU(duration=_gpu_duration)(_steps_gpu)
def _job(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of):
prompt = " ".join(str(prompt or "").split())[:160]
if not prompt:
raise gr.Error("Type a prompt first.")
dev = "gpu" if (HAS_GPU and device != "CPU") else "cpu"
max_n, max_steps = MAX[dev]
n = int(min(max(int(n), 1), max_n))
seed = random.randint(0, 2**31 - 1) if random_seed or seed is None else int(seed) % 2**31
return {"prompt": prompt, "n": n, "draw": min(2 * n, 32) if best_of else n,
"steps": int(min(max(steps, 4), max_steps)), "guidance": float(guidance),
"temperature": float(temperature), "seed": seed, "dev": dev}
def _run(job: dict):
"""Yields (card images, status markdown, final tokens or None)."""
t0 = time.perf_counter()
gen = _steps_gpu(job) if job["dev"] == "gpu" else _steps(PIPE_CPU, job)
label = ("ZeroGPU" if ON_ZERO_GPU else "GPU") if job["dev"] == "gpu" else "CPU"
pick = f" · keeping the best {job['n']} of {job['draw']}" if job["draw"] > job["n"] else ""
last = conf = None
for k, total, tok, pre, cf in gen:
last, conf = tok, cf
bar = "▰" * (k + 1) + "▱" * (total - k - 1)
yield ([card(t, PAL, LAB, pre=p, size=CARD) for t, p in zip(tok, pre)],
f"`{bar}` painting · step {k + 1}/{total} · {label}{pick}", None)
order = sorted(range(len(last)), key=lambda i: -score(last[i], conf[i]))[:job["n"]]
best = last[order]
ms = round((time.perf_counter() - t0) * 1000)
yield ([card(t, PAL, LAB, size=CARD) for t in best],
f"**{job['n']} sprite{'s' if job['n'] > 1 else ''}** · {ms} ms · {label} · seed `{job['seed']}`{pick}", best)
def _dl(path):
return gr.DownloadButton(value=path, interactive=True)
def _emit(job, title=""):
for imgs, msg, tok in _run(job):
if tok is None:
yield imgs, msg, gr.skip(), gr.skip(), gr.skip()
else:
yield imgs, title + msg, {"prompt": job["prompt"], "tokens": tok.tolist()}, \
_dl(zip_of(tok, job["prompt"])), job["seed"]
def forge(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of):
yield from _emit(_job(prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of))
def remix(state, sel, prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of, keep_share):
if not state:
raise gr.Error("Paint some sprites first, then click one to remix it.")
base = np.asarray(state["tokens"][sel if sel is not None and sel < len(state["tokens"]) else 0], dtype=np.int64)
job = _job(prompt or state["prompt"], n, steps, guidance, temperature, seed, random_seed, device, best_of)
rng = np.random.default_rng(job["seed"])
keep = rng.random(N) < float(keep_share)
if keep.all():
keep[rng.integers(0, N)] = False
job["canvas"], job["keep"] = base, keep
yield from _emit(job, "Remix · ")
def palette_swap(state, sel):
if not state:
raise gr.Error("Paint some sprites first, then click one to recolour it.")
base = np.asarray(state["tokens"][sel if sel is not None and sel < len(state["tokens"]) else 0], dtype=np.int64)
toks = np.stack([base] + [hue_shift(base, d) for d in (45, 90, 135, 180, 225, 270, 315)])
name = state["prompt"] + " recolours"
return ([card(t, PAL, LAB, size=CARD) for t in toks], "**8 recolours** of the selected sprite (palette-exact)",
{"prompt": name, "tokens": toks.tolist()}, _dl(zip_of(toks, name)))
def pick(evt: gr.SelectData):
return evt.index
def set_kind(kind, prompt):
p = (prompt or "").strip()
for pre in PREFIXES:
if p.lower().startswith(pre):
p = p[len(pre):]
break
if not p or kind == "Letter":
return dice(kind)
return KINDS[kind] + p
def dice(kind):
s = random.choice(IDEAS.get(kind, IDEAS["Object"]))
return s + random.choice("abcdefghijklmnopqrstuvwxyz") if kind == "Letter" else s
def generate(prompt: str, n: int = 4, seed: int = -1, steps: int = 16, guidance: float = 3.0,
temperature: float = 0.4, best_of: bool = True) -> dict:
"""Generate 16x16 sprites. Returns {"seed", "sprites": [[palette id x 256], ...], "png": [base64 16x16 PNG]}."""
job = _job(prompt, n, steps, guidance, temperature, None if seed is None or seed < 0 else seed,
seed is None or seed < 0, "GPU", best_of)
tok = None
for _, _, tok in _run(job): # same path as the UI (ZeroGPU when available); the last yield has the tokens
pass
pngs = []
for t in tok:
buf = io.BytesIO()
Image.fromarray(rgba(t), "RGBA").save(buf, "PNG")
pngs.append(base64.b64encode(buf.getvalue()).decode("ascii"))
return {"seed": job["seed"], "sprites": tok.tolist(), "png": pngs}
# ------------------------------------------------------------------------------------------------- static pages
LOGO = base64.b64encode((HERE / "assets" / "logo.png").read_bytes()).decode("ascii")
EXPLORE = json.loads((HERE / "assets" / "explore.json").read_text())
SIDE_HEAD = f"""
<div class="sm-side-head">
<img class="sm-logo" alt="smalt" src="data:image/png;base64,{LOGO}">
<p class="sm-blurb"><b>{NAME}</b> is a <b>{PARAMS / 1e6:.1f}M-parameter</b> model that paints <b>16×16 pixel-art sprites</b> from a
short prompt. Every pixel comes from a fixed 512-colour palette, so sprites are crisp, transparent and game-ready.</p>
<p class="sm-by">by <b>Pixilab</b> · MIT · <a href="{CARD_URL}" target="_blank">model card ↗</a></p>
</div>
"""
def explore_html() -> str:
cards = []
for i, it in enumerate(EXPLORE["items"]):
cards.append(
f'<figure class="ex-card" style="--frames:{it["frames"]};animation-delay:{i * 35}ms">'
f'<div class="ex-anim" style="background-image:url({it["strip"]})"></div>'
f'<img class="ex-img" alt="{html.escape(it["prompt"])}" src="{it["card"]}">'
f'<figcaption>{html.escape(it["prompt"])}</figcaption></figure>')
return ('<div class="ex-head"><h2>Explore</h2><p>Sprites painted by ' + NAME + ', picked from 8 by the model\'s own '
'confidence and detail. <b>Hover</b> to replay how each one was painted, step by step. Type any of these prompts in '
'the sidebar and press <b>Paint</b> to make your own.</p></div>'
f'<div class="ex-grid">{"".join(cards)}</div>')
def palette_html() -> str:
sw = "".join(f'<i style="background:{s["hex"]}" title="{s["hex"]} · #{s["i"]}"></i>' for s in EXPLORE["palette"])
return ('<div class="ex-head"><h2>Palette</h2><p>All 511 colours smalt paints with (plus transparent). Every pixel '
'of every sprite is exactly one of these, so there is never blur or a stray in-between shade.</p></div>'
f'<div class="pal-grid">{sw}</div>')
HOW = """
## How it works
smalt starts from a **blank 16×16 canvas** where every pixel is *masked*. At each step it looks at the prompt and at
the pixels already placed, predicts a colour for every empty pixel, and **keeps the ones it is most sure about**.
After about **16 steps** the whole sprite is filled in. You can watch it happen in the Studio, or hover a sprite in
Explore to replay it.
- **Palette tokens, not RGB.** Each pixel is one of 512 palette entries (0 = transparent), so outputs are pixel-perfect.
- **Its own little text encoder.** No CLIP, no VAE; the whole thing is __PARAMS__M parameters and runs on a laptop CPU.
- **Best of N.** With *best of 2×* on, the Studio paints twice as many sprites and keeps the ones the model was most
confident about.
- **Remix** keeps a random part of the selected sprite and repaints the rest around it (inpainting).
- **Recolour** rotates the hue of every saturated colour and snaps it back onto the palette.
**Prompting:** __PROMPTING__
**Limitations:** __LIMITS__
"""
HOW = (HOW.replace("__PARAMS__", f"{PARAMS / 1e6:.1f}")
.replace("__PROMPTING__", SPACE.get("prompting", "short, colour first, then the thing: `red health potion`, "
"`purple slime monster`, `silver sword`. Tiles start with `tile with`, effects with `effect`, interface "
"pieces with `ui`, letters with `text` (`text gold letter a`)."))
.replace("__LIMITS__", SPACE.get("limits", "16×16 only; trees, crowns, coins, effects and UI bars are weaker "
"than objects and creatures.")))
CSS = (HERE / "style.css").read_text()
THEME_COLORS = dict(
body_background_fill="#0b1029", body_text_color="#ece6d6", body_text_color_subdued="#9aa3d4",
block_background_fill="#121a45", block_border_color="#232c66", block_label_text_color="#9aa3d4",
block_title_text_color="#ece6d6", block_label_background_fill="#121a45", block_info_text_color="#9aa3d4",
background_fill_primary="#121a45", background_fill_secondary="#0e1538", border_color_primary="#232c66",
border_color_accent="#f2c45a", input_background_fill="#0b1029", input_border_color="#2a3474",
input_placeholder_color="#6871a8", button_primary_background_fill="#f2c45a",
button_primary_background_fill_hover="#ffd472", button_primary_text_color="#0b1029",
button_secondary_background_fill="#1a2357", button_secondary_background_fill_hover="#243079",
button_secondary_text_color="#ece6d6", button_secondary_border_color="#2a3474", slider_color="#f2c45a",
color_accent="#f2c45a", color_accent_soft="#1a2357", checkbox_background_color="#0b1029",
checkbox_background_color_selected="#f2c45a", checkbox_border_color="#2a3474", link_text_color="#f2c45a",
code_background_fill="#1a2357", table_even_background_fill="#121a45", table_odd_background_fill="#0e1538",
panel_background_fill="#0e1538",
)
_SETTABLE = set(inspect.signature(gr.themes.Base.set).parameters)
THEME = gr.themes.Base( # dark in both modes
primary_hue=gr.themes.Color(*["#fff4d6", "#ffe8ad", "#ffdb85", "#f8cd6a", "#f2c45a", "#e0b04a", "#b5852a",
"#8f6720", "#6e4d12", "#4d3509", "#2e1f05"]),
neutral_hue=gr.themes.Color(*["#ece6d6", "#c9cdea", "#9aa3d4", "#6871a8", "#3a4796", "#2a3474", "#1a2357",
"#121a45", "#0e1538", "#0b1029", "#050818"]),
font=[gr.themes.GoogleFont("Instrument Sans"), "ui-sans-serif", "sans-serif"],
font_mono=[gr.themes.GoogleFont("Martian Mono"), "ui-monospace", "monospace"],
radius_size=gr.themes.sizes.radius_lg,
).set(**THEME_COLORS, **{k + "_dark": v for k, v in THEME_COLORS.items() if k + "_dark" in _SETTABLE})
with gr.Blocks(title=f"{NAME} · pixel painter") as demo:
state = gr.State(None)
sel = gr.State(0)
with gr.Row(equal_height=False, elem_id="sm-shell"):
with gr.Column(scale=1, min_width=320, elem_id="sm-side"):
gr.HTML(SIDE_HEAD)
prompt = gr.Textbox(lines=2, max_lines=3, show_label=False, placeholder="Type a prompt here",
max_length=160, elem_id="sm-prompt", autofocus=True)
with gr.Row(elem_id="sm-chips"):
chips = [gr.Button(c, size="sm", elem_classes="sm-chip") for c in CHIPS]
kind = gr.Radio(list(KINDS), value="Object", label="kind", elem_id="sm-kinds")
n = gr.Radio([1, 4, 8, 16] if HAS_GPU else [1, 4, 8], value=4, label="images", elem_id="sm-n")
with gr.Row():
dice_btn = gr.Button("🎲 random", elem_id="sm-dice", scale=1)
go = gr.Button("Paint", variant="primary", elem_id="sm-go", scale=2)
with gr.Accordion("settings", open=False, elem_id="sm-settings"):
best_of = gr.Checkbox(value=True, label="best of 2× (paint twice as many, keep the cleanest)")
steps = gr.Slider(4, 32, value=16, step=1, label="steps")
guidance = gr.Slider(1.0, 8.0, value=3.0, step=0.5, label="guidance")
temperature = gr.Slider(0.1, 1.5, value=0.4, step=0.05, label="temperature")
keep_share = gr.Slider(0.1, 0.9, value=0.5, step=0.05, label="remix: share of pixels kept")
with gr.Row():
seed = gr.Number(value=0, precision=0, label="seed", minimum=0)
random_seed = gr.Checkbox(value=True, label="random seed")
device = gr.Radio(["GPU", "CPU"], value="GPU", label="run on", visible=HAS_GPU)
with gr.Column(scale=3, elem_id="sm-mainc"):
with gr.Tabs(selected="explore", elem_id="sm-tabs") as tabs:
with gr.Tab("Explore", id="explore"):
gr.HTML(explore_html())
with gr.Tab("Studio", id="studio"):
status = gr.Markdown("Type a prompt, or click one of the chips, and press **Paint**.",
elem_id="sm-status")
gallery = gr.Gallery(show_label=False, columns=4, height="auto", object_fit="contain",
format="png", allow_preview=False, elem_id="sm-gallery", interactive=False)
with gr.Row(elem_id="sm-actions"):
remix_btn = gr.Button("↻ Remix selected", elem_classes="sm-act")
swap_btn = gr.Button("◐ Recolour selected", elem_classes="sm-act")
files = gr.DownloadButton("⬇ PNGs + sprite sheet", value=None, interactive=False,
elem_classes="sm-act sm-dl")
with gr.Tab("Palette", id="palette"):
gr.HTML(palette_html())
with gr.Tab("How it works", id="how"):
gr.Markdown(HOW, elem_id="sm-how")
run_in = [prompt, n, steps, guidance, temperature, seed, random_seed, device, best_of]
run_out = [gallery, status, state, files, seed]
lim = 4 if HAS_GPU else 1
def to_studio():
return gr.Tabs(selected="studio")
for trig in (go.click, prompt.submit):
trig(to_studio, None, tabs, api_name=False).then(forge, run_in, run_out, concurrency_limit=lim,
show_progress="hidden", api_name=False)
for b, text in zip(chips, CHIPS):
b.click(lambda t=text: t, None, prompt, api_name=False).then(to_studio, None, tabs, api_name=False).then(
forge, run_in, run_out, concurrency_limit=lim, show_progress="hidden", api_name=False)
remix_btn.click(remix, [state, sel] + run_in + [keep_share], run_out, concurrency_limit=lim,
show_progress="hidden", api_name=False)
swap_btn.click(palette_swap, [state, sel], [gallery, status, state, files], api_name=False)
gallery.select(pick, None, sel, api_name=False)
kind.change(set_kind, [kind, prompt], prompt, api_name=False)
dice_btn.click(dice, kind, prompt, api_name=False)
gr.api(generate, api_name="generate")
demo.queue(max_size=64)
if __name__ == "__main__":
demo.launch(theme=THEME, css=CSS, footer_links=[], ssr_mode=False,
head='<link href="https://fonts.googleapis.com/css2?family=Jersey+10&display=swap" rel="stylesheet">')