File size: 1,374 Bytes
d1c62da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""BigGAN-deep-128 run locally (the serverless Inference API that used to host it is gone)."""
import io
import threading

import nltk
import torch
from huggingface_hub import snapshot_download
from pytorch_pretrained_biggan import BigGAN, one_hot_from_names, truncated_noise_sample
from torchvision import transforms

_lock = threading.Lock()
_model = None
TRUNCATION = 0.1


def _get_model():
    global _model
    with _lock:
        if _model is None:
            nltk.download("wordnet", quiet=True)
            nltk.download("omw-1.4", quiet=True)
            path = snapshot_download("osanseviero/BigGAN-deep-128", allow_patterns=["config.json", "pytorch_model.bin"])
            _model = BigGAN.from_pretrained(path).eval()
        return _model


def infer_biggan(name: str) -> bytes:
    """Return PNG bytes of an ImageNet class `name`, or raise ValueError."""
    model = _get_model()
    class_vector = one_hot_from_names([name], batch_size=1)
    if class_vector is None:
        raise ValueError("Input is not in ImageNet")
    noise = torch.from_numpy(truncated_noise_sample(truncation=TRUNCATION, batch_size=1))
    with torch.no_grad():
        out = model(noise, torch.from_numpy(class_vector), TRUNCATION)
    img = transforms.ToPILImage()(((out[0] + 1) / 2.0).clamp(0, 1))
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    return buf.getvalue()