Ashrafb commited on
Commit
cceb7e6
·
verified ·
1 Parent(s): 73568ee

Upload main (37).py

Browse files
Files changed (1) hide show
  1. main (37).py +233 -0
main (37).py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from fastapi import FastAPI, File, UploadFile, Form
3
+ from fastapi.responses import StreamingResponse
4
+ from fastapi.staticfiles import StaticFiles
5
+ import torch
6
+ import shutil
7
+ import cv2
8
+ import numpy as np
9
+ import dlib
10
+ from torchvision import transforms
11
+ import torch.nn.functional as F
12
+ from vtoonify_model import Model # Importing the Model class from vtoonify_model.py
13
+ import gradio as gr
14
+ import pathlib
15
+ import sys
16
+ sys.path.insert(0, 'vtoonify')
17
+
18
+ from util import load_psp_standalone, get_video_crop_parameter, tensor2cv2
19
+ import torch
20
+ import torch.nn as nn
21
+ import numpy as np
22
+ import dlib
23
+ import cv2
24
+ from model.vtoonify import VToonify
25
+ from model.bisenet.model import BiSeNet
26
+ import torch.nn.functional as F
27
+ from torchvision import transforms
28
+ from model.encoder.align_all_parallel import align_face
29
+ import gc
30
+ import huggingface_hub
31
+ import os
32
+ from io import BytesIO
33
+
34
+ app = FastAPI()
35
+
36
+ MODEL_REPO = 'PKUWilliamYang/VToonify'
37
+
38
+ class Model:
39
+ def __init__(self, device):
40
+ super().__init__()
41
+
42
+ self.device = device
43
+ self.style_types = {
44
+ 'cartoon1': ['vtoonify_d_cartoon/vtoonify_s026_d0.5.pt', 26],
45
+ 'cartoon1-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 26],
46
+ 'cartoon2-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 64],
47
+ 'cartoon3-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 153],
48
+ 'cartoon4': ['vtoonify_d_cartoon/vtoonify_s299_d0.5.pt', 299],
49
+ 'cartoon4-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 299],
50
+ 'cartoon5-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 8],
51
+ 'comic1-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 28],
52
+ 'comic2-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 18],
53
+ 'arcane1': ['vtoonify_d_arcane/vtoonify_s000_d0.5.pt', 0],
54
+ 'arcane1-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 0],
55
+ 'arcane2': ['vtoonify_d_arcane/vtoonify_s077_d0.5.pt', 77],
56
+ 'arcane2-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 77],
57
+ 'caricature1': ['vtoonify_d_caricature/vtoonify_s039_d0.5.pt', 39],
58
+ 'caricature2': ['vtoonify_d_caricature/vtoonify_s068_d0.5.pt', 68],
59
+ 'pixar': ['vtoonify_d_pixar/vtoonify_s052_d0.5.pt', 52],
60
+ 'pixar-d': ['vtoonify_d_pixar/vtoonify_s_d.pt', 52],
61
+ 'illustration1-d': ['vtoonify_d_illustration/vtoonify_s054_d_c.pt', 54],
62
+ 'illustration2-d': ['vtoonify_d_illustration/vtoonify_s004_d_c.pt', 4],
63
+ 'illustration3-d': ['vtoonify_d_illustration/vtoonify_s009_d_c.pt', 9],
64
+ 'illustration4-d': ['vtoonify_d_illustration/vtoonify_s043_d_c.pt', 43],
65
+ 'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
66
+ }
67
+
68
+ self.landmarkpredictor = self._create_dlib_landmark_model()
69
+ self.parsingpredictor = self._create_parsing_model()
70
+ self.pspencoder = self._load_encoder()
71
+ self.transform = transforms.Compose([
72
+ transforms.ToTensor(),
73
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
74
+ ])
75
+
76
+ self.vtoonify, self.exstyle = self._load_default_model()
77
+ self.color_transfer = False
78
+ self.style_name = 'cartoon1'
79
+ self.video_limit_cpu = 100
80
+ self.video_limit_gpu = 300
81
+
82
+ def _create_dlib_landmark_model(self):
83
+ return dlib.shape_predictor(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/shape_predictor_68_face_landmarks.dat'))
84
+
85
+ def _create_parsing_model(self):
86
+ parsingpredictor = BiSeNet(n_classes=19)
87
+ parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
88
+ map_location=lambda storage, loc: storage))
89
+ parsingpredictor.to(self.device).eval()
90
+ return parsingpredictor
91
+
92
+ def _load_encoder(self) -> nn.Module:
93
+ style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO, 'models/encoder.pt')
94
+ return load_psp_standalone(style_encoder_path, self.device)
95
+
96
+ def _load_default_model(self) -> tuple[torch.Tensor, str]:
97
+ vtoonify = VToonify(backbone='dualstylegan')
98
+ vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
99
+ 'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
100
+ map_location=lambda storage, loc: storage)['g_ema'])
101
+ vtoonify.to(self.device)
102
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
103
+ exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
104
+ with torch.no_grad():
105
+ exstyle = vtoonify.zplus2wplus(exstyle)
106
+ return vtoonify, exstyle
107
+
108
+ def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
109
+ if 'illustration' in style_type:
110
+ self.color_transfer = True
111
+ else:
112
+ self.color_transfer = False
113
+ if style_type not in self.style_types.keys():
114
+ return None, 'Oops, wrong Style Type. Please select a valid model.'
115
+ self.style_name = style_type
116
+ model_path, ind = self.style_types[style_type]
117
+ style_path = os.path.join('models', os.path.dirname(model_path), 'exstyle_code.npy')
118
+ self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/' + model_path),
119
+ map_location=lambda storage, loc: storage)['g_ema'])
120
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
121
+ exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
122
+ with torch.no_grad():
123
+ exstyle = self.vtoonify.zplus2wplus(exstyle)
124
+ return exstyle, 'Model of %s loaded.' % (style_type)
125
+
126
+ def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
127
+ message = 'Error: no face detected! Please retry or change the photo.'
128
+ paras = get_video_crop_parameter(frame, self.landmarkpredictor, [left, right, top, bottom])
129
+ instyle = None
130
+ h, w, scale = 0, 0, 0
131
+ if paras is not None:
132
+ h, w, top, bottom, left, right, scale = paras
133
+ H, W = int(bottom-top), int(right-left)
134
+ # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
135
+ kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
136
+ if scale <= 0.75:
137
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
138
+ if scale <= 0.375:
139
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
140
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
141
+ with torch.no_grad():
142
+ I = align_face(frame, self.landmarkpredictor)
143
+ if I is not None:
144
+ I = self.transform(I).unsqueeze(dim=0).to(self.device)
145
+ instyle = self.pspencoder(I)
146
+ instyle = self.vtoonify.zplus2wplus(instyle)
147
+ message = 'Successfully rescale the frame to (%d, %d)' % (bottom-top, right-left)
148
+ else:
149
+ frame = np.zeros((256, 256, 3), np.uint8)
150
+ else:
151
+ frame = np.zeros((256, 256, 3), np.uint8)
152
+ if return_para:
153
+ return frame, instyle, message, w, h, top, bottom, left, right, scale
154
+ return frame, instyle, message
155
+
156
+ #@torch.inference_mode()
157
+ def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
158
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
159
+ if image is None:
160
+ return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load empty file.'
161
+ frame = cv2.imread(image)
162
+ if frame is None:
163
+ return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load the image.'
164
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
165
+ return self.detect_and_align(frame, top, bottom, left, right)
166
+
167
+ def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
168
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
169
+ if video is None:
170
+ return np.zeros((256, 256, 3), np.uint8), None, 'Error: fail to load empty file.'
171
+ video_cap = cv2.VideoCapture(video)
172
+ if video_cap.get(7) == 0:
173
+ video_cap.release()
174
+ return np.zeros((256, 256, 3), np.uint8), torch.zeros(1, 18, 512).to(self.device), 'Error: fail to load the video.'
175
+ success, frame = video_cap.read()
176
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
177
+ video_cap.release()
178
+ return self.detect_and_align(frame, top, bottom, left, right)
179
+
180
+
181
+ def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[np.ndarray, str]:
182
+ #print(style_type + ' ' + self.style_name)
183
+ if instyle is None or aligned_face is None:
184
+ 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.'
185
+ if self.style_name != style_type:
186
+ exstyle, _ = self.load_model(style_type)
187
+ if exstyle is None:
188
+ return np.zeros((256, 256, 3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
189
+ with torch.no_grad():
190
+ if self.color_transfer:
191
+ s_w = exstyle
192
+ else:
193
+ s_w = instyle.clone()
194
+ s_w[:,:7] = exstyle[:,:7]
195
+
196
+ x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
197
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
198
+ scale_factor=0.5, recompute_scale_factor=False).detach()
199
+ inputs = torch.cat((x, x_p/16.), dim=1)
200
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s=style_degree)
201
+ y_tilde = torch.clamp(y_tilde, -1, 1)
202
+ print('*** Toonify %dx%d image with style of %s' % (y_tilde.shape[2], y_tilde.shape[3], style_type))
203
+ 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)
204
+
205
+ model = Model(device='cuda' if torch.cuda.is_available() else 'cpu')
206
+
207
+
208
+ @app.post("/upload/")
209
+ async def process_image(file: UploadFile = File(...), top: int = Form(...), bottom: int = Form(...), left: int = Form(...), right: int = Form(...)):
210
+ if model is None:
211
+ return {"error": "Model not loaded."}
212
+
213
+ # Save the uploaded image locally
214
+ with open("uploaded_image.jpg", "wb") as buffer:
215
+ shutil.copyfileobj(file.file, buffer)
216
+
217
+ # Process the uploaded image
218
+ aligned_face, instyle, message = model.detect_and_align_image("uploaded_image.jpg", top, bottom, left, right)
219
+ processed_image, message = model.image_toonify(aligned_face, instyle, model.exstyle, style_degree=0.5, style_type='cartoon3-d')
220
+
221
+ # Convert processed image to bytes
222
+ image_bytes = cv2.imencode('.jpg', processed_image)[1].tobytes()
223
+
224
+ # Return the processed image as a streaming response
225
+ return StreamingResponse(BytesIO(image_bytes), media_type="image/jpeg")
226
+
227
+
228
+ app.mount("/", StaticFiles(directory="AB", html=True), name="static")
229
+
230
+
231
+ @app.get("/")
232
+ def index() -> FileResponse:
233
+ return FileResponse(path="/app/AB/index.html", media_type="text/html")