|
| 1 | +import os |
| 2 | +import math |
| 3 | +import tempfile |
| 4 | +from pathlib import Path |
| 5 | +import torch |
| 6 | +from torchvision import utils |
| 7 | +import cog |
| 8 | + |
| 9 | +from generate import sample, get_mean_style |
| 10 | +from model import StyledGenerator |
| 11 | + |
| 12 | +SIZE = 1024 |
| 13 | + |
| 14 | + |
| 15 | +class Predictor(cog.Predictor): |
| 16 | + def setup(self): |
| 17 | + self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 18 | + self.generator = StyledGenerator(512).to(self.device) |
| 19 | + print("Loading checkpoint") |
| 20 | + self.generator.load_state_dict( |
| 21 | + torch.load( |
| 22 | + "stylegan-1024px-new.model", |
| 23 | + map_location=self.device, |
| 24 | + )["g_running"], |
| 25 | + ) |
| 26 | + self.generator.eval() |
| 27 | + |
| 28 | + @cog.input("seed", type=int, default=-1, help="Random seed, -1 for random") |
| 29 | + def predict(self, seed): |
| 30 | + if seed < 0: |
| 31 | + seed = int.from_bytes(os.urandom(2), "big") |
| 32 | + torch.manual_seed(seed) |
| 33 | + print(f"seed: {seed}") |
| 34 | + |
| 35 | + mean_style = get_mean_style(self.generator, self.device) |
| 36 | + step = int(math.log(SIZE, 2)) - 2 |
| 37 | + img = sample(self.generator, step, mean_style, 1, self.device) |
| 38 | + output_path = Path(tempfile.mkdtemp()) / "output.png" |
| 39 | + utils.save_image(img, output_path, normalize=True) |
| 40 | + return output_path |
0 commit comments