Arnaudding001 commited on
Commit
e7c3832
·
1 Parent(s): f8f5c75

Create vtoonify_model.py

Browse files
Files changed (1) hide show
  1. vtoonify_model.py +282 -0
vtoonify_model.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import gradio as gr
3
+ import pathlib
4
+ import sys
5
+ sys.path.insert(0, 'vtoonify')
6
+
7
+ from util import load_psp_standalone, get_video_crop_parameter, tensor2cv2
8
+ import torch
9
+ import torch.nn as nn
10
+ import numpy as np
11
+ import dlib
12
+ import cv2
13
+ from model.vtoonify import VToonify
14
+ from model.bisenet.model import BiSeNet
15
+ import torch.nn.functional as F
16
+ from torchvision import transforms
17
+ from model.encoder.align_all_parallel import align_face
18
+ import gc
19
+ import huggingface_hub
20
+ import os
21
+
22
+ MODEL_REPO = 'PKUWilliamYang/VToonify'
23
+
24
+ class Model():
25
+ def __init__(self, device):
26
+ super().__init__()
27
+
28
+ self.device = device
29
+ self.style_types = {
30
+ 'cartoon1': ['vtoonify_d_cartoon/vtoonify_s026_d0.5.pt', 26],
31
+ 'cartoon1-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 26],
32
+ 'cartoon2-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 64],
33
+ 'cartoon3-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 153],
34
+ 'cartoon4': ['vtoonify_d_cartoon/vtoonify_s299_d0.5.pt', 299],
35
+ 'cartoon4-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 299],
36
+ 'cartoon5-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 8],
37
+ 'comic1-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 28],
38
+ 'comic2-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 18],
39
+ 'arcane1': ['vtoonify_d_arcane/vtoonify_s000_d0.5.pt', 0],
40
+ 'arcane1-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 0],
41
+ 'arcane2': ['vtoonify_d_arcane/vtoonify_s077_d0.5.pt', 77],
42
+ 'arcane2-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 77],
43
+ 'caricature1': ['vtoonify_d_caricature/vtoonify_s039_d0.5.pt', 39],
44
+ 'caricature2': ['vtoonify_d_caricature/vtoonify_s068_d0.5.pt', 68],
45
+ 'pixar': ['vtoonify_d_pixar/vtoonify_s052_d0.5.pt', 52],
46
+ 'pixar-d': ['vtoonify_d_pixar/vtoonify_s_d.pt', 52],
47
+ 'illustration1-d': ['vtoonify_d_illustration/vtoonify_s054_d_c.pt', 54],
48
+ 'illustration2-d': ['vtoonify_d_illustration/vtoonify_s004_d_c.pt', 4],
49
+ 'illustration3-d': ['vtoonify_d_illustration/vtoonify_s009_d_c.pt', 9],
50
+ 'illustration4-d': ['vtoonify_d_illustration/vtoonify_s043_d_c.pt', 43],
51
+ 'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
52
+ }
53
+
54
+ self.landmarkpredictor = self._create_dlib_landmark_model()
55
+ self.parsingpredictor = self._create_parsing_model()
56
+ self.pspencoder = self._load_encoder()
57
+ self.transform = transforms.Compose([
58
+ transforms.ToTensor(),
59
+ transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
60
+ ])
61
+
62
+ self.vtoonify, self.exstyle = self._load_default_model()
63
+ self.color_transfer = False
64
+ self.style_name = 'cartoon1'
65
+ self.video_limit_cpu = 100
66
+ self.video_limit_gpu = 300
67
+
68
+ @staticmethod
69
+ def _create_dlib_landmark_model():
70
+ return dlib.shape_predictor(huggingface_hub.hf_hub_download(MODEL_REPO,
71
+ 'models/shape_predictor_68_face_landmarks.dat'))
72
+
73
+ def _create_parsing_model(self):
74
+ parsingpredictor = BiSeNet(n_classes=19)
75
+ parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
76
+ map_location=lambda storage, loc: storage))
77
+ parsingpredictor.to(self.device).eval()
78
+ return parsingpredictor
79
+
80
+ def _load_encoder(self) -> nn.Module:
81
+ style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO,'models/encoder.pt')
82
+ return load_psp_standalone(style_encoder_path, self.device)
83
+
84
+ def _load_default_model(self) -> tuple[torch.Tensor, str]:
85
+ vtoonify = VToonify(backbone = 'dualstylegan')
86
+ vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
87
+ 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
88
+ map_location=lambda storage, loc: storage)['g_ema'])
89
+ vtoonify.to(self.device)
90
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
91
+ exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
92
+ with torch.no_grad():
93
+ exstyle = vtoonify.zplus2wplus(exstyle)
94
+ return vtoonify, exstyle
95
+
96
+ def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
97
+ if 'illustration' in style_type:
98
+ self.color_transfer = True
99
+ else:
100
+ self.color_transfer = False
101
+ if style_type not in self.style_types.keys():
102
+ return None, 'Oops, wrong Style Type. Please select a valid model.'
103
+ self.style_name = style_type
104
+ model_path, ind = self.style_types[style_type]
105
+ style_path = os.path.join('models',os.path.dirname(model_path),'exstyle_code.npy')
106
+ self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/'+model_path),
107
+ map_location=lambda storage, loc: storage)['g_ema'])
108
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
109
+ exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
110
+ with torch.no_grad():
111
+ exstyle = self.vtoonify.zplus2wplus(exstyle)
112
+ return exstyle, 'Model of %s loaded.'%(style_type)
113
+
114
+ def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
115
+ message = 'Error: no face detected! Please retry or change the photo.'
116
+ paras = get_video_crop_parameter(frame, self.landmarkpredictor, [left, right, top, bottom])
117
+ instyle = None
118
+ h, w, scale = 0, 0, 0
119
+ if paras is not None:
120
+ h,w,top,bottom,left,right,scale = paras
121
+ H, W = int(bottom-top), int(right-left)
122
+ # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
123
+ kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
124
+ if scale <= 0.75:
125
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
126
+ if scale <= 0.375:
127
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
128
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
129
+ with torch.no_grad():
130
+ I = align_face(frame, self.landmarkpredictor)
131
+ if I is not None:
132
+ I = self.transform(I).unsqueeze(dim=0).to(self.device)
133
+ instyle = self.pspencoder(I)
134
+ instyle = self.vtoonify.zplus2wplus(instyle)
135
+ message = 'Successfully rescale the frame to (%d, %d)'%(bottom-top, right-left)
136
+ else:
137
+ frame = np.zeros((256,256,3), np.uint8)
138
+ else:
139
+ frame = np.zeros((256,256,3), np.uint8)
140
+ if return_para:
141
+ return frame, instyle, message, w, h, top, bottom, left, right, scale
142
+ return frame, instyle, message
143
+
144
+ #@torch.inference_mode()
145
+ def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
146
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
147
+ if image is None:
148
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
149
+ frame = cv2.imread(image)
150
+ if frame is None:
151
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load the image.'
152
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
153
+ return self.detect_and_align(frame, top, bottom, left, right)
154
+
155
+ def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
156
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
157
+ if video is None:
158
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
159
+ video_cap = cv2.VideoCapture(video)
160
+ if video_cap.get(7) == 0:
161
+ video_cap.release()
162
+ return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
163
+ success, frame = video_cap.read()
164
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
165
+ video_cap.release()
166
+ return self.detect_and_align(frame, top, bottom, left, right)
167
+
168
+ def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple[str, torch.Tensor, str]:
169
+ message = 'Error: no face detected! Please retry or change the video.'
170
+ instyle = None
171
+ if video is None:
172
+ return 'default.mp4', instyle, 'Error: fail to load empty file.'
173
+ video_cap = cv2.VideoCapture(video)
174
+ if video_cap.get(7) == 0:
175
+ video_cap.release()
176
+ return 'default.mp4', instyle, 'Error: fail to load the video.'
177
+ num = min(self.video_limit_gpu, int(video_cap.get(7)))
178
+ if self.device == 'cpu':
179
+ num = min(self.video_limit_cpu, num)
180
+ success, frame = video_cap.read()
181
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
182
+ frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
183
+ if instyle is None:
184
+ return 'default.mp4', instyle, message
185
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
186
+ videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
187
+ videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
188
+ kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
189
+ for i in range(num-1):
190
+ success, frame = video_cap.read()
191
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
192
+ if scale <= 0.75:
193
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
194
+ if scale <= 0.375:
195
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
196
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
197
+ videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
198
+
199
+ videoWriter.release()
200
+ video_cap.release()
201
+
202
+ return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)'%(bottom-top, right-left)
203
+
204
+ def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[np.ndarray, str]:
205
+ #print(style_type + ' ' + self.style_name)
206
+ if instyle is None or aligned_face is None:
207
+ return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the input. Please go to Step 2 and Rescale Image/First Frame again.'
208
+ if self.style_name != style_type:
209
+ exstyle, _ = self.load_model(style_type)
210
+ if exstyle is None:
211
+ return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
212
+ with torch.no_grad():
213
+ if self.color_transfer:
214
+ s_w = exstyle
215
+ else:
216
+ s_w = instyle.clone()
217
+ s_w[:,:7] = exstyle[:,:7]
218
+
219
+ x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
220
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
221
+ scale_factor=0.5, recompute_scale_factor=False).detach()
222
+ inputs = torch.cat((x, x_p/16.), dim=1)
223
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = style_degree)
224
+ y_tilde = torch.clamp(y_tilde, -1, 1)
225
+ print('*** Toonify %dx%d image with style of %s'%(y_tilde.shape[2], y_tilde.shape[3], style_type))
226
+ return ((y_tilde[0].cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8), 'Successfully toonify the image with style of %s'%(self.style_name)
227
+
228
+ def video_tooniy(self, aligned_video: str, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[str, str]:
229
+ #print(style_type + ' ' + self.style_name)
230
+ if aligned_video is None:
231
+ return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
232
+ video_cap = cv2.VideoCapture(aligned_video)
233
+ if instyle is None or aligned_video is None or video_cap.get(7) == 0:
234
+ video_cap.release()
235
+ return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
236
+ if self.style_name != style_type:
237
+ exstyle, _ = self.load_model(style_type)
238
+ if exstyle is None:
239
+ return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
240
+ num = min(self.video_limit_gpu, int(video_cap.get(7)))
241
+ if self.device == 'cpu':
242
+ num = min(self.video_limit_cpu, num)
243
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
244
+ videoWriter = cv2.VideoWriter('output.mp4', fourcc,
245
+ video_cap.get(5), (int(video_cap.get(3)*4),
246
+ int(video_cap.get(4)*4)))
247
+
248
+ batch_frames = []
249
+ if video_cap.get(3) != 0:
250
+ if self.device == 'cpu':
251
+ batch_size = max(1, int(4 * 256* 256/ video_cap.get(3) / video_cap.get(4)))
252
+ else:
253
+ batch_size = min(max(1, int(4 * 400 * 360/ video_cap.get(3) / video_cap.get(4))), 4)
254
+ else:
255
+ batch_size = 1
256
+ print('*** Toonify using batch size of %d on %dx%d video of %d frames with style of %s'%(batch_size, int(video_cap.get(3)*4), int(video_cap.get(4)*4), num, style_type))
257
+ with torch.no_grad():
258
+ if self.color_transfer:
259
+ s_w = exstyle
260
+ else:
261
+ s_w = instyle.clone()
262
+ s_w[:,:7] = exstyle[:,:7]
263
+ for i in range(num):
264
+ success, frame = video_cap.read()
265
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
266
+ batch_frames += [self.transform(frame).unsqueeze(dim=0).to(self.device)]
267
+ if len(batch_frames) == batch_size or (i+1) == num:
268
+ x = torch.cat(batch_frames, dim=0)
269
+ batch_frames = []
270
+ with torch.no_grad():
271
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
272
+ scale_factor=0.5, recompute_scale_factor=False).detach()
273
+ inputs = torch.cat((x, x_p/16.), dim=1)
274
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), style_degree)
275
+ y_tilde = torch.clamp(y_tilde, -1, 1)
276
+ for k in range(y_tilde.size(0)):
277
+ videoWriter.write(tensor2cv2(y_tilde[k].cpu()))
278
+ gc.collect()
279
+
280
+ videoWriter.release()
281
+ video_cap.release()
282
+ return 'output.mp4', 'Successfully toonify video of %d frames with style of %s'%(num, self.style_name)