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