Spaces:
Paused
Paused
Download biggan.py from Nymbo/http-server: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/spaces/Nymbo/http-server/resolve/main/biggan.py
- Command line
-
hf download hf://spaces/Nymbo/http-server/biggan.py
-
curl -L -o biggan.py https://huggingface.co/spaces/Nymbo/http-server/resolve/main/biggan.py
1.37 kB
| """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() | |