Views
No views yet
1import torch
2from io import BytesIO
3from urllib.request import urlopen
4import librosa
5from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor, BitsAndBytesConfig
6
7processor = AutoProcessor.from_pretrained("alicekyting/Qwen2-Audio-7B-Instruct-4bit")
8bnb_config = BitsAndBytesConfig(
9 load_in_4bit=True,
10 bnb_4bit_compute_dtype=torch.float16
11)
12model = Qwen2AudioForConditionalGeneration.from_pretrained(
13 "alicekyting/Qwen2-Audio-7B-Instruct-4bit",
14 device_map="auto",
15 quantization_config=bnb_config
16)
17
18conversation = [
19 {'role': 'system', 'content': 'You are a helpful assistant.'},
20 {"role": "user", "content": [
21 {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3"},
22 {"type": "text", "text": "What's that sound?"},
23 ]},
24 {"role": "assistant", "content": "It is the sound of glass shattering."},
25 {"role": "user", "content": [
26 {"type": "text", "text": "What can you do when you hear that?"},
27 ]},
28 {"role": "assistant", "content": "Stay alert and cautious, and check if anyone is hurt or if there is any damage to property."},
29 {"role": "user", "content": [
30 {"type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/1272-128104-0000.flac"},
31 {"type": "text", "text": "What does the person say?"},
32 ]},
33]
34text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
35audios = []
36for message in conversation:
37 if isinstance(message["content"], list):
38 for ele in message["content"]:
39 if ele["type"] == "audio":
40 audios.append(
41 librosa.load(
42 BytesIO(urlopen(ele['audio_url']).read()),
43 sr=processor.feature_extractor.sampling_rate,
44 mono=True
45 )[0]
46 )
47
48inputs = processor(text=text, audios=audios, return_tensors="pt", padding=True)
49inputs = {k: v.to(model.device) for k, v in inputs.items()}
50
51generate_ids = model.generate(**inputs, max_length=256)
52generate_ids = generate_ids[:, inputs['input_ids'].size(1):]
53
54response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
55print(response)