1# This inference script is adapted from:
2# https://huggingface.co/lmms-lab/LLaVA-Video-7B-Qwen2
3
4from vica2.model.builder import load_pretrained_model
5from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
6from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
7from llava.conversation import conv_templates, SeparatorStyle
8from PIL import Image
9import requests
10import copy
11import torch
12import sys
13import warnings
14from decord import VideoReader, cpu
15import numpy as np
16
17warnings.filterwarnings("ignore")
18def load_video(video_path, max_frames_num,fps=1,force_sample=False):
19 if max_frames_num == 0:
20 return np.zeros((1, 336, 336, 3))
21 vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
22 total_frame_num = len(vr)
23 video_time = total_frame_num / vr.get_avg_fps()
24 fps = round(vr.get_avg_fps()/fps)
25 frame_idx = [i for i in range(0, len(vr), fps)]
26 frame_time = [i/fps for i in frame_idx]
27 if len(frame_idx) > max_frames_num or force_sample:
28 sample_fps = max_frames_num
29 uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
30 frame_idx = uniform_sampled_frames.tolist()
31 frame_time = [i/vr.get_avg_fps() for i in frame_idx]
32 frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
33 spare_frames = vr.get_batch(frame_idx).asnumpy()
34 return spare_frames,frame_time,video_time
35
36pretrained = "nkkbr/ViCA2"
37model_name = "vica_qwen"
38device = "cuda"
39device_map = "auto"
40tokenizer, model, image_processor, image_processor_for_sam, max_length = load_pretrained_model(pretrained, None, model_name, torch_dtype="bfloat16", device_map=device_map)
41model.eval()
42
43
44from datasets import load_dataset
45vsi_bench = load_dataset("nyu-visionx/VSI-Bench")
46vsi_bench = vsi_bench['test']
47
48data_curr = vsi_bench[90]
49
50video_path = f"[VIDEO PATH]"
51max_frames_num = 64
52video,frame_time,video_time = load_video(video_path, max_frames_num, 1, force_sample=True)
53
54video1= image_processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
55video1 = [video1]
56video2 = image_processor_for_sam.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
57video2 = [video2]
58conv_template = "qwen_1_5"
59# time_instruciton = f"The video lasts for {video_time:.2f} seconds, and {len(video[0])} frames are uniformly sampled from it. These frames are located at {frame_time}.Please answer the following questions related to this video."
60time_instruciton = ""
61question = DEFAULT_IMAGE_TOKEN + f"\n{time_instruciton}\n\n"
62question += f"These are frames of a video.\n\n"
63question += f"Question: {data_curr['question']}\n"
64if data_curr['options'] is not None:
65 question += '\n'.join(data_curr['options']) + "\n"
66 question += f"Answer with the option’s letter from the given choices directly.\n"
67else:
68 question += f"Please answer the question using a single word or phrase.\n"
69print(f"Prompt:\n{question}")
70
71conv = copy.deepcopy(conv_templates[conv_template])
72conv.append_message(conv.roles[0], question)
73conv.append_message(conv.roles[1], None)
74prompt_question = conv.get_prompt()
75input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
76cont = model.generate(
77 input_ids,
78 images=video1,
79 images_for_sam=video2,
80 modalities= ["video"],
81 do_sample=False,
82 temperature=0,
83 max_new_tokens=1024,
84)
85text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)[0].strip()
86print(repr(text_outputs))