minhdang commited on
Commit
326a251
1 Parent(s): ae37444

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -5
app.py CHANGED
@@ -1,7 +1,145 @@
1
- import gradio as gr
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/Mini-InternVL-Chat-2B-V1-5"
89
+ model = AutoModel.from_pretrained(
90
+ path,
91
+ torch_dtype=torch.bfloat16,
92
+ low_cpu_mem_usage=True,
93
+ trust_remote_code=True).eval().cuda()
94
+
95
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
96
+ # set the max number of tiles in `max_num`
97
+ pixel_values = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
98
+
99
+ generation_config = dict(
100
+ num_beams=1,
101
+ max_new_tokens=512,
102
+ do_sample=False,
103
+ )
104
+
105
+ # single-round single-image conversation
106
+ question = "请详细描述图片" # Please describe the picture in detail
107
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
108
+ print(question, response)
109
+
110
+ # multi-round single-image conversation
111
+ question = "请详细描述图片" # Please describe the picture in detail
112
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
113
+ print(question, response)
114
+
115
+ question = "请根据图片写一首诗" # Please write a poem according to the picture
116
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
117
+ print(question, response)
118
+
119
+ # multi-round multi-image conversation
120
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
121
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
122
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
123
+
124
+ question = "详细描述这两张图片" # Describe the two pictures in detail
125
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
126
+ print(question, response)
127
+
128
+ question = "这两张图片的相同点和区别分别是什么" # What are the similarities and differences between these two pictures
129
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
130
+ print(question, response)
131
+
132
+ # batch inference (single image per sample)
133
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
134
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
135
+ image_counts = [pixel_values1.size(0), pixel_values2.size(0)]
136
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
137
+
138
+ questions = ["Describe the image in detail."] * len(image_counts)
139
+ responses = model.batch_chat(tokenizer, pixel_values,
140
+ image_counts=image_counts,
141
+ questions=questions,
142
+ generation_config=generation_config)
143
+ for question, response in zip(questions, responses):
144
+ print(question)
145
+ print(response)