forked from HighCWu/stylegan2-faceapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
193 lines (157 loc) · 5.43 KB
/
utils.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import inspect
import numpy as np
import moviepy.editor as mpy
import paddle
import paddle.nn as nn
from paddle.utils.download import get_weights_path_from_url
from ppgan.models.generators import StyleGANv2Generator as Generator
from ppgan.models.generators import Pixel2Style2Pixel
LMS_URL = 'https://paddlegan.bj.bcebos.com/models/lms.dat'
generator_model_cfgs = {
'ffhq-config-f': {
'model_urls': 'https://paddlegan.bj.bcebos.com/models/stylegan2-ffhq-config-f.pdparams',
'size': 1024,
'style_dim': 512,
'n_mlp': 8,
'channel_multiplier': 2
}
}
pSp_model_cfgs = {
'ffhq-inversion': {
'model_urls': 'https://paddlegan.bj.bcebos.com/models/pSp-ffhq-inversion.pdparams',
'size': 1024,
'style_dim': 512,
'n_mlp': 8,
'channel_multiplier': 2
}
}
class AttrDict(dict):
def __getattr__(self, key):
# return self[key]
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setattr__(self, key, value):
if key in self.__dict__:
self.__dict__[key] = value
else:
self[key] = value
__arg_types__ = []
__kwarg_types__ = {}
def arg_type(base_cls, *args, **kwargs):
if hasattr(base_cls, '__args__'):
base_type = base_cls.__args__[0]
nargs = True
else:
base_type = base_cls
nargs = False
cls_sig = None
if isinstance(base_cls, str):
cls_sig = base_cls
base_cls = object
base_type = bool
class ChildCls(base_cls):
__type__ = base_type
__args__ = list(args)
__kwargs__ = kwargs
__nargs__ = nargs
__arg_types__.append(ChildCls)
if cls_sig is not None:
__kwarg_types__[cls_sig] = ChildCls
return bool
return ChildCls
def func_args(parser, func):
sig = inspect.signature(func)
arg_names = []
for arg_name, arg_attrs in sig.parameters.items():
arg_cls = arg_attrs.annotation
type_sig = func.__name__ + ':' + arg_name
if arg_cls == bool and type_sig in __kwarg_types__:
arg_cls = __kwarg_types__[type_sig]
if arg_cls in __arg_types__:
use_default = not isinstance(arg_attrs.default, inspect._empty)
args = ['--'+arg_name] + arg_cls.__args__
kwargs = dict(**arg_cls.__kwargs__)
if not 'action' in kwargs:
kwargs['type'] = arg_cls.__type__
if use_default:
if not 'action' in kwargs:
kwargs['default'] = arg_attrs.default
else:
kwargs['required'] = True
if arg_cls.__nargs__:
kwargs['nargs'] = '+'
parser.add_argument(*args, **kwargs)
arg_names.append(arg_name)
return parser, arg_names
def make_image(tensor):
return (
((tensor.detach() + 1) / 2 * 255)
.clip(min=0, max=255)
.transpose((0, 2, 3, 1))
.numpy()
.astype('uint8')
)
def save_video(images, filename, fps, duration):
def make_frame(t):
idx = min(int(np.ceil(t / duration * len(images))), len(images)-1)
frame = images[idx]
return frame
clip = mpy.VideoClip(make_frame, duration=duration)
clip.write_videofile(filename, fps=fps)
def get_generator(
weight_path=None,
model_type='ffhq-config-f',
size=1024,
style_dim=512,
n_mlp=8,
channel_multiplier=2
):
if weight_path is None:
if model_type in generator_model_cfgs.keys():
weight_path = get_weights_path_from_url(generator_model_cfgs[model_type]['model_urls'])
size = generator_model_cfgs[model_type].get('size', size)
style_dim = generator_model_cfgs[model_type].get('style_dim', style_dim)
n_mlp = generator_model_cfgs[model_type].get('n_mlp', n_mlp)
channel_multiplier = generator_model_cfgs[model_type].get('channel_multiplier', channel_multiplier)
checkpoint = paddle.load(weight_path)
else:
raise ValueError('Predictor need a weight path or a pretrained model type')
else:
checkpoint = paddle.load(weight_path)
generator = Generator(size, style_dim, n_mlp, channel_multiplier)
generator.set_state_dict(checkpoint)
return generator
def get_pSp(
weight_path=None,
model_type='ffhq-inversion',
size=1024,
style_dim=512,
n_mlp=8,
channel_multiplier=2
):
if weight_path is None:
if model_type in pSp_model_cfgs.keys():
weight_path = get_weights_path_from_url(pSp_model_cfgs[model_type]['model_urls'])
size = pSp_model_cfgs[model_type].get('size', size)
style_dim = pSp_model_cfgs[model_type].get('style_dim', style_dim)
n_mlp = pSp_model_cfgs[model_type].get('n_mlp', n_mlp)
channel_multiplier = pSp_model_cfgs[model_type].get('channel_multiplier', channel_multiplier)
checkpoint = paddle.load(weight_path)
else:
raise ValueError('Predictor need a weight path or a pretrained model type')
else:
checkpoint = paddle.load(weight_path)
opts = checkpoint.pop('opts')
opts = AttrDict(opts)
_opts = AttrDict(
size=size,
style_dim=style_dim,
n_mlp=n_mlp,
channel_multiplier=channel_multiplier
)
opts.update(_opts)
pSp = Pixel2Style2Pixel(opts)
pSp.set_state_dict(checkpoint)
return pSp