Implements Kosmos2 handler
Browse files- handler.py +187 -94
handler.py
CHANGED
@@ -2,13 +2,14 @@ from typing import Dict, List, Any
|
|
2 |
import base64
|
3 |
from PIL import Image
|
4 |
from io import BytesIO
|
5 |
-
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
6 |
-
import torch
|
7 |
-
|
8 |
-
|
9 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
10 |
import cv2
|
11 |
-
import
|
12 |
|
13 |
# set device
|
14 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
@@ -17,109 +18,201 @@ if device.type != 'cuda':
|
|
17 |
# set mixed precision dtype
|
18 |
dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] == 8 else torch.float16
|
19 |
|
20 |
-
# controlnet mapping for controlnet id and control hinter
|
21 |
-
CONTROLNET_MAPPING = {
|
22 |
-
"canny_edge": {
|
23 |
-
"model_id": "lllyasviel/sd-controlnet-canny",
|
24 |
-
"hinter": controlnet_hinter.hint_canny
|
25 |
-
},
|
26 |
-
"pose": {
|
27 |
-
"model_id": "lllyasviel/sd-controlnet-openpose",
|
28 |
-
"hinter": controlnet_hinter.hint_openpose
|
29 |
-
},
|
30 |
-
"depth": {
|
31 |
-
"model_id": "lllyasviel/sd-controlnet-depth",
|
32 |
-
"hinter": controlnet_hinter.hint_depth
|
33 |
-
},
|
34 |
-
"scribble": {
|
35 |
-
"model_id": "lllyasviel/sd-controlnet-scribble",
|
36 |
-
"hinter": controlnet_hinter.hint_scribble,
|
37 |
-
},
|
38 |
-
"segmentation": {
|
39 |
-
"model_id": "lllyasviel/sd-controlnet-seg",
|
40 |
-
"hinter": controlnet_hinter.hint_segmentation,
|
41 |
-
},
|
42 |
-
"normal": {
|
43 |
-
"model_id": "lllyasviel/sd-controlnet-normal",
|
44 |
-
"hinter": controlnet_hinter.hint_normal,
|
45 |
-
},
|
46 |
-
"hed": {
|
47 |
-
"model_id": "lllyasviel/sd-controlnet-hed",
|
48 |
-
"hinter": controlnet_hinter.hint_hed,
|
49 |
-
},
|
50 |
-
"hough": {
|
51 |
-
"model_id": "lllyasviel/sd-controlnet-mlsd",
|
52 |
-
"hinter": controlnet_hinter.hint_hough,
|
53 |
-
}
|
54 |
-
}
|
55 |
-
|
56 |
|
57 |
class EndpointHandler():
|
58 |
def __init__(self, path=""):
|
59 |
-
|
60 |
-
|
61 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
73 |
"""
|
74 |
:param data: A dictionary contains `inputs` and optional `image` field.
|
75 |
:return: A dictionary with `image` field contains image in base64.
|
76 |
"""
|
77 |
-
prompt = data.pop("inputs", None)
|
78 |
image = data.pop("image", None)
|
79 |
-
|
80 |
-
|
81 |
-
#
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
# Check if a new controlnet is provided
|
86 |
-
if controlnet_type is not None and controlnet_type != self.control_type:
|
87 |
-
print(f"changing controlnet from {self.control_type} to {controlnet_type} using {CONTROLNET_MAPPING[controlnet_type]['model_id']} model")
|
88 |
-
self.control_type = controlnet_type
|
89 |
-
self.controlnet = ControlNetModel.from_pretrained(CONTROLNET_MAPPING[self.control_type]["model_id"],
|
90 |
-
torch_dtype=dtype).to(device)
|
91 |
-
self.pipe.controlnet = self.controlnet
|
92 |
-
|
93 |
-
|
94 |
-
# hyperparamters
|
95 |
-
num_inference_steps = data.pop("num_inference_steps", 30)
|
96 |
-
guidance_scale = data.pop("guidance_scale", 7.5)
|
97 |
-
negative_prompt = data.pop("negative_prompt", None)
|
98 |
-
height = data.pop("height", None)
|
99 |
-
width = data.pop("width", None)
|
100 |
-
controlnet_conditioning_scale = data.pop("controlnet_conditioning_scale", 1.0)
|
101 |
-
|
102 |
-
# process image
|
103 |
-
image = self.decode_base64_image(image)
|
104 |
-
control_image = CONTROLNET_MAPPING[self.control_type]["hinter"](image)
|
105 |
|
106 |
-
#
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
118 |
)
|
|
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
# helper to decode input image
|
125 |
def decode_base64_image(self, image_string):
|
|
|
2 |
import base64
|
3 |
from PIL import Image
|
4 |
from io import BytesIO
|
|
|
|
|
|
|
|
|
5 |
import numpy as np
|
6 |
+
import os
|
7 |
+
import requests
|
8 |
+
import torch
|
9 |
+
import torchvision.transforms as T
|
10 |
+
from transformers import AutoProcessor, AutoModelForVision2Seq
|
11 |
import cv2
|
12 |
+
import ast
|
13 |
|
14 |
# set device
|
15 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
|
|
18 |
# set mixed precision dtype
|
19 |
dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] == 8 else torch.float16
|
20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
class EndpointHandler():
|
23 |
def __init__(self, path=""):
|
24 |
+
self.ckpt_id = "ydshieh/kosmos-2-patch14-224"
|
25 |
+
|
26 |
+
self.model = AutoModelForVision2Seq.from_pretrained(ckpt_id, trust_remote_code=True).to("cuda")
|
27 |
+
self.processor = AutoProcessor.from_pretrained(ckpt, trust_remote_code=True)
|
28 |
+
|
29 |
+
def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, entity_index=-1):
|
30 |
+
"""_summary_
|
31 |
+
Args:
|
32 |
+
image (_type_): image or image path
|
33 |
+
collect_entity_location (_type_): _description_
|
34 |
+
"""
|
35 |
+
if isinstance(image, Image.Image):
|
36 |
+
image_h = image.height
|
37 |
+
image_w = image.width
|
38 |
+
image = np.array(image)[:, :, [2, 1, 0]]
|
39 |
+
elif isinstance(image, str):
|
40 |
+
if os.path.exists(image):
|
41 |
+
pil_img = Image.open(image).convert("RGB")
|
42 |
+
image = np.array(pil_img)[:, :, [2, 1, 0]]
|
43 |
+
image_h = pil_img.height
|
44 |
+
image_w = pil_img.width
|
45 |
+
else:
|
46 |
+
raise ValueError(f"invaild image path, {image}")
|
47 |
+
elif isinstance(image, torch.Tensor):
|
48 |
+
# pdb.set_trace()
|
49 |
+
image_tensor = image.cpu()
|
50 |
+
reverse_norm_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073])[:, None, None]
|
51 |
+
reverse_norm_std = torch.tensor([0.26862954, 0.26130258, 0.27577711])[:, None, None]
|
52 |
+
image_tensor = image_tensor * reverse_norm_std + reverse_norm_mean
|
53 |
+
pil_img = T.ToPILImage()(image_tensor)
|
54 |
+
image_h = pil_img.height
|
55 |
+
image_w = pil_img.width
|
56 |
+
image = np.array(pil_img)[:, :, [2, 1, 0]]
|
57 |
+
else:
|
58 |
+
raise ValueError(f"invaild image format, {type(image)} for {image}")
|
59 |
+
|
60 |
+
if len(entities) == 0:
|
61 |
+
return image
|
62 |
+
|
63 |
+
indices = list(range(len(entities)))
|
64 |
+
if entity_index >= 0:
|
65 |
+
indices = [entity_index]
|
66 |
+
|
67 |
+
# Not to show too many bboxes
|
68 |
+
entities = entities[:len(color_map)]
|
69 |
|
70 |
+
new_image = image.copy()
|
71 |
+
previous_bboxes = []
|
72 |
+
# size of text
|
73 |
+
text_size = 1
|
74 |
+
# thickness of text
|
75 |
+
text_line = 1 # int(max(1 * min(image_h, image_w) / 512, 1))
|
76 |
+
box_line = 3
|
77 |
+
(c_width, text_height), _ = cv2.getTextSize("F", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line)
|
78 |
+
base_height = int(text_height * 0.675)
|
79 |
+
text_offset_original = text_height - base_height
|
80 |
+
text_spaces = 3
|
81 |
+
|
82 |
+
# num_bboxes = sum(len(x[-1]) for x in entities)
|
83 |
+
used_colors = colors # random.sample(colors, k=num_bboxes)
|
84 |
+
|
85 |
+
color_id = -1
|
86 |
+
for entity_idx, (entity_name, (start, end), bboxes) in enumerate(entities):
|
87 |
+
color_id += 1
|
88 |
+
if entity_idx not in indices:
|
89 |
+
continue
|
90 |
+
for bbox_id, (x1_norm, y1_norm, x2_norm, y2_norm) in enumerate(bboxes):
|
91 |
+
# if start is None and bbox_id > 0:
|
92 |
+
# color_id += 1
|
93 |
+
orig_x1, orig_y1, orig_x2, orig_y2 = int(x1_norm * image_w), int(y1_norm * image_h), int(x2_norm * image_w), int(y2_norm * image_h)
|
94 |
+
|
95 |
+
# draw bbox
|
96 |
+
# random color
|
97 |
+
color = used_colors[color_id] # tuple(np.random.randint(0, 255, size=3).tolist())
|
98 |
+
new_image = cv2.rectangle(new_image, (orig_x1, orig_y1), (orig_x2, orig_y2), color, box_line)
|
99 |
+
|
100 |
+
l_o, r_o = box_line // 2 + box_line % 2, box_line // 2 + box_line % 2 + 1
|
101 |
+
|
102 |
+
x1 = orig_x1 - l_o
|
103 |
+
y1 = orig_y1 - l_o
|
104 |
+
|
105 |
+
if y1 < text_height + text_offset_original + 2 * text_spaces:
|
106 |
+
y1 = orig_y1 + r_o + text_height + text_offset_original + 2 * text_spaces
|
107 |
+
x1 = orig_x1 + r_o
|
108 |
+
|
109 |
+
# add text background
|
110 |
+
(text_width, text_height), _ = cv2.getTextSize(f" {entity_name}", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line)
|
111 |
+
text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2 = x1, y1 - (text_height + text_offset_original + 2 * text_spaces), x1 + text_width, y1
|
112 |
+
|
113 |
+
for prev_bbox in previous_bboxes:
|
114 |
+
while is_overlapping((text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2), prev_bbox):
|
115 |
+
text_bg_y1 += (text_height + text_offset_original + 2 * text_spaces)
|
116 |
+
text_bg_y2 += (text_height + text_offset_original + 2 * text_spaces)
|
117 |
+
y1 += (text_height + text_offset_original + 2 * text_spaces)
|
118 |
+
|
119 |
+
if text_bg_y2 >= image_h:
|
120 |
+
text_bg_y1 = max(0, image_h - (text_height + text_offset_original + 2 * text_spaces))
|
121 |
+
text_bg_y2 = image_h
|
122 |
+
y1 = image_h
|
123 |
+
break
|
124 |
+
|
125 |
+
alpha = 0.5
|
126 |
+
for i in range(text_bg_y1, text_bg_y2):
|
127 |
+
for j in range(text_bg_x1, text_bg_x2):
|
128 |
+
if i < image_h and j < image_w:
|
129 |
+
if j < text_bg_x1 + 1.35 * c_width:
|
130 |
+
# original color
|
131 |
+
bg_color = color
|
132 |
+
else:
|
133 |
+
# white
|
134 |
+
bg_color = [255, 255, 255]
|
135 |
+
new_image[i, j] = (alpha * new_image[i, j] + (1 - alpha) * np.array(bg_color)).astype(np.uint8)
|
136 |
+
|
137 |
+
cv2.putText(
|
138 |
+
new_image, f" {entity_name}", (x1, y1 - text_offset_original - 1 * text_spaces), cv2.FONT_HERSHEY_COMPLEX, text_size, (0, 0, 0), text_line, cv2.LINE_AA
|
139 |
+
)
|
140 |
+
# previous_locations.append((x1, y1))
|
141 |
+
previous_bboxes.append((text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2))
|
142 |
+
|
143 |
+
pil_image = Image.fromarray(new_image[:, :, [2, 1, 0]])
|
144 |
+
if save_path:
|
145 |
+
pil_image.save(save_path)
|
146 |
+
if show:
|
147 |
+
pil_image.show()
|
148 |
+
|
149 |
+
return pil_image
|
150 |
+
|
151 |
|
152 |
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
153 |
"""
|
154 |
:param data: A dictionary contains `inputs` and optional `image` field.
|
155 |
:return: A dictionary with `image` field contains image in base64.
|
156 |
"""
|
|
|
157 |
image = data.pop("image", None)
|
158 |
+
image_input = self.decode_base64_image(image)
|
159 |
+
|
160 |
+
# Save the image and load it again to match the original Kosmos-2 demo.
|
161 |
+
# (https://github.com/microsoft/unilm/blob/f4695ed0244a275201fff00bee495f76670fbe70/kosmos-2/demo/gradio_app.py#L345-L346)
|
162 |
+
user_image_path = "/tmp/user_input_test_image.jpg"
|
163 |
+
image_input.save(user_image_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
+
# This might give different results from the original argument `image_input`
|
166 |
+
image_input = Image.open(user_image_path)
|
167 |
+
text_input = "<grounding>Describe this image in detail:"
|
168 |
+
#text_input = f"<grounding>{text_input}"
|
169 |
+
|
170 |
+
inputs = processor(text=text_input, images=image_input, return_tensors="pt")
|
171 |
+
|
172 |
+
generated_ids = self.model.generate(
|
173 |
+
pixel_values=inputs["pixel_values"].to("cuda"),
|
174 |
+
input_ids=inputs["input_ids"][:, :-1].to("cuda"),
|
175 |
+
attention_mask=inputs["attention_mask"][:, :-1].to("cuda"),
|
176 |
+
img_features=None,
|
177 |
+
img_attn_mask=inputs["img_attn_mask"][:, :-1].to("cuda"),
|
178 |
+
use_cache=True,
|
179 |
+
max_new_tokens=128,
|
180 |
)
|
181 |
+
generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
182 |
|
183 |
+
# By default, the generated text is cleanup and the entities are extracted.
|
184 |
+
processed_text, entities = processor.post_process_generation(generated_text)
|
185 |
+
|
186 |
+
annotated_image = self.draw_entity_boxes_on_image(image_input, entities, show=False)
|
187 |
+
|
188 |
+
color_id = -1
|
189 |
+
entity_info = []
|
190 |
+
filtered_entities = []
|
191 |
+
for entity in entities:
|
192 |
+
entity_name, (start, end), bboxes = entity
|
193 |
+
if start == end:
|
194 |
+
# skip bounding bbox without a `phrase` associated
|
195 |
+
continue
|
196 |
+
color_id += 1
|
197 |
+
# for bbox_id, _ in enumerate(bboxes):
|
198 |
+
# if start is None and bbox_id > 0:
|
199 |
+
# color_id += 1
|
200 |
+
entity_info.append(((start, end), color_id))
|
201 |
+
filtered_entities.append(entity)
|
202 |
+
|
203 |
+
colored_text = []
|
204 |
+
prev_start = 0
|
205 |
+
end = 0
|
206 |
+
for idx, ((start, end), color_id) in enumerate(entity_info):
|
207 |
+
if start > prev_start:
|
208 |
+
colored_text.append((processed_text[prev_start:start], None))
|
209 |
+
colored_text.append((processed_text[start:end], f"{color_id}"))
|
210 |
+
prev_start = end
|
211 |
+
|
212 |
+
if end < len(processed_text):
|
213 |
+
colored_text.append((processed_text[end:len(processed_text)], None))
|
214 |
+
|
215 |
+
return annotated_image, colored_text, str(filtered_entities)
|
216 |
|
217 |
# helper to decode input image
|
218 |
def decode_base64_image(self, image_string):
|