lets debug everything and see whats happening ill give you the output and then lets fix it rather than brute forcing solutions error : .
Error processing file: not enough values to unpack (expected 3, got 2)
script : import whisperx
import torch
import torchaudio
from demucs.pretrained import get_model
from demucs.apply import apply_model
import numpy as np
import soundfile as sf
import subprocess
from pathlib import Path
import os
from config import *
from torch.hub import load as torch_hub_load
from silero_vad import load_silero_vad, get_speech_timestamps
class AudioProcessor:
def init(self, model_size=DEFAULT_MODEL_SIZE, whisper_version=DEFAULT_WHISPER_VERSION):
torch.set_num_threads(CPU_THREADS)
print(f"Initializing AudioProcessor with {DEVICE}")
# Process in chunks
chunk_samples = int(CHUNK_DURATION * SAMPLE_RATE)
speech_timestamps = []
for i in range(0, len(audio_numpy), chunk_samples):
chunk = audio_numpy[i:min(i + chunk_samples, len(audio_numpy))]
chunk_tensor = torch.FloatTensor(chunk)
# Get speech timestamps for the chunk
chunk_timestamps = self.get_speech_timestamps(
chunk_tensor,
self.vad_model,
sampling_rate=SAMPLE_RATE
)
# Adjust timestamps for chunk position
for ts in chunk_timestamps:
ts['start'] += i
ts['end'] += i
speech_timestamps.extend(chunk_timestamps)
# Create masked audio
masked_audio = torch.zeros_like(audio_mono)
for ts in speech_timestamps:
start_frame = ts['start']
end_frame = ts['end']
if start_frame < len(masked_audio) and end_frame <= len(masked_audio):
masked_audio[start_frame:end_frame] = audio_mono[start_frame:end_frame]
return masked_audio
segments = []
for i in range(0, len(change_points)-1, 2):
start = change_points[i]
end = change_points[i+1] if i+1 < len(change_points) else len(audio)-1
segments.append((start, end))
return segments
try:
sf.write(str(temp_file), audio.numpy(), SAMPLE_RATE)
# Load and transcribe
audio_data = whisperx.load_audio(str(temp_file))
result = self.whisper_model.transcribe(
audio_data,
batch_size=1, # Optimized for CPU
beam_size=beam_size,
patience=patience,
temperature=temperature
)
# Align timestamps
model_a, metadata, _ = whisperx.load_align_model(
language_code=result["language"],
device=DEVICE
)
result = whisperx.align(
result["segments"],
model_a,
metadata,
audio_data,
DEVICE,
extend_duration=0.0
)
return result
except Exception as e:
print(f"Transcription error: {e}")
return None
def verify_transcription(self, transcription):
"""Verify if transcription contains markers"""
if not transcription or 'segments' not in transcription:
return False
marker_patterns = ["*", "beep", "tone", "[noise]", "[sound]"]
return any(
any(pattern in segment['text'].lower() for pattern in marker_patterns)
for segment in transcription['segments']
)
def save_transcription(self, transcription, output_file):
"""Save transcription to file"""
if not transcription:
return False
try:
with open(output_file, 'w', encoding='utf-8') as f:
for segment in transcription['segments']:
f.write(
f"[{segment['start']:.2f} - {segment['end']:.2f}] {segment['text']}\n"
)
return True
except Exception as e:
print(f"Error saving transcription: {e}")
return False
Based on the error message "not enough values to unpack (expected 3, got 2)" and looking at your code, this error typically occurs when trying to unpack a tuple or list with fewer elements than expected. Let's identify and fix the likely source of this error.
The most probable location for this error is in the VAD model loading section. Let's fix the VAD model initialization:
This will help isolate and identify any issues specifically related to the VAD model initialization.
why wonder about might let make everything explicit and debug ill return the output to you so you can identify exactly where it is
Initializing AudioProcessor with cpu
=== Starting model initialization ===
Loading Whisper model...
Model size: base
Whisper version: v2
Device: cpu
Models directory: /home/ubuntu/Desktop/new/models
No language specified, language will be first be detected for each audio file (increases inference time).
Lightning automatically upgraded your loaded checkpoint from v1.5.4 to v2.4.0. To apply the upgrade to your files permanently, run python -m pytorch_lightning.utilities.upgrade_checkpoint ../../.cache/torch/whisperx-vad-segmentation.bin
Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.
Model was trained with torch 1.10.0+cu102, yours is 2.5.1. Bad things might happen unless you revert torch to 1.x.
✓ Whisper model loaded successfully
Loading Demucs model...
Model name: htdemucs_ft
✓ Demucs model loaded successfully
Loading VAD model...
Attempting to load from snakers4/silero-vad
! Error during VAD model loading: load() missing 1 required positional argument: 'repo_or_dir'
! Error type: <class 'TypeError'>
!!! Error in model initialization !!!
Error type: <class 'TypeError'>
Error message: load() missing 1 required positional argument: 'repo_or_dir'
Full traceback:
Traceback (most recent call last):
File "/home/ubuntu/Desktop/new/audio_processor.py", line 54, in init_models
vad_result = torch_hub_load(
TypeError: load() missing 1 required positional argument: 'repo_or_dir'
script :
import whisperx
import torch
import torchaudio
from demucs.pretrained import get_model
from demucs.apply import apply_model
import numpy as np
import soundfile as sf
import subprocess
from pathlib import Path
import os
from config import *
from torch.hub import load as torch_hub_load
from silero_vad import load_silero_vad, get_speech_timestamps
class AudioProcessor:
def init(self, model_size=DEFAULT_MODEL_SIZE, whisper_version=DEFAULT_WHISPER_VERSION):
torch.set_num_threads(CPU_THREADS)
print(f"Initializing AudioProcessor with {DEVICE}")
self.init_models(model_size, whisper_version)
def init_models(self, model_size, whisper_version):
try:
print(f"Loading Whisper {whisper_version} model: {model_size}")
self.whisper_model = whisperx.load_model(
model_size,
device=DEVICE,
compute_type="float32",
download_root=str(MODELS_DIR)
)
print("Loading Demucs model...")
self.demucs_model = get_model(name="htdemucs_ft")
self.demucs_model.to(DEVICE)
print("Loading VAD model...")
# Correct way to load Silero VAD
self.vad_model, utils = torch.hub.load(
repo_or_dir='snakers4/silero-vad',
model='silero_vad',
force_reload=True
)
# Unpack utils properly
(self.get_speech_timestamps,
self.save_audio,
self.read_audio,
self.VADIterator,
self.collect_chunks) = utils
self.vad_model = self.vad_model.to(DEVICE)
print("Models loaded successfully!")
except Exception as e:
print(f"Error initializing models: {e}")
raise
def process_file(self, input_file, output_file, beam_size=2, patience=1, temperature=0.0):
"""Main processing pipeline"""
try:
# 1. Extract vocals
vocals, sr = self.extract_vocals(input_file)
# 2. Normalize and remove silence
normalized = self.normalize_audio(vocals, sr)
# 3. Apply VAD
vad_audio = self.apply_vad(normalized)
# 4. Add markers
marked_audio = self.add_markers(vad_audio)
# 5. Apply compression
compressed = self.apply_compression(marked_audio)
# Try transcription with different approaches
transcription = None
# With markers
transcription = self.transcribe(compressed, beam_size, patience, temperature)
if self.verify_transcription(transcription):
return self.save_transcription(transcription, output_file)
# With inverted markers
transcription = self.transcribe(-compressed, beam_size, patience, temperature)
if self.verify_transcription(transcription):
return self.save_transcription(transcription, output_file)
# Without markers
transcription = self.transcribe(vad_audio, beam_size, patience, temperature)
return self.save_transcription(transcription, output_file)
except Exception as e:
print(f"Error processing file: {e}")
raise
finally:
cleanup_temp()
def extract_vocals(self, audio_path):
"""Extract vocals using Demucs"""
print("Extracting vocals...")
audio, sr = torchaudio.load(audio_path)
audio = audio.to(DEVICE)
# Process in chunks
chunk_samples = int(CHUNK_DURATION * sr)
if audio.shape[1] > chunk_samples:
vocals_chunks = []
for i in range(0, audio.shape[1], chunk_samples):
chunk = audio[:, i:min(i+chunk_samples, audio.shape[1])]
sources = apply_model(self.demucs_model, chunk, device=DEVICE)
vocals_chunks.append(sources['vocals'])
vocals = torch.cat(vocals_chunks, dim=1)
else:
sources = apply_model(self.demucs_model, audio, device=DEVICE)
vocals = sources['vocals']
return vocals, sr
def normalize_audio(self, audio, sr):
"""Normalize audio and remove silence using ffmpeg"""
temp_in = TEMP_DIR / "temp_in.wav"
temp_out = TEMP_DIR / "temp_out.wav"
try:
sf.write(str(temp_in), audio.cpu().numpy(), sr)
cmd = [
'ffmpeg', '-y',
'-i', str(temp_in),
'-af', f'silenceremove=stop_periods=-1:stop_duration=1:stop_threshold={VAD_THRESHOLD}dB,loudnorm=I=-16:TP=-1.5:LRA=11',
'-ar', str(sr),
str(temp_out)
]
subprocess.run(cmd, check=True, capture_output=True)
normalized, sr = torchaudio.load(str(temp_out))
return normalized
except Exception as e:
print(f"Error normalizing audio: {e}")
raise
def apply_vad(self, audio):
"""Apply Voice Activity Detection"""
print("Applying VAD...")
audio_mono = audio.mean(dim=0) if audio.dim() > 1 else audio
audio_numpy = audio_mono.numpy()
# Process in chunks
chunk_samples = int(CHUNK_DURATION * SAMPLE_RATE)
speech_timestamps = []
for i in range(0, len(audio_numpy), chunk_samples):
chunk = audio_numpy[i:min(i + chunk_samples, len(audio_numpy))]
chunk_tensor = torch.FloatTensor(chunk)
# Get speech timestamps for the chunk
chunk_timestamps = self.get_speech_timestamps(
chunk_tensor,
self.vad_model,
sampling_rate=SAMPLE_RATE
)
# Adjust timestamps for chunk position
for ts in chunk_timestamps:
ts['start'] += i
ts['end'] += i
speech_timestamps.extend(chunk_timestamps)
# Create masked audio
masked_audio = torch.zeros_like(audio_mono)
for ts in speech_timestamps:
start_frame = ts['start']
end_frame = ts['end']
if start_frame < len(masked_audio) and end_frame <= len(masked_audio):
masked_audio[start_frame:end_frame] = audio_mono[start_frame:end_frame]
return masked_audio
def add_markers(self, audio):
"""Add voice markers at speech boundaries"""
print("Adding markers...")
marked_audio = audio.clone()
# Generate marker signal
t = np.arange(int(MARKER_DURATION * SAMPLE_RATE))
marker = torch.from_numpy(
0.1 * np.sin(2 * np.pi * MARKER_FREQUENCY * t / SAMPLE_RATE)
).float()
# Find speech segments
speech_segments = self.find_speech_segments(audio)
# Add markers at segment boundaries
for start, end in speech_segments:
if start + len(marker) < len(marked_audio):
marked_audio[start:start + len(marker)] += marker
if end - len(marker) >= 0:
marked_audio[end - len(marker):end] += marker
return marked_audio
def find_speech_segments(self, audio, threshold=0.01):
"""Find speech segments in audio"""
is_speech = torch.abs(audio) > threshold
changes = torch.diff(is_speech.long())
change_points = torch.nonzero(changes).flatten()
segments = []
for i in range(0, len(change_points)-1, 2):
start = change_points[i]
end = change_points[i+1] if i+1 < len(change_points) else len(audio)-1
segments.append((start, end))
return segments
def apply_compression(self, audio):
"""Apply speech compression using ffmpeg"""
print("Applying compression...")
temp_in = TEMP_DIR / "temp_compress_in.wav"
temp_out = TEMP_DIR / "temp_compress_out.wav"
try:
sf.write(str(temp_in), audio.numpy(), SAMPLE_RATE)
cmd = [
'ffmpeg', '-y',
'-i', str(temp_in),
'-af', 'acompressor=threshold=-12dB:ratio=2:attack=200:release=1000',
'-ar', str(SAMPLE_RATE),
str(temp_out)
]
subprocess.run(cmd, check=True, capture_output=True)
compressed, _ = torchaudio.load(str(temp_out))
return compressed.squeeze()
except Exception as e:
print(f"Error applying compression: {e}")
raise
def transcribe(self, audio, beam_size=2, patience=1, temperature=0.0):
"""Transcribe audio using WhisperX"""
print("Transcribing...")
temp_file = TEMP_DIR / "temp_transcribe.wav"
try:
sf.write(str(temp_file), audio.numpy(), SAMPLE_RATE)
# Load and transcribe
audio_data = whisperx.load_audio(str(temp_file))
result = self.whisper_model.transcribe(
audio_data,
batch_size=1, # Optimized for CPU
beam_size=beam_size,
patience=patience,
temperature=temperature
)
# Align timestamps
model_a, metadata, _ = whisperx.load_align_model(
language_code=result["language"],
device=DEVICE
)
result = whisperx.align(
result["segments"],
model_a,
metadata,
audio_data,
DEVICE,
extend_duration=0.0
)
return result
except Exception as e:
print(f"Transcription error: {e}")
return None
def verify_transcription(self, transcription):
"""Verify if transcription contains markers"""
if not transcription or 'segments' not in transcription:
return False
marker_patterns = ["*", "beep", "tone", "[noise]", "[sound]"]
return any(
any(pattern in segment['text'].lower() for pattern in marker_patterns)
for segment in transcription['segments']
)
def save_transcription(self, transcription, output_file):
"""Save transcription to file"""
if not transcription:
return False
try:
with open(output_file, 'w', encoding='utf-8') as f:
for segment in transcription['segments']:
f.write(
f"[{segment['start']:.2f} - {segment['end']:.2f}] {segment['text']}\n"
)
return True
except Exception as e:
print(f"Error saving transcription: {e}")
return False
ubuntu@ubuntu-virtual-machine:~/Desktop/new$ ./main.py
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/core/io.py:43: UserWarning: torchaudio._backend.set_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
torchaudio.set_audio_backend("soundfile")
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:43: UserWarning: torchaudio._backend.get_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
backend = torchaudio.get_audio_backend()
INFO:speechbrain.utils.quirks:Applied quirks (see speechbrain.utils.quirks): [allow_tf32, disable_jit_profiling]
INFO:speechbrain.utils.quirks:Excluded quirks specified by the SB_DISABLE_QUIRKS environment (comma-separated list): []
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:45: UserWarning: Module 'speechbrain.pretrained' was deprecated, redirecting to 'speechbrain.inference'. Please update your script. This is a change from SpeechBrain 1.0. See: https://github.com/speechbrain/speechbrain/releases/tag/v1.0.0
from speechbrain.pretrained import (
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:53: UserWarning: torchaudio._backend.set_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
torchaudio.set_audio_backend(backend)
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/tasks/segmentation/mixins.py:37: UserWarning: torchaudio.backend.common.AudioMetaData has been moved to torchaudio.AudioMetaData. Please update the import path.
from torchaudio.backend.common import AudioMetaData
Initializing AudioProcessor with cpu
Loading Whisper v2 model: base
No language specified, language will be first be detected for each audio file (increases inference time).
Lightning automatically upgraded your loaded checkpoint from v1.5.4 to v2.4.0. To apply the upgrade to your files permanently, run python -m pytorch_lightning.utilities.upgrade_checkpoint ../../.cache/torch/whisperx-vad-segmentation.bin
Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.
Model was trained with torch 1.10.0+cu102, yours is 2.5.1. Bad things might happen unless you revert torch to 1.x.
Loading Demucs model...
Loading VAD model...
Downloading: "https://github.com/snakers4/silero-vad/zipball/master" to /home/ubuntu/.cache/torch/hub/master.zip
Models loaded successfully!
Extracting vocals...
Error processing file: not enough values to unpack (expected 3, got 2)
Start new chat
Starred
Star chats you use often
Recents
Debugging Vocal Extraction Error
Building a Medical Knowledge Graph
Manim Visualization in Jupyter Notebook
Fast Phoneme Search Algorithm
Phoneme class constructor issue
Troubleshooting Python code errors
Indentation Error in Python Code
Mastering AI and Machine Learning
View all
Free plan
Help & support
S
S
Based on the error message and the context, it seems the error is occurring during the extract_vocals method. The line indicating the error suggests there's an issue with unpacking values returned by apply_model.
Let's modify the extract_vocals method to handle this more robustly:
python
def extract_vocals(self, audio_path):
"""Extract vocals using Demucs"""
print("Extracting vocals...")
audio, sr = torchaudio.load(audio_path)
audio = audio.to(DEVICE)
# Process in chunks
chunk_samples = int(CHUNK_DURATION * sr)
if audio.shape[1] > chunk_samples:
vocals_chunks = []
for i in range(0, audio.shape[1], chunk_samples):
chunk = audio[:, i:min(i+chunk_samples, audio.shape[1])]
# Modify this part to handle potential return variations
sources = apply_model(self.demucs_model, chunk, device=DEVICE)
# Check the type of sources and extract vocals accordingly
if isinstance(sources, dict):
vocals_chunk = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
# Assuming vocals might be the first or last item
vocals_chunk = sources[0] if 'vocals' not in sources else sources['vocals']
else:
raise ValueError(f"Unexpected return type from apply_model: {type(sources)}")
if vocals_chunk is None:
raise ValueError("Could not extract vocals from chunk")
vocals_chunks.append(vocals_chunk)
vocals = torch.cat(vocals_chunks, dim=1)
else:
sources = apply_model(self.demucs_model, audio, device=DEVICE)
# Same handling as above for full audio
if isinstance(sources, dict):
vocals = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
vocals = sources[0] if 'vocals' not in sources else sources['vocals']
else:
raise ValueError(f"Unexpected return type from apply_model: {type(sources)}")
if vocals is None:
raise ValueError("Could not extract vocals from full audio")
return vocals, sr
The key changes are:
Added robust handling for different return types from apply_model
Added explicit checks and error handling for extracting vocals
Handled potential scenarios where vocals might not be directly accessible
Additionally, could you confirm the following:
Are you using the latest version of demucs?
Can you print out the exact type and content of sources returned by apply_model in your environment?
You can add a debug print before returning vocals:
This will help me understand exactly what's being returned by the model and why the unpacking is failing.
Also, make sure in your config.py or wherever you define CHUNK_DURATION that it's a reasonable value (e.g., 10-30 seconds) that doesn't cause issues with model processing.
Would you like me to help you debug further by adding more detailed logging?
S
why guess and instead debug everything and ill provide you output
You're absolutely right. Instead of making assumptions, let's systematically debug the code. I'll modify the extract_vocals method to add comprehensive logging and error tracking:
python
def extract_vocals(self, audio_path):
"""Extract vocals using Demucs"""
print("=== Extracting Vocals Debug Information ===")
print(f"Input audio path: {audio_path}")
try:
# Load audio
print("1. Loading audio file...")
audio, sr = torchaudio.load(audio_path)
print(f"- Audio loaded successfully")
print(f"- Audio shape: {audio.shape}")
print(f"- Sample rate: {sr}")
# Move to device
audio = audio.to(DEVICE)
print(f"- Audio moved to device: {DEVICE}")
# Chunk processing setup
chunk_samples = int(CHUNK_DURATION * sr)
print(f"- Chunk duration: {CHUNK_DURATION} seconds")
print(f"- Chunk samples: {chunk_samples}")
print(f"- Total audio samples: {audio.shape[1]}")
# Process chunked or full audio
if audio.shape[1] > chunk_samples:
print("2. Processing audio in chunks...")
vocals_chunks = []
for i in range(0, audio.shape[1], chunk_samples):
chunk = audio[:, i:min(i+chunk_samples, audio.shape[1])]
print(f" - Processing chunk {i//chunk_samples + 1}")
print(f" - Chunk shape: {chunk.shape}")
try:
# Detailed logging for sources
sources = apply_model(self.demucs_model, chunk, device=DEVICE)
print(" - apply_model result:")
print(f" - Type of sources: {type(sources)}")
print(f" - Keys if dict: {sources.keys() if isinstance(sources, dict) else 'N/A'}")
print(f" - Length if list/tuple: {len(sources) if isinstance(sources, (list, tuple)) else 'N/A'}")
# Extract vocals
if isinstance(sources, dict):
vocals_chunk = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
vocals_chunk = sources[0] if 'vocals' not in sources else sources['vocals']
else:
raise ValueError(f"Unexpected sources type: {type(sources)}")
if vocals_chunk is None:
raise ValueError("No vocals extracted from chunk")
print(f" - Vocals chunk shape: {vocals_chunk.shape}")
vocals_chunks.append(vocals_chunk)
except Exception as chunk_error:
print(f" !! Error processing chunk {i//chunk_samples + 1}: {chunk_error}")
raise
vocals = torch.cat(vocals_chunks, dim=1)
print(f"- Concatenated vocals shape: {vocals.shape}")
else:
print("2. Processing full audio...")
sources = apply_model(self.demucs_model, audio, device=DEVICE)
print(" - apply_model result:")
print(f" - Type of sources: {type(sources)}")
print(f" - Keys if dict: {sources.keys() if isinstance(sources, dict) else 'N/A'}")
print(f" - Length if list/tuple: {len(sources) if isinstance(sources, (list, tuple)) else 'N/A'}")
# Extract vocals for full audio
if isinstance(sources, dict):
vocals = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
vocals = sources[0] if 'vocals' not in sources else sources['vocals']
else:
raise ValueError(f"Unexpected sources type: {type(sources)}")
if vocals is None:
raise ValueError("No vocals extracted from full audio")
print(f" - Vocals shape: {vocals.shape}")
return vocals, sr
except Exception as e:
print("=== FATAL ERROR IN EXTRACT_VOCALS ===")
print(f"Error details: {e}")
import traceback
traceback.print_exc()
raise
This version will:
Print detailed information about audio loading
Log chunk processing details
Capture and log exact details about sources from apply_model
Provide comprehensive error tracking
Help identify exactly where and why the extraction might fail
Before running, please confirm:
The exact version of demucs you're using
The version of PyTorch
The content of your config.py, especially CHUNK_DURATION and related settings
Could you run this and share the complete output? This will help us pinpoint the exact issue with vocal extraction.
ubuntu@ubuntu-virtual-machine:~/Desktop/new$ ./main.py
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/core/io.py:43: UserWarning: torchaudio._backend.set_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
torchaudio.set_audio_backend("soundfile")
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:43: UserWarning: torchaudio._backend.get_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
backend = torchaudio.get_audio_backend()
INFO:speechbrain.utils.quirks:Applied quirks (see speechbrain.utils.quirks): [disable_jit_profiling, allow_tf32]
INFO:speechbrain.utils.quirks:Excluded quirks specified by the SB_DISABLE_QUIRKS environment (comma-separated list): []
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:45: UserWarning: Module 'speechbrain.pretrained' was deprecated, redirecting to 'speechbrain.inference'. Please update your script. This is a change from SpeechBrain 1.0. See: https://github.com/speechbrain/speechbrain/releases/tag/v1.0.0
from speechbrain.pretrained import (
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/pipelines/speaker_verification.py:53: UserWarning: torchaudio._backend.set_audio_backend has been deprecated. With dispatcher enabled, this function is no-op. You can remove the function call.
torchaudio.set_audio_backend(backend)
/home/ubuntu/.local/lib/python3.10/site-packages/pyannote/audio/tasks/segmentation/mixins.py:37: UserWarning: torchaudio.backend.common.AudioMetaData has been moved to torchaudio.AudioMetaData. Please update the import path.
from torchaudio.backend.common import AudioMetaData
Initializing AudioProcessor with cpu
Loading Whisper v2 model: base
No language specified, language will be first be detected for each audio file (increases inference time).
Lightning automatically upgraded your loaded checkpoint from v1.5.4 to v2.4.0. To apply the upgrade to your files permanently, run python -m pytorch_lightning.utilities.upgrade_checkpoint ../../.cache/torch/whisperx-vad-segmentation.bin
Model was trained with pyannote.audio 0.0.1, yours is 3.1.1. Bad things might happen unless you revert pyannote.audio to 0.x.
Model was trained with torch 1.10.0+cu102, yours is 2.5.1. Bad things might happen unless you revert torch to 1.x.
Loading Demucs model...
Loading VAD model...
Downloading: "https://github.com/snakers4/silero-vad/zipball/master" to /home/ubuntu/.cache/torch/hub/master.zip
Models loaded successfully!
=== Extracting Vocals Debug Information ===
Input audio path: /home/ubuntu/Downloads/audio.mp3
Loading audio file...
Audio loaded successfully
Audio shape: torch.Size([2, 599040])
Sample rate: 48000
Audio moved to device: cpu
Chunk duration: 30 seconds
Chunk samples: 1440000
Total audio samples: 599040
Processing full audio...
=== FATAL ERROR IN EXTRACT_VOCALS ===
Error details: not enough values to unpack (expected 3, got 2)
Traceback (most recent call last):
File "/home/ubuntu/Desktop/new/audio_processor.py", line 162, in extract_vocals
sources = apply_model(self.demucs_model, audio, device=DEVICE)
File "/home/ubuntu/.local/lib/python3.10/site-packages/demucs/apply.py", line 189, in apply_model
out = apply_model(sub_model, mix, **kwargs)
File "/home/ubuntu/.local/lib/python3.10/site-packages/demucs/apply.py", line 205, in apply_model
batch, channels, length = mix.shape
ValueError: not enough values to unpack (expected 3, got 2)
Error processing file: not enough values to unpack (expected 3, got 2)
^CTraceback (most recent call last):
File "/home/ubuntu/Desktop/new/./main.py", line 69, in
main()
File "/home/ubuntu/Desktop/new/./main.py", line 60, in main
root.mainloop()
File "/usr/lib/python3.10/tkinter/init.py", line 1458, in mainloop
self.tk.mainloop(n)
Thank you for providing detailed information and the error traceback. Based on the error message and your latest output, it appears that the issue occurs during the vocal extraction phase, specifically when the apply_model function from Demucs is invoked. Let's delve deeper into the problem and implement a robust solution.
Understanding the Error
Error Message:
ValueError: not enough values to unpack (expected 3, got 2)
Traceback Snippet:
File "/home/ubuntu/Desktop/new/audio_processor.py", line 162, in extract_vocals
sources = apply_model(self.demucs_model, audio, device=DEVICE)
...
File "/home/ubuntu/.local/lib/python3.10/site-packages/demucs/apply.py", line 205, in apply_model
batch, channels, length = mix.shape
ValueError: not enough values to unpack (expected 3, got 2)
Analysis:
The apply_model function expects the input mix to have 3 dimensions: [batch, channels, samples].
Currently, the audio tensor has 2 dimensions: [channels, samples].
This mismatch leads to the unpacking error.
Solution Overview
To resolve this issue, we need to ensure that the mix tensor passed to apply_model has the expected 3D shape. This can be achieved by adding a batch dimension to the audio tensor before passing it to apply_model. After processing, we'll remove this batch dimension from the output.
Step-by-Step Fix
Modify the extract_vocals Method:
Add a Batch Dimension: Use unsqueeze(0) to add a new dimension at the beginning, transforming the shape from [channels, samples] to [1, channels, samples].
Remove the Batch Dimension: After processing, use squeeze(0) to remove the batch dimension from the output.
Implement Robust Error Handling:
Check Tensor Shapes: Ensure that tensors have the correct number of dimensions before processing.
Log Detailed Information: Enhance logging to capture tensor shapes and types, aiding future debugging.
Verify Demucs Version:
Ensure that you're using a compatible version of Demucs that aligns with your codebase.
Updated extract_vocals Method
Here's the revised extract_vocals method incorporating the necessary changes:
def extract_vocals(self, audio_path):
"""Extract vocals using Demucs"""
print("=== Extracting Vocals Debug Information ===")
print(f"Input audio path: {audio_path}")
try:
# Load audio
print("1. Loading audio file...")
audio, sr = torchaudio.load(audio_path)
print(f"- Audio loaded successfully")
print(f"- Audio shape: {audio.shape}")
print(f"- Sample rate: {sr}")
# Move to device
audio = audio.to(DEVICE)
print(f"- Audio moved to device: {DEVICE}")
# Chunk processing setup
chunk_samples = int(CHUNK_DURATION * sr)
print(f"- Chunk duration: {CHUNK_DURATION} seconds")
print(f"- Chunk samples: {chunk_samples}")
print(f"- Total audio samples: {audio.shape[1]}")
# Process chunked or full audio
if audio.shape[1] > chunk_samples:
print("2. Processing audio in chunks...")
vocals_chunks = []
for i in range(0, audio.shape[1], chunk_samples):
chunk = audio[:, i:min(i+chunk_samples, audio.shape[1])]
print(f" - Processing chunk {i//chunk_samples + 1}")
print(f" - Chunk shape before unsqueeze: {chunk.shape}")
# Add batch dimension
chunk = chunk.unsqueeze(0) # Shape: [1, channels, samples]
print(f" - Chunk shape after unsqueeze: {chunk.shape}")
try:
# Apply Demucs model
sources = apply_model(self.demucs_model, chunk, device=DEVICE)
print(" - apply_model result:")
print(f" - Type of sources: {type(sources)}")
if isinstance(sources, dict):
print(f" - Keys: {sources.keys()}")
vocals_chunk = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
vocals_chunk = sources[0] # Adjust based on actual structure
print(f" - Vocals chunk (assumed first element in list/tuple): {vocals_chunk.shape}")
else:
raise ValueError(f"Unexpected sources type: {type(sources)}")
if vocals_chunk is None:
raise ValueError("No vocals extracted from chunk")
# Remove batch dimension
vocals_chunk = vocals_chunk.squeeze(0) # Shape: [channels, samples]
print(f" - Vocals chunk shape after squeeze: {vocals_chunk.shape}")
vocals_chunks.append(vocals_chunk)
except Exception as chunk_error:
print(f" !! Error processing chunk {i//chunk_samples + 1}: {chunk_error}")
raise
# Concatenate all vocal chunks
vocals = torch.cat(vocals_chunks, dim=1)
print(f"- Concatenated vocals shape: {vocals.shape}")
else:
print("2. Processing full audio...")
print(f" - Audio shape before unsqueeze: {audio.shape}")
# Add batch dimension
audio = audio.unsqueeze(0) # Shape: [1, channels, samples]
print(f" - Audio shape after unsqueeze: {audio.shape}")
# Apply Demucs model
sources = apply_model(self.demucs_model, audio, device=DEVICE)
print(" - apply_model result:")
print(f" - Type of sources: {type(sources)}")
if isinstance(sources, dict):
print(f" - Keys: {sources.keys()}")
vocals = sources.get('vocals')
elif isinstance(sources, (list, tuple)):
vocals = sources[0] # Adjust based on actual structure
print(f" - Vocals chunk (assumed first element in list/tuple): {vocals.shape}")
else:
raise ValueError(f"Unexpected sources type: {type(sources)}")
if vocals is None:
raise ValueError("No vocals extracted from full audio")
# Remove batch dimension
vocals = vocals.squeeze(0) # Shape: [channels, samples]
print(f" - Vocals shape after squeeze: {vocals.shape}")
return vocals, sr
except Exception as e:
print("=== FATAL ERROR IN EXTRACT_VOCALS ===")
print(f"Error details: {e}")
import traceback
traceback.print_exc()
raise
Explanation of Changes
Adding Batch Dimension:
Before Processing:chunk = chunk.unsqueeze(0) transforms the tensor from [channels, samples] to [1, channels, samples].
Before Processing Full Audio: Similarly, audio = audio.unsqueeze(0) ensures the full audio has the correct shape.
Removing Batch Dimension:
After Processing Chunks:vocals_chunk = vocals_chunk.squeeze(0) reverts the shape back to [channels, samples] for concatenation.
After Processing Full Audio:vocals = vocals.squeeze(0) ensures consistency.
Detailed Logging:
Tensor Shapes: Logs before and after adding/removing dimensions to verify correctness.
Sources Inspection: Logs the type and keys (if dictionary) of the sources returned by apply_model.
Error Handling:
Chunk-Specific Errors: If processing a chunk fails, it logs the chunk number and error before raising the exception.
General Exceptions: Captures and prints the full traceback for fatal errors in vocal extraction.
Additional Recommendations
Verify Demucs Version:
Ensure that the version of Demucs installed is compatible with your code. You can check the version using:
pip show demucs
If necessary, update Demucs to the latest version:
pip install --upgrade demucs
Check apply_model Expectations:
Although we've adjusted the input shape, it's good practice to refer to Demucs's documentation or source code to verify the expected input structure, especially if custom modifications have been made.
Handle Different Source Structures:
Depending on the Demucs version, the sources returned by apply_model might vary. Ensure that accessing sources['vocals'] or sources[0] aligns with the actual structure.
Optimize Chunk Duration:
Currently, CHUNK_DURATION is set to 30 seconds. Ensure this duration is optimal for your use case and system resources.
Monitor Resource Usage:
Processing large audio files can be resource-intensive. Monitor CPU and memory usage to prevent potential bottlenecks.
Silent Failures:
Ensure that all subprocess calls (like ffmpeg) are successful. You might want to log stdout and stderr from these subprocesses for better visibility.
Next Steps
Implement the Updated Method:
Replace your existing extract_vocals method with the updated version provided above.
Run the Script again:
Execute your main script to see if the error persists.
Share the Updated Output:
If the error continues or new issues arise, please provide the updated console output. This will help in further pinpointing the problem.
Conclusion
The primary issue stemmed from a mismatch in the expected tensor dimensions when invoking the Demucs apply_model function. By ensuring that the input tensor conforms to the expected shape [batch, channels, samples], we align with the function's requirements, thereby resolving the unpacking error.
Feel free to reach out if you encounter further issues or need additional assistance!