Sergidev commited on
Commit
f037fe5
Β·
1 Parent(s): addbfa5
Files changed (2) hide show
  1. app.py +128 -39
  2. requirements.txt +4 -3
app.py CHANGED
@@ -1,54 +1,143 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
  import torch
 
 
 
4
  import tempfile
 
 
5
 
6
- # Initialize Qwen2.5-Omni-7B with multimodal support
7
- model = AutoModelForCausalLM.from_pretrained(
8
- "Qwen/Qwen2.5-Omni-7B",
9
- torch_dtype=torch.float16,
10
- device_map="auto"
11
- )
12
- tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Omni-7B")
13
-
14
- def analyze_media(video_path, prompt, request: gr.Request):
15
- # ZeroGPU rate limiting headers
16
- headers = {"X-IP-Token": request.headers.get('x-ip-token', '')}
17
-
18
- # Create multimodal pipeline
19
- pipe = pipeline(
20
- "multimodal-generation",
21
- model=model,
22
- tokenizer=tokenizer,
23
- device=model.device,
24
- max_new_tokens=1024,
25
- generate_speech=True
26
- )
27
 
28
- # Process 120s video with TMRoPE alignment
29
- result = pipe(
30
- media=video_path,
31
- text=prompt,
32
- headers=headers,
33
- timeout=120
 
 
 
 
 
34
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # Save speech output to temporary file
37
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
38
- result["speech"].export(f.name, format="wav")
39
- return result["text"], f.name
40
 
 
 
 
 
 
 
 
41
  with gr.Blocks() as demo:
42
  gr.Markdown("## Qwen2.5-Omni-7B Multimodal Demo")
43
 
44
  with gr.Row():
45
- media_input = gr.Video(
46
- label="Upload Video (max 120s)",
47
- sources=["upload"],
48
- max_length=120
49
- )
50
  prompt_input = gr.Textbox(label="Analysis Prompt", placeholder="Describe or ask about the video...")
51
 
 
 
 
52
  submit_btn = gr.Button("Analyze", variant="primary")
53
 
54
  with gr.Column():
@@ -56,8 +145,8 @@ with gr.Blocks() as demo:
56
  audio_output = gr.Audio(label="Speech Response", autoplay=True)
57
 
58
  submit_btn.click(
59
- analyze_media,
60
- inputs=[media_input, prompt_input, gr.Request()],
61
  outputs=[text_output, audio_output]
62
  )
63
 
 
1
  import gradio as gr
 
2
  import torch
3
+ from transformers import Qwen2_5OmniModel, Qwen2_5OmniProcessor, TextStreamer
4
+ from qwen_omni_utils import process_mm_info
5
+ import soundfile as sf
6
  import tempfile
7
+ import spaces
8
+ import gc
9
 
10
+ # Initialize the model and processor
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def get_model():
15
+ if torch.cuda.is_available():
16
+ torch.cuda.empty_cache()
17
+ gc.collect()
18
+ model = Qwen2_5OmniModel.from_pretrained(
19
+ "Qwen/Qwen2.5-Omni-7B",
20
+ torch_dtype=torch_dtype,
21
+ device_map="auto",
22
+ enable_audio_output=True,
23
+ low_cpu_mem_usage=True,
24
+ attn_implementation="flash_attention_2" if torch.cuda.is_available() else None
25
  )
26
+ return model
27
+
28
+ model = get_model()
29
+ processor = Qwen2_5OmniProcessor.from_pretrained("Qwen/Qwen2.5-Omni-7B")
30
+
31
+ # System prompt
32
+ SYSTEM_PROMPT = {
33
+ "role": "system",
34
+ "content": "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."
35
+ }
36
+
37
+ # Voice options
38
+ VOICE_OPTIONS = {
39
+ "Chelsie (Female)": "Chelsie",
40
+ "Ethan (Male)": "Ethan"
41
+ }
42
+
43
+ @spaces.GPU(duration=120)
44
+ def process_input(video, text, voice_type, enable_audio_output):
45
+ try:
46
+ # Clear GPU memory before processing
47
+ if torch.cuda.is_available():
48
+ torch.cuda.empty_cache()
49
+ gc.collect()
50
+
51
+ # Prepare multimodal input
52
+ user_input = {
53
+ "text": text,
54
+ "video": video if video is not None else None,
55
+ }
56
+
57
+ # Prepare conversation history for model processing
58
+ conversation = [SYSTEM_PROMPT]
59
+ conversation.append({"role": "user", "content": user_input})
60
+
61
+ # Process multimedia information
62
+ try:
63
+ audios, images, videos = process_mm_info(conversation, use_audio_in_video=False)
64
+ except Exception as e:
65
+ print(f"Error processing multimedia: {str(e)}")
66
+ audios, images, videos = [], [], []
67
+
68
+ inputs = processor(
69
+ text=processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False),
70
+ videos=videos,
71
+ return_tensors="pt",
72
+ padding=True
73
+ )
74
+
75
+ # Move inputs to device and convert dtype
76
+ inputs = {k: v.to(device=model.device, dtype=model.dtype) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
77
+
78
+ # Generate response with streaming and audio output
79
+ text_ids = None
80
+ audio_path = None
81
+
82
+ if enable_audio_output:
83
+ voice_type_value = VOICE_OPTIONS.get(voice_type, "Chelsie")
84
+ try:
85
+ generation_output = model.generate(
86
+ **inputs,
87
+ use_audio_in_video=False,
88
+ return_audio=True,
89
+ spk=voice_type_value,
90
+ max_new_tokens=512,
91
+ do_sample=True,
92
+ temperature=0.7,
93
+ top_p=0.9,
94
+ streamer=TextStreamer(processor, skip_prompt=True)
95
+ )
96
+ if isinstance(generation_output, tuple) and len(generation_output) == 2:
97
+ text_ids, audio = generation_output
98
+ if audio is not None:
99
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
100
+ sf.write(tmp_file.name, audio.reshape(-1).detach().cpu().numpy(), samplerate=24000)
101
+ audio_path = tmp_file.name
102
+ except Exception as e:
103
+ print(f"Error during audio generation: {str(e)}")
104
+
105
+ # Fall back to text-only generation if audio fails
106
+ if text_ids is None:
107
+ try:
108
+ text_ids = model.generate(
109
+ **inputs,
110
+ use_audio_in_video=False,
111
+ return_audio=False,
112
+ max_new_tokens=512,
113
+ do_sample=True,
114
+ temperature=0.7,
115
+ top_p=0.9,
116
+ streamer=TextStreamer(processor, skip_prompt=True)
117
+ )
118
+ except Exception as e:
119
+ print(f"Error during fallback text generation: {str(e)}")
120
 
121
+ # Decode text response
122
+ text_response = processor.batch_decode(text_ids, skip_special_tokens=True)[0] if text_ids is not None else "Error generating response."
 
 
123
 
124
+ return text_response.strip(), audio_path
125
+
126
+ except Exception as e:
127
+ print(f"Error in process_input: {str(e)}")
128
+ return "Error processing input.", None
129
+
130
+ # Gradio interface setup
131
  with gr.Blocks() as demo:
132
  gr.Markdown("## Qwen2.5-Omni-7B Multimodal Demo")
133
 
134
  with gr.Row():
135
+ video_input = gr.Video(label="Upload Video (max 120s)", sources=["upload"], max_length=120)
 
 
 
 
136
  prompt_input = gr.Textbox(label="Analysis Prompt", placeholder="Describe or ask about the video...")
137
 
138
+ voice_selection = gr.Dropdown(label="Voice Type", choices=list(VOICE_OPTIONS.keys()), value="Chelsie (Female)")
139
+ enable_audio_checkbox = gr.Checkbox(label="Enable Audio Output", value=True)
140
+
141
  submit_btn = gr.Button("Analyze", variant="primary")
142
 
143
  with gr.Column():
 
145
  audio_output = gr.Audio(label="Speech Response", autoplay=True)
146
 
147
  submit_btn.click(
148
+ process_input,
149
+ inputs=[video_input, prompt_input, voice_selection, enable_audio_checkbox],
150
  outputs=[text_output, audio_output]
151
  )
152
 
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  torch>=2.3.0
2
- transformers>=4.41.0
3
- gradio>=4.26.0
4
- soundfile>=0.12.1
 
 
1
  torch>=2.3.0
2
+ git+https://github.com/huggingface/transformers@f742a644ca32e65758c3adb36225aef1731bd2a8
3
+ accelerate>=0.30.0
4
+ qwen-omni-utils[decord]>=1.0.0 # For multimedia processing
5
+ soundfile>=0.12.1 # Audio support