Views
No views yet
1# pip install git+https://github.com/LLaVA-VL/LLaVA-NeXT.git
2from llava.model.builder import load_pretrained_model
3from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
4from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IGNORE_INDEX
5from llava.conversation import conv_templates, SeparatorStyle
6from PIL import Image
7import requests
8import copy
9import torch
10import sys
11import warnings
12from decord import VideoReader, cpu
13import numpy as np
14warnings.filterwarnings("ignore")
15def load_video(self, video_path, max_frames_num,fps=1,force_sample=False):
16 if max_frames_num == 0:
17 return np.zeros((1, 336, 336, 3))
18 vr = VideoReader(video_path, ctx=cpu(0),num_threads=1)
19 total_frame_num = len(vr)
20 video_time = total_frame_num / vr.get_avg_fps()
21 fps = round(vr.get_avg_fps()/fps)
22 frame_idx = [i for i in range(0, len(vr), fps)]
23 frame_time = [i/fps for i in frame_idx]
24 if len(frame_idx) > max_frames_num or force_sample:
25 sample_fps = max_frames_num
26 uniform_sampled_frames = np.linspace(0, total_frame_num - 1, sample_fps, dtype=int)
27 frame_idx = uniform_sampled_frames.tolist()
28 frame_time = [i/vr.get_avg_fps() for i in frame_idx]
29 frame_time = ",".join([f"{i:.2f}s" for i in frame_time])
30 spare_frames = vr.get_batch(frame_idx).asnumpy()
31 # import pdb;pdb.set_trace()
32 return spare_frames,frame_time,video_time
33pretrained = "lmms-lab/LLaVA-Video-7B-Qwen2-Video-Only "
34model_name = "llava_qwen"
35device = "cuda"
36device_map = "auto"
37tokenizer, model, image_processor, max_length = load_pretrained_model(pretrained, None, model_name, torch_dtype="bfloat16", device_map=device_map) # Add any other thing you want to pass in llava_model_args
38model.eval()
39video_path = "XXXX"
40max_frames_num = "64"
41video,frame_time,video_time = load_video(video_path, max_frames_num, 1, force_sample=True)
42video = image_processor.preprocess(video, return_tensors="pt")["pixel_values"].cuda().bfloat16()
43video = [video]
44conv_template = "qwen_1_5" # Make sure you use correct chat template for different models
45time_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."
46question = DEFAULT_IMAGE_TOKEN + f"{time_instruciton}\nPlease describe this video in detail."
47conv = copy.deepcopy(conv_templates[conv_template])
48conv.append_message(conv.roles[0], question)
49conv.append_message(conv.roles[1], None)
50prompt_question = conv.get_prompt()
51input_ids = tokenizer_image_token(prompt_question, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)
52cont = model.generate(
53 input_ids,
54 images=video,
55 modalities= ["video"],
56 do_sample=False,
57 temperature=0,
58 max_new_tokens=4096,
59)
60text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)[0].strip()
61print(text_outputs)1
2@misc{zhang2024videoinstructiontuningsynthetic,
3 title={Video Instruction Tuning With Synthetic Data},
4 author={Yuanhan Zhang and Jinming Wu and Wei Li and Bo Li and Zejun Ma and Ziwei Liu and Chunyuan Li},
5 year={2024},
6 eprint={2410.02713},
7 archivePrefix={arXiv},
8 primaryClass={cs.CV},
9 url={https://arxiv.org/abs/2410.02713},
10}