TienAnh commited on
Commit
8daee79
·
verified ·
1 Parent(s): bf4601c

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +117 -0
README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - vi
5
+ base_model:
6
+ - OpenGVLab/InternVL3-1B
7
+ - 5CD-AI/Vintern-1B-v3_5
8
+ pipeline_tag: visual-question-answering
9
+ ---
10
+
11
+ ```python
12
+ import numpy as np
13
+ import torch
14
+ import torchvision.transforms as T
15
+ # from decord import VideoReader, cpu
16
+ from PIL import Image
17
+ from torchvision.transforms.functional import InterpolationMode
18
+ from transformers import AutoModel, AutoTokenizer
19
+
20
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
21
+ IMAGENET_STD = (0.229, 0.224, 0.225)
22
+
23
+ def build_transform(input_size):
24
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
25
+ transform = T.Compose([
26
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
27
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
28
+ T.ToTensor(),
29
+ T.Normalize(mean=MEAN, std=STD)
30
+ ])
31
+ return transform
32
+
33
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
34
+ best_ratio_diff = float('inf')
35
+ best_ratio = (1, 1)
36
+ area = width * height
37
+ for ratio in target_ratios:
38
+ target_aspect_ratio = ratio[0] / ratio[1]
39
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
40
+ if ratio_diff < best_ratio_diff:
41
+ best_ratio_diff = ratio_diff
42
+ best_ratio = ratio
43
+ elif ratio_diff == best_ratio_diff:
44
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
45
+ best_ratio = ratio
46
+ return best_ratio
47
+
48
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
49
+ orig_width, orig_height = image.size
50
+ aspect_ratio = orig_width / orig_height
51
+
52
+ # calculate the existing image aspect ratio
53
+ target_ratios = set(
54
+ (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
55
+ i * j <= max_num and i * j >= min_num)
56
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
57
+
58
+ # find the closest aspect ratio to the target
59
+ target_aspect_ratio = find_closest_aspect_ratio(
60
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
61
+
62
+ # calculate the target width and height
63
+ target_width = image_size * target_aspect_ratio[0]
64
+ target_height = image_size * target_aspect_ratio[1]
65
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
66
+
67
+ # resize the image
68
+ resized_img = image.resize((target_width, target_height))
69
+ processed_images = []
70
+ for i in range(blocks):
71
+ box = (
72
+ (i % (target_width // image_size)) * image_size,
73
+ (i // (target_width // image_size)) * image_size,
74
+ ((i % (target_width // image_size)) + 1) * image_size,
75
+ ((i // (target_width // image_size)) + 1) * image_size
76
+ )
77
+ # split the image
78
+ split_img = resized_img.crop(box)
79
+ processed_images.append(split_img)
80
+ assert len(processed_images) == blocks
81
+ if use_thumbnail and len(processed_images) != 1:
82
+ thumbnail_img = image.resize((image_size, image_size))
83
+ processed_images.append(thumbnail_img)
84
+ return processed_images
85
+
86
+ def load_image(image_file, input_size=448, max_num=12):
87
+ image = Image.open(image_file).convert('RGB')
88
+ transform = build_transform(input_size=input_size)
89
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
90
+ pixel_values = [transform(image) for image in images]
91
+ pixel_values = torch.stack(pixel_values)
92
+ return pixel_values
93
+
94
+ model = AutoModel.from_pretrained(
95
+ "TienAnh/Finetune_VQA_1B",
96
+ torch_dtype=torch.bfloat16,
97
+ low_cpu_mem_usage=True,
98
+ trust_remote_code=True,
99
+ use_flash_attn=False,
100
+ ).eval().cuda()
101
+
102
+ tokenizer = AutoTokenizer.from_pretrained("TienAnh/Finetune_VQA_1B", trust_remote_code=True, use_fast=False)
103
+
104
+ test_image = 'test-image.jpg'
105
+
106
+ pixel_values = load_image(test_image, max_num=6).to(torch.bfloat16).cuda()
107
+ generation_config = dict(max_new_tokens= 1024, do_sample=False, num_beams = 3, repetition_penalty=2.5)
108
+
109
+ question = '<image>\nTrích xuất thông tin chính trong ảnh và trả về dạng markdown.'
110
+
111
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
112
+ print(f'User: {question}\nAssistant: {response}')
113
+
114
+ #question = "Câu hỏi khác ......"
115
+ #response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
116
+ #print(f'User: {question}\nAssistant: {response}')
117
+ ```