Ashrafb commited on
Commit
add003d
·
verified ·
1 Parent(s): d7d0186

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -151
main.py CHANGED
@@ -34,160 +34,9 @@ import huggingface_hub
34
  import os
35
 
36
  app = FastAPI()
37
- model = None
38
 
39
- MODEL_REPO = 'PKUWilliamYang/VToonify'
40
-
41
- class Model():
42
- def __init__(self, device):
43
- super().__init__()
44
-
45
- self.device = device
46
- self.style_types = {
47
- 'cartoon1': ['vtoonify_d_cartoon/vtoonify_s026_d0.5.pt', 26],
48
-
49
- }
50
-
51
- self.landmarkpredictor = self._create_dlib_landmark_model()
52
- self.parsingpredictor = self._create_parsing_model()
53
- self.pspencoder = self._load_encoder()
54
- self.transform = transforms.Compose([
55
- transforms.ToTensor(),
56
- transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
57
- ])
58
-
59
- self.vtoonify, self.exstyle = self._load_default_model()
60
- self.color_transfer = False
61
- self.style_name = 'cartoon1'
62
- self.video_limit_cpu = 100
63
- self.video_limit_gpu = 300
64
-
65
- @staticmethod
66
- def _create_dlib_landmark_model():
67
- return dlib.shape_predictor(huggingface_hub.hf_hub_download(MODEL_REPO,
68
- 'models/shape_predictor_68_face_landmarks.dat'))
69
-
70
- def _create_parsing_model(self):
71
- parsingpredictor = BiSeNet(n_classes=19)
72
- parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
73
- map_location=lambda storage, loc: storage))
74
- parsingpredictor.to(self.device).eval()
75
- return parsingpredictor
76
-
77
- def _load_encoder(self) -> nn.Module:
78
- style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO,'models/encoder.pt')
79
- return load_psp_standalone(style_encoder_path, self.device)
80
-
81
- def _load_default_model(self) -> tuple[torch.Tensor, str]:
82
- vtoonify = VToonify(backbone = 'dualstylegan')
83
- vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
84
- 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
85
- map_location=lambda storage, loc: storage)['g_ema'])
86
- vtoonify.to(self.device)
87
- tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
88
- exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
89
- with torch.no_grad():
90
- exstyle = vtoonify.zplus2wplus(exstyle)
91
- return vtoonify, exstyle
92
-
93
- def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
94
- if 'illustration' in style_type:
95
- self.color_transfer = True
96
- else:
97
- self.color_transfer = False
98
- if style_type not in self.style_types.keys():
99
- return None, 'Oops, wrong Style Type. Please select a valid model.'
100
- self.style_name = style_type
101
- model_path, ind = self.style_types[style_type]
102
- style_path = os.path.join('models',os.path.dirname(model_path),'exstyle_code.npy')
103
- self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/'+model_path),
104
- map_location=lambda storage, loc: storage)['g_ema'])
105
- tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
106
- exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
107
- with torch.no_grad():
108
- exstyle = self.vtoonify.zplus2wplus(exstyle)
109
- return exstyle, 'Model of %s loaded.'%(style_type)
110
-
111
- def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
112
- message = 'Error: no face detected! Please retry or change the photo.'
113
- paras = get_video_crop_parameter(frame, self.landmarkpredictor, [left, right, top, bottom])
114
- instyle = None
115
- h, w, scale = 0, 0, 0
116
- if paras is not None:
117
- h,w,top,bottom,left,right,scale = paras
118
- H, W = int(bottom-top), int(right-left)
119
- # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
120
- kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
121
- if scale <= 0.75:
122
- frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
123
- if scale <= 0.375:
124
- frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
125
- frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
126
- with torch.no_grad():
127
- I = align_face(frame, self.landmarkpredictor)
128
- if I is not None:
129
- I = self.transform(I).unsqueeze(dim=0).to(self.device)
130
- instyle = self.pspencoder(I)
131
- instyle = self.vtoonify.zplus2wplus(instyle)
132
- message = 'Successfully rescale the frame to (%d, %d)'%(bottom-top, right-left)
133
- else:
134
- frame = np.zeros((256,256,3), np.uint8)
135
- else:
136
- frame = np.zeros((256,256,3), np.uint8)
137
- if return_para:
138
- return frame, instyle, message, w, h, top, bottom, left, right, scale
139
- return frame, instyle, message
140
-
141
- #@torch.inference_mode()
142
- def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
143
- ) -> tuple[np.ndarray, torch.Tensor, str]:
144
- if image is None:
145
- return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
146
- frame = cv2.imread(image)
147
- if frame is None:
148
- return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load the image.'
149
- frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
150
- return self.detect_and_align(frame, top, bottom, left, right)
151
-
152
- def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
153
- ) -> tuple[np.ndarray, torch.Tensor, str]:
154
- if video is None:
155
- return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
156
- video_cap = cv2.VideoCapture(video)
157
- if video_cap.get(7) == 0:
158
- video_cap.release()
159
- return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
160
- success, frame = video_cap.read()
161
- frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
162
- video_cap.release()
163
- return self.detect_and_align(frame, top, bottom, left, right)
164
-
165
 
166
- def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[np.ndarray, str]:
167
- #print(style_type + ' ' + self.style_name)
168
- if instyle is None or aligned_face is None:
169
- 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.'
170
- if self.style_name != style_type:
171
- exstyle, _ = self.load_model(style_type)
172
- if exstyle is None:
173
- return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
174
- with torch.no_grad():
175
- if self.color_transfer:
176
- s_w = exstyle
177
- else:
178
- s_w = instyle.clone()
179
- s_w[:,:7] = exstyle[:,:7]
180
-
181
- x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
182
- x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
183
- scale_factor=0.5, recompute_scale_factor=False).detach()
184
- inputs = torch.cat((x, x_p/16.), dim=1)
185
- y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = style_degree)
186
- y_tilde = torch.clamp(y_tilde, -1, 1)
187
- print('*** Toonify %dx%d image with style of %s'%(y_tilde.shape[2], y_tilde.shape[3], style_type))
188
- 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)
189
 
190
-
191
  @app.on_event("startup")
192
  async def load_model():
193
  global model
 
34
  import os
35
 
36
  app = FastAPI()
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
 
40
  @app.on_event("startup")
41
  async def load_model():
42
  global model