a commited on
Commit
9c75821
·
1 Parent(s): 5d965c9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2022aug31
2
+
3
+ #import gradio as gr
4
+
5
+ #def greet(name):
6
+ # return "Hello " + name + "!!"
7
+
8
+ #iface = gr.Interface(fn=greet, inputs="text", outputs="text")
9
+ #iface.launch()
10
+
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ import einops
15
+ import gradio as gr
16
+ import numpy as np
17
+ import torch
18
+ from huggingface_hub import hf_hub_download
19
+ from PIL import Image
20
+ from torch import nn
21
+ from torchvision.utils import save_image
22
+
23
+
24
+ class Generator(nn.Module):
25
+ def __init__(self, nc=4, nz=100, ngf=64):
26
+ super(Generator, self).__init__()
27
+ self.network = nn.Sequential(
28
+ nn.ConvTranspose2d(nz, ngf * 4, 3, 1, 0, bias=False),
29
+ nn.BatchNorm2d(ngf * 4),
30
+ nn.ReLU(True),
31
+ nn.ConvTranspose2d(ngf * 4, ngf * 2, 3, 2, 1, bias=False),
32
+ nn.BatchNorm2d(ngf * 2),
33
+ nn.ReLU(True),
34
+ nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 0, bias=False),
35
+ nn.BatchNorm2d(ngf),
36
+ nn.ReLU(True),
37
+ nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),
38
+ nn.Tanh(),
39
+ )
40
+
41
+ def forward(self, input):
42
+ output = self.network(input)
43
+ return output
44
+
45
+
46
+ model = Generator()
47
+ weights_path = hf_hub_download('nateraw/cryptopunks-gan', 'generator.pth')
48
+ model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
49
+
50
+
51
+ @torch.no_grad()
52
+ def interpolate(save_dir='./lerp/', frames=100, rows=8, cols=8):
53
+ save_dir = Path(save_dir)
54
+ save_dir.mkdir(exist_ok=True, parents=True)
55
+
56
+ z1 = torch.randn(rows * cols, 100, 1, 1)
57
+ z2 = torch.randn(rows * cols, 100, 1, 1)
58
+
59
+ zs = []
60
+ for i in range(frames):
61
+ alpha = i / frames
62
+ z = (1 - alpha) * z1 + alpha * z2
63
+ zs.append(z)
64
+
65
+ zs += zs[::-1] # also go in reverse order to complete loop
66
+
67
+ for i, z in enumerate(zs):
68
+ imgs = model(z)
69
+
70
+ # normalize
71
+ imgs = (imgs + 1) / 2
72
+
73
+ imgs = (imgs.permute(0, 2, 3, 1).cpu().numpy() * 255).astype(np.uint8)
74
+
75
+ # create grid
76
+ imgs = einops.rearrange(imgs, "(b1 b2) h w c -> (b1 h) (b2 w) c", b1=rows, b2=cols)
77
+
78
+ Image.fromarray(imgs).save(save_dir / f"{i:03}.png")
79
+
80
+ subprocess.call(f"convert -dispose previous -delay 10 -loop 0 {save_dir}/*.png out.gif".split())
81
+
82
+
83
+ def predict(choice, seed):
84
+ torch.manual_seed(seed)
85
+
86
+ if choice == 'interpolation':
87
+ interpolate()
88
+ return 'out.gif'
89
+ else:
90
+ z = torch.randn(64, 100, 1, 1)
91
+ punks = model(z)
92
+ save_image(punks, "punks.png", normalize=True)
93
+ return 'punks.png'
94
+
95
+
96
+ gr.Interface(
97
+ predict,
98
+ inputs=[
99
+ gr.inputs.Dropdown(['image', 'interpolation'], label='Output Type'),
100
+ gr.inputs.Slider(label='Seed', minimum=0, maximum=1000, default=42),
101
+ ],
102
+ outputs="image",
103
+ title="Cryptopunks GAN",
104
+ description="These CryptoPunks do not exist. You have the choice of either generating random punks, or a gif showing the interpolation between two random punk grids.",
105
+ article="<p style='text-align: center'><a href='https://arxiv.org/pdf/1511.06434.pdf'>Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks</a> | <a href='https://github.com/teddykoker/cryptopunks-gan'>Github Repo</a></p>",
106
+ examples=[["interpolation", 123], ["interpolation", 42], ["image", 456], ["image", 42]],
107
+ ).launch(cache_examples=True)