Spaces:
Running on Zero
Running on Zero
File size: 4,791 Bytes
4885364 b91f504 4885364 1398b5d b802031 4885364 b91f504 4885364 1398b5d 4885364 1398b5d b802031 1398b5d ec5b19a 9386e67 b91f504 e538fa3 b91f504 1398b5d b91f504 1398b5d b91f504 ec5b19a b91f504 ec5b19a b91f504 e538fa3 b91f504 ec5b19a b91f504 e538fa3 1398b5d b91f504 4885364 e538fa3 1398b5d b91f504 1398b5d e538fa3 b91f504 1398b5d e538fa3 b91f504 4885364 b91f504 9386e67 b91f504 e538fa3 1398b5d ec5b19a 9386e67 1398b5d 4885364 ec5b19a 4885364 b91f504 e538fa3 1398b5d b91f504 e538fa3 b91f504 1398b5d b91f504 e538fa3 b91f504 1398b5d b91f504 1398b5d b91f504 1398b5d b91f504 9386e67 1398b5d b91f504 1398b5d 9386e67 b91f504 1398b5d b91f504 9386e67 1398b5d b91f504 9386e67 1398b5d 4885364 1398b5d 4885364 1398b5d 9386e67 1398b5d 4885364 1398b5d 9386e67 e538fa3 4885364 b91f504 1398b5d 4885364 1398b5d b91f504 4885364 b91f504 1398b5d e538fa3 b91f504 1398b5d b91f504 1398b5d b91f504 4885364 1398b5d ec5b19a b91f504 ec5b19a b91f504 ec5b19a e538fa3 b91f504 ec5b19a b91f504 ec5b19a 1398b5d b91f504 1398b5d b91f504 1398b5d b91f504 1398b5d 4885364 1398b5d | 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
"""
AlignDRAW — 512x512 canvas adaptation.
Uses the original COCO checkpoint, adapting its initial canvas parameter.
IMPORTANT: This is not a newly trained 512x512 checkpoint.
"""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces
import pickle
import numpy as np
import torch
import torch.nn.functional as F
import gradio as gr
import imageio.v2 as imageio
from PIL import Image
from huggingface_hub import hf_hub_download
from model import AlignDRAW
REPO = "mediasynthesismuseum/aligndraw"
HERE = os.path.dirname(os.path.abspath(__file__))
IMAGE_SIZE = 512
DRAW_STEPS = 69
# Build the actual 512x512 model.
model = AlignDRAW(imgSize=IMAGE_SIZE, runSteps=DRAW_STEPS)
# Download the original checkpoint.
checkpoint_path = hf_hub_download(REPO, "aligndraw_coco.pt")
checkpoint = torch.load(checkpoint_path, map_location="cpu")
# Adapt the original learned 32x32 initial canvas to 512x512.
old_c0 = checkpoint["c0"].reshape(1, 3, 32, 32)
new_c0 = F.interpolate(
old_c0,
size=(IMAGE_SIZE, IMAGE_SIZE),
mode="bilinear",
align_corners=False
)
checkpoint["c0"] = new_c0.reshape(1, -1)
# Load the original weights, including the adapted canvas.
model.load_state_dict(checkpoint, strict=True)
model.eval().to("cuda")
# Original vocabulary.
DICT_PATH = hf_hub_download(REPO, "dictionary.pkl")
with open(DICT_PATH, "rb") as f:
DICT = pickle.load(f, encoding="latin1")
def _tokens(caption):
words = caption.strip().lower().replace(".", " .").split()
unknown = sorted({
w for w in words
if w not in DICT and w != "."
})
toks = [
DICT.get(w, DICT["UNK"])
for w in words
] or [DICT["UNK"]]
return toks, unknown
def _to_image(t):
"""Convert a native 512x512 tensor into a PIL image."""
array = (
t.detach()
.cpu()
.permute(1, 2, 0)
.numpy() * 255
).clip(0, 255).astype(np.uint8)
return Image.fromarray(array)
@spaces.GPU(duration=120)
def generate(caption, n_samples):
if not caption.strip():
raise gr.Error("Type a caption first.")
toks, unknown = _tokens(caption)
y = torch.tensor(
[toks],
dtype=torch.long,
device="cuda"
)
count = int(n_samples)
# Generate native 512x512 samples.
imgs = model.generate(
y.expand(count, -1),
steps=DRAW_STEPS
)
gallery = [
_to_image(imgs[i])
for i in range(count)
]
# Generate the 69-step drawing sequence.
_, sequence = model.generate(
y,
steps=DRAW_STEPS,
return_seq=True
)
frames = [
np.array(_to_image(step[0]))
for step in sequence
]
frames += [frames[-1]] * 8
gif_path = os.path.join(HERE, "draw.gif")
imageio.mimsave(gif_path, frames, duration=0.09)
note = (
"💡 Not in the original vocabulary (treated as UNK): "
+ ", ".join(unknown)
) if unknown else ""
note += (
"\n\n⚠️ 512x512 canvas adaptation using original weights. "
"This model has not been retrained at 512x512."
)
return gallery, gif_path, note
EXAMPLES = [
"a red stop sign on a street corner .",
"a herd of elephants walking in a field .",
"a yellow school bus on the road .",
"a bowl of oranges on a table .",
"a plate with a sandwich and french fries .",
"a large blue passenger jet in the sky .",
]
CSS = """
.gradio-container {
max-width: 1100px !important;
margin: 0 auto !important;
}
#ad-title {
text-align: center;
}
"""
with gr.Blocks(title="AlignDRAW 512") as demo:
gr.Markdown(
"# 🖍️ AlignDRAW — 512×512",
elem_id="ad-title"
)
gr.Markdown(
"A 512×512 canvas adaptation of the 2015 AlignDRAW "
"architecture, using the original COCO checkpoint. "
"The drawing process runs for 69 steps."
)
with gr.Row():
cap = gr.Textbox(
label="Caption",
value=EXAMPLES[0],
scale=4
)
n = gr.Slider(
1, 4, 1,
step=1,
label="Samples",
scale=1
)
go = gr.Button("🖍️ Draw", variant="primary")
note = gr.Markdown()
with gr.Row():
gallery = gr.Gallery(
label="Native 512×512 samples",
columns=2,
height=520
)
anim = gr.Image(
label="69-step drawing process",
height=400
)
go.click(
generate,
inputs=[cap, n],
outputs=[gallery, anim, note]
)
gr.Examples(EXAMPLES, inputs=cap)
if __name__ == "__main__":
demo.queue().launch(
theme=gr.themes.Citrus(),
css=CSS
)
|