try this import os
import torchaudio
from simple_diarizer.diarizer import Diarizer
from transformers import WhisperForConditionalGeneration, WhisperProcessor, pipeline
Constants
SAMPLING_RATE = 16000
AUDIO_SAVE_DIRECTORY = "path/to/audio/save/directory" # Update with your directory
MODEL_DIRECTORY = "model" # Update if you have a different directory
def read_audio(file_path, sampling_rate=SAMPLING_RATE):
"""Reads an audio file and resamples it to the specified sampling rate.
Args:
file_path (str): Path to the audio file.
sampling_rate (int): Desired sampling rate (default: 16000 Hz).
Returns:
torch.Tensor: The audio waveform as a PyTorch tensor.
"""
waveform, sr = torchaudio.load(file_path, mono=True) # Load as mono
if sr != sampling_rate:
resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=sampling_rate)
waveform = resampler(waveform)
return waveform
def save_audio(file_path, audio, sampling_rate=SAMPLING_RATE):
"""Saves an audio tensor to a file.
Args:
file_path (str): Path to save the audio file.
audio (torch.Tensor): Audio waveform as a PyTorch tensor.
sampling_rate (int): Sampling rate (default: 16000 Hz).
"""
torchaudio.save(file_path, audio, sampling_rate)
if name == "main":
# Get the audio file path from user input or your preferred method
audio_file_path = input("Enter the path to your audio file: ")
# File handling and format conversion
audio_filename = os.path.basename(audio_file_path)
audio_name, audio_ext = os.path.splitext(audio_filename)
wav_file_path = os.path.join(AUDIO_SAVE_DIRECTORY, f"{audio_name}.wav")
if not os.path.exists(wav_file_path):
audio_data = read_audio(audio_file_path)
save_audio(wav_file_path, audio_data)
# Load the audio signal and diarize
signal = read_audio(wav_file_path)
diarizer = Diarizer(embed_model="xvec", cluster_method="sc")
segments = diarizer.diarize(wav_file_path, num_speakers=2, silence_tolerance=1)
# Load the Whisper model and processor
model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small")
processor = WhisperProcessor.from_pretrained("openai/whisper-small")
asr_pipeline = pipeline(task="automatic-speech-recognition", model=model, tokenizer=processor.tokenizer)
# Transcribe each segment
transcriptions = []
for segment in segments:
start_sample = segment["start_sample"]
end_sample = segment["end_sample"]
segment_audio = signal[:, start_sample:end_sample]
# Preprocess audio with WhisperProcessor
input_features = processor(segment_audio.squeeze(0).numpy(), sampling_rate=SAMPLING_RATE, return_tensors="pt").input_features
# Pass preprocessed audio to the pipeline
transcription = asr_pipeline(input_features)
transcriptions.append(transcription["text"])
# Print or process transcriptions (e.g., save to file, display in UI)
for i, transcription in enumerate(transcriptions):
print(f"Segment {i+1}: {transcription}")