Ashrafb commited on
Commit
8e5d3ec
·
verified ·
1 Parent(s): 8213472

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +99 -3
main.py CHANGED
@@ -10,6 +10,103 @@ from vtoonify_model import Model
10
  app = FastAPI()
11
  model = Model(device='cuda' if torch.cuda.is_available() else 'cpu')
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  @app.post("/upload/")
14
  async def process_image(file: UploadFile = File(...)):
15
  # Save the uploaded image locally
@@ -20,10 +117,9 @@ async def process_image(file: UploadFile = File(...)):
20
  exstyle, load_info = model.load_model('cartoon1')
21
 
22
  # Process the uploaded image
23
-
24
- top, bottom, left, right = 200, 200,200, 200
25
  aligned_face, _, input_info = model.detect_and_align_image("uploaded_image.jpg", top, bottom, left, right)
26
- processed_image, message = model.image_toonify(aligned_face, exstyle, style_type = 'cartoon1' , style_degree=0.5)
27
 
28
  # Save the processed image
29
  with open("result_image.jpg", "wb") as result_buffer:
 
10
  app = FastAPI()
11
  model = Model(device='cuda' if torch.cuda.is_available() else 'cpu')
12
 
13
+ def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
14
+ if 'illustration' in style_type:
15
+ self.color_transfer = True
16
+ else:
17
+ self.color_transfer = False
18
+ if style_type not in self.style_types.keys():
19
+ return None, 'Oops, wrong Style Type. Please select a valid model.'
20
+ self.style_name = style_type
21
+ model_path, ind = self.style_types[style_type]
22
+ style_path = os.path.join('models',os.path.dirname(model_path),'exstyle_code.npy')
23
+ self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/'+model_path),
24
+ map_location=lambda storage, loc: storage)['g_ema'])
25
+ tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
26
+ exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
27
+ with torch.no_grad():
28
+ exstyle = self.vtoonify.zplus2wplus(exstyle)
29
+ return exstyle, 'Model of %s loaded.'%(style_type)
30
+
31
+ def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
32
+ message = 'Error: no face detected! Please retry or change the photo.'
33
+ paras = get_video_crop_parameter(frame, self.landmarkpredictor, [left, right, top, bottom])
34
+ instyle = None
35
+ h, w, scale = 0, 0, 0
36
+ if paras is not None:
37
+ h,w,top,bottom,left,right,scale = paras
38
+ H, W = int(bottom-top), int(right-left)
39
+ # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
40
+ kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
41
+ if scale <= 0.75:
42
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
43
+ if scale <= 0.375:
44
+ frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
45
+ frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
46
+ with torch.no_grad():
47
+ I = align_face(frame, self.landmarkpredictor)
48
+ if I is not None:
49
+ I = self.transform(I).unsqueeze(dim=0).to(self.device)
50
+ instyle = self.pspencoder(I)
51
+ instyle = self.vtoonify.zplus2wplus(instyle)
52
+ message = 'Successfully rescale the frame to (%d, %d)'%(bottom-top, right-left)
53
+ else:
54
+ frame = np.zeros((256,256,3), np.uint8)
55
+ else:
56
+ frame = np.zeros((256,256,3), np.uint8)
57
+ if return_para:
58
+ return frame, instyle, message, w, h, top, bottom, left, right, scale
59
+ return frame, instyle, message
60
+
61
+ #@torch.inference_mode()
62
+ def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
63
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
64
+ if image is None:
65
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
66
+ frame = cv2.imread(image)
67
+ if frame is None:
68
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load the image.'
69
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
70
+ return self.detect_and_align(frame, top, bottom, left, right)
71
+
72
+ def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
73
+ ) -> tuple[np.ndarray, torch.Tensor, str]:
74
+ if video is None:
75
+ return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
76
+ video_cap = cv2.VideoCapture(video)
77
+ if video_cap.get(7) == 0:
78
+ video_cap.release()
79
+ return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
80
+ success, frame = video_cap.read()
81
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
82
+ video_cap.release()
83
+ return self.detect_and_align(frame, top, bottom, left, right)
84
+
85
+
86
+ def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float, style_type: str) -> tuple[np.ndarray, str]:
87
+ #print(style_type + ' ' + self.style_name)
88
+ if instyle is None or aligned_face is None:
89
+ 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.'
90
+ if self.style_name != style_type:
91
+ exstyle, _ = self.load_model(style_type)
92
+ if exstyle is None:
93
+ return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
94
+ with torch.no_grad():
95
+ if self.color_transfer:
96
+ s_w = exstyle
97
+ else:
98
+ s_w = instyle.clone()
99
+ s_w[:,:7] = exstyle[:,:7]
100
+
101
+ x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
102
+ x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
103
+ scale_factor=0.5, recompute_scale_factor=False).detach()
104
+ inputs = torch.cat((x, x_p/16.), dim=1)
105
+ y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = style_degree)
106
+ y_tilde = torch.clamp(y_tilde, -1, 1)
107
+ print('*** Toonify %dx%d image with style of %s'%(y_tilde.shape[2], y_tilde.shape[3], style_type))
108
+ 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)
109
+
110
  @app.post("/upload/")
111
  async def process_image(file: UploadFile = File(...)):
112
  # Save the uploaded image locally
 
117
  exstyle, load_info = model.load_model('cartoon1')
118
 
119
  # Process the uploaded image
120
+ top, bottom, left, right = 200, 200, 200, 200
 
121
  aligned_face, _, input_info = model.detect_and_align_image("uploaded_image.jpg", top, bottom, left, right)
122
+ processed_image, message = model.image_toonify(aligned_face, instyle=exstyle, exstyle=exstyle, style_degree=0.5, style_type='cartoon1')
123
 
124
  # Save the processed image
125
  with open("result_image.jpg", "wb") as result_buffer: