Devops-hestabit
commited on
Update handler.py
Browse files- handler.py +104 -25
handler.py
CHANGED
@@ -1,31 +1,110 @@
|
|
1 |
-
from
|
2 |
-
|
3 |
-
|
4 |
-
from
|
|
|
|
|
|
|
5 |
|
6 |
class EndpointHandler():
|
7 |
def __init__(self, path):
|
8 |
-
|
9 |
-
|
10 |
-
self.
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
|
|
|
|
20 |
inputs = data.pop("inputs", data)
|
21 |
image_url = inputs.get("image_url")
|
22 |
prompt = inputs.get("prompt")
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModel
|
2 |
+
import torch
|
3 |
+
import torchvision.transforms as T
|
4 |
+
from PIL import Image
|
5 |
+
from io import BytesIO
|
6 |
+
import requests
|
7 |
+
from torchvision.transforms.functional import InterpolationMode
|
8 |
|
9 |
class EndpointHandler():
|
10 |
def __init__(self, path):
|
11 |
+
|
12 |
+
# If you have an 80G A100 GPU, you can put the entire model on a single GPU.
|
13 |
+
self.model = AutoModel.from_pretrained(
|
14 |
+
path,
|
15 |
+
torch_dtype=torch.bfloat16,
|
16 |
+
low_cpu_mem_usage=True,
|
17 |
+
trust_remote_code=True).eval().cuda()
|
18 |
+
|
19 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
20 |
+
self.IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
21 |
+
self.IMAGENET_STD = (0.229, 0.224, 0.225)
|
22 |
+
|
23 |
+
def __call__(self, data):
|
24 |
+
|
25 |
inputs = data.pop("inputs", data)
|
26 |
image_url = inputs.get("image_url")
|
27 |
prompt = inputs.get("prompt")
|
28 |
+
# set the max number of tiles in `max_num`
|
29 |
+
pixel_values = self.load_image(image_url, max_num=6).to(torch.bfloat16).cuda()
|
30 |
+
generation_config = dict(
|
31 |
+
num_beams=1,
|
32 |
+
max_new_tokens=1000,
|
33 |
+
do_sample=False,
|
34 |
+
)
|
35 |
+
|
36 |
+
# single-round single-image conversation
|
37 |
+
response = self.model.chat(self.tokenizer, pixel_values, prompt, generation_config)
|
38 |
+
return {"response": response}
|
39 |
+
|
40 |
+
def load_image(self, image_file, input_size=448, max_num=6):
|
41 |
+
response = requests.get(image_file)
|
42 |
+
image = Image.open(BytesIO(response.content)).convert('RGB')
|
43 |
+
transform = self.build_transform(input_size=input_size)
|
44 |
+
images = self.dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
45 |
+
pixel_values = [transform(image) for image in images]
|
46 |
+
pixel_values = torch.stack(pixel_values)
|
47 |
+
return pixel_values
|
48 |
+
|
49 |
+
def build_transform(self, input_size):
|
50 |
+
MEAN, STD = self.IMAGENET_MEAN, self.IMAGENET_STD
|
51 |
+
transform = T.Compose([
|
52 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
53 |
+
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
|
54 |
+
T.ToTensor(),
|
55 |
+
T.Normalize(mean=MEAN, std=STD)
|
56 |
+
])
|
57 |
+
return transform
|
58 |
+
|
59 |
+
def dynamic_preprocess(self, image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
|
60 |
+
orig_width, orig_height = image.size
|
61 |
+
aspect_ratio = orig_width / orig_height
|
62 |
+
|
63 |
+
# calculate the existing image aspect ratio
|
64 |
+
target_ratios = set(
|
65 |
+
(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
|
66 |
+
i * j <= max_num and i * j >= min_num)
|
67 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
68 |
+
|
69 |
+
# find the closest aspect ratio to the target
|
70 |
+
target_aspect_ratio = self.find_closest_aspect_ratio(
|
71 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
72 |
+
|
73 |
+
# calculate the target width and height
|
74 |
+
target_width = image_size * target_aspect_ratio[0]
|
75 |
+
target_height = image_size * target_aspect_ratio[1]
|
76 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
77 |
+
|
78 |
+
# resize the image
|
79 |
+
resized_img = image.resize((target_width, target_height))
|
80 |
+
processed_images = []
|
81 |
+
for i in range(blocks):
|
82 |
+
box = (
|
83 |
+
(i % (target_width // image_size)) * image_size,
|
84 |
+
(i // (target_width // image_size)) * image_size,
|
85 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
86 |
+
((i // (target_width // image_size)) + 1) * image_size
|
87 |
+
)
|
88 |
+
# split the image
|
89 |
+
split_img = resized_img.crop(box)
|
90 |
+
processed_images.append(split_img)
|
91 |
+
assert len(processed_images) == blocks
|
92 |
+
if use_thumbnail and len(processed_images) != 1:
|
93 |
+
thumbnail_img = image.resize((image_size, image_size))
|
94 |
+
processed_images.append(thumbnail_img)
|
95 |
+
return processed_images
|
96 |
+
|
97 |
+
def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height, image_size):
|
98 |
+
best_ratio_diff = float('inf')
|
99 |
+
best_ratio = (1, 1)
|
100 |
+
area = width * height
|
101 |
+
for ratio in target_ratios:
|
102 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
103 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
104 |
+
if ratio_diff < best_ratio_diff:
|
105 |
+
best_ratio_diff = ratio_diff
|
106 |
+
best_ratio = ratio
|
107 |
+
elif ratio_diff == best_ratio_diff:
|
108 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
109 |
+
best_ratio = ratio
|
110 |
+
return best_ratio
|