File size: 10,893 Bytes
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa4803
95b1715
 
cfa4803
95b1715
 
 
 
 
 
 
 
cfa4803
95b1715
 
 
cfa4803
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96c63c3
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa4803
95b1715
 
cfa4803
95b1715
 
ad8ad02
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa4803
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa4803
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa4803
95b1715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import os
import sys
import torch
import pickle
import argparse
import numpy as np

from editings import ganspace
from editings.styleclip.mapper.styleclip_mapper import StyleCLIPMapper
from editings.styleclip.mapper.gloabl_mapper import StyleCLIPGlobalDirection
from editings.deltaedit.editor import DeltaEditor


STYLESPACE_IDX = [
            0,
            1,
            1,
            2,
            2,
            3,
            4,
            4,
            5,
            6,
            6,
            7,
            8,
            8,
            9,
            10,
            10,
            11,
            12,
            12,
            13,
            14,
            14,
            15,
            16,
            16,
        ]


class LatentEditor:
    def __init__(self, domain="human_faces", device="cpu"):

        self.domain = domain
        self.device = torch.device(device)

        if self.domain == "human_faces":
            self.interfacegan_directions = {
                "age": "editings/interfacegan_directions/age.pt",
                "smile": "editings/interfacegan_directions/smile.pt",
                "rotation": "editings/interfacegan_directions/rotation.pt",
            }
            self.interfacegan_tensors = {
                name: torch.load(path, map_location=self.device)
                for name, path in self.interfacegan_directions.items()
            }

            self.ganspace_pca = torch.load("editings/ganspace_pca/ffhq_pca.pt", map_location=self.device)
            self.ganspace_directions = {
                "eye_openness": (54, 7, 8, 5),
                "trimmed_beard": (58, 7, 9, 7),
                "lipstick": (34, 10, 11, 20),
                "face_roundness": (37, 0, 5, 20.0),
                "nose_length": (51, 4, 5, -30.0),
                "eyebrow_thickness": (37, 8, 9, 20.0),
                "head_angle_up": (11, 1, 4, -10.5),
                "displeased": (36, 4, 7, 10.0),
            }

            self.styleclip_directions = {
                "afro": [False, False, True],
                "angry": [False, False, True],
                "beyonce": [False, False, False],
                "bobcut": [False, False, True],
                "bowlcut": [False, False, True],
                "curly_hair": [False, False, True],
                "hilary_clinton": [False, False, False],
                "depp": [False, False, False],
                "mohawk": [False, False, True],
                "purple_hair": [False, False, False],
                "surprised": [False, False, True],
                "taylor_swift": [False, False, False],
                "trump": [False, False, False],
                "zuckerberg": [False, False, False],
            }
            self.styleclip_global_editor = self.load_styleclip_global()

            self.stylespace_directions = {
                "black hair": [(12, 479)],
                "blond hair": [(12, 479), (12, 266)],
                "grey hair": [(11, 286)],
                "wavy hair": [(6, 500), (8, 128), (5, 92), (6, 394), (6, 323)],
                "bangs": [
                    (3, 259),
                    (6, 285),
                    (5, 414),
                    (6, 128),
                    (9, 295),
                    (6, 322),
                    (6, 487),
                    (6, 504),
                ],
                "receding hairline": [(5, 414), (6, 322), (6, 497), (6, 504)],
                "smiling": [(6, 501)],
                "sslipstick": [(15, 45)],
                "sideburns": [(12, 237)],
                "goatee": [(9, 421)],
                "earrings": [(8, 81)],
                "glasses": [(3, 288), (2, 175), (3, 120), (2, 97)],
                "wear suit": [(9, 441), (8, 292), (11, 358), (6, 223)],
                "gender": [(9, 6)],
            }
            
            self.fs_directions = {
                "fs_glasses": "editings/bound/Eyeglasses_boundary.npy",
                "fs_smiling": "editings/bound/Smiling_boundary.npy",
                "fs_makeup": "editings/bound/Heavy_Makeup_boundary.npy"
             }

            self.deltaedit_editor = DeltaEditor(device=self.device)

        elif self.domain == "car":

            self.stylespace_directions = {
                "front": [(8, 411)],
                "headlights": [(8, 441), (9, 355)],
                "grill": [(9, 191)],
                "trees": [(9, 108)],
                "grass_ss": [(12, 107)],
                "sky": [(12, 76)],
                "hubcap": [(12, 113), (12, 439)],
                "car color": [(12, 142), (15, 227)],
                "logo": [(9, 185)],
                "wheel angle": [(8, 420)],
            }

            self.ganspace_pca = torch.load("editings/ganspace_pca/cars_pca.pt")
            self.ganspace_directions = {
                "pose_1": (0, 0, 5, 2),
                "pose_2": (0, 0, 5, -2),
                "cube": (16, 3, 6, 25),
                "color": (22, 9, 11, -8),
                "grass": (41, 9, 11, -18)
            }


    def load_styleclip_global(self):
        delta_i_c = torch.from_numpy(np.load("editings/styleclip/global_mapper_data/delta_i_c.npy")).float().to(self.device)
        with open("editings/styleclip/global_mapper_data/S_mean_std", "rb") as channels_statistics:
            _, s_std = pickle.load(channels_statistics)
            s_std = [torch.from_numpy(s_i).float().to(self.device) for s_i in s_std]
        with open("editings/styleclip/global_mapper_data/templates.txt", "r") as templates:
            text_prompt_templates = templates.readlines()
        global_direction_calculator = StyleCLIPGlobalDirection(delta_i_c, s_std, text_prompt_templates, device=self.device)
        return global_direction_calculator


    def get_styleclip_mapper_edits(self, start_w, factors, direction):
        latents_to_display = []
        mapper_checkpoint_path = os.path.join(
            "pretrained_models/styleclip_mappers",
            f"{direction}.pt",
        )
        ckpt = torch.load(mapper_checkpoint_path, map_location="cpu")
        opts = ckpt["opts"]
        styleclip_opts = argparse.Namespace(
            **{
                "mapper_type": "LevelsMapper",
                "no_coarse_mapper": self.styleclip_directions[direction][0],
                "no_medium_mapper": self.styleclip_directions[direction][1],
                "no_fine_mapper": self.styleclip_directions[direction][2],
                "stylegan_size": 1024,
                "checkpoint_path": mapper_checkpoint_path,
            }
        )
        opts.update(vars(styleclip_opts))
        opts = argparse.Namespace(**opts)
        style_clip_net = StyleCLIPMapper(opts)
        style_clip_net.eval()
        style_clip_net.to(self.device)
        direction = style_clip_net.mapper(start_w)
        for factor in factors:
            edited_latent = start_w + factor * direction
            latents_to_display.append(edited_latent)

        return latents_to_display


    def get_styleclip_global_edits(self, start_s, factors, direction):
        latents_to_display = []

        neutral_text, target_text, disentanglement = direction.split("_")
        disentanglement = float(disentanglement)

        directions = self.styleclip_global_editor.get_delta_s(neutral_text, target_text, disentanglement)
        factors = torch.tensor(factors).to(self.device).view(-1, 1)
        srart_ss, start_rgb = start_s

        edits_rgb = []
        edits_ss = []
        for i in range(26):
            if i in [1, 4, 7, 10, 13, 16, 19, 22, 25]:
                edits_rgb.append(directions[i].view(1, -1).repeat(len(factors), 1))
            else:
                edits_ss.append(directions[i].view(1, -1).repeat(len(factors), 1))

        edited_rgb = []
        edited_ss = []
        for orig, edit in zip(srart_ss, edits_ss):
            edited_ss.append(orig.repeat(len(factors), 1) + edit * factors.repeat(1, orig.size(1)) / 1.5)
        for orig, edit in zip(start_rgb, edits_rgb):
            edited_rgb.append(orig.repeat(len(factors), 1) + edit * factors.repeat(1, orig.size(1)) / 1.5)
 

        return edited_ss, edited_rgb

    def get_deltaedit_edits(self, start_s, factors, direction, original_image):
        latents_to_display = []

        neutral_text, target_text, disentanglement = direction.split("_")
        disentanglement = float(disentanglement)

        factors = torch.tensor(factors).to(self.device).view(-1, 1)
        srart_ss, edited_rgb = start_s
        edits_ss = self.deltaedit_editor.get_delta_s(neutral_text, target_text, disentanglement, original_image, srart_ss)

        edited_rgb = [latent.repeat(len(factors), 1) for latent in edited_rgb]
        edited_ss = []
        for orig, edit in zip(srart_ss, edits_ss):
            edited_ss.append(orig.repeat(len(factors), 1) + edit * factors.repeat(1, orig.size(1)))

        return edited_ss, edited_rgb


    def get_ganspace_edits(self, start_w, factors, direction):
        latents_to_display = []
        for factor in factors:
            ganspace_direction = self.ganspace_directions[direction]
            edit_direction = list(ganspace_direction)
            edit_direction[-1] = factor
            edit_direction = tuple(edit_direction)

            new_w = ganspace.edit(start_w, self.ganspace_pca, [edit_direction])
            latents_to_display.append(new_w)
        return latents_to_display


    def get_interface_gan_edits(self, start_w, factors, direction):
        latents_to_display = []
        for factor in factors:
            tensor_direction = self.interfacegan_tensors[direction]
            edited_latent = start_w + factor / 2 * tensor_direction
            latents_to_display.append(edited_latent)
        return latents_to_display


    def get_stylespace_edits(self, start_s, factors, direction):
        edits = self.stylespace_directions[direction]
        start_stylespaces, start_stylespaces_rgb = start_s
        device = start_stylespaces[0].device
        latents_to_display = []

        edited_latent = [
            s.clone().repeat(len(factors), 1)
            for s in start_stylespaces
        ]
        factors = torch.tensor(factors).to(device)
        for layer_num, feat_num in edits:
            edited_latent[STYLESPACE_IDX[layer_num]][:, feat_num] += factors * 3
        edited_stylespaces_rgb = [
            rgb.repeat(len(factors), 1) for rgb in start_stylespaces_rgb
        ]

        return edited_latent, edited_stylespaces_rgb
        

    def get_fs_edits(self, w, factors, direction):
        path = self.fs_directions[direction]
        boundary = np.load(path)
        device = w.device
        bs = w.size(0)
        w_0 = w.cpu().numpy().reshape(bs, -1)
        boundary = boundary.reshape(1, -1).repeat(bs, 0)

        edits = [torch.tensor(w_0 + factor * boundary).view(bs, -1, 512).to(device) for factor in factors]

        return edits