Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,6 +10,7 @@ from transformers import AutoProcessor, AutoModelForVision2Seq
|
|
| 10 |
import cv2
|
| 11 |
import ast
|
| 12 |
|
|
|
|
| 13 |
colors = [
|
| 14 |
(0, 255, 0),
|
| 15 |
(0, 0, 255),
|
|
@@ -30,18 +31,21 @@ colors = [
|
|
| 30 |
]
|
| 31 |
|
| 32 |
color_map = {
|
| 33 |
-
f"{color_id}": f"#{hex(color[2])[2:].zfill(2)}{hex(color[1])[2:].zfill(2)}{hex(color[0])[2:].zfill(2)}"
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
|
| 37 |
def is_overlapping(rect1, rect2):
|
| 38 |
x1, y1, x2, y2 = rect1
|
| 39 |
x3, y3, x4, y4 = rect2
|
|
|
|
| 40 |
return not (x2 < x3 or x1 > x4 or y2 < y3 or y1 > y4)
|
| 41 |
|
| 42 |
|
| 43 |
def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, entity_index=-1):
|
| 44 |
"""_summary_
|
|
|
|
| 45 |
Args:
|
| 46 |
image (_type_): image or image path
|
| 47 |
collect_entity_location (_type_): _description_
|
|
@@ -59,10 +63,13 @@ def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, enti
|
|
| 59 |
else:
|
| 60 |
raise ValueError(f"invaild image path, {image}")
|
| 61 |
elif isinstance(image, torch.Tensor):
|
| 62 |
-
# pdb.set_trace()
|
| 63 |
image_tensor = image.cpu()
|
| 64 |
-
reverse_norm_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073])[
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
image_tensor = image_tensor * reverse_norm_std + reverse_norm_mean
|
| 67 |
pil_img = T.ToPILImage()(image_tensor)
|
| 68 |
image_h = pil_img.height
|
|
@@ -79,59 +86,85 @@ def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, enti
|
|
| 79 |
indices = [entity_index]
|
| 80 |
|
| 81 |
# Not to show too many bboxes
|
| 82 |
-
entities = entities[:len(color_map)]
|
| 83 |
-
|
| 84 |
new_image = image.copy()
|
| 85 |
previous_bboxes = []
|
| 86 |
-
|
| 87 |
text_size = 1
|
| 88 |
-
|
| 89 |
-
text_line = 1 # int(max(1 * min(image_h, image_w) / 512, 1))
|
| 90 |
box_line = 3
|
| 91 |
-
(c_width, text_height), _ = cv2.getTextSize(
|
|
|
|
|
|
|
| 92 |
base_height = int(text_height * 0.675)
|
| 93 |
text_offset_original = text_height - base_height
|
| 94 |
text_spaces = 3
|
| 95 |
-
|
| 96 |
-
# num_bboxes = sum(len(x[-1]) for x in entities)
|
| 97 |
-
used_colors = colors # random.sample(colors, k=num_bboxes)
|
| 98 |
-
|
| 99 |
color_id = -1
|
|
|
|
| 100 |
for entity_idx, (entity_name, (start, end), bboxes) in enumerate(entities):
|
| 101 |
color_id += 1
|
| 102 |
if entity_idx not in indices:
|
| 103 |
continue
|
| 104 |
-
for bbox_id, (x1_norm, y1_norm, x2_norm, y2_norm) in enumerate(bboxes):
|
| 105 |
-
# if start is None and bbox_id > 0:
|
| 106 |
-
# color_id += 1
|
| 107 |
-
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)
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
x1 = orig_x1 - l_o
|
| 117 |
y1 = orig_y1 - l_o
|
| 118 |
|
| 119 |
if y1 < text_height + text_offset_original + 2 * text_spaces:
|
| 120 |
-
y1 =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
x1 = orig_x1 + r_o
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
for prev_bbox in previous_bboxes:
|
| 128 |
-
while is_overlapping(
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
| 132 |
|
| 133 |
if text_bg_y2 >= image_h:
|
| 134 |
-
text_bg_y1 = max(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
text_bg_y2 = image_h
|
| 136 |
y1 = image_h
|
| 137 |
break
|
|
@@ -141,22 +174,34 @@ def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, enti
|
|
| 141 |
for j in range(text_bg_x1, text_bg_x2):
|
| 142 |
if i < image_h and j < image_w:
|
| 143 |
if j < text_bg_x1 + 1.35 * c_width:
|
| 144 |
-
# original color
|
| 145 |
bg_color = color
|
| 146 |
else:
|
| 147 |
-
# white
|
| 148 |
bg_color = [255, 255, 255]
|
| 149 |
-
new_image[i, j] = (
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
cv2.putText(
|
| 152 |
-
new_image,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
)
|
| 154 |
-
# previous_locations.append((x1, y1))
|
| 155 |
-
previous_bboxes.append((text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2))
|
| 156 |
|
| 157 |
pil_image = Image.fromarray(new_image[:, :, [2, 1, 0]])
|
|
|
|
| 158 |
if save_path:
|
| 159 |
pil_image.save(save_path)
|
|
|
|
| 160 |
if show:
|
| 161 |
pil_image.show()
|
| 162 |
|
|
@@ -164,29 +209,41 @@ def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, enti
|
|
| 164 |
|
| 165 |
|
| 166 |
def main():
|
| 167 |
-
|
| 168 |
ckpt = "microsoft/kosmos-2-patch14-224"
|
| 169 |
-
|
| 170 |
model = AutoModelForVision2Seq.from_pretrained(ckpt).to("cuda")
|
| 171 |
processor = AutoProcessor.from_pretrained(ckpt)
|
| 172 |
|
| 173 |
def generate_predictions(image_input, text_input):
|
|
|
|
|
|
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
# Save the image and load it again to match the original Kosmos-2 demo.
|
| 176 |
# (https://github.com/microsoft/unilm/blob/f4695ed0244a275201fff00bee495f76670fbe70/kosmos-2/demo/gradio_app.py#L345-L346)
|
| 177 |
user_image_path = "/tmp/user_input_test_image.jpg"
|
| 178 |
image_input.save(user_image_path)
|
|
|
|
| 179 |
# This might give different results from the original argument `image_input`
|
| 180 |
image_input = Image.open(user_image_path)
|
| 181 |
|
| 182 |
if text_input == "Brief":
|
| 183 |
-
text_input = "
|
| 184 |
elif text_input == "Detailed":
|
| 185 |
-
text_input = "
|
| 186 |
else:
|
| 187 |
-
text_input = f"
|
| 188 |
|
| 189 |
-
inputs = processor(text=text_input, images=image_input, return_tensors="pt").to(
|
|
|
|
|
|
|
| 190 |
|
| 191 |
generated_ids = model.generate(
|
| 192 |
pixel_values=inputs["pixel_values"],
|
|
@@ -198,9 +255,11 @@ def main():
|
|
| 198 |
max_new_tokens=128,
|
| 199 |
)
|
| 200 |
|
| 201 |
-
generated_text = processor.batch_decode(
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
# By default, the generated
|
| 204 |
processed_text, entities = processor.post_process_generation(generated_text)
|
| 205 |
|
| 206 |
annotated_image = draw_entity_boxes_on_image(image_input, entities, show=False)
|
|
@@ -208,21 +267,22 @@ def main():
|
|
| 208 |
color_id = -1
|
| 209 |
entity_info = []
|
| 210 |
filtered_entities = []
|
|
|
|
| 211 |
for entity in entities:
|
| 212 |
entity_name, (start, end), bboxes = entity
|
|
|
|
| 213 |
if start == end:
|
| 214 |
# skip bounding bbox without a `phrase` associated
|
| 215 |
continue
|
|
|
|
| 216 |
color_id += 1
|
| 217 |
-
# for bbox_id, _ in enumerate(bboxes):
|
| 218 |
-
# if start is None and bbox_id > 0:
|
| 219 |
-
# color_id += 1
|
| 220 |
entity_info.append(((start, end), color_id))
|
| 221 |
filtered_entities.append(entity)
|
| 222 |
|
| 223 |
colored_text = []
|
| 224 |
prev_start = 0
|
| 225 |
end = 0
|
|
|
|
| 226 |
for idx, ((start, end), color_id) in enumerate(entity_info):
|
| 227 |
if start > prev_start:
|
| 228 |
colored_text.append((processed_text[prev_start:start], None))
|
|
@@ -230,55 +290,73 @@ def main():
|
|
| 230 |
prev_start = end
|
| 231 |
|
| 232 |
if end < len(processed_text):
|
| 233 |
-
colored_text.append((processed_text[end:len(processed_text)], None))
|
| 234 |
|
| 235 |
return annotated_image, colored_text, str(filtered_entities)
|
| 236 |
|
| 237 |
term_of_use = """
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
with gr.Blocks(title="Kosmos-2", theme=gr.themes.Base()).queue() as demo:
|
| 249 |
-
gr.Markdown(
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
with gr.Row():
|
| 254 |
with gr.Column():
|
| 255 |
image_input = gr.Image(type="pil", label="Test Image")
|
| 256 |
-
text_input = gr.Radio(
|
| 257 |
-
|
|
|
|
| 258 |
run_button = gr.Button("Run", visible=True)
|
| 259 |
|
| 260 |
with gr.Column():
|
| 261 |
image_output = gr.Image(type="pil")
|
| 262 |
text_output1 = gr.HighlightedText(
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
|
| 269 |
with gr.Row():
|
| 270 |
with gr.Column():
|
| 271 |
-
gr.Examples(
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
with gr.Column():
|
| 277 |
-
gr.Examples(
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
gr.Markdown(term_of_use)
|
| 283 |
|
| 284 |
# record which text span (label) is selected
|
|
@@ -291,25 +369,43 @@ def main():
|
|
| 291 |
def get_text_span_label(evt: gr.SelectData):
|
| 292 |
if evt.value[-1] is None:
|
| 293 |
return -1
|
|
|
|
| 294 |
return int(evt.value[-1])
|
|
|
|
| 295 |
# and set this information to `selected`
|
| 296 |
-
text_output1.select(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
# update output image when we change the span (enity) selection
|
| 299 |
def update_output_image(img_input, image_output, entities, idx):
|
| 300 |
entities = ast.literal_eval(entities)
|
| 301 |
-
updated_image = draw_entity_boxes_on_image(
|
|
|
|
|
|
|
| 302 |
return updated_image
|
| 303 |
-
selected.change(update_output_image, [image_input, image_output, entity_output, selected], [image_output])
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
-
demo.launch(share=False, ssr_mode=False)
|
| 311 |
|
| 312 |
|
| 313 |
if __name__ == "__main__":
|
| 314 |
main()
|
| 315 |
-
|
|
|
|
| 10 |
import cv2
|
| 11 |
import ast
|
| 12 |
|
| 13 |
+
|
| 14 |
colors = [
|
| 15 |
(0, 255, 0),
|
| 16 |
(0, 0, 255),
|
|
|
|
| 31 |
]
|
| 32 |
|
| 33 |
color_map = {
|
| 34 |
+
f"{color_id}": f"#{hex(color[2])[2:].zfill(2)}{hex(color[1])[2:].zfill(2)}{hex(color[0])[2:].zfill(2)}"
|
| 35 |
+
for color_id, color in enumerate(colors)
|
| 36 |
}
|
| 37 |
|
| 38 |
|
| 39 |
def is_overlapping(rect1, rect2):
|
| 40 |
x1, y1, x2, y2 = rect1
|
| 41 |
x3, y3, x4, y4 = rect2
|
| 42 |
+
|
| 43 |
return not (x2 < x3 or x1 > x4 or y2 < y3 or y1 > y4)
|
| 44 |
|
| 45 |
|
| 46 |
def draw_entity_boxes_on_image(image, entities, show=False, save_path=None, entity_index=-1):
|
| 47 |
"""_summary_
|
| 48 |
+
|
| 49 |
Args:
|
| 50 |
image (_type_): image or image path
|
| 51 |
collect_entity_location (_type_): _description_
|
|
|
|
| 63 |
else:
|
| 64 |
raise ValueError(f"invaild image path, {image}")
|
| 65 |
elif isinstance(image, torch.Tensor):
|
|
|
|
| 66 |
image_tensor = image.cpu()
|
| 67 |
+
reverse_norm_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073])[
|
| 68 |
+
:, None, None
|
| 69 |
+
]
|
| 70 |
+
reverse_norm_std = torch.tensor([0.26862954, 0.26130258, 0.27577711])[
|
| 71 |
+
:, None, None
|
| 72 |
+
]
|
| 73 |
image_tensor = image_tensor * reverse_norm_std + reverse_norm_mean
|
| 74 |
pil_img = T.ToPILImage()(image_tensor)
|
| 75 |
image_h = pil_img.height
|
|
|
|
| 86 |
indices = [entity_index]
|
| 87 |
|
| 88 |
# Not to show too many bboxes
|
| 89 |
+
entities = entities[: len(color_map)]
|
|
|
|
| 90 |
new_image = image.copy()
|
| 91 |
previous_bboxes = []
|
| 92 |
+
|
| 93 |
text_size = 1
|
| 94 |
+
text_line = 1
|
|
|
|
| 95 |
box_line = 3
|
| 96 |
+
(c_width, text_height), _ = cv2.getTextSize(
|
| 97 |
+
"F", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line
|
| 98 |
+
)
|
| 99 |
base_height = int(text_height * 0.675)
|
| 100 |
text_offset_original = text_height - base_height
|
| 101 |
text_spaces = 3
|
| 102 |
+
used_colors = colors
|
|
|
|
|
|
|
|
|
|
| 103 |
color_id = -1
|
| 104 |
+
|
| 105 |
for entity_idx, (entity_name, (start, end), bboxes) in enumerate(entities):
|
| 106 |
color_id += 1
|
| 107 |
if entity_idx not in indices:
|
| 108 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
for bbox_id, (x1_norm, y1_norm, x2_norm, y2_norm) in enumerate(bboxes):
|
| 111 |
+
orig_x1, orig_y1, orig_x2, orig_y2 = (
|
| 112 |
+
int(x1_norm * image_w),
|
| 113 |
+
int(y1_norm * image_h),
|
| 114 |
+
int(x2_norm * image_w),
|
| 115 |
+
int(y2_norm * image_h),
|
| 116 |
+
)
|
| 117 |
|
| 118 |
+
color = used_colors[color_id]
|
| 119 |
+
new_image = cv2.rectangle(
|
| 120 |
+
new_image,
|
| 121 |
+
(orig_x1, orig_y1),
|
| 122 |
+
(orig_x2, orig_y2),
|
| 123 |
+
color,
|
| 124 |
+
box_line,
|
| 125 |
+
)
|
| 126 |
|
| 127 |
+
l_o, r_o = (
|
| 128 |
+
box_line // 2 + box_line % 2,
|
| 129 |
+
box_line // 2 + box_line % 2 + 1,
|
| 130 |
+
)
|
| 131 |
x1 = orig_x1 - l_o
|
| 132 |
y1 = orig_y1 - l_o
|
| 133 |
|
| 134 |
if y1 < text_height + text_offset_original + 2 * text_spaces:
|
| 135 |
+
y1 = (
|
| 136 |
+
orig_y1
|
| 137 |
+
+ r_o
|
| 138 |
+
+ text_height
|
| 139 |
+
+ text_offset_original
|
| 140 |
+
+ 2 * text_spaces
|
| 141 |
+
)
|
| 142 |
x1 = orig_x1 + r_o
|
| 143 |
|
| 144 |
+
(text_width, text_height), _ = cv2.getTextSize(
|
| 145 |
+
f" {entity_name}", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line
|
| 146 |
+
)
|
| 147 |
+
text_bg_x1 = x1
|
| 148 |
+
text_bg_y1 = y1 - (
|
| 149 |
+
text_height + text_offset_original + 2 * text_spaces
|
| 150 |
+
)
|
| 151 |
+
text_bg_x2 = x1 + text_width
|
| 152 |
+
text_bg_y2 = y1
|
| 153 |
|
| 154 |
for prev_bbox in previous_bboxes:
|
| 155 |
+
while is_overlapping(
|
| 156 |
+
(text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2), prev_bbox
|
| 157 |
+
):
|
| 158 |
+
text_bg_y1 += text_height + text_offset_original + 2 * text_spaces
|
| 159 |
+
text_bg_y2 += text_height + text_offset_original + 2 * text_spaces
|
| 160 |
+
y1 += text_height + text_offset_original + 2 * text_spaces
|
| 161 |
|
| 162 |
if text_bg_y2 >= image_h:
|
| 163 |
+
text_bg_y1 = max(
|
| 164 |
+
0,
|
| 165 |
+
image_h
|
| 166 |
+
- (text_height + text_offset_original + 2 * text_spaces),
|
| 167 |
+
)
|
| 168 |
text_bg_y2 = image_h
|
| 169 |
y1 = image_h
|
| 170 |
break
|
|
|
|
| 174 |
for j in range(text_bg_x1, text_bg_x2):
|
| 175 |
if i < image_h and j < image_w:
|
| 176 |
if j < text_bg_x1 + 1.35 * c_width:
|
|
|
|
| 177 |
bg_color = color
|
| 178 |
else:
|
|
|
|
| 179 |
bg_color = [255, 255, 255]
|
| 180 |
+
new_image[i, j] = (
|
| 181 |
+
alpha * new_image[i, j]
|
| 182 |
+
+ (1 - alpha) * np.array(bg_color)
|
| 183 |
+
).astype(np.uint8)
|
| 184 |
|
| 185 |
cv2.putText(
|
| 186 |
+
new_image,
|
| 187 |
+
f" {entity_name}",
|
| 188 |
+
(x1, y1 - text_offset_original - 1 * text_spaces),
|
| 189 |
+
cv2.FONT_HERSHEY_COMPLEX,
|
| 190 |
+
text_size,
|
| 191 |
+
(0, 0, 0),
|
| 192 |
+
text_line,
|
| 193 |
+
cv2.LINE_AA,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
previous_bboxes.append(
|
| 197 |
+
(text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2)
|
| 198 |
)
|
|
|
|
|
|
|
| 199 |
|
| 200 |
pil_image = Image.fromarray(new_image[:, :, [2, 1, 0]])
|
| 201 |
+
|
| 202 |
if save_path:
|
| 203 |
pil_image.save(save_path)
|
| 204 |
+
|
| 205 |
if show:
|
| 206 |
pil_image.show()
|
| 207 |
|
|
|
|
| 209 |
|
| 210 |
|
| 211 |
def main():
|
|
|
|
| 212 |
ckpt = "microsoft/kosmos-2-patch14-224"
|
|
|
|
| 213 |
model = AutoModelForVision2Seq.from_pretrained(ckpt).to("cuda")
|
| 214 |
processor = AutoProcessor.from_pretrained(ckpt)
|
| 215 |
|
| 216 |
def generate_predictions(image_input, text_input):
|
| 217 |
+
"""
|
| 218 |
+
Generate a grounded image description and annotated entity boxes with Kosmos-2.
|
| 219 |
|
| 220 |
+
Use this tool when you need to describe an image and identify grounded visual entities.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
image_input (PIL.Image.Image): Input image to describe and ground.
|
| 224 |
+
text_input (str): Description mode, either "Brief" or "Detailed".
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
tuple: Annotated image, highlighted generated description, and serialized entity data.
|
| 228 |
+
"""
|
| 229 |
# Save the image and load it again to match the original Kosmos-2 demo.
|
| 230 |
# (https://github.com/microsoft/unilm/blob/f4695ed0244a275201fff00bee495f76670fbe70/kosmos-2/demo/gradio_app.py#L345-L346)
|
| 231 |
user_image_path = "/tmp/user_input_test_image.jpg"
|
| 232 |
image_input.save(user_image_path)
|
| 233 |
+
|
| 234 |
# This might give different results from the original argument `image_input`
|
| 235 |
image_input = Image.open(user_image_path)
|
| 236 |
|
| 237 |
if text_input == "Brief":
|
| 238 |
+
text_input = "An image of"
|
| 239 |
elif text_input == "Detailed":
|
| 240 |
+
text_input = "Describe this image in detail:"
|
| 241 |
else:
|
| 242 |
+
text_input = f"{text_input}"
|
| 243 |
|
| 244 |
+
inputs = processor(text=text_input, images=image_input, return_tensors="pt").to(
|
| 245 |
+
"cuda"
|
| 246 |
+
)
|
| 247 |
|
| 248 |
generated_ids = model.generate(
|
| 249 |
pixel_values=inputs["pixel_values"],
|
|
|
|
| 255 |
max_new_tokens=128,
|
| 256 |
)
|
| 257 |
|
| 258 |
+
generated_text = processor.batch_decode(
|
| 259 |
+
generated_ids, skip_special_tokens=True
|
| 260 |
+
)[0]
|
| 261 |
|
| 262 |
+
# By default, the generated text is cleanup and the entities are extracted.
|
| 263 |
processed_text, entities = processor.post_process_generation(generated_text)
|
| 264 |
|
| 265 |
annotated_image = draw_entity_boxes_on_image(image_input, entities, show=False)
|
|
|
|
| 267 |
color_id = -1
|
| 268 |
entity_info = []
|
| 269 |
filtered_entities = []
|
| 270 |
+
|
| 271 |
for entity in entities:
|
| 272 |
entity_name, (start, end), bboxes = entity
|
| 273 |
+
|
| 274 |
if start == end:
|
| 275 |
# skip bounding bbox without a `phrase` associated
|
| 276 |
continue
|
| 277 |
+
|
| 278 |
color_id += 1
|
|
|
|
|
|
|
|
|
|
| 279 |
entity_info.append(((start, end), color_id))
|
| 280 |
filtered_entities.append(entity)
|
| 281 |
|
| 282 |
colored_text = []
|
| 283 |
prev_start = 0
|
| 284 |
end = 0
|
| 285 |
+
|
| 286 |
for idx, ((start, end), color_id) in enumerate(entity_info):
|
| 287 |
if start > prev_start:
|
| 288 |
colored_text.append((processed_text[prev_start:start], None))
|
|
|
|
| 290 |
prev_start = end
|
| 291 |
|
| 292 |
if end < len(processed_text):
|
| 293 |
+
colored_text.append((processed_text[end : len(processed_text)], None))
|
| 294 |
|
| 295 |
return annotated_image, colored_text, str(filtered_entities)
|
| 296 |
|
| 297 |
term_of_use = """
|
| 298 |
+
### Terms of use
|
| 299 |
+
|
| 300 |
+
By using this model, users are required to agree to the following terms:
|
| 301 |
+
|
| 302 |
+
The model is intended for academic and research purposes.
|
| 303 |
+
The utilization of the model to create unsuitable material is strictly forbidden and not endorsed by this work.
|
| 304 |
+
The accountability for any improper or unacceptable application of the model rests exclusively with the individuals who generated such content.
|
| 305 |
+
|
| 306 |
+
### License
|
| 307 |
+
|
| 308 |
+
This project is licensed under the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct).
|
| 309 |
+
"""
|
| 310 |
|
| 311 |
with gr.Blocks(title="Kosmos-2", theme=gr.themes.Base()).queue() as demo:
|
| 312 |
+
gr.Markdown(
|
| 313 |
+
(
|
| 314 |
+
"""
|
| 315 |
+
# Kosmos-2: Grounding Multimodal Large Language Models to the World
|
| 316 |
+
|
| 317 |
+
[[Paper]](https://arxiv.org/abs/2306.14824) [[Code]](https://github.com/microsoft/unilm/blob/master/kosmos-2)
|
| 318 |
+
"""
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
with gr.Row():
|
| 323 |
with gr.Column():
|
| 324 |
image_input = gr.Image(type="pil", label="Test Image")
|
| 325 |
+
text_input = gr.Radio(
|
| 326 |
+
["Brief", "Detailed"], label="Description Type", value="Brief"
|
| 327 |
+
)
|
| 328 |
run_button = gr.Button("Run", visible=True)
|
| 329 |
|
| 330 |
with gr.Column():
|
| 331 |
image_output = gr.Image(type="pil")
|
| 332 |
text_output1 = gr.HighlightedText(
|
| 333 |
+
label="Generated Description",
|
| 334 |
+
combine_adjacent=False,
|
| 335 |
+
show_legend=True,
|
| 336 |
+
color_map=color_map,
|
| 337 |
+
)
|
| 338 |
|
| 339 |
with gr.Row():
|
| 340 |
with gr.Column():
|
| 341 |
+
gr.Examples(
|
| 342 |
+
examples=[
|
| 343 |
+
["images/two_dogs.jpg", "Detailed"],
|
| 344 |
+
["images/snowman.png", "Brief"],
|
| 345 |
+
["images/man_ball.png", "Detailed"],
|
| 346 |
+
],
|
| 347 |
+
inputs=[image_input, text_input],
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
with gr.Column():
|
| 351 |
+
gr.Examples(
|
| 352 |
+
examples=[
|
| 353 |
+
["images/six_planes.png", "Brief"],
|
| 354 |
+
["images/quadrocopter.jpg", "Brief"],
|
| 355 |
+
["images/carnaby_street.jpg", "Brief"],
|
| 356 |
+
],
|
| 357 |
+
inputs=[image_input, text_input],
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
gr.Markdown(term_of_use)
|
| 361 |
|
| 362 |
# record which text span (label) is selected
|
|
|
|
| 369 |
def get_text_span_label(evt: gr.SelectData):
|
| 370 |
if evt.value[-1] is None:
|
| 371 |
return -1
|
| 372 |
+
|
| 373 |
return int(evt.value[-1])
|
| 374 |
+
|
| 375 |
# and set this information to `selected`
|
| 376 |
+
text_output1.select(
|
| 377 |
+
get_text_span_label,
|
| 378 |
+
None,
|
| 379 |
+
selected,
|
| 380 |
+
api_visibility="private",
|
| 381 |
+
)
|
| 382 |
|
| 383 |
# update output image when we change the span (enity) selection
|
| 384 |
def update_output_image(img_input, image_output, entities, idx):
|
| 385 |
entities = ast.literal_eval(entities)
|
| 386 |
+
updated_image = draw_entity_boxes_on_image(
|
| 387 |
+
img_input, entities, entity_index=idx
|
| 388 |
+
)
|
| 389 |
return updated_image
|
|
|
|
| 390 |
|
| 391 |
+
selected.change(
|
| 392 |
+
update_output_image,
|
| 393 |
+
[image_input, image_output, entity_output, selected],
|
| 394 |
+
[image_output],
|
| 395 |
+
api_visibility="private",
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
run_button.click(
|
| 399 |
+
fn=generate_predictions,
|
| 400 |
+
inputs=[image_input, text_input],
|
| 401 |
+
outputs=[image_output, text_output1, entity_output],
|
| 402 |
+
show_progress=True,
|
| 403 |
+
queue=True,
|
| 404 |
+
)
|
| 405 |
|
| 406 |
+
demo.launch(share=False, ssr_mode=False, mcp_server=True)
|
| 407 |
|
| 408 |
|
| 409 |
if __name__ == "__main__":
|
| 410 |
main()
|
| 411 |
+
# trigger
|