1import os
2import torch
3from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
4from qwen_omni_utils import process_mm_info
5
6# Constants (same spirit as reference)
7VIDEO_MAX_PIXELS = 401408 # 512*28*28
8VIDEO_TOTAL_PIXELS = 20070400 # 512*28*28*50
9USE_AUDIO_IN_VIDEO = True
10
11# Some pipelines use this env var
12os.environ["VIDEO_MAX_PIXELS"] = str(VIDEO_TOTAL_PIXELS)
13
14model_id = "AudioVisual-Caption/ASID-Captioner-3B"
15
16model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
17 model_id,
18 torch_dtype=torch.bfloat16,
19 device_map="cuda",
20 attn_implementation="flash_attention_2", # optional; remove if not available
21 low_cpu_mem_usage=True,
22)
23model.disable_talker()
24
25processor = Qwen2_5OmniProcessor.from_pretrained(model_id)
26
27file_path = "/path/to/video.mp4"
28prompt = "Provide a comprehensive description of all the content in the video, leaving out no details, and naturally covering the scene, characters, objects, actions, narrative elements, speech, camera, and emotions in a single coherent account."
29
30conversation = [
31 {
32 "role": "system",
33 "content": [
34 {
35 "type": "text",
36 "text": "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."
37 }
38 ],
39 },
40 {
41 "role": "user",
42 "content": [
43 {"type": "video", "video": file_path, "max_pixels": VIDEO_MAX_PIXELS},
44 {"type": "text", "text": prompt},
45 ],
46 },
47]
48
49text = processor.apply_chat_template(
50 conversation,
51 add_generation_prompt=True,
52 tokenize=False,
53)
54
55# IMPORTANT: reference-style multimodal extraction
56audios, images, videos = process_mm_info(
57 conversation,
58 use_audio_in_video=USE_AUDIO_IN_VIDEO,
59)
60
61inputs = processor(
62 text=text,
63 audio=audios,
64 images=images,
65 videos=videos,
66 return_tensors="pt",
67 padding=True,
68 use_audio_in_video=USE_AUDIO_IN_VIDEO,
69)
70
71device = "cuda"
72inputs = inputs.to(device).to(model.dtype)
73
74with torch.no_grad():
75 text_ids = model.generate(
76 **inputs,
77 use_audio_in_video=USE_AUDIO_IN_VIDEO,
78 do_sample=False,
79 thinker_max_new_tokens=4096,
80 repetition_penalty=1.1,
81 use_cache=True,
82 )
83
84decoded = processor.batch_decode(
85 text_ids,
86 skip_special_tokens=True,
87 clean_up_tokenization_spaces=False,
88)[0]
89
90answer = decoded.split("\nassistant\n")[-1].strip()
91print(answer)