Мясников Филипп Сергеевич commited on
Commit
45e462d
1 Parent(s): fab4ed0
Files changed (3) hide show
  1. app.py +0 -2
  2. model.py +0 -688
  3. util.py +0 -220
app.py CHANGED
@@ -5,7 +5,6 @@ import gradio as gr
5
  import torch
6
  torch.backends.cudnn.benchmark = True
7
  from torchvision import transforms, utils
8
- from util import *
9
  from PIL import Image
10
  import math
11
  import random
@@ -33,7 +32,6 @@ from e4e.utils.common import tensor2im
33
  from e4e.models.psp import pSp
34
  from e4e.models.encoders import psp_encoders
35
  from e4e.models.stylegan2.model import Generator
36
- from util import *
37
  from huggingface_hub import hf_hub_download
38
 
39
  import dlib
 
5
  import torch
6
  torch.backends.cudnn.benchmark = True
7
  from torchvision import transforms, utils
 
8
  from PIL import Image
9
  import math
10
  import random
 
32
  from e4e.models.psp import pSp
33
  from e4e.models.encoders import psp_encoders
34
  from e4e.models.stylegan2.model import Generator
 
35
  from huggingface_hub import hf_hub_download
36
 
37
  import dlib
model.py DELETED
@@ -1,688 +0,0 @@
1
- import math
2
- import random
3
- import functools
4
- import operator
5
-
6
- import torch
7
- from torch import nn
8
- from torch.nn import functional as F
9
- from torch.autograd import Function
10
-
11
- from op import conv2d_gradfix
12
- if torch.cuda.is_available():
13
- from op.fused_act import FusedLeakyReLU, fused_leaky_relu
14
- from op.upfirdn2d import upfirdn2d
15
- else:
16
- from op.fused_act_cpu import FusedLeakyReLU, fused_leaky_relu
17
- from op.upfirdn2d_cpu import upfirdn2d
18
-
19
-
20
- class PixelNorm(nn.Module):
21
- def __init__(self):
22
- super().__init__()
23
-
24
- def forward(self, input):
25
- return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)
26
-
27
-
28
- def make_kernel(k):
29
- k = torch.tensor(k, dtype=torch.float32)
30
-
31
- if k.ndim == 1:
32
- k = k[None, :] * k[:, None]
33
-
34
- k /= k.sum()
35
-
36
- return k
37
-
38
-
39
- class Upsample(nn.Module):
40
- def __init__(self, kernel, factor=2):
41
- super().__init__()
42
-
43
- self.factor = factor
44
- kernel = make_kernel(kernel) * (factor ** 2)
45
- self.register_buffer("kernel", kernel)
46
-
47
- p = kernel.shape[0] - factor
48
-
49
- pad0 = (p + 1) // 2 + factor - 1
50
- pad1 = p // 2
51
-
52
- self.pad = (pad0, pad1)
53
-
54
- def forward(self, input):
55
- out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad)
56
-
57
- return out
58
-
59
-
60
- class Downsample(nn.Module):
61
- def __init__(self, kernel, factor=2):
62
- super().__init__()
63
-
64
- self.factor = factor
65
- kernel = make_kernel(kernel)
66
- self.register_buffer("kernel", kernel)
67
-
68
- p = kernel.shape[0] - factor
69
-
70
- pad0 = (p + 1) // 2
71
- pad1 = p // 2
72
-
73
- self.pad = (pad0, pad1)
74
-
75
- def forward(self, input):
76
- out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad)
77
-
78
- return out
79
-
80
-
81
- class Blur(nn.Module):
82
- def __init__(self, kernel, pad, upsample_factor=1):
83
- super().__init__()
84
-
85
- kernel = make_kernel(kernel)
86
-
87
- if upsample_factor > 1:
88
- kernel = kernel * (upsample_factor ** 2)
89
-
90
- self.register_buffer("kernel", kernel)
91
-
92
- self.pad = pad
93
-
94
- def forward(self, input):
95
- out = upfirdn2d(input, self.kernel, pad=self.pad)
96
-
97
- return out
98
-
99
-
100
- class EqualConv2d(nn.Module):
101
- def __init__(
102
- self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True
103
- ):
104
- super().__init__()
105
-
106
- self.weight = nn.Parameter(
107
- torch.randn(out_channel, in_channel, kernel_size, kernel_size)
108
- )
109
- self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
110
-
111
- self.stride = stride
112
- self.padding = padding
113
-
114
- if bias:
115
- self.bias = nn.Parameter(torch.zeros(out_channel))
116
-
117
- else:
118
- self.bias = None
119
-
120
- def forward(self, input):
121
- out = conv2d_gradfix.conv2d(
122
- input,
123
- self.weight * self.scale,
124
- bias=self.bias,
125
- stride=self.stride,
126
- padding=self.padding,
127
- )
128
-
129
- return out
130
-
131
- def __repr__(self):
132
- return (
133
- f"{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},"
134
- f" {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})"
135
- )
136
-
137
-
138
- class EqualLinear(nn.Module):
139
- def __init__(
140
- self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None
141
- ):
142
- super().__init__()
143
-
144
- self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
145
-
146
- if bias:
147
- self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
148
-
149
- else:
150
- self.bias = None
151
-
152
- self.activation = activation
153
-
154
- self.scale = (1 / math.sqrt(in_dim)) * lr_mul
155
- self.lr_mul = lr_mul
156
-
157
- def forward(self, input):
158
- if self.activation:
159
- out = F.linear(input, self.weight * self.scale)
160
- out = fused_leaky_relu(out, self.bias * self.lr_mul)
161
-
162
- else:
163
- out = F.linear(
164
- input, self.weight * self.scale, bias=self.bias * self.lr_mul
165
- )
166
-
167
- return out
168
-
169
- def __repr__(self):
170
- return (
171
- f"{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})"
172
- )
173
-
174
-
175
- class ModulatedConv2d(nn.Module):
176
- def __init__(
177
- self,
178
- in_channel,
179
- out_channel,
180
- kernel_size,
181
- style_dim,
182
- demodulate=True,
183
- upsample=False,
184
- downsample=False,
185
- blur_kernel=[1, 3, 3, 1],
186
- fused=True,
187
- ):
188
- super().__init__()
189
-
190
- self.eps = 1e-8
191
- self.kernel_size = kernel_size
192
- self.in_channel = in_channel
193
- self.out_channel = out_channel
194
- self.upsample = upsample
195
- self.downsample = downsample
196
-
197
- if upsample:
198
- factor = 2
199
- p = (len(blur_kernel) - factor) - (kernel_size - 1)
200
- pad0 = (p + 1) // 2 + factor - 1
201
- pad1 = p // 2 + 1
202
-
203
- self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor)
204
-
205
- if downsample:
206
- factor = 2
207
- p = (len(blur_kernel) - factor) + (kernel_size - 1)
208
- pad0 = (p + 1) // 2
209
- pad1 = p // 2
210
-
211
- self.blur = Blur(blur_kernel, pad=(pad0, pad1))
212
-
213
- fan_in = in_channel * kernel_size ** 2
214
- self.scale = 1 / math.sqrt(fan_in)
215
- self.padding = kernel_size // 2
216
-
217
- self.weight = nn.Parameter(
218
- torch.randn(1, out_channel, in_channel, kernel_size, kernel_size)
219
- )
220
-
221
- self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
222
-
223
- self.demodulate = demodulate
224
- self.fused = fused
225
-
226
- def __repr__(self):
227
- return (
228
- f"{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, "
229
- f"upsample={self.upsample}, downsample={self.downsample})"
230
- )
231
-
232
- def forward(self, input, style):
233
- batch, in_channel, height, width = input.shape
234
-
235
- if not self.fused:
236
- weight = self.scale * self.weight.squeeze(0)
237
- style = self.modulation(style)
238
-
239
- if self.demodulate:
240
- w = weight.unsqueeze(0) * style.view(batch, 1, in_channel, 1, 1)
241
- dcoefs = (w.square().sum((2, 3, 4)) + 1e-8).rsqrt()
242
-
243
- input = input * style.reshape(batch, in_channel, 1, 1)
244
-
245
- if self.upsample:
246
- weight = weight.transpose(0, 1)
247
- out = conv2d_gradfix.conv_transpose2d(
248
- input, weight, padding=0, stride=2
249
- )
250
- out = self.blur(out)
251
-
252
- elif self.downsample:
253
- input = self.blur(input)
254
- out = conv2d_gradfix.conv2d(input, weight, padding=0, stride=2)
255
-
256
- else:
257
- out = conv2d_gradfix.conv2d(input, weight, padding=self.padding)
258
-
259
- if self.demodulate:
260
- out = out * dcoefs.view(batch, -1, 1, 1)
261
-
262
- return out
263
-
264
- style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
265
- weight = self.scale * self.weight * style
266
-
267
- if self.demodulate:
268
- demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8)
269
- weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
270
-
271
- weight = weight.view(
272
- batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size
273
- )
274
-
275
- if self.upsample:
276
- input = input.view(1, batch * in_channel, height, width)
277
- weight = weight.view(
278
- batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size
279
- )
280
- weight = weight.transpose(1, 2).reshape(
281
- batch * in_channel, self.out_channel, self.kernel_size, self.kernel_size
282
- )
283
- out = conv2d_gradfix.conv_transpose2d(
284
- input, weight, padding=0, stride=2, groups=batch
285
- )
286
- _, _, height, width = out.shape
287
- out = out.view(batch, self.out_channel, height, width)
288
- out = self.blur(out)
289
-
290
- elif self.downsample:
291
- input = self.blur(input)
292
- _, _, height, width = input.shape
293
- input = input.view(1, batch * in_channel, height, width)
294
- out = conv2d_gradfix.conv2d(
295
- input, weight, padding=0, stride=2, groups=batch
296
- )
297
- _, _, height, width = out.shape
298
- out = out.view(batch, self.out_channel, height, width)
299
-
300
- else:
301
- input = input.view(1, batch * in_channel, height, width)
302
- out = conv2d_gradfix.conv2d(
303
- input, weight, padding=self.padding, groups=batch
304
- )
305
- _, _, height, width = out.shape
306
- out = out.view(batch, self.out_channel, height, width)
307
-
308
- return out
309
-
310
-
311
- class NoiseInjection(nn.Module):
312
- def __init__(self):
313
- super().__init__()
314
-
315
- self.weight = nn.Parameter(torch.zeros(1))
316
-
317
- def forward(self, image, noise=None):
318
- if noise is None:
319
- batch, _, height, width = image.shape
320
- noise = image.new_empty(batch, 1, height, width).normal_()
321
-
322
- return image + self.weight * noise
323
-
324
-
325
- class ConstantInput(nn.Module):
326
- def __init__(self, channel, size=4):
327
- super().__init__()
328
-
329
- self.input = nn.Parameter(torch.randn(1, channel, size, size))
330
-
331
- def forward(self, input):
332
- batch = input.shape[0]
333
- out = self.input.repeat(batch, 1, 1, 1)
334
-
335
- return out
336
-
337
-
338
- class StyledConv(nn.Module):
339
- def __init__(
340
- self,
341
- in_channel,
342
- out_channel,
343
- kernel_size,
344
- style_dim,
345
- upsample=False,
346
- blur_kernel=[1, 3, 3, 1],
347
- demodulate=True,
348
- ):
349
- super().__init__()
350
-
351
- self.conv = ModulatedConv2d(
352
- in_channel,
353
- out_channel,
354
- kernel_size,
355
- style_dim,
356
- upsample=upsample,
357
- blur_kernel=blur_kernel,
358
- demodulate=demodulate,
359
- )
360
-
361
- self.noise = NoiseInjection()
362
- # self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1))
363
- # self.activate = ScaledLeakyReLU(0.2)
364
- self.activate = FusedLeakyReLU(out_channel)
365
-
366
- def forward(self, input, style, noise=None):
367
- out = self.conv(input, style)
368
- out = self.noise(out, noise=noise)
369
- # out = out + self.bias
370
- out = self.activate(out)
371
-
372
- return out
373
-
374
-
375
- class ToRGB(nn.Module):
376
- def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]):
377
- super().__init__()
378
-
379
- if upsample:
380
- self.upsample = Upsample(blur_kernel)
381
-
382
- self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False)
383
- self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))
384
-
385
- def forward(self, input, style, skip=None):
386
- out = self.conv(input, style)
387
- out = out + self.bias
388
-
389
- if skip is not None:
390
- skip = self.upsample(skip)
391
-
392
- out = out + skip
393
-
394
- return out
395
-
396
-
397
- class Generator(nn.Module):
398
- def __init__(
399
- self,
400
- size,
401
- style_dim,
402
- n_mlp,
403
- channel_multiplier=2,
404
- blur_kernel=[1, 3, 3, 1],
405
- lr_mlp=0.01,
406
- ):
407
- super().__init__()
408
-
409
- self.size = size
410
-
411
- self.style_dim = style_dim
412
-
413
- layers = [PixelNorm()]
414
-
415
- for i in range(n_mlp):
416
- layers.append(
417
- EqualLinear(
418
- style_dim, style_dim, lr_mul=lr_mlp, activation="fused_lrelu"
419
- )
420
- )
421
-
422
- self.style = nn.Sequential(*layers)
423
-
424
- self.channels = {
425
- 4: 512,
426
- 8: 512,
427
- 16: 512,
428
- 32: 512,
429
- 64: 256 * channel_multiplier,
430
- 128: 128 * channel_multiplier,
431
- 256: 64 * channel_multiplier,
432
- 512: 32 * channel_multiplier,
433
- 1024: 16 * channel_multiplier,
434
- }
435
-
436
- self.input = ConstantInput(self.channels[4])
437
- self.conv1 = StyledConv(
438
- self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel
439
- )
440
- self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False)
441
-
442
- self.log_size = int(math.log(size, 2))
443
- self.num_layers = (self.log_size - 2) * 2 + 1
444
-
445
- self.convs = nn.ModuleList()
446
- self.upsamples = nn.ModuleList()
447
- self.to_rgbs = nn.ModuleList()
448
- self.noises = nn.Module()
449
-
450
- in_channel = self.channels[4]
451
-
452
- for layer_idx in range(self.num_layers):
453
- res = (layer_idx + 5) // 2
454
- shape = [1, 1, 2 ** res, 2 ** res]
455
- self.noises.register_buffer(f"noise_{layer_idx}", torch.randn(*shape))
456
-
457
- for i in range(3, self.log_size + 1):
458
- out_channel = self.channels[2 ** i]
459
-
460
- self.convs.append(
461
- StyledConv(
462
- in_channel,
463
- out_channel,
464
- 3,
465
- style_dim,
466
- upsample=True,
467
- blur_kernel=blur_kernel,
468
- )
469
- )
470
-
471
- self.convs.append(
472
- StyledConv(
473
- out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel
474
- )
475
- )
476
-
477
- self.to_rgbs.append(ToRGB(out_channel, style_dim))
478
-
479
- in_channel = out_channel
480
-
481
- self.n_latent = self.log_size * 2 - 2
482
-
483
- def make_noise(self):
484
- device = self.input.input.device
485
-
486
- noises = [torch.randn(1, 1, 2 ** 2, 2 ** 2, device=device)]
487
-
488
- for i in range(3, self.log_size + 1):
489
- for _ in range(2):
490
- noises.append(torch.randn(1, 1, 2 ** i, 2 ** i, device=device))
491
-
492
- return noises
493
-
494
- @torch.no_grad()
495
- def mean_latent(self, n_latent):
496
- latent_in = torch.randn(
497
- n_latent, self.style_dim, device=self.input.input.device
498
- )
499
- latent = self.style(latent_in).mean(0, keepdim=True)
500
-
501
- return latent
502
-
503
- @torch.no_grad()
504
- def get_latent(self, input):
505
- return self.style(input)
506
-
507
- def forward(
508
- self,
509
- styles,
510
- return_latents=False,
511
- inject_index=None,
512
- truncation=1,
513
- truncation_latent=None,
514
- input_is_latent=False,
515
- noise=None,
516
- randomize_noise=True,
517
- ):
518
-
519
- if noise is None:
520
- if randomize_noise:
521
- noise = [None] * self.num_layers
522
- else:
523
- noise = [
524
- getattr(self.noises, f"noise_{i}") for i in range(self.num_layers)
525
- ]
526
-
527
- if not input_is_latent:
528
- styles = [self.style(s) for s in styles]
529
-
530
- if truncation < 1:
531
- style_t = []
532
-
533
- for style in styles:
534
- style_t.append(
535
- truncation_latent + truncation * (style - truncation_latent)
536
- )
537
-
538
- styles = style_t
539
- latent = styles[0].unsqueeze(1).repeat(1, self.n_latent, 1)
540
- else:
541
- latent = styles
542
-
543
- out = self.input(latent)
544
- out = self.conv1(out, latent[:, 0], noise=noise[0])
545
-
546
- skip = self.to_rgb1(out, latent[:, 1])
547
-
548
- i = 1
549
- for conv1, conv2, noise1, noise2, to_rgb in zip(
550
- self.convs[::2], self.convs[1::2], noise[1::2], noise[2::2], self.to_rgbs
551
- ):
552
- out = conv1(out, latent[:, i], noise=noise1)
553
- out = conv2(out, latent[:, i + 1], noise=noise2)
554
- skip = to_rgb(out, latent[:, i + 2], skip)
555
-
556
- i += 2
557
-
558
- image = skip
559
-
560
- return image
561
-
562
-
563
- class ConvLayer(nn.Sequential):
564
- def __init__(
565
- self,
566
- in_channel,
567
- out_channel,
568
- kernel_size,
569
- downsample=False,
570
- blur_kernel=[1, 3, 3, 1],
571
- bias=True,
572
- activate=True,
573
- ):
574
- layers = []
575
-
576
- if downsample:
577
- factor = 2
578
- p = (len(blur_kernel) - factor) + (kernel_size - 1)
579
- pad0 = (p + 1) // 2
580
- pad1 = p // 2
581
-
582
- layers.append(Blur(blur_kernel, pad=(pad0, pad1)))
583
-
584
- stride = 2
585
- self.padding = 0
586
-
587
- else:
588
- stride = 1
589
- self.padding = kernel_size // 2
590
-
591
- layers.append(
592
- EqualConv2d(
593
- in_channel,
594
- out_channel,
595
- kernel_size,
596
- padding=self.padding,
597
- stride=stride,
598
- bias=bias and not activate,
599
- )
600
- )
601
-
602
- if activate:
603
- layers.append(FusedLeakyReLU(out_channel, bias=bias))
604
-
605
- super().__init__(*layers)
606
-
607
-
608
- class ResBlock(nn.Module):
609
- def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]):
610
- super().__init__()
611
-
612
- self.conv1 = ConvLayer(in_channel, in_channel, 3)
613
- self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True)
614
-
615
- self.skip = ConvLayer(
616
- in_channel, out_channel, 1, downsample=True, activate=False, bias=False
617
- )
618
-
619
- def forward(self, input):
620
- out = self.conv1(input)
621
- out = self.conv2(out)
622
-
623
- skip = self.skip(input)
624
- out = (out + skip) / math.sqrt(2)
625
-
626
- return out
627
-
628
-
629
- class Discriminator(nn.Module):
630
- def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]):
631
- super().__init__()
632
-
633
- channels = {
634
- 4: 512,
635
- 8: 512,
636
- 16: 512,
637
- 32: 512,
638
- 64: 256 * channel_multiplier,
639
- 128: 128 * channel_multiplier,
640
- 256: 64 * channel_multiplier,
641
- 512: 32 * channel_multiplier,
642
- 1024: 16 * channel_multiplier,
643
- }
644
-
645
- convs = [ConvLayer(3, channels[size], 1)]
646
-
647
- log_size = int(math.log(size, 2))
648
-
649
- in_channel = channels[size]
650
-
651
- for i in range(log_size, 2, -1):
652
- out_channel = channels[2 ** (i - 1)]
653
-
654
- convs.append(ResBlock(in_channel, out_channel, blur_kernel))
655
-
656
- in_channel = out_channel
657
-
658
- self.convs = nn.Sequential(*convs)
659
-
660
- self.stddev_group = 4
661
- self.stddev_feat = 1
662
-
663
- self.final_conv = ConvLayer(in_channel + 1, channels[4], 3)
664
- self.final_linear = nn.Sequential(
665
- EqualLinear(channels[4] * 4 * 4, channels[4], activation="fused_lrelu"),
666
- EqualLinear(channels[4], 1),
667
- )
668
-
669
- def forward(self, input):
670
- out = self.convs(input)
671
-
672
- batch, channel, height, width = out.shape
673
- group = min(batch, self.stddev_group)
674
- stddev = out.view(
675
- group, -1, self.stddev_feat, channel // self.stddev_feat, height, width
676
- )
677
- stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8)
678
- stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2)
679
- stddev = stddev.repeat(group, 1, height, width)
680
- out = torch.cat([out, stddev], 1)
681
-
682
- out = self.final_conv(out)
683
-
684
- out = out.view(batch, -1)
685
- out = self.final_linear(out)
686
-
687
- return out
688
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
util.py DELETED
@@ -1,220 +0,0 @@
1
- from matplotlib import pyplot as plt
2
- import torch
3
- import torch.nn.functional as F
4
- import os
5
- import cv2
6
- import dlib
7
- from PIL import Image
8
- import numpy as np
9
- import math
10
- import torchvision
11
- import scipy
12
- import scipy.ndimage
13
- import torchvision.transforms as transforms
14
-
15
- from huggingface_hub import hf_hub_download
16
-
17
-
18
- shape_predictor_path = hf_hub_download(repo_id="akhaliq/jojogan_dlib", filename="shape_predictor_68_face_landmarks.dat")
19
-
20
-
21
- google_drive_paths = {
22
- "models/stylegan2-ffhq-config-f.pt": "https://drive.google.com/uc?id=1Yr7KuD959btpmcKGAUsbAk5rPjX2MytK",
23
- "models/dlibshape_predictor_68_face_landmarks.dat": "https://drive.google.com/uc?id=11BDmNKS1zxSZxkgsEvQoKgFd8J264jKp",
24
- "models/e4e_ffhq_encode.pt": "https://drive.google.com/uc?id=1o6ijA3PkcewZvwJJ73dJ0fxhndn0nnh7",
25
- "models/restyle_psp_ffhq_encode.pt": "https://drive.google.com/uc?id=1nbxCIVw9H3YnQsoIPykNEFwWJnHVHlVd",
26
- "models/arcane_caitlyn.pt": "https://drive.google.com/uc?id=1gOsDTiTPcENiFOrhmkkxJcTURykW1dRc",
27
- "models/arcane_caitlyn_preserve_color.pt": "https://drive.google.com/uc?id=1cUTyjU-q98P75a8THCaO545RTwpVV-aH",
28
- "models/arcane_jinx_preserve_color.pt": "https://drive.google.com/uc?id=1jElwHxaYPod5Itdy18izJk49K1nl4ney",
29
- "models/arcane_jinx.pt": "https://drive.google.com/uc?id=1quQ8vPjYpUiXM4k1_KIwP4EccOefPpG_",
30
- "models/disney.pt": "https://drive.google.com/uc?id=1zbE2upakFUAx8ximYnLofFwfT8MilqJA",
31
- "models/disney_preserve_color.pt": "https://drive.google.com/uc?id=1Bnh02DjfvN_Wm8c4JdOiNV4q9J7Z_tsi",
32
- "models/jojo.pt": "https://drive.google.com/uc?id=13cR2xjIBj8Ga5jMO7gtxzIJj2PDsBYK4",
33
- "models/jojo_preserve_color.pt": "https://drive.google.com/uc?id=1ZRwYLRytCEKi__eT2Zxv1IlV6BGVQ_K2",
34
- "models/jojo_yasuho.pt": "https://drive.google.com/uc?id=1grZT3Gz1DLzFoJchAmoj3LoM9ew9ROX_",
35
- "models/jojo_yasuho_preserve_color.pt": "https://drive.google.com/uc?id=1SKBu1h0iRNyeKBnya_3BBmLr4pkPeg_L",
36
- "models/supergirl.pt": "https://drive.google.com/uc?id=1L0y9IYgzLNzB-33xTpXpecsKU-t9DpVC",
37
- "models/supergirl_preserve_color.pt": "https://drive.google.com/uc?id=1VmKGuvThWHym7YuayXxjv0fSn32lfDpE",
38
- }
39
-
40
- @torch.no_grad()
41
- def load_model(generator, model_file_path):
42
- ensure_checkpoint_exists(model_file_path)
43
- ckpt = torch.load(model_file_path, map_location=lambda storage, loc: storage)
44
- generator.load_state_dict(ckpt["g_ema"], strict=False)
45
- return generator.mean_latent(50000)
46
-
47
- def ensure_checkpoint_exists(model_weights_filename):
48
- if not os.path.isfile(model_weights_filename) and (
49
- model_weights_filename in google_drive_paths
50
- ):
51
- gdrive_url = google_drive_paths[model_weights_filename]
52
- try:
53
- from gdown import download as drive_download
54
-
55
- drive_download(gdrive_url, model_weights_filename, quiet=False)
56
- except ModuleNotFoundError:
57
- print(
58
- "gdown module not found.",
59
- "pip3 install gdown or, manually download the checkpoint file:",
60
- gdrive_url
61
- )
62
-
63
- if not os.path.isfile(model_weights_filename) and (
64
- model_weights_filename not in google_drive_paths
65
- ):
66
- print(
67
- model_weights_filename,
68
- " not found, you may need to manually download the model weights."
69
- )
70
-
71
- # given a list of filenames, load the inverted style code
72
- @torch.no_grad()
73
- def load_source(files, generator, device='cuda'):
74
- sources = []
75
-
76
- for file in files:
77
- source = torch.load(f'./inversion_codes/{file}.pt')['latent'].to(device)
78
-
79
- if source.size(0) != 1:
80
- source = source.unsqueeze(0)
81
-
82
- if source.ndim == 3:
83
- source = generator.get_latent(source, truncation=1, is_latent=True)
84
- source = list2style(source)
85
-
86
- sources.append(source)
87
-
88
- sources = torch.cat(sources, 0)
89
- if type(sources) is not list:
90
- sources = style2list(sources)
91
-
92
- return sources
93
-
94
- def display_image(image, size=None, mode='nearest', unnorm=False, title=''):
95
- # image is [3,h,w] or [1,3,h,w] tensor [0,1]
96
- if not isinstance(image, torch.Tensor):
97
- image = transforms.ToTensor()(image).unsqueeze(0)
98
- if image.is_cuda:
99
- image = image.cpu()
100
- if size is not None and image.size(-1) != size:
101
- image = F.interpolate(image, size=(size,size), mode=mode)
102
- if image.dim() == 4:
103
- image = image[0]
104
- image = image.permute(1, 2, 0).detach().numpy()
105
- plt.figure()
106
- plt.title(title)
107
- plt.axis('off')
108
- plt.imshow(image)
109
-
110
- def get_landmark(filepath, predictor):
111
- """get landmark with dlib
112
- :return: np.array shape=(68, 2)
113
- """
114
- detector = dlib.get_frontal_face_detector()
115
-
116
- img = dlib.load_rgb_image(filepath)
117
- dets = detector(img, 1)
118
- assert len(dets) > 0, "Face not detected, try another face image"
119
-
120
- for k, d in enumerate(dets):
121
- shape = predictor(img, d)
122
-
123
- t = list(shape.parts())
124
- a = []
125
- for tt in t:
126
- a.append([tt.x, tt.y])
127
- lm = np.array(a)
128
- return lm
129
-
130
-
131
- def align_face(filepath, output_size=256, transform_size=1024, enable_padding=True):
132
-
133
- """
134
- :param filepath: str
135
- :return: PIL Image
136
- """
137
- predictor = dlib.shape_predictor(shape_predictor_path)
138
- lm = get_landmark(filepath, predictor)
139
-
140
- lm_chin = lm[0: 17] # left-right
141
- lm_eyebrow_left = lm[17: 22] # left-right
142
- lm_eyebrow_right = lm[22: 27] # left-right
143
- lm_nose = lm[27: 31] # top-down
144
- lm_nostrils = lm[31: 36] # top-down
145
- lm_eye_left = lm[36: 42] # left-clockwise
146
- lm_eye_right = lm[42: 48] # left-clockwise
147
- lm_mouth_outer = lm[48: 60] # left-clockwise
148
- lm_mouth_inner = lm[60: 68] # left-clockwise
149
-
150
- # Calculate auxiliary vectors.
151
- eye_left = np.mean(lm_eye_left, axis=0)
152
- eye_right = np.mean(lm_eye_right, axis=0)
153
- eye_avg = (eye_left + eye_right) * 0.5
154
- eye_to_eye = eye_right - eye_left
155
- mouth_left = lm_mouth_outer[0]
156
- mouth_right = lm_mouth_outer[6]
157
- mouth_avg = (mouth_left + mouth_right) * 0.5
158
- eye_to_mouth = mouth_avg - eye_avg
159
-
160
- # Choose oriented crop rectangle.
161
- x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
162
- x /= np.hypot(*x)
163
- x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
164
- y = np.flipud(x) * [-1, 1]
165
- c = eye_avg + eye_to_mouth * 0.1
166
- quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
167
- qsize = np.hypot(*x) * 2
168
-
169
- # read image
170
- img = Image.open(filepath)
171
-
172
- transform_size = output_size
173
- enable_padding = True
174
-
175
- # Shrink.
176
- shrink = int(np.floor(qsize / output_size * 0.5))
177
- if shrink > 1:
178
- rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
179
- img = img.resize(rsize, Image.ANTIALIAS)
180
- quad /= shrink
181
- qsize /= shrink
182
-
183
- # Crop.
184
- border = max(int(np.rint(qsize * 0.1)), 3)
185
- crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
186
- int(np.ceil(max(quad[:, 1]))))
187
- crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]),
188
- min(crop[3] + border, img.size[1]))
189
- if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
190
- img = img.crop(crop)
191
- quad -= crop[0:2]
192
-
193
- # Pad.
194
- pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))), int(np.ceil(max(quad[:, 0]))),
195
- int(np.ceil(max(quad[:, 1]))))
196
- pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0),
197
- max(pad[3] - img.size[1] + border, 0))
198
- if enable_padding and max(pad) > border - 4:
199
- pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
200
- img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
201
- h, w, _ = img.shape
202
- y, x, _ = np.ogrid[:h, :w, :1]
203
- mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
204
- 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
205
- blur = qsize * 0.02
206
- img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
207
- img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
208
- img = Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
209
- quad += pad[:2]
210
-
211
- # Transform.
212
- img = img.transform((transform_size, transform_size), Image.QUAD, (quad + 0.5).flatten(), Image.BILINEAR)
213
- if output_size < transform_size:
214
- img = img.resize((output_size, output_size), Image.ANTIALIAS)
215
-
216
- # Return aligned image.
217
- return img
218
-
219
- def strip_path_extension(path):
220
- return os.path.splitext(path)[0]