cyttic's picture
add minimal inference code
5e5b0dd verified
Raw History Blame Contribute Delete
6.26 kB
"""
Minimal Hebrew word sampler for cyttic/diffusionpen-matan-ft (DiffusionPen fine-tuned on Hebrew handwriting).
Everything is fetched from the Hugging Face Hub on first run:
- UNet EMA checkpoint, style encoder, vocab/writer maps <- cyttic/diffusionpen-matan-ft (this repo)
- reference word crops (5 per writer drive the style) <- cyttic/matan-hebrew-handwriting-words
- VAE + DDIM scheduler <- stable-diffusion-v1-5/stable-diffusion-v1-5
- CANINE tokenizer/config <- google/canine-c
Usage:
python sample.py --text "ืฉืœื•ื ืขื•ืœื" --style w100 --n 2
python sample.py --text "ืฉืœื•ื" --refs a.png b.png c.png d.png e.png # your own style references
Images are written to ./samples/<word>_<style>_v<k>.png (64x256, white background).
Supported characters: the 27 Hebrew letters (incl. final forms); one word per image.
"""
import argparse, json, os, random, sys
from types import SimpleNamespace
import numpy as np
import pandas as pd
import torch
from diffusers import AutoencoderKL, DDIMScheduler
from huggingface_hub import hf_hub_download, snapshot_download
from PIL import Image, ImageOps
from io import BytesIO
from torchvision import transforms
from transformers import CanineModel, CanineTokenizer
REPO = "cyttic/diffusionpen-matan-ft"
REF_DATA = "cyttic/matan-hebrew-handwriting-words"
SD = "stable-diffusion-v1-5/stable-diffusion-v1-5"
IMG = (64, 256)
here = snapshot_download(REPO, allow_patterns=["*.py", "*.json", "style_models/*"])
sys.path.insert(0, here)
from unet import UNetModel # noqa: E402 (DiffusionPen code, MIT)
from feature_extractor import ImageEncoder # noqa: E402
tf = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,) * 3, (0.5,) * 3)])
def prep(img):
"""Word crop -> 64x256 RGB tensor, same as DiffusionPen training (resize to 64 px high, pad or shrink to 256 wide)."""
img = img.convert("RGB"); w, h = img.size
img = img.resize((max(1, int(w * 64 / h)), 64))
if img.width > 256: img = img.resize((256, 64))
return tf(ImageOps.pad(img, (256, 64), color="white"))
def strip_dp(sd):
"""Checkpoint was saved from DataParallel-wrapped modules; drop every 'module.' so it loads on CPU or one GPU."""
return {k.replace("module.", ""): v for k, v in sd.items()}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--text", default="ืฉืœื•ื ืขื•ืœื")
ap.add_argument("--style", default=None, help="writer id from writers_dict_train.json, e.g. w100 (random if unset)")
ap.add_argument("--refs", nargs="*", default=None, help="up to 5 own word images to use as style references")
ap.add_argument("--n", type=int, default=1, help="variants per word")
ap.add_argument("--steps", type=int, default=50, help="DDIM steps")
ap.add_argument("--seed", type=int, default=None)
ap.add_argument("--out", default="samples")
a = ap.parse_args()
dev = "cuda" if torch.cuda.is_available() else "cpu"
if a.seed is not None: random.seed(a.seed); torch.manual_seed(a.seed)
os.makedirs(a.out, exist_ok=True)
vocab = json.load(open(os.path.join(here, "character_classes.json"), encoding="utf-8"))
writers = json.load(open(os.path.join(here, "writers_dict_train.json")))
tok = CanineTokenizer.from_pretrained("google/canine-c")
unet = UNetModel(image_size=IMG, in_channels=4, model_channels=320, out_channels=4, num_res_blocks=1,
attention_resolutions=(1, 1), channel_mult=(1, 1), num_heads=4, num_classes=len(writers),
context_dim=320, vocab_size=len(vocab), text_encoder=CanineModel.from_pretrained("google/canine-c"),
args=SimpleNamespace(interpolation=False, mix_rate=None))
unet.load_state_dict(strip_dp(torch.load(hf_hub_download(REPO, "ema_ckpt.pt"), map_location="cpu", weights_only=False)))
unet.to(dev).eval()
vae = AutoencoderKL.from_pretrained(SD, subfolder="vae").to(dev).eval()
ddim = DDIMScheduler.from_pretrained(SD, subfolder="scheduler")
feat = ImageEncoder(model_name="mobilenetv2_100", num_classes=0, pretrained=True, trainable=True)
st = torch.load(os.path.join(here, "style_models", "iam_style_diffusionpen.pth"), map_location="cpu", weights_only=False)
md = feat.state_dict()
feat.load_state_dict({**md, **{k: v for k, v in strip_dp(st).items() if k in md and md[k].shape == v.shape}})
feat.to(dev).eval()
by_writer = None
if not a.refs:
df = pd.read_parquet(hf_hub_download(REF_DATA, "data/train.parquet", repo_type="dataset"))
by_writer = {w: g for w, g in df[df.text.str.len() > 2].groupby("writer_id")}
for word in a.text.split():
bad = [c for c in word if c not in vocab]
if bad: print(f"skip {word!r}: unsupported characters {bad}"); continue
for v in range(a.n):
wid = a.style or random.choice(list(writers))
if a.refs:
refs = [Image.open(p) for p in (a.refs * 5)[:5]]; label = 0; name = "own"
else:
g = by_writer[wid]; rows = g.sample(min(5, len(g)))
refs = [Image.open(BytesIO(r["bytes"])) for r in rows.image]; refs = (refs * 5)[:5]
label = writers[wid]; name = wid
ref = torch.stack([prep(r) for r in refs]).to(dev)
with torch.no_grad():
style = feat(ref)
text = tok([word], padding="max_length", truncation=True, return_tensors="pt", max_length=40).to(dev)
x = torch.randn((1, 4, IMG[0] // 8, IMG[1] // 8), device=dev)
ddim.set_timesteps(a.steps)
for t in ddim.timesteps:
eps = unet(x, torch.full((1,), int(t), device=dev, dtype=torch.long), text,
torch.tensor([label], device=dev), original_images=None, mix_rate=None, style_extractor=style)
x = ddim.step(eps, t, x).prev_sample
im = (vae.decode(x / 0.18215).sample / 2 + 0.5).clamp(0, 1)[0].cpu()
p = os.path.join(a.out, f"{word}_{name}_v{v}.png")
transforms.ToPILImage()(im).convert("RGB").save(p); print("saved", p)
if __name__ == "__main__":
main()