ydshieh commited on
Commit
699fb43
1 Parent(s): 605cc24
Files changed (1) hide show
  1. app.py +146 -1
app.py CHANGED
@@ -1,10 +1,155 @@
1
  import gradio as gr
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  def main():
4
 
 
 
 
 
 
5
  def generate_predictions(image_input, text_input, do_sample, sampling_topp, sampling_temperature):
6
 
7
- return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  term_of_use = """
10
  ### Terms of use
 
1
  import gradio as gr
2
 
3
+ import numpy as np
4
+ import os
5
+ import requests
6
+ import torch
7
+ import torchvision.transforms as T
8
+ from PIL import Image
9
+ from transformers import AutoProcessor, AutoModelForVision2Seq
10
+ import cv2
11
+
12
+
13
+ def is_overlapping(rect1, rect2):
14
+ x1, y1, x2, y2 = rect1
15
+ x3, y3, x4, y4 = rect2
16
+ return not (x2 < x3 or x1 > x4 or y2 < y3 or y1 > y4)
17
+
18
+
19
+ def draw_entity_boxes_on_image(image, entities, show=False, save_path=None):
20
+ """_summary_
21
+ Args:
22
+ image (_type_): image or image path
23
+ collect_entity_location (_type_): _description_
24
+ """
25
+ if isinstance(image, Image.Image):
26
+ image_h = image.height
27
+ image_w = image.width
28
+ image = np.array(image)[:, :, [2, 1, 0]]
29
+ elif isinstance(image, str):
30
+ if os.path.exists(image):
31
+ pil_img = Image.open(image).convert("RGB")
32
+ image = np.array(pil_img)[:, :, [2, 1, 0]]
33
+ image_h = pil_img.height
34
+ image_w = pil_img.width
35
+ else:
36
+ raise ValueError(f"invaild image path, {image}")
37
+ elif isinstance(image, torch.Tensor):
38
+ # pdb.set_trace()
39
+ image_tensor = image.cpu()
40
+ reverse_norm_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073])[:, None, None]
41
+ reverse_norm_std = torch.tensor([0.26862954, 0.26130258, 0.27577711])[:, None, None]
42
+ image_tensor = image_tensor * reverse_norm_std + reverse_norm_mean
43
+ pil_img = T.ToPILImage()(image_tensor)
44
+ image_h = pil_img.height
45
+ image_w = pil_img.width
46
+ image = np.array(pil_img)[:, :, [2, 1, 0]]
47
+ else:
48
+ raise ValueError(f"invaild image format, {type(image)} for {image}")
49
+
50
+ if len(entities) == 0:
51
+ return image
52
+
53
+ new_image = image.copy()
54
+ previous_bboxes = []
55
+ # size of text
56
+ text_size = 2
57
+ # thickness of text
58
+ text_line = 1 # int(max(1 * min(image_h, image_w) / 512, 1))
59
+ box_line = 3
60
+ (c_width, text_height), _ = cv2.getTextSize("F", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line)
61
+ base_height = int(text_height * 0.675)
62
+ text_offset_original = text_height - base_height
63
+ text_spaces = 3
64
+
65
+ for entity_name, (start, end), bboxes in entities:
66
+ for (x1_norm, y1_norm, x2_norm, y2_norm) in bboxes:
67
+ 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)
68
+ # draw bbox
69
+ # random color
70
+ color = tuple(np.random.randint(0, 255, size=3).tolist())
71
+ new_image = cv2.rectangle(new_image, (orig_x1, orig_y1), (orig_x2, orig_y2), color, box_line)
72
+
73
+ l_o, r_o = box_line // 2 + box_line % 2, box_line // 2 + box_line % 2 + 1
74
+
75
+ x1 = orig_x1 - l_o
76
+ y1 = orig_y1 - l_o
77
+
78
+ if y1 < text_height + text_offset_original + 2 * text_spaces:
79
+ y1 = orig_y1 + r_o + text_height + text_offset_original + 2 * text_spaces
80
+ x1 = orig_x1 + r_o
81
+
82
+ # add text background
83
+ (text_width, text_height), _ = cv2.getTextSize(f" {entity_name}", cv2.FONT_HERSHEY_COMPLEX, text_size, text_line)
84
+ 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
85
+
86
+ for prev_bbox in previous_bboxes:
87
+ while is_overlapping((text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2), prev_bbox):
88
+ text_bg_y1 += (text_height + text_offset_original + 2 * text_spaces)
89
+ text_bg_y2 += (text_height + text_offset_original + 2 * text_spaces)
90
+ y1 += (text_height + text_offset_original + 2 * text_spaces)
91
+
92
+ if text_bg_y2 >= image_h:
93
+ text_bg_y1 = max(0, image_h - (text_height + text_offset_original + 2 * text_spaces))
94
+ text_bg_y2 = image_h
95
+ y1 = image_h
96
+ break
97
+
98
+ alpha = 0.5
99
+ for i in range(text_bg_y1, text_bg_y2):
100
+ for j in range(text_bg_x1, text_bg_x2):
101
+ if i < image_h and j < image_w:
102
+ if j < text_bg_x1 + 1.35 * c_width:
103
+ # original color
104
+ bg_color = color
105
+ else:
106
+ # white
107
+ bg_color = [255, 255, 255]
108
+ new_image[i, j] = (alpha * new_image[i, j] + (1 - alpha) * np.array(bg_color)).astype(np.uint8)
109
+
110
+ cv2.putText(
111
+ 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
112
+ )
113
+ # previous_locations.append((x1, y1))
114
+ previous_bboxes.append((text_bg_x1, text_bg_y1, text_bg_x2, text_bg_y2))
115
+
116
+ pil_image = Image.fromarray(new_image[:, :, [2, 1, 0]])
117
+ if save_path:
118
+ pil_image.save(save_path)
119
+ if show:
120
+ pil_image.show()
121
+
122
+ return new_image
123
+
124
+
125
  def main():
126
 
127
+ ckpt = "ydshieh/kosmos-2-patch14-224"
128
+
129
+ model = AutoModelForVision2Seq.from_pretrained(ckpt, trust_remote_code=True)
130
+ processor = AutoProcessor.from_pretrained(ckpt, trust_remote_code=True)
131
+
132
  def generate_predictions(image_input, text_input, do_sample, sampling_topp, sampling_temperature):
133
 
134
+ inputs = processor(text=text_input, images=image_input, return_tensors="pt")
135
+
136
+ generated_ids = model.generate(
137
+ pixel_values=inputs["pixel_values"],
138
+ input_ids=inputs["input_ids"][:, :-1],
139
+ attention_mask=inputs["attention_mask"][:, :-1],
140
+ img_features=None,
141
+ img_attn_mask=inputs["img_attn_mask"][:, :-1],
142
+ use_cache=True,
143
+ max_new_tokens=128,
144
+ )
145
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
146
+
147
+ # By default, the generated text is cleanup and the entities are extracted.
148
+ processed_text, entities = processor.post_processor_generation(generated_text)
149
+
150
+ annotated_image = draw_entity_boxes_on_image(image_input, entities, show=True)
151
+
152
+ return annotated_image, processed_text
153
 
154
  term_of_use = """
155
  ### Terms of use