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| 2 |
+
import torch
|
| 3 |
+
import torchvision.transforms as T
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 7 |
+
|
| 8 |
+
from transformers import AutoModel, AutoTokenizer
|
| 9 |
+
|
| 10 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 11 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 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 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
| 24 |
+
best_ratio_diff = float('inf')
|
| 25 |
+
best_ratio = (1, 1)
|
| 26 |
+
area = width * height
|
| 27 |
+
for ratio in target_ratios:
|
| 28 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
| 29 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
| 30 |
+
if ratio_diff < best_ratio_diff:
|
| 31 |
+
best_ratio_diff = ratio_diff
|
| 32 |
+
best_ratio = ratio
|
| 33 |
+
elif ratio_diff == best_ratio_diff:
|
| 34 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
| 35 |
+
best_ratio = ratio
|
| 36 |
+
return best_ratio
|
| 37 |
+
|
| 38 |
+
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
|
| 39 |
+
orig_width, orig_height = image.size
|
| 40 |
+
aspect_ratio = orig_width / orig_height
|
| 41 |
+
|
| 42 |
+
# calculate the existing image aspect ratio
|
| 43 |
+
target_ratios = set(
|
| 44 |
+
(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
|
| 45 |
+
i * j <= max_num and i * j >= min_num)
|
| 46 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
| 47 |
+
|
| 48 |
+
# find the closest aspect ratio to the target
|
| 49 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
| 50 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
| 51 |
+
|
| 52 |
+
# calculate the target width and height
|
| 53 |
+
target_width = image_size * target_aspect_ratio[0]
|
| 54 |
+
target_height = image_size * target_aspect_ratio[1]
|
| 55 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
| 56 |
+
|
| 57 |
+
# resize the image
|
| 58 |
+
resized_img = image.resize((target_width, target_height))
|
| 59 |
+
processed_images = []
|
| 60 |
+
for i in range(blocks):
|
| 61 |
+
box = (
|
| 62 |
+
(i % (target_width // image_size)) * image_size,
|
| 63 |
+
(i // (target_width // image_size)) * image_size,
|
| 64 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
| 65 |
+
((i // (target_width // image_size)) + 1) * image_size
|
| 66 |
+
)
|
| 67 |
+
# split the image
|
| 68 |
+
split_img = resized_img.crop(box)
|
| 69 |
+
processed_images.append(split_img)
|
| 70 |
+
assert len(processed_images) == blocks
|
| 71 |
+
if use_thumbnail and len(processed_images) != 1:
|
| 72 |
+
thumbnail_img = image.resize((image_size, image_size))
|
| 73 |
+
processed_images.append(thumbnail_img)
|
| 74 |
+
return processed_images
|
| 75 |
+
|
| 76 |
+
def load_image(image, input_size=448, max_num=12):
|
| 77 |
+
transform = build_transform(input_size=input_size)
|
| 78 |
+
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
| 79 |
+
pixel_values = [transform(image) for image in images]
|
| 80 |
+
pixel_values = torch.stack(pixel_values)
|
| 81 |
+
return pixel_values
|
| 82 |
+
|
| 83 |
+
# Load model and tokenizer globally to avoid reloading for each request
|
| 84 |
+
@torch.inference_mode()
|
| 85 |
+
def load_models():
|
| 86 |
+
model = AutoModel.from_pretrained(
|
| 87 |
+
"5CD-AI/Vintern-1B-v3_5",
|
| 88 |
+
torch_dtype=torch.bfloat16,
|
| 89 |
+
low_cpu_mem_usage=True,
|
| 90 |
+
trust_remote_code=True,
|
| 91 |
+
use_flash_attn=False,
|
| 92 |
+
).eval()
|
| 93 |
+
|
| 94 |
+
# Move model to GPU if available
|
| 95 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 96 |
+
model = model.to(device)
|
| 97 |
+
|
| 98 |
+
tokenizer = AutoTokenizer.from_pretrained("5CD-AI/Vintern-1B-v3_5", trust_remote_code=True, use_fast=False)
|
| 99 |
+
|
| 100 |
+
return model, tokenizer, device
|
| 101 |
+
|
| 102 |
+
model, tokenizer, device = load_models()
|
| 103 |
+
|
| 104 |
+
def generate_response(image, question):
|
| 105 |
+
if image is None:
|
| 106 |
+
return "Vui lòng tải lên một hình ảnh."
|
| 107 |
+
if not question:
|
| 108 |
+
question = '<image>\nTrích xuất thông tin chính trong ảnh và trả về dạng markdown.'
|
| 109 |
+
|
| 110 |
+
# Convert image to PIL if it's a file upload
|
| 111 |
+
if isinstance(image, str):
|
| 112 |
+
image = Image.open(image).convert('RGB')
|
| 113 |
+
else:
|
| 114 |
+
image = Image.fromarray(image).convert('RGB')
|
| 115 |
+
|
| 116 |
+
# Process image
|
| 117 |
+
pixel_values = load_image(image, max_num=6).to(torch.bfloat16).to(device)
|
| 118 |
+
|
| 119 |
+
# Generate response
|
| 120 |
+
generation_config = dict(max_new_tokens=1024, do_sample=False, num_beams=3, repetition_penalty=2.5)
|
| 121 |
+
|
| 122 |
+
response, _ = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
|
| 123 |
+
|
| 124 |
+
return response
|
| 125 |
+
|
| 126 |
+
# Create Gradio interface
|
| 127 |
+
with gr.Blocks() as demo:
|
| 128 |
+
gr.Markdown("# Vintern-1B-v3.5 Demo")
|
| 129 |
+
gr.Markdown("Tải lên hình ảnh và đặt câu hỏi (hoặc để trống để trích xuất thông tin).")
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
with gr.Column():
|
| 133 |
+
image_input = gr.Image(type="pil", label="Hình ảnh")
|
| 134 |
+
question_input = gr.Textbox(
|
| 135 |
+
placeholder="<image>\nTrích xuất thông tin chính trong ảnh và trả về dạng markdown.",
|
| 136 |
+
label="Câu hỏi (để trống để trích xuất thông tin)"
|
| 137 |
+
)
|
| 138 |
+
submit_btn = gr.Button("Gửi")
|
| 139 |
+
|
| 140 |
+
with gr.Column():
|
| 141 |
+
output = gr.Markdown(label="Kết quả")
|
| 142 |
+
|
| 143 |
+
submit_btn.click(
|
| 144 |
+
fn=generate_response,
|
| 145 |
+
inputs=[image_input, question_input],
|
| 146 |
+
outputs=output
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# gr.Examples(
|
| 150 |
+
# [
|
| 151 |
+
# ["example1.jpg", "<image>\nTrích xuất thông tin chính trong ảnh và trả về dạng markdown."],
|
| 152 |
+
# ["example2.jpg", "<image>\nĐây là hình ảnh gì?"],
|
| 153 |
+
# ],
|
| 154 |
+
# inputs=[image_input, question_input],
|
| 155 |
+
# )
|
| 156 |
+
|
| 157 |
+
demo.launch()
|