Create demo.py
Browse files
demo.py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModel, AutoTokenizer
|
2 |
+
|
3 |
+
# model setting
|
4 |
+
model_path = 'OpenGVLab/InternVideo2_5_Chat_8B'
|
5 |
+
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
7 |
+
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().cuda()
|
8 |
+
|
9 |
+
|
10 |
+
def build_transform(input_size):
|
11 |
+
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
|
12 |
+
transform = T.Compose([T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img), T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), T.ToTensor(), T.Normalize(mean=MEAN, std=STD)])
|
13 |
+
return transform
|
14 |
+
|
15 |
+
|
16 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
17 |
+
best_ratio_diff = float("inf")
|
18 |
+
best_ratio = (1, 1)
|
19 |
+
area = width * height
|
20 |
+
for ratio in target_ratios:
|
21 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
22 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
23 |
+
if ratio_diff < best_ratio_diff:
|
24 |
+
best_ratio_diff = ratio_diff
|
25 |
+
best_ratio = ratio
|
26 |
+
elif ratio_diff == best_ratio_diff:
|
27 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
28 |
+
best_ratio = ratio
|
29 |
+
return best_ratio
|
30 |
+
|
31 |
+
|
32 |
+
def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
|
33 |
+
orig_width, orig_height = image.size
|
34 |
+
aspect_ratio = orig_width / orig_height
|
35 |
+
|
36 |
+
# calculate the existing image aspect ratio
|
37 |
+
target_ratios = set((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 i * j <= max_num and i * j >= min_num)
|
38 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
39 |
+
|
40 |
+
# find the closest aspect ratio to the target
|
41 |
+
target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
42 |
+
|
43 |
+
# calculate the target width and height
|
44 |
+
target_width = image_size * target_aspect_ratio[0]
|
45 |
+
target_height = image_size * target_aspect_ratio[1]
|
46 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
47 |
+
|
48 |
+
# resize the image
|
49 |
+
resized_img = image.resize((target_width, target_height))
|
50 |
+
processed_images = []
|
51 |
+
for i in range(blocks):
|
52 |
+
box = ((i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size)
|
53 |
+
# split the image
|
54 |
+
split_img = resized_img.crop(box)
|
55 |
+
processed_images.append(split_img)
|
56 |
+
assert len(processed_images) == blocks
|
57 |
+
if use_thumbnail and len(processed_images) != 1:
|
58 |
+
thumbnail_img = image.resize((image_size, image_size))
|
59 |
+
processed_images.append(thumbnail_img)
|
60 |
+
return processed_images
|
61 |
+
|
62 |
+
|
63 |
+
def load_image(image, input_size=448, max_num=6):
|
64 |
+
transform = build_transform(input_size=input_size)
|
65 |
+
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
66 |
+
pixel_values = [transform(image) for image in images]
|
67 |
+
pixel_values = torch.stack(pixel_values)
|
68 |
+
return pixel_values
|
69 |
+
|
70 |
+
|
71 |
+
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
|
72 |
+
if bound:
|
73 |
+
start, end = bound[0], bound[1]
|
74 |
+
else:
|
75 |
+
start, end = -100000, 100000
|
76 |
+
start_idx = max(first_idx, round(start * fps))
|
77 |
+
end_idx = min(round(end * fps), max_frame)
|
78 |
+
seg_size = float(end_idx - start_idx) / num_segments
|
79 |
+
frame_indices = np.array([int(start_idx + (seg_size / 2) + np.round(seg_size * idx)) for idx in range(num_segments)])
|
80 |
+
return frame_indices
|
81 |
+
|
82 |
+
def get_num_frames_by_duration(duration):
|
83 |
+
local_num_frames = 4
|
84 |
+
num_segments = int(duration // local_num_frames)
|
85 |
+
if num_segments == 0:
|
86 |
+
num_frames = local_num_frames
|
87 |
+
else:
|
88 |
+
num_frames = local_num_frames * num_segments
|
89 |
+
|
90 |
+
num_frames = min(512, num_frames)
|
91 |
+
num_frames = max(128, num_frames)
|
92 |
+
|
93 |
+
return num_frames
|
94 |
+
|
95 |
+
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32, get_frame_by_duration = False):
|
96 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
97 |
+
max_frame = len(vr) - 1
|
98 |
+
fps = float(vr.get_avg_fps())
|
99 |
+
|
100 |
+
pixel_values_list, num_patches_list = [], []
|
101 |
+
transform = build_transform(input_size=input_size)
|
102 |
+
if get_frame_by_duration:
|
103 |
+
duration = max_frame / fps
|
104 |
+
num_segments = get_num_frames_by_duration(duration)
|
105 |
+
frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
|
106 |
+
for frame_index in frame_indices:
|
107 |
+
img = Image.fromarray(vr[frame_index].asnumpy()).convert("RGB")
|
108 |
+
img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
109 |
+
pixel_values = [transform(tile) for tile in img]
|
110 |
+
pixel_values = torch.stack(pixel_values)
|
111 |
+
num_patches_list.append(pixel_values.shape[0])
|
112 |
+
pixel_values_list.append(pixel_values)
|
113 |
+
pixel_values = torch.cat(pixel_values_list)
|
114 |
+
return pixel_values, num_patches_list
|
115 |
+
|
116 |
+
# evaluation setting
|
117 |
+
max_num_frames = 512
|
118 |
+
generation_config = dict(
|
119 |
+
do_sample=False,
|
120 |
+
temperature=0.0,
|
121 |
+
max_new_tokens=1024,
|
122 |
+
top_p=0.1,
|
123 |
+
num_beams=1
|
124 |
+
)
|
125 |
+
video_path = "your_video.mp4"
|
126 |
+
num_segments=128
|
127 |
+
|
128 |
+
|
129 |
+
with torch.no_grad():
|
130 |
+
|
131 |
+
pixel_values, num_patches_list = load_video(video_path, num_segments=num_segments, max_num=1, get_frame_by_duration=False)
|
132 |
+
pixel_values = pixel_values.to(torch.bfloat16).to(model.device)
|
133 |
+
video_prefix = "".join([f"Frame{i+1}: <image>\n" for i in range(len(num_patches_list))])
|
134 |
+
# single-turn conversation
|
135 |
+
question1 = "Describe this video in detail."
|
136 |
+
question = video_prefix + question1
|
137 |
+
output1, chat_history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=None, return_history=True)
|
138 |
+
print(output1)
|
139 |
+
|
140 |
+
# multi-turn conversation
|
141 |
+
question2 = "How many people appear in the video?"
|
142 |
+
output2, chat_history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list, history=chat_history, return_history=True)
|
143 |
+
|
144 |
+
print(output2)
|