Ashrafb commited on
Commit
6f9b2c1
·
verified ·
1 Parent(s): 3fc1121

Upload vtoonify_model-1.py

Browse files
Files changed (1) hide show
  1. vtoonify_model-1.py +312 -0
vtoonify_model-1.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 insightface
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.face_detector = self._create_insightface_detector()
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
+ def _create_insightface_detector(self):
69
+ # Initialize InsightFace
70
+ app = insightface.app.FaceAnalysis()
71
+ app.prepare(ctx_id=0, det_size=(640, 640)) # ctx_id=-1 for CPU, 0 for GPU
72
+ return app
73
+
74
+ def _create_parsing_model(self):
75
+ parsingpredictor = BiSeNet(n_classes=19)
76
+ parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
77
+ map_location=lambda storage, loc: storage))
78
+ parsingpredictor.to(self.device).eval()
79
+ return parsingpredictor
80
+
81
+ def _load_encoder(self) -> nn.Module:
82
+ style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
83
+ return load_psp_standalone(style_encoder_path, self.device)
84
+
85
+ def _load_default_model(self) -> tuple[torch.Tensor, str]:
86
+ vtoonify = VToonify(backbone='dualstylegan')
87
+ vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
88
+ 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
89
+ map_location=lambda storage, loc: storage)['g_ema'])
90
+ vtoonify.to(self.device)
91
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
92
+ exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
93
+ with torch.no_grad():
94
+ exstyle = vtoonify.zplus2wplus(exstyle)
95
+ return vtoonify, exstyle
96
+
97
+ def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
98
+ message = 'Error: no face detected! Please retry or change the photo.'
99
+ instyle = None
100
+ # Use InsightFace for face detection
101
+ faces = self.face_detector.get(frame)
102
+ if len(faces) > 0:
103
+ face = faces[0]
104
+ bbox = face.bbox.astype(int)
105
+ x, y, w, h = bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]
106
+ top, bottom, left, right = y, y + h, x, x + w
107
+ scale = 1.0 # Adjust scale as needed
108
+ h, w = frame.shape[:2]
109
+ H, W = int(bottom-top), int(right-left)
110
+ # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
111
+ kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]])
112
+ if scale <= 0.75:
113
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
114
+ if scale <= 0.375:
115
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
116
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
117
+ with torch.no_grad():
118
+ I = align_face(frame, self.face_detector)
119
+ if I is not None:
120
+ I = self.transform(I).unsqueeze(dim=0).to(self.device)
121
+ instyle = self.pspencoder(I)
122
+ instyle = self.vtoonify.zplus2wplus(instyle)
123
+ message = 'Successfully rescale the frame to (%d, %d)' % (bottom-top, right-left)
124
+ else:
125
+ frame = np.zeros((256, 256, 3), np.uint8)
126
+ else:
127
+ frame = np.zeros((256, 256, 3), np.uint8)
128
+ if return_para:
129
+ return frame, instyle, message, w, h, top, bottom, left, right, scale
130
+ return frame, instyle, message
131
+
132
+ # Other methods remain unchanged
133
+ def _create_parsing_model(self):
134
+ parsingpredictor = BiSeNet(n_classes=19)
135
+ parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
136
+ map_location=lambda storage, loc: storage))
137
+ parsingpredictor.to(self.device).eval()
138
+ return parsingpredictor
139
+
140
+ def _load_encoder(self) -> nn.Module:
141
+ style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
142
+ return load_psp_standalone(style_encoder_path, self.device)
143
+
144
+ def _load_default_model(self) -> tuple:
145
+ vtoonify = VToonify(backbone='dualstylegan')
146
+ vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
147
+ 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
148
+ map_location=lambda storage, loc: storage)['g_ema'])
149
+ vtoonify.to(self.device)
150
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
151
+ exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
152
+ with torch.no_grad():
153
+ exstyle = vtoonify.zplus2wplus(exstyle)
154
+ return vtoonify, exstyle
155
+
156
+ def load_model(self, style_type: str) -> tuple:
157
+ if 'illustration' in style_type:
158
+ self.color_transfer = True
159
+ else:
160
+ self.color_transfer = False
161
+ if style_type not in self.style_types.keys():
162
+ return None, 'Oops, wrong Style Type. Please select a valid model.'
163
+ self.style_name = style_type
164
+ model_path, ind = self.style_types[style_type]
165
+ style_path = os.path.join('models', os.path.dirname(model_path), 'exstyle_code.npy')
166
+ self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/' + model_path),
167
+ map_location=lambda storage, loc: storage)['g_ema'])
168
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
169
+ exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
170
+ with torch.no_grad():
171
+ exstyle = self.vtoonify.zplus2wplus(exstyle)
172
+ return exstyle, 'Model of %s loaded.' % (style_type)
173
+
174
+ def detect_and_align_image(self, frame_rgb: np.ndarray, top: int, bottom: int, left: int, right: int) -> tuple:
175
+ if frame_rgb is None:
176
+ return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load the image.'
177
+
178
+ # Convert RGB to BGR
179
+ frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
180
+ return self.detect_and_align(frame_bgr, top, bottom, left, right)
181
+
182
+ def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple:
183
+ if video is None:
184
+ return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load empty file.'
185
+ video_cap = cv2.VideoCapture(video)
186
+ if video_cap.get(7) == 0:
187
+ video_cap.release()
188
+ return np.zeros((256, 256, 3), np.uint8), torch.zeros(1, 18, 512).to(self.device), 'Error: fail to load the video.'
189
+ success, frame = video_cap.read()
190
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
191
+ video_cap.release()
192
+ return self.detect_and_align(frame, top, bottom, left, right)
193
+
194
+ def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple:
195
+ message = 'Error: no face detected! Please retry or change the video.'
196
+ instyle = None
197
+ if video is None:
198
+ return 'default.mp4', instyle, 'Error: fail to load empty file.'
199
+ video_cap = cv2.VideoCapture(video)
200
+ if video_cap.get(7) == 0:
201
+ video_cap.release()
202
+ return 'default.mp4', instyle, 'Error: fail to load the video.'
203
+ num = min(self.video_limit_gpu, int(video_cap.get(7)))
204
+ if self.device == 'cpu':
205
+ num = min(self.video_limit_cpu, num)
206
+ success, frame = video_cap.read()
207
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
208
+ frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
209
+ if instyle is None:
210
+ return 'default.mp4', instyle, message
211
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
212
+ videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
213
+ videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
214
+ kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]])
215
+ for i in range(num-1):
216
+ success, frame = video_cap.read()
217
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
218
+ if scale <= 0.75:
219
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
220
+ if scale <= 0.375:
221
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
222
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
223
+ videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
224
+
225
+ videoWriter.release()
226
+ video_cap.release()
227
+
228
+ return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)' % (bottom-top, right-left)
229
+
230
+ def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple:
231
+ if instyle is None or aligned_face is None:
232
+ 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.'
233
+ if self.style_name != style_type:
234
+ exstyle, _ = self.load_model(style_type)
235
+ if exstyle is None:
236
+ return np.zeros((256, 256, 3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
237
+ with torch.no_grad():
238
+ if self.color_transfer:
239
+ s_w = exstyle
240
+ else:
241
+ s_w = instyle.clone()
242
+ s_w[:, :7] = exstyle[:, :7]
243
+
244
+ x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
245
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
246
+ scale_factor=0.5, recompute_scale_factor=False).detach()
247
+ inputs = torch.cat((x, x_p/16.), dim=1)
248
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s=style_degree)
249
+ y_tilde = torch.clamp(y_tilde, -1, 1)
250
+ print('*** Toonify %dx%d image with style of %s' % (y_tilde.shape[2], y_tilde.shape[3], style_type))
251
+ 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)
252
+
253
+ def video_toonify(self, aligned_video: str, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple:
254
+ if aligned_video is None:
255
+ return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
256
+ video_cap = cv2.VideoCapture(aligned_video)
257
+ if instyle is None or aligned_video is None or video_cap.get(7) == 0:
258
+ video_cap.release()
259
+ return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
260
+ if self.style_name != style_type:
261
+ exstyle, _ = self.load_model(style_type)
262
+ if exstyle is None:
263
+ return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
264
+ num = min(self.video_limit_gpu, int(video_cap.get(7)))
265
+ if self.device == 'cpu':
266
+ num = min(self.video_limit_cpu, num)
267
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
268
+ videoWriter = cv2.VideoWriter('output.mp4', fourcc,
269
+ video_cap.get(5), (int(video_cap.get(3)*4),
270
+ int(video_cap.get(4)*4)))
271
+
272
+ batch_frames = []
273
+ if video_cap.get(3) != 0:
274
+ if self.device == 'cpu':
275
+ batch_size = max(1, int(4 * 256 * 256 / video_cap.get(3) / video_cap.get(4)))
276
+ else:
277
+ batch_size = min(max(1, int(4 * 400 * 360 / video_cap.get(3) / video_cap.get(4))), 4)
278
+ else:
279
+ batch_size = 1
280
+ 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))
281
+ with torch.no_grad():
282
+ if self.color_transfer:
283
+ s_w = exstyle
284
+ else:
285
+ s_w = instyle.clone()
286
+ s_w[:, :7] = exstyle[:, :7]
287
+ for i in range(num):
288
+ success, frame = video_cap.read()
289
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
290
+ batch_frames += [self.transform(frame).unsqueeze(dim=0).to(self.device)]
291
+ if len(batch_frames) == batch_size or (i+1) == num:
292
+ x = torch.cat(batch_frames, dim=0)
293
+ batch_frames = []
294
+ with torch.no_grad():
295
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
296
+ scale_factor=0.5, recompute_scale_factor=False).detach()
297
+ inputs = torch.cat((x, x_p/16.), dim=1)
298
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), style_degree)
299
+ y_tilde = torch.clamp(y_tilde, -1, 1)
300
+ for k in range(y_tilde.size(0)):
301
+ videoWriter.write(tensor2cv2(y_tilde[k].cpu()))
302
+ gc.collect()
303
+
304
+ videoWriter.release()
305
+ video_cap.release()
306
+ return 'output.mp4', 'Successfully toonify video of %d frames with style of %s' % (num, self.style_name)
307
+
308
+ def tensor2cv2(self, img):
309
+ """Convert a tensor image to OpenCV format."""
310
+ tmp = ((img.cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8).copy()
311
+ logging.debug(f"Converted image shape: {tmp.shape}, strides: {tmp.strides}")
312
+ return cv2.cvtColor(tmp, cv2.COLOR_RGB2BGR)