error : 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 Debug Information ===
Input audio path: /home/ubuntu/Downloads/audio.mp3
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),
language=None, # Set to None for automatic language detection, or specify 'en' for English
)
# 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).to(DEVICE)
# 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].item()
end = change_points[i+1].item() if i+1 < len(change_points) else len(audio)-1
segments.append((start, end))
return segments
try:
sf.write(str(temp_file), audio.cpu().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
The error message you're encountering:
Transcription error: FasterWhisperPipeline.transcribe() got an unexpected keyword argument 'beam_size'
indicates that the transcribe method of the FasterWhisperPipeline class is being called with an unexpected keyword argument beam_size. This typically happens due to version mismatches between your script and the libraries it depends on, or changes in the library APIs over time.
Here's a step-by-step guide to help you resolve this issue:
1. Understand the Root Cause
API Changes: Libraries like whisperx and faster-whisper frequently update their APIs. If your script was written for an older version of these libraries, newer versions might have deprecated or altered certain parameters.
Version Mismatch: The warnings in your logs also suggest version mismatches, especially with pyannote.audio and torch. These mismatches can lead to unexpected behaviors and compatibility issues.
2. Verify Installed Library Versions
First, check the versions of the critical libraries involved:
pip show whisperx
pip show faster-whisper
pip show pyannote.audio
pip show torch
Note: Ensure you're using the same pip associated with your python3.10 environment. If you're using a virtual environment, activate it before running the above commands.
3. Align Library Versions
Given the warnings in your logs, it's evident that some libraries are outdated compared to what your script expects. Here's how to align them:
a. Upgrade whisperx and faster-whisper
Ensure you're using the latest versions of these libraries, as they often include bug fixes and updated APIs.
pip install --upgrade whisperx faster-whisper
b. Check whisperx Documentation
Refer to the WhisperX GitHub Repository to understand the latest API changes. Specifically, check how the transcribe method is defined in the version you have installed.
4. Modify Your Script to Match the Updated API
Based on the error, the transcribe method no longer accepts the beam_size argument. Here's how you can adjust your script:
a. Remove or Adjust beam_size
Locate the transcribe method call in your script:
result = self.whisper_model.transcribe(
audio_data,
batch_size=1, # Optimized for CPU
beam_size=beam_size, # This line causes the error
patience=patience,
temperature=temperature,
)
Solution:
Option 1:Remove beam_size
If beam_size is deprecated or no longer supported, simply remove it:
result = self.whisper_model.transcribe(
audio_data,
batch_size=1, # Optimized for CPU
patience=patience,
temperature=temperature,
)
Option 2:Use Updated Parameters
If whisperx has replaced beam_size with a new parameter or a different configuration approach, update accordingly. For example, some libraries switch from individual parameters to a configuration dictionary.
Note: Refer to the latest whisperx documentation to see the exact parameters supported.
b. Handle Other Deprecations
Your logs also show several deprecation warnings, such as:
UserWarning: Module 'speechbrain.pretrained' was deprecated, redirecting to 'speechbrain.inference'. Please update your script.
Solution:
Update Import Statements:
Replace deprecated imports with their updated counterparts. For example:
# Old import
from speechbrain.pretrained import SomeClass
# Updated import
from speechbrain.inference import SomeClass
Review Other Warnings:
Address other warnings similarly by consulting the respective library documentation.
5. Ensure Compatibility with pyannote.audio and torch
Your logs indicate significant version mismatches:
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.
a. Option 1: Downgrade Libraries
If your project strictly depends on older versions, you might consider downgrading:
Caution: Downgrading torch can affect other dependencies that rely on newer versions. Ensure that this won't break other parts of your project.
b. Option 2: Update the Model
If possible, retrain or update your models to be compatible with the latest versions of pyannote.audio and torch. This approach is more sustainable in the long run.
6. Test Incrementally
After making the above changes:
Run Individual Components:
Test the transcription part independently to ensure transcribe works without errors.
Test other components like VAD, compression, etc., separately.
Monitor Logs:
Ensure that no new warnings or errors emerge.
Address any additional issues as they arise.
Full Workflow Test:
Once individual components work, run the full script to ensure end-to-end functionality.
7. Example of Updated transcribe Method
Here's how you might adjust the transcribe method in your script after removing beam_size:
def transcribe(self, audio, 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.cpu().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
patience=patience,
temperature=temperature,
# beam_size=beam_size, # Removed
)
# 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
8. Final Recommendations
Version Control: Use a requirements.txt file or pipenv to manage and lock your dependencies. This ensures consistency across environments.
Example requirements.txt:
whisperx==<desired_version>
faster-whisper==<desired_version>
pyannote.audio==3.1.1
torch==2.5.1
# Add other dependencies with specific versions
Install with:
pip install -r requirements.txt
Virtual Environments: Always use virtual environments to manage dependencies and avoid conflicts with system-wide packages.
Stay Updated: Regularly check for updates in the libraries you use and adapt your scripts accordingly.
By following the above steps, you should be able to resolve the beam_size error and ensure your script runs smoothly. If you encounter further issues, consider consulting the documentation of the respective libraries or seeking assistance from their support channels.