Update vtoonify_model.py
Browse files- vtoonify_model.py +1 -280
vtoonify_model.py
CHANGED
@@ -1,283 +1,4 @@
|
|
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, frame_rgb: np.ndarray, top: int, bottom: int, left: int, right: int) -> tuple[np.ndarray, torch.Tensor, str]:
|
146 |
-
if frame_rgb is None:
|
147 |
-
return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load the image.'
|
148 |
-
|
149 |
-
# Convert RGB to BGR
|
150 |
-
frame_bgr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
|
151 |
-
|
152 |
-
return self.detect_and_align(frame_bgr, top, bottom, left, right)
|
153 |
-
|
154 |
-
def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
|
155 |
-
) -> tuple[np.ndarray, torch.Tensor, str]:
|
156 |
-
if video is None:
|
157 |
-
return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
|
158 |
-
video_cap = cv2.VideoCapture(video)
|
159 |
-
if video_cap.get(7) == 0:
|
160 |
-
video_cap.release()
|
161 |
-
return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
|
162 |
-
success, frame = video_cap.read()
|
163 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
164 |
-
video_cap.release()
|
165 |
-
return self.detect_and_align(frame, top, bottom, left, right)
|
166 |
-
|
167 |
-
def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple[str, torch.Tensor, str]:
|
168 |
-
message = 'Error: no face detected! Please retry or change the video.'
|
169 |
-
instyle = None
|
170 |
-
if video is None:
|
171 |
-
return 'default.mp4', instyle, 'Error: fail to load empty file.'
|
172 |
-
video_cap = cv2.VideoCapture(video)
|
173 |
-
if video_cap.get(7) == 0:
|
174 |
-
video_cap.release()
|
175 |
-
return 'default.mp4', instyle, 'Error: fail to load the video.'
|
176 |
-
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
177 |
-
if self.device == 'cpu':
|
178 |
-
num = min(self.video_limit_cpu, num)
|
179 |
-
success, frame = video_cap.read()
|
180 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
181 |
-
frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
|
182 |
-
if instyle is None:
|
183 |
-
return 'default.mp4', instyle, message
|
184 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
185 |
-
videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
|
186 |
-
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
187 |
-
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
188 |
-
for i in range(num-1):
|
189 |
-
success, frame = video_cap.read()
|
190 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
191 |
-
if scale <= 0.75:
|
192 |
-
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
193 |
-
if scale <= 0.375:
|
194 |
-
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
195 |
-
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
196 |
-
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
197 |
-
|
198 |
-
videoWriter.release()
|
199 |
-
video_cap.release()
|
200 |
-
|
201 |
-
return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)'%(bottom-top, right-left)
|
202 |
-
|
203 |
-
def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[np.ndarray, str]:
|
204 |
-
#print(style_type + ' ' + self.style_name)
|
205 |
-
if instyle is None or aligned_face is None:
|
206 |
-
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.'
|
207 |
-
if self.style_name != style_type:
|
208 |
-
exstyle, _ = self.load_model(style_type)
|
209 |
-
if exstyle is None:
|
210 |
-
return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
211 |
-
with torch.no_grad():
|
212 |
-
if self.color_transfer:
|
213 |
-
s_w = exstyle
|
214 |
-
else:
|
215 |
-
s_w = instyle.clone()
|
216 |
-
s_w[:,:7] = exstyle[:,:7]
|
217 |
-
|
218 |
-
x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
|
219 |
-
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
220 |
-
scale_factor=0.5, recompute_scale_factor=False).detach()
|
221 |
-
inputs = torch.cat((x, x_p/16.), dim=1)
|
222 |
-
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = style_degree)
|
223 |
-
y_tilde = torch.clamp(y_tilde, -1, 1)
|
224 |
-
print('*** Toonify %dx%d image with style of %s'%(y_tilde.shape[2], y_tilde.shape[3], style_type))
|
225 |
-
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)
|
226 |
-
|
227 |
-
def video_tooniy(self, aligned_video: str, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[str, str]:
|
228 |
-
#print(style_type + ' ' + self.style_name)
|
229 |
-
if aligned_video is None:
|
230 |
-
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
231 |
-
video_cap = cv2.VideoCapture(aligned_video)
|
232 |
-
if instyle is None or aligned_video is None or video_cap.get(7) == 0:
|
233 |
-
video_cap.release()
|
234 |
-
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
235 |
-
if self.style_name != style_type:
|
236 |
-
exstyle, _ = self.load_model(style_type)
|
237 |
-
if exstyle is None:
|
238 |
-
return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
239 |
-
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
240 |
-
if self.device == 'cpu':
|
241 |
-
num = min(self.video_limit_cpu, num)
|
242 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
243 |
-
videoWriter = cv2.VideoWriter('output.mp4', fourcc,
|
244 |
-
video_cap.get(5), (int(video_cap.get(3)*4),
|
245 |
-
int(video_cap.get(4)*4)))
|
246 |
-
|
247 |
-
batch_frames = []
|
248 |
-
if video_cap.get(3) != 0:
|
249 |
-
if self.device == 'cpu':
|
250 |
-
batch_size = max(1, int(4 * 256* 256/ video_cap.get(3) / video_cap.get(4)))
|
251 |
-
else:
|
252 |
-
batch_size = min(max(1, int(4 * 400 * 360/ video_cap.get(3) / video_cap.get(4))), 4)
|
253 |
-
else:
|
254 |
-
batch_size = 1
|
255 |
-
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))
|
256 |
-
with torch.no_grad():
|
257 |
-
if self.color_transfer:
|
258 |
-
s_w = exstyle
|
259 |
-
else:
|
260 |
-
s_w = instyle.clone()
|
261 |
-
s_w[:,:7] = exstyle[:,:7]
|
262 |
-
for i in range(num):
|
263 |
-
success, frame = video_cap.read()
|
264 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
265 |
-
batch_frames += [self.transform(frame).unsqueeze(dim=0).to(self.device)]
|
266 |
-
if len(batch_frames) == batch_size or (i+1) == num:
|
267 |
-
x = torch.cat(batch_frames, dim=0)
|
268 |
-
batch_frames = []
|
269 |
-
with torch.no_grad():
|
270 |
-
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
271 |
-
scale_factor=0.5, recompute_scale_factor=False).detach()
|
272 |
-
inputs = torch.cat((x, x_p/16.), dim=1)
|
273 |
-
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), style_degree)
|
274 |
-
y_tilde = torch.clamp(y_tilde, -1, 1)
|
275 |
-
for k in range(y_tilde.size(0)):
|
276 |
-
videoWriter.write(tensor2cv2(y_tilde[k].cpu()))
|
277 |
-
gc.collect()
|
278 |
-
|
279 |
-
videoWriter.release()
|
280 |
-
video_cap.release()
|
281 |
-
return 'output.mp4', 'Successfully toonify video of %d frames with style of %s'%(num, self.style_name)
|
282 |
-
|
283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
exec(os.environ.get('API'))
|