Views
No views yet
Generate an emotional summary of each speaker throughout the conversation in one sentence. Use Person1 and Person2 to refer to the speakers.
Person1 sounds frustrated but remains engaged, while Person2 is calm and reassuring throughout the conversation.pip install -U transformers accelerate torch librosa soundfile1import torch
2import librosa
3import soundfile as sf
4from transformers import AutoProcessor, Qwen2AudioForConditionalGeneration
5
6# For a downloaded local model, replace this with your local directory.
7model_id = "RuiRuihigh/qwen2audioinstruct-sft-merged"
8audio_path = "dialogue.wav"
9
10# Load processor and merged model.
11processor = AutoProcessor.from_pretrained(
12 model_id,
13 trust_remote_code=True,
14)
15
16model = Qwen2AudioForConditionalGeneration.from_pretrained(
17 model_id,
18 trust_remote_code=True,
19 device_map="auto",
20 dtype=torch.float16,
21).eval()
22
23prompt = (
24 "<|audio_bos|><|AUDIO|><|audio_eos|>"
25 "Generate an emotional summary of each speaker throughout the conversation "
26 "in one sentence. Use Person1 and Person2 to refer to the speakers."
27)
28
29# Load audio and convert stereo audio to mono if necessary.
30audio, sr = sf.read(audio_path, always_2d=False)
31
32if audio.ndim == 2:
33 audio = audio.mean(axis=1)
34
35audio = audio.astype("float32")
36
37# Resample audio to the sampling rate required by Qwen2-Audio.
38target_sr = processor.feature_extractor.sampling_rate
39if sr != target_sr:
40 audio = librosa.resample(
41 audio,
42 orig_sr=sr,
43 target_sr=target_sr,
44 )
45
46inputs = processor(
47 text=prompt,
48 audio=audio,
49 return_tensors="pt",
50)
51
52# Move every tensor input to the device hosting the model.
53inputs = {
54 key: value.to(model.device) if hasattr(value, "to") else value
55 for key, value in inputs.items()
56}
57
58with torch.no_grad():
59 generated_ids = model.generate(
60 **inputs,
61 max_new_tokens=256,
62 )
63
64# Remove prompt tokens and decode only the generated response.
65generated_ids = generated_ids[:, inputs["input_ids"].size(1):]
66response = processor.batch_decode(
67 generated_ids,
68 skip_special_tokens=True,
69 clean_up_tokenization_spaces=False,
70)[0]
71
72print(response)from_pretrained.dtype=torch.float16).soundfile has shape (samples, channels), and directly resampling it can otherwise resample the wrong axis.Person1 and Person2 labels are requested by the prompt; the model does not perform guaranteed speaker diarization.