File size: 5,243 Bytes
27ea2f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Draw a walk cycle for a 32x32 sprite with AnimGPT (pixelsprite-animgpt).

    python example.py examples/archer32.png --az 270 --out walk.gif
    python example.py my_sprite.png --kind quadruped --action walk --az 90

Works from a local clone of the repo, or downloads it from the Hub (--repo ihor-umanets/pixelsprite-animgpt).
CPU is fine: one direction takes ~3 minutes at 32 px and ~30 s at 16 px (see the model card).
"""
import argparse
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from safetensors.torch import load_file


def locate(repo: str) -> Path:
    here = Path(__file__).resolve().parent
    if (here / "code" / "anim_model.py").exists() and (here / "model.safetensors").exists():
        return here
    from huggingface_hub import snapshot_download      # private repo: needs `hf auth login`
    return Path(snapshot_download(repo, allow_patterns=["model.safetensors", "config.json", "code/*"]))


def quantise(png: Path, size: int, palette: np.ndarray, empty: int) -> torch.Tensor:
    """RGBA sprite (32x32, or any square) -> (size*size,) palette indices, EMPTY where transparent"""
    im = Image.open(png).convert("RGBA").resize((size, size), Image.NEAREST)
    a = np.asarray(im)
    d = ((a[..., None, :3].astype(np.int32) - palette[None, None].astype(np.int32)) ** 2).sum(-1)
    idx = d.argmin(-1)
    idx[a[..., 3] < 128] = empty
    return torch.from_numpy(idx.reshape(-1)).long()


def to_rgba(idx: torch.Tensor, size: int, palette: np.ndarray, empty: int) -> np.ndarray:
    i = idx.view(size, size).numpy()
    out = np.zeros((size, size, 4), np.uint8)
    on = i < empty
    out[on, :3] = palette[i[on]]
    out[on, 3] = 255
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("sprite")
    ap.add_argument("--repo", default="ihor-umanets/pixelsprite-animgpt")
    ap.add_argument("--kind", default="human", choices=["human", "quadruped", "bird"])
    ap.add_argument("--action", default="walk")
    ap.add_argument("--az", type=int, default=270, help="direction: 0 front, 90, 180 back, 270 (see the card)")
    ap.add_argument("--size", type=int, default=32, choices=[16, 24, 32])
    ap.add_argument("--frames", type=int, default=8)
    ap.add_argument("--temperature", type=float, default=0.8)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default="walk.gif")
    a = ap.parse_args()

    root = locate(a.repo)
    sys.path.insert(0, str(root / "code"))
    from anim_model import ACTIONS, AZIMUTHS, KINDS, AnimGPT
    from pixelsprite_model import CanvasConfig
    import json

    cfg = json.load(open(root / "config.json"))
    model = AnimGPT(CanvasConfig.from_dict(cfg["model"]))
    model.load_state_dict(load_file(root / "model.safetensors"))
    model.eval()
    palette = np.load(root / "code" / "palette.npy")
    empty, S = model.EMPTY, a.size
    torch.manual_seed(a.seed)
    gen = torch.Generator().manual_seed(a.seed)

    native = Image.open(a.sprite).size[0]                    # the size the sprite was drawn at (v2 draws 16 or 32)
    refk = 0 if native == S else 1                           # 0: a v2-style sprite of this size; 1: "front render" (24 px, or a 32 px sprite drawn at 16)
    ref = quantise(Path(a.sprite), S, palette, empty)[None]
    allowed = torch.zeros((1, empty + 1), dtype=torch.bool)       # only the sprite's own colours (+ transparent)
    allowed[0, ref[0].unique()] = True
    allowed[0, empty] = True

    def cond(action, frame, nfr):
        t = lambda v: torch.tensor([v])
        return dict(kind=t(KINDS.index(a.kind)), action=t(ACTIONS.index(action)), az=t(AZIMUTHS.index(a.az)),
                    el=t(0), frame=t(frame), nfr=t(nfr), refk=t(refk))

    # 1) the view: the sprite turned to the direction (previous = reference)
    view = model.sample(S, cond("view", 0, 1), ref, ref, a.temperature, allowed, gen)
    # 2) the action, frame by frame: frame 0 follows the view, frame k follows frame k-1
    frames, prev = [], view
    for k in range(a.frames):
        prev = model.sample(S, cond(a.action, k, a.frames), ref, prev, a.temperature, allowed, gen)
        frames.append(prev)
        print(f"frame {k + 1}/{a.frames}", flush=True)

    scale = max(1, 256 // S)
    imgs = []
    for f in frames:
        rgba = Image.fromarray(to_rgba(f[0], S, palette, empty), "RGBA").resize((S * scale, S * scale), Image.NEAREST)
        bg = Image.new("RGBA", rgba.size, (225, 225, 225, 255))
        bg.alpha_composite(rgba)
        imgs.append(bg.convert("RGB").quantize(256))
    imgs[0].save(a.out, save_all=True, append_images=imgs[1:], duration=120, loop=0, disposal=1, optimize=False)
    # a PNG strip: input, the turned view, then the frames
    tiles = [ref[0], view[0]] + [f[0] for f in frames]
    strip = Image.new("RGBA", (S * scale * len(tiles), S * scale), (225, 225, 225, 255))
    for i, t in enumerate(tiles):
        strip.alpha_composite(Image.fromarray(to_rgba(t, S, palette, empty), "RGBA").resize((S * scale,) * 2, Image.NEAREST),
                              (i * S * scale, 0))
    strip.convert("RGB").save(Path(a.out).with_suffix(".png"))
    print("saved", a.out)


if __name__ == "__main__":
    main()