ONNX
Jacobmadwed commited on
Commit
d16e4c8
·
verified ·
1 Parent(s): 9298723

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +29 -103
handler.py CHANGED
@@ -1,14 +1,12 @@
1
  from fastapi import FastAPI, HTTPException, UploadFile, File
2
  from pydantic import BaseModel
3
  import torch
4
- import random
5
  import numpy as np
6
  from PIL import Image
7
  import io
8
  import base64
9
  import traceback
10
- from diffusers import ControlNetModel, MultiControlNetModel
11
- from diffusers.utils import load_image
12
  from insightface.app import FaceAnalysis
13
  from controlnet_aux import OpenposeDetector
14
  from depth_anything.dpt import DepthAnything
@@ -16,8 +14,8 @@ from depth_anything.util.transform import Resize, NormalizeImage, PrepareForNet
16
  import torch.nn.functional as F
17
  from torchvision.transforms import Compose
18
 
19
- # Import the custom pipeline
20
- from pipeline_stable_diffusion_xl_instantid_full import StableDiffusionXLInstantIDPipeline, draw_kps
21
 
22
  app = FastAPI()
23
 
@@ -25,13 +23,6 @@ app = FastAPI()
25
  MAX_SEED = np.iinfo(np.int32).max
26
  device = "cuda" if torch.cuda.is_available() else "cpu"
27
  dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32
28
- enable_lcm_arg = False
29
-
30
- # Download checkpoints
31
- hf_hub_download = lambda *args, **kwargs: None # Placeholder to avoid execution
32
- hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/config.json", local_dir="./checkpoints")
33
- hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/diffusion_pytorch_model.safetensors", local_dir="./checkpoints")
34
- hf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints")
35
 
36
  # Load face encoder
37
  face_analysis = FaceAnalysis(name="antelopev2", root="./", providers=["CPUExecutionProvider"])
@@ -50,6 +41,10 @@ transform = Compose([
50
  face_adapter = "./checkpoints/ip-adapter.bin"
51
  controlnet_path = "./checkpoints/ControlNetModel"
52
 
 
 
 
 
53
  controlnet_identitynet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=dtype)
54
 
55
  controlnet_pose_model = "thibaud/controlnet-openpose-sdxl-1.0"
@@ -67,47 +62,10 @@ controlnet_map = {
67
  }
68
  controlnet_map_fn = {
69
  "pose": openpose,
70
- "canny": get_canny_image,
71
- "depth": get_depth_map,
72
  }
73
 
74
- pretrained_model_name_or_path = "wangqixun/YamerMIX_v8"
75
-
76
- pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
77
- pretrained_model_name_or_path,
78
- controlnet=[controlnet_identitynet],
79
- torch_dtype=dtype,
80
- safety_checker=None,
81
- feature_extractor=None,
82
- ).to(device)
83
-
84
- pipe.scheduler = diffusers.EulerDiscreteScheduler.from_config(pipe.scheduler.config)
85
-
86
- pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
87
- pipe.disable_lora()
88
-
89
- pipe.cuda()
90
- pipe.load_ip_adapter_instantid(face_adapter)
91
- pipe.image_proj_model.to("cuda")
92
- pipe.unet.to("cuda")
93
-
94
- def get_depth_map(image):
95
- image = np.array(image) / 255.0
96
- h, w = image.shape[:2]
97
- image = transform({'image': image})['image']
98
- image = torch.from_numpy(image).unsqueeze(0).to(device)
99
- with torch.no_grad():
100
- depth = depth_anything(image)
101
- depth = F.interpolate(depth[None], (h, w), mode='bilinear', align_corners=False)[0, 0]
102
- depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0
103
- depth = depth.cpu().numpy().astype(np.uint8)
104
- return Image.fromarray(depth)
105
-
106
- def get_canny_image(image, t1=100, t2=200):
107
- image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
108
- edges = cv2.Canny(image, t1, t2)
109
- return Image.fromarray(edges, "L")
110
-
111
  class GenerateImageRequest(BaseModel):
112
  prompt: str
113
  negative_prompt: str
@@ -127,10 +85,7 @@ class GenerateImageRequest(BaseModel):
127
  def convert_from_cv2_to_image(img: np.ndarray) -> Image:
128
  return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
129
 
130
- def convert_from_image_to_cv2(img: Image) -> np.ndarray:
131
- return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
132
-
133
- def resize_img(input_image, max_side=1280, min_side=1024, size=None, pad_to_max_side=False, mode=PIL.Image.BILINEAR, base_pixel_number=64):
134
  w, h = input_image.size
135
  if size is not None:
136
  w_resize_new, h_resize_new = size
@@ -150,8 +105,8 @@ def resize_img(input_image, max_side=1280, min_side=1024, size=None, pad_to_max_
150
  input_image = Image.fromarray(res)
151
  return input_image
152
 
153
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
154
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
155
  return p.replace("{prompt}", positive), n + " " + negative
156
 
157
  @app.post("/generate-image/")
@@ -159,8 +114,7 @@ async def generate_image(request: GenerateImageRequest, face_file: UploadFile =
159
  try:
160
  face_image = Image.open(face_file.file)
161
  face_image = resize_img(face_image, max_side=1024)
162
- face_image_cv2 = convert_from_image_to_cv2(face_image)
163
- height, width, _ = face_image_cv2.shape
164
 
165
  face_info = face_analysis.get(face_image_cv2)
166
  if len(face_info) == 0:
@@ -168,13 +122,12 @@ async def generate_image(request: GenerateImageRequest, face_file: UploadFile =
168
 
169
  face_info = sorted(face_info, key=lambda x: (x["bbox"][2] - x["bbox"][0]) * x["bbox"][3] - x["bbox"][1])[-1]
170
  face_emb = face_info["embedding"]
171
- face_kps = draw_kps(convert_from_cv2_to_image(face_image_cv2), face_info["kps"])
172
 
173
  if pose_file:
174
  pose_image = Image.open(pose_file.file)
175
  pose_image = resize_img(pose_image, max_side=1024)
176
- img_controlnet = pose_image
177
- pose_image_cv2 = convert_from_image_to_cv2(pose_image)
178
 
179
  face_info = face_analysis.get(pose_image_cv2)
180
  if len(face_info) == 0:
@@ -182,25 +135,13 @@ async def generate_image(request: GenerateImageRequest, face_file: UploadFile =
182
 
183
  face_info = face_info[-1]
184
  face_kps = draw_kps(pose_image, face_info["kps"])
185
- width, height = face_kps.size
186
-
187
- else:
188
- img_controlnet = face_image
189
 
 
190
  if request.enhance_face_region:
191
- control_mask = np.zeros([height, width, 3])
192
- x1, y1, x2, y2 = face_info["bbox"]
193
- x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
194
  control_mask[y1:y2, x1:x2] = 255
195
- control_mask = Image.fromarray(control_mask.astype(np.uint8))
196
- else:
197
- control_mask = None
198
-
199
- if request.enable_LCM:
200
- pipe.scheduler = diffusers.LCMScheduler.from_config(pipe.scheduler.config)
201
- pipe.enable_lora()
202
- else:
203
- pipe.disable_lora()
204
 
205
  controlnet_scales = {
206
  "pose": request.pose_strength,
@@ -208,34 +149,21 @@ async def generate_image(request: GenerateImageRequest, face_file: UploadFile =
208
  "depth": request.depth_strength,
209
  }
210
 
211
- if len(request.controlnet_selection) > 0:
212
- pipe.controlnet = MultiControlNetModel(
213
- [controlnet_identitynet] + [controlnet_map[s] for s in request.controlnet_selection]
214
- )
215
- control_scales = [float(request.identitynet_strength_ratio)] + [
216
- controlnet_scales[s] for s in request.controlnet_selection
217
- ]
218
- control_images = [face_kps] + [
219
- controlnet_map_fn[s](img_controlnet).resize((width, height)) for s in request.controlnet_selection
220
- ]
221
- else:
222
- pipe.controlnet = controlnet_identitynet
223
- control_scales = float(request.identitynet_strength_ratio)
224
- control_images = face_kps
225
 
226
  generator = torch.Generator(device=device).manual_seed(request.seed)
 
227
 
228
- images = pipe(
229
- prompt=request.prompt,
230
- negative_prompt=request.negative_prompt,
231
  image_embeds=face_emb,
232
  image=control_images,
233
  control_mask=control_mask,
234
- controlnet_conditioning_scale=control_scales,
235
  num_inference_steps=request.num_steps,
236
  guidance_scale=request.guidance_scale,
237
- height=height,
238
- width=width,
239
  generator=generator,
240
  ).images
241
 
@@ -244,9 +172,7 @@ async def generate_image(request: GenerateImageRequest, face_file: UploadFile =
244
  img_str = base64.b64encode(buffered.getvalue()).decode()
245
 
246
  return {"image": img_str}
247
- except Exception as e:
248
- return {"error": str(e), "traceback": traceback.format_exc()}
249
 
250
- if __name__ == "__main__":
251
- import uvicorn
252
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
  from fastapi import FastAPI, HTTPException, UploadFile, File
2
  from pydantic import BaseModel
3
  import torch
 
4
  import numpy as np
5
  from PIL import Image
6
  import io
7
  import base64
8
  import traceback
9
+ from diffusers import DiffusionPipeline, ControlNetModel
 
10
  from insightface.app import FaceAnalysis
11
  from controlnet_aux import OpenposeDetector
12
  from depth_anything.dpt import DepthAnything
 
14
  import torch.nn.functional as F
15
  from torchvision.transforms import Compose
16
 
17
+ from pipeline_stable_diffusion_xl_instantid_full import draw_kps
18
+ from style_template import styles
19
 
20
  app = FastAPI()
21
 
 
23
  MAX_SEED = np.iinfo(np.int32).max
24
  device = "cuda" if torch.cuda.is_available() else "cpu"
25
  dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32
 
 
 
 
 
 
 
26
 
27
  # Load face encoder
28
  face_analysis = FaceAnalysis(name="antelopev2", root="./", providers=["CPUExecutionProvider"])
 
41
  face_adapter = "./checkpoints/ip-adapter.bin"
42
  controlnet_path = "./checkpoints/ControlNetModel"
43
 
44
+ # Load the pipeline using DiffusionPipeline
45
+ pipeline = DiffusionPipeline.from_pretrained("InstantX/InstantID").to(device)
46
+ pipeline.load_ip_adapter_instantid(face_adapter)
47
+
48
  controlnet_identitynet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=dtype)
49
 
50
  controlnet_pose_model = "thibaud/controlnet-openpose-sdxl-1.0"
 
62
  }
63
  controlnet_map_fn = {
64
  "pose": openpose,
65
+ "canny": lambda img: Image.fromarray(cv2.Canny(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR), 100, 200), "L"),
66
+ "depth": lambda img: transform({'image': np.array(img) / 255.0})['image'].unsqueeze(0).to(device),
67
  }
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  class GenerateImageRequest(BaseModel):
70
  prompt: str
71
  negative_prompt: str
 
85
  def convert_from_cv2_to_image(img: np.ndarray) -> Image:
86
  return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
87
 
88
+ def resize_img(input_image, max_side=1280, min_side=1024, size=None, pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64):
 
 
 
89
  w, h = input_image.size
90
  if size is not None:
91
  w_resize_new, h_resize_new = size
 
105
  input_image = Image.fromarray(res)
106
  return input_image
107
 
108
+ def apply_style(style_name: str, positive: str, negative: str = "") -> tuple:
109
+ p, n = styles.get(style_name, styles["Spring Festival"])
110
  return p.replace("{prompt}", positive), n + " " + negative
111
 
112
  @app.post("/generate-image/")
 
114
  try:
115
  face_image = Image.open(face_file.file)
116
  face_image = resize_img(face_image, max_side=1024)
117
+ face_image_cv2 = np.array(face_image)
 
118
 
119
  face_info = face_analysis.get(face_image_cv2)
120
  if len(face_info) == 0:
 
122
 
123
  face_info = sorted(face_info, key=lambda x: (x["bbox"][2] - x["bbox"][0]) * x["bbox"][3] - x["bbox"][1])[-1]
124
  face_emb = face_info["embedding"]
125
+ face_kps = draw_kps(face_image, face_info["kps"])
126
 
127
  if pose_file:
128
  pose_image = Image.open(pose_file.file)
129
  pose_image = resize_img(pose_image, max_side=1024)
130
+ pose_image_cv2 = np.array(pose_image)
 
131
 
132
  face_info = face_analysis.get(pose_image_cv2)
133
  if len(face_info) == 0:
 
135
 
136
  face_info = face_info[-1]
137
  face_kps = draw_kps(pose_image, face_info["kps"])
 
 
 
 
138
 
139
+ control_mask = None
140
  if request.enhance_face_region:
141
+ control_mask = np.zeros((face_image_cv2.shape[0], face_image_cv2.shape[1], 3), dtype=np.uint8)
142
+ x1, y1, x2, y2 = map(int, face_info["bbox"])
 
143
  control_mask[y1:y2, x1:x2] = 255
144
+ control_mask = Image.fromarray(control_mask)
 
 
 
 
 
 
 
 
145
 
146
  controlnet_scales = {
147
  "pose": request.pose_strength,
 
149
  "depth": request.depth_strength,
150
  }
151
 
152
+ controlnet_selection = [controlnet_identitynet] + [controlnet_map[s] for s in request.controlnet_selection]
153
+ control_images = [face_kps] + [controlnet_map_fn[s](face_image) for s in request.controlnet_selection]
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
  generator = torch.Generator(device=device).manual_seed(request.seed)
156
+ prompt, negative_prompt = apply_style(request.style, request.prompt, request.negative_prompt)
157
 
158
+ images = pipeline(
159
+ prompt=prompt,
160
+ negative_prompt=negative_prompt,
161
  image_embeds=face_emb,
162
  image=control_images,
163
  control_mask=control_mask,
164
+ controlnet_conditioning_scale=[request.identitynet_strength_ratio] + [controlnet_scales[s] for s in request.controlnet_selection],
165
  num_inference_steps=request.num_steps,
166
  guidance_scale=request.guidance_scale,
 
 
167
  generator=generator,
168
  ).images
169
 
 
172
  img_str = base64.b64encode(buffered.getvalue()).decode()
173
 
174
  return {"image": img_str}
 
 
175
 
176
+ except Exception as e:
177
+ traceback.print_exc()
178
+ raise HTTPException(status_code=500, detail=str(e))