Luisgust commited on
Commit
82270d6
·
verified ·
1 Parent(s): 93e583d

Create vtoonify_model.py

Browse files
Files changed (1) hide show
  1. vtoonify_model.py +248 -0
vtoonify_model.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import logging
22
+ from PIL import Image
23
+
24
+
25
+
26
+
27
+ # Configure logging
28
+ logging.basicConfig(level=logging.INFO)
29
+
30
+ MODEL_REPO = 'PKUWilliamYang/VToonify'
31
+
32
+ class Model():
33
+ def __init__(self, device):
34
+ super().__init__()
35
+
36
+ self.device = device
37
+ self.style_types = {
38
+ 'cartoon1': ['vtoonify_d_cartoon/vtoonify_s026_d0.5.pt', 26],
39
+ 'cartoon1-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 26],
40
+ 'cartoon2-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 64],
41
+ 'cartoon3-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 153],
42
+ 'cartoon4': ['vtoonify_d_cartoon/vtoonify_s299_d0.5.pt', 299],
43
+ 'cartoon4-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 299],
44
+ 'cartoon5-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 8],
45
+ 'comic1-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 28],
46
+ 'comic2-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 18],
47
+ 'arcane1': ['vtoonify_d_arcane/vtoonify_s000_d0.5.pt', 0],
48
+ 'arcane1-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 0],
49
+ 'arcane2': ['vtoonify_d_arcane/vtoonify_s077_d0.5.pt', 77],
50
+ 'arcane2-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 77],
51
+ 'caricature1': ['vtoonify_d_caricature/vtoonify_s039_d0.5.pt', 39],
52
+ 'caricature2': ['vtoonify_d_caricature/vtoonify_s068_d0.5.pt', 68],
53
+ 'pixar': ['vtoonify_d_pixar/vtoonify_s052_d0.5.pt', 52],
54
+ 'pixar-d': ['vtoonify_d_pixar/vtoonify_s_d.pt', 52],
55
+ 'illustration1-d': ['vtoonify_d_illustration/vtoonify_s054_d_c.pt', 54],
56
+ 'illustration2-d': ['vtoonify_d_illustration/vtoonify_s004_d_c.pt', 4],
57
+ 'illustration3-d': ['vtoonify_d_illustration/vtoonify_s009_d_c.pt', 9],
58
+ 'illustration4-d': ['vtoonify_d_illustration/vtoonify_s043_d_c.pt', 43],
59
+ 'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
60
+ }
61
+
62
+ self.face_detector = self._create_insightface_detector()
63
+ self.parsingpredictor = self._create_parsing_model()
64
+ self.pspencoder = self._load_encoder()
65
+ self.transform = transforms.Compose([
66
+ transforms.ToTensor(),
67
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
68
+ ])
69
+
70
+ self.vtoonify, self.exstyle = self._load_default_model()
71
+ self.color_transfer = False
72
+ self.style_name = 'cartoon1'
73
+
74
+ def _create_insightface_detector(self):
75
+ # Initialize InsightFace
76
+ app = insightface.app.FaceAnalysis()
77
+ app.prepare(ctx_id=0 if self.device == 'cuda' else -1, det_size=(640, 640))
78
+ return app
79
+
80
+ def _create_parsing_model(self):
81
+ parsingpredictor = BiSeNet(n_classes=19)
82
+ parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
83
+ map_location=lambda storage, loc: storage))
84
+ parsingpredictor.to(self.device).eval()
85
+ return parsingpredictor
86
+
87
+ def _load_encoder(self) -> nn.Module:
88
+ style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
89
+ return load_psp_standalone(style_encoder_path, self.device)
90
+
91
+ def _load_default_model(self) -> tuple:
92
+ vtoonify = VToonify(backbone='dualstylegan')
93
+ vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
94
+ 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
95
+ map_location=lambda storage, loc: storage)['g_ema'])
96
+ vtoonify.to(self.device)
97
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
98
+ exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
99
+ with torch.no_grad():
100
+ exstyle = vtoonify.zplus2wplus(exstyle)
101
+ return vtoonify, exstyle
102
+
103
+ def load_model(self, style_type: str) -> tuple:
104
+ if 'illustration' in style_type:
105
+ self.color_transfer = True
106
+ else:
107
+ self.color_transfer = False
108
+ if style_type not in self.style_types.keys():
109
+ return None, 'Oops, wrong Style Type. Please select a valid model.'
110
+ self.style_name = style_type
111
+ model_path, ind = self.style_types[style_type]
112
+ style_path = os.path.join('models', os.path.dirname(model_path), 'exstyle_code.npy')
113
+ self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/' + model_path),
114
+ map_location=lambda storage, loc: storage)['g_ema'])
115
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
116
+ exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
117
+ with torch.no_grad():
118
+ exstyle = self.vtoonify.zplus2wplus(exstyle)
119
+ return exstyle, 'Model of %s loaded.' % (style_type)
120
+
121
+ def convert_106_to_68(self, landmarks_106):
122
+ # Mapping from 106 landmarks to 68 landmarks
123
+ landmark106to68 = [
124
+ 1, 10, 12, 14, 16, 3, 5, 7, 0, 23, 21, 19, 32, 30, 28, 26, 17, # Face outline
125
+ 43, 48, 49, 51, 50, # Left eyebrow
126
+ 102, 103, 104, 105, 101, # Right eyebrow
127
+ 72, 73, 74, 86, 78, 79, 80, 85, 84, # Nose
128
+ 35, 41, 42, 39, 37, 36, # Left eye
129
+ 89, 95, 96, 93, 91, 90, # Right eye
130
+ 52, 64, 63, 71, 67, 68, 61, 58, 59, 53, 56, 55, 65, 66, 62, 70, 69, 57, 60, 54 # Mouth
131
+ ]
132
+
133
+ # Convert 106 landmarks to 68 landmarks
134
+ landmarks_68 = [landmarks_106[index] for index in landmark106to68]
135
+
136
+ return landmarks_68
137
+
138
+ def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
139
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
140
+ if image is None:
141
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
142
+ frame = cv2.imread(image)
143
+ if frame is None:
144
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load the image.'
145
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
146
+ return self.detect_and_align(frame, top, bottom, left, right)
147
+ def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
148
+ message = 'Error: no face detected! Please retry or change the photo.'
149
+ instyle = None
150
+
151
+ # Use InsightFace for face detection
152
+ faces = self.face_detector.get(frame)
153
+ if len(faces) > 0:
154
+ logging.info(f"Detected {len(faces)} face(s).")
155
+ face = faces[0]
156
+ landmarks_106 = face.landmark_2d_106
157
+ landmarks_68 = self.convert_106_to_68(landmarks_106)
158
+
159
+ # Align face based on mapped landmarks
160
+ aligned_face = self.align_face(frame, landmarks_68)
161
+ if aligned_face is not None:
162
+ logging.info(f"Aligned face shape: {aligned_face.shape}")
163
+ with torch.no_grad():
164
+ I = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
165
+ instyle = self.pspencoder(I)
166
+ instyle = self.vtoonify.zplus2wplus(instyle)
167
+ message = 'Successfully aligned the face.'
168
+ else:
169
+ logging.warning("Failed to align face.")
170
+ frame = np.zeros((256, 256, 3), np.uint8)
171
+ else:
172
+ logging.warning("No face detected.")
173
+ frame = np.zeros((256, 256, 3), np.uint8)
174
+
175
+ if return_para:
176
+ return frame, instyle, message
177
+ return frame, instyle, message
178
+
179
+ def align_face(self, image, landmarks):
180
+ # Example alignment logic using 68 landmarks
181
+ eye_left = np.mean(landmarks[36:42], axis=0)
182
+ eye_right = np.mean(landmarks[42:48], axis=0)
183
+ mouth_left = landmarks[48]
184
+ mouth_right = landmarks[54]
185
+
186
+ # Calculate transformation parameters
187
+ eye_center = (eye_left + eye_right) / 2
188
+ mouth_center = (mouth_left + mouth_right) / 2
189
+ eye_to_eye = eye_right - eye_left
190
+ eye_to_mouth = mouth_center - eye_center
191
+
192
+ # Define the transformation matrix
193
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
194
+ x /= np.hypot(*x)
195
+ x *= np.hypot(*eye_to_eye) * 2.0
196
+ y = np.flipud(x) * [-1, 1]
197
+ c = eye_center + eye_to_mouth * 0.1
198
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
199
+ qsize = np.hypot(*x) * 2
200
+
201
+ # Transform and crop the image
202
+ transform_size = 256
203
+ output_size = 256
204
+ img = Image.fromarray(image)
205
+ img = img.transform((transform_size, transform_size), Image.QUAD, (quad + 0.5).flatten(), Image.BILINEAR)
206
+ if output_size < transform_size:
207
+ img = img.resize((output_size, output_size), Image.ANTIALIAS)
208
+
209
+ return np.array(img)
210
+
211
+
212
+ def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple:
213
+ if instyle is None or aligned_face is None:
214
+ logging.error("Invalid input: instyle or aligned_face is None.")
215
+ return np.zeros((256, 256, 3), np.uint8), 'Oops, something wrong with the input. Please go to Step 2 and Rescale Image/First Frame again.'
216
+
217
+ if self.style_name != style_type:
218
+ exstyle, _ = self.load_model(style_type)
219
+ if exstyle is None:
220
+ logging.error("Failed to load style model.")
221
+ return np.zeros((256, 256, 3), np.uint8), 'Oops, something wrong with the style type. Please go to Step 1 and load model again.'
222
+
223
+ try:
224
+ with torch.no_grad():
225
+ if self.color_transfer:
226
+ s_w = exstyle
227
+ else:
228
+ s_w = instyle.clone()
229
+ s_w[:, :7] = exstyle[:, :7]
230
+
231
+ # Ensure the input is resized to 256x256
232
+ aligned_face_resized = cv2.resize(aligned_face, (256, 256))
233
+ x = self.transform(aligned_face_resized).unsqueeze(dim=0).to(self.device)
234
+ logging.info(f"Input to VToonify shape: {x.shape}")
235
+ x_p = F.interpolate(self.parsingpredictor(2 * (F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
236
+ scale_factor=0.5, recompute_scale_factor=False).detach()
237
+ inputs = torch.cat((x, x_p / 16.), dim=1)
238
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s=style_degree)
239
+ y_tilde = torch.clamp(y_tilde, -1, 1)
240
+ logging.info(f"Output from VToonify shape: {y_tilde.shape}")
241
+ print('*** Toonify %dx%d image with style of %s' % (y_tilde.shape[2], y_tilde.shape[3], style_type))
242
+
243
+ 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)
244
+
245
+ except Exception as e:
246
+ logging.error(f"Error during model execution: {e}")
247
+ return np.zeros((256, 256, 3), np.uint8), f"Error during processing: {str(e)}"
248
+