Forkei commited on
Commit
48e0ba1
1 Parent(s): 9330f51

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -0
app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModel
2
+ import torch
3
+ import torchvision.transforms as T
4
+ from PIL import Image
5
+
6
+ from torchvision.transforms.functional import InterpolationMode
7
+
8
+
9
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
10
+ IMAGENET_STD = (0.229, 0.224, 0.225)
11
+
12
+
13
+ def build_transform(input_size):
14
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
15
+ transform = T.Compose([
16
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
17
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
18
+ T.ToTensor(),
19
+ T.Normalize(mean=MEAN, std=STD)
20
+ ])
21
+ return transform
22
+
23
+
24
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
25
+ best_ratio_diff = float('inf')
26
+ best_ratio = (1, 1)
27
+ area = width * height
28
+ for ratio in target_ratios:
29
+ target_aspect_ratio = ratio[0] / ratio[1]
30
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
31
+ if ratio_diff < best_ratio_diff:
32
+ best_ratio_diff = ratio_diff
33
+ best_ratio = ratio
34
+ elif ratio_diff == best_ratio_diff:
35
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
36
+ best_ratio = ratio
37
+ return best_ratio
38
+
39
+
40
+ def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
41
+ orig_width, orig_height = image.size
42
+ aspect_ratio = orig_width / orig_height
43
+
44
+ # calculate the existing image aspect ratio
45
+ target_ratios = set(
46
+ (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
47
+ i * j <= max_num and i * j >= min_num)
48
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
49
+
50
+ # find the closest aspect ratio to the target
51
+ target_aspect_ratio = find_closest_aspect_ratio(
52
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
53
+
54
+ # calculate the target width and height
55
+ target_width = image_size * target_aspect_ratio[0]
56
+ target_height = image_size * target_aspect_ratio[1]
57
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
58
+
59
+ # resize the image
60
+ resized_img = image.resize((target_width, target_height))
61
+ processed_images = []
62
+ for i in range(blocks):
63
+ box = (
64
+ (i % (target_width // image_size)) * image_size,
65
+ (i // (target_width // image_size)) * image_size,
66
+ ((i % (target_width // image_size)) + 1) * image_size,
67
+ ((i // (target_width // image_size)) + 1) * image_size
68
+ )
69
+ # split the image
70
+ split_img = resized_img.crop(box)
71
+ processed_images.append(split_img)
72
+ assert len(processed_images) == blocks
73
+ if use_thumbnail and len(processed_images) != 1:
74
+ thumbnail_img = image.resize((image_size, image_size))
75
+ processed_images.append(thumbnail_img)
76
+ return processed_images
77
+
78
+
79
+ def load_image(image_file, input_size=448, max_num=6):
80
+ image = Image.open(image_file).convert('RGB')
81
+ transform = build_transform(input_size=input_size)
82
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
83
+ pixel_values = [transform(image) for image in images]
84
+ pixel_values = torch.stack(pixel_values)
85
+ return pixel_values
86
+
87
+
88
+ path = "OpenGVLab/InternVL-Chat-V1-5"
89
+ # If you have an 80G A100 GPU, you can put the entire model on a single GPU.
90
+ model = AutoModel.from_pretrained(
91
+ path,
92
+ torch_dtype=torch.bfloat16,
93
+ low_cpu_mem_usage=True,
94
+ trust_remote_code=True).eval().cuda()
95
+ # Otherwise, you need to set device_map='auto' to use multiple GPUs for inference.
96
+ # import os
97
+ # os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
98
+ # model = AutoModel.from_pretrained(
99
+ # path,
100
+ # torch_dtype=torch.bfloat16,
101
+ # low_cpu_mem_usage=True,
102
+ # trust_remote_code=True,
103
+ # device_map='auto').eval()
104
+
105
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
106
+ # set the max number of tiles in `max_num`
107
+ pixel_values = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
108
+
109
+ generation_config = dict(
110
+ num_beams=1,
111
+ max_new_tokens=512,
112
+ do_sample=False,
113
+ )
114
+
115
+ # single-round single-image conversation
116
+ question = "what is this?" # Please describe the picture in detail
117
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
118
+ print(question, response)
119
+
120
+ questions = ["Describe the image in detail."] * len(image_counts)
121
+ responses = model.batch_chat(tokenizer, pixel_values,
122
+ image_counts=image_counts,
123
+ questions=questions,
124
+ generation_config=generation_config)
125
+ for question, response in zip(questions, responses):
126
+ print(question)
127
+ print(response)