import os
import librosa
import soundfile as sf
import torch
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
def transcribe_audio(video_path, transcription_path, model_name="facebook/wav2vec2-base-960h", chunk_duration=60):
"""
Transcribe audio from a video file using Wav2Vec2 ASR model.
code
Args:
video_path (str): Path to the input video.
transcription_path (str): Path to save the transcription text.
model_name (str): Pre-trained model name.
chunk_duration (int): Duration (in seconds) to process at a time to manage memory.
"""
# Extract audio from video using librosa and save as WAV
print("Extracting audio from video...")
y, sr = librosa.load(video_path, sr=16000, mono=True) # Wav2Vec2 expects 16kHz mono audio
audio_path = "temp_audio.wav"
sf.write(audio_path, y, sr)
print(f"Audio extracted to {audio_path}")
# Load pre-trained Wav2Vec2 model and tokenizer
print("Loading ASR model and tokenizer...")
tokenizer = Wav2Vec2Tokenizer.from_pretrained(model_name)
model = Wav2Vec2ForCTC.from_pretrained(model_name)
model.eval()
# Load audio
speech, sr = librosa.load(audio_path, sr=16000, mono=True)
# Split audio into chunks to handle long durations
total_duration = librosa.get_duration(y=speech, sr=sr)
chunks = []
for start in range(0, int(total_duration), chunk_duration):
end = min(start + chunk_duration, total_duration)
chunk = speech[start * sr : end * sr]
chunks.append(chunk)
print(f"Total audio duration: {total_duration} seconds, split into {len(chunks)} chunks.")
# Transcribe each chunk
transcription = ""
for i, chunk in enumerate(chunks):
print(f"Transcribing chunk {i+1}/{len(chunks)}...")
input_values = tokenizer(chunk, return_tensors="pt", padding="longest").input_values
with torch.no_grad():
logits = model(input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
chunk_transcription = tokenizer.decode(predicted_ids[0])
transcription += chunk_transcription.lower() + " "
# Save transcription to file
with open(transcription_path, 'w') as f:
f.write(transcription.strip())
print(f"Transcription saved to {transcription_path}")
# Cleanup
os.remove(audio_path)
print(f"Temporary audio file {audio_path} removed.")
# Example usage
Assistant
video_path = '/kaggle/input/triala/Suits - Season 8 Official Opening Credits.mp4'
transcription_path = '/kaggle/working/transcription.txt'
transcribe_audio(video_path, transcription_path, model_name="facebook/wav2vec2-base-960h", chunk_duration=60)
can it do transcript of any video avaiable on youtube?
Yes, you can adapt your script to transcribe videos from YouTube, but it requires a few additional steps. Here's a comprehensive guide on how to achieve this:
1. Downloading YouTube Videos
To transcribe a YouTube video, you first need to download it to your local machine. You can use libraries like pytube or yt-dlp for this purpose. Here's an example using pytube:
python
from pytube import YouTube
import os
def download_youtube_video(youtube_url, output_path='downloaded_video.mp4'):
"""
Downloads a YouTube video.
Args:
youtube_url (str): URL of the YouTube video.
output_path (str): Path where the video will be saved.
Returns:
str: Path to the downloaded video.
"""
yt = YouTube(youtube_url)
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
if stream is None:
raise Exception("No suitable stream found.")
stream.download(filename=output_path)
print(f"Video downloaded to {output_path}")
return output_path
# Example usage
youtube_url = 'https://www.youtube.com/watch?v=YOUR_VIDEO_ID'
video_path = download_youtube_video(youtube_url, output_path='temp_video.mp4')
2. Integrating with Your Transcription Script
Once you've downloaded the video, you can integrate the download step with your transcription function. Here's an updated version of your script that includes YouTube downloading:
python
import os
import librosa
import soundfile as sf
import torch
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
from pytube import YouTube
def download_youtube_video(youtube_url, output_path='temp_video.mp4'):
yt = YouTube(youtube_url)
stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
if stream is None:
raise Exception("No suitable stream found.")
stream.download(filename=output_path)
print(f"Video downloaded to {output_path}")
return output_path
def transcribe_audio(video_path, transcription_path, model_name="facebook/wav2vec2-base-960h", chunk_duration=60):
"""
Transcribe audio from a video file using Wav2Vec2 ASR model.
Args:
video_path (str): Path to the input video.
transcription_path (str): Path to save the transcription text.
model_name (str): Pre-trained model name.
chunk_duration (int): Duration (in seconds) to process at a time to manage memory.
"""
# Extract audio from video using librosa and save as WAV
print("Extracting audio from video...")
y, sr = librosa.load(video_path, sr=16000, mono=True) # Wav2Vec2 expects 16kHz mono audio
audio_path = "temp_audio.wav"
sf.write(audio_path, y, sr)
print(f"Audio extracted to {audio_path}")
# Load pre-trained Wav2Vec2 model and tokenizer
print("Loading ASR model and tokenizer...")
tokenizer = Wav2Vec2Tokenizer.from_pretrained(model_name)
model = Wav2Vec2ForCTC.from_pretrained(model_name)
model.eval()
# Load audio
speech, sr = librosa.load(audio_path, sr=16000, mono=True)
# Split audio into chunks to handle long durations
total_duration = librosa.get_duration(y=speech, sr=sr)
chunks = []
for start in range(0, int(total_duration), chunk_duration):
end = min(start + chunk_duration, total_duration)
chunk = speech[start * sr : end * sr]
chunks.append(chunk)
print(f"Total audio duration: {total_duration} seconds, split into {len(chunks)} chunks.")
# Transcribe each chunk
transcription = ""
for i, chunk in enumerate(chunks):
print(f"Transcribing chunk {i+1}/{len(chunks)}...")
input_values = tokenizer(chunk, return_tensors="pt", padding="longest").input_values
with torch.no_grad():
logits = model(input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
chunk_transcription = tokenizer.decode(predicted_ids[0])
transcription += chunk_transcription.lower() + " "
# Save transcription to file
with open(transcription_path, 'w') as f:
f.write(transcription.strip())
print(f"Transcription saved to {transcription_path}")
# Cleanup
os.remove(audio_path)
print(f"Temporary audio file {audio_path} removed.")
os.remove(video_path)
print(f"Temporary video file {video_path} removed.")
# Example usage
youtube_url = 'https://www.youtube.com/watch?v=YOUR_VIDEO_ID'
downloaded_video_path = download_youtube_video(youtube_url, output_path='temp_video.mp4')
transcription_path = 'transcription.txt'
transcribe_audio(downloaded_video_path, transcription_path, model_name="facebook/wav2vec2-base-960h", chunk_duration=60)
3. Additional Considerations
Dependencies: Ensure you have pytube, librosa, soundfile, torch, and transformers installed. You can install them using pip:
Model Limitations: The facebook/wav2vec2-base-960h model works well for English but may not perform as effectively for other languages.
Audio Quality: The transcription accuracy heavily depends on the audio quality of the video. Background noise, multiple speakers, and accents can affect results.
Processing Time: Transcribing long videos can be time-consuming, especially if you're using a CPU. Consider leveraging a GPU for faster processing if available.
Chunk Duration: Adjust the chunk_duration based on your system's memory and the length of the video. Shorter chunks consume less memory but may increase processing time.
Error Handling: Implement robust error handling to manage scenarios like unavailable YouTube videos, network issues during download, or unsupported video formats.
Legal Considerations: Ensure you have the right to download and transcribe the YouTube videos you work with, especially concerning copyright laws and YouTube’s terms of service.
4. Alternative Approach Using yt-dlp
yt-dlp is a more actively maintained fork of youtube-dl and offers better performance and feature support. Here's how you can use it:
python
import yt_dlp
def download_youtube_video_yt_dlp(youtube_url, output_path='temp_video.mp4'):
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': output_path,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp4',
'preferredquality': '192',
}],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([youtube_url])
print(f"Video downloaded to {output_path}")
return output_path
# Replace the download function in the main script with this one if preferred.
5. Conclusion
While your original script is designed to work with local video files, with the addition of a YouTube downloading step, it can be adapted to transcribe any publicly available YouTube video. Ensure you handle potential exceptions and respect copyright laws when downloading and transcribing content.
If you encounter any specific issues while implementing these steps, feel free to ask for further assistance!