provide me a comprehensive python code that uses torch, whisper ai, etc. to transcribe a youtube video
Assistant
Certainly! Below is a comprehensive Python script that uses PyTorch and OpenAI's Whisper to download and transcribe a YouTube video. This script uses yt-dlp to download the audio from the YouTube video and then uses Whisper to transcribe the audio.
Important Note: Please ensure that you have the rights or permissions to download and transcribe the YouTube video, as downloading content without permission may violate YouTube's Terms of Service and copyright laws.
Prerequisites
Before running the script, you'll need to install the following packages:
PyTorch: Deep learning framework needed for running Whisper.
Whisper: OpenAI's speech recognition model.
yt-dlp: A command-line program to download videos from YouTube.com and other video platforms.
import os
import yt_dlp
import whisper
def download_audio_from_youtube(youtube_url, output_filename):
"""
Downloads the audio from a YouTube video and saves it to a file.
Parameters:
- youtube_url: str, the URL of the YouTube video.
- output_filename: str, the output filename for the audio file.
Returns:
- audio_filename: str, the path to the downloaded audio file.
"""
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': output_filename,
'postprocessors': [
{ 'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}
],
'quiet': True
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
print(f"Downloading audio from {youtube_url}...")
ydl.download([youtube_url])
audio_filename = f"{output_filename}.mp3"
if os.path.exists(audio_filename):
print(f"Audio downloaded successfully: {audio_filename}")
return audio_filename
else:
raise Exception("Failed to download audio.")
def transcribe_audio(audio_filename, model_name="base"):
"""
Transcribes an audio file using OpenAI's Whisper model.
Parameters:
- audio_filename: str, the path to the audio file.
- model_name: str, the name of the Whisper model to use.
Returns:
- transcription: str, the transcribed text.
"""
print(f"Loading Whisper model '{model_name}'...")
model = whisper.load_model(model_name)
print(f"Transcribing audio file {audio_filename}...")
result = model.transcribe(audio_filename)
transcription = result["text"]
print("Transcription completed.")
return transcription
def save_transcription(transcription, output_textfile):
"""
Saves the transcription to a text file.
Parameters:
- transcription: str, the transcribed text.
- output_textfile: str, the output text file path.
"""
with open(output_textfile, "w", encoding="utf-8") as f:
f.write(transcription)
print(f"Transcription saved to {output_textfile}")
def main():
# Input YouTube URL
youtube_url = input("Enter the YouTube video URL: ").strip()
# Output filenames
output_audiofile = "downloaded_audio"
output_textfile = "transcription.txt"
try:
# Step 1: Download audio from YouTube
audio_filename = download_audio_from_youtube(youtube_url, output_audiofile)
# Step 2: Transcribe the audio using Whisper
transcription = transcribe_audio(audio_filename, model_name="base")
# Step 3: Save the transcription to a text file
save_transcription(transcription, output_textfile)
print("All done!")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
How to Use the Script
Save the script: Copy and paste the script into a file named youtube_transcribe.py.
Install the prerequisites: Ensure you have installed the required packages as per the instructions above.
Run the script: Open a terminal in the directory where youtube_transcribe.py is located and run:
bash
python youtube_transcribe.py
Enter the YouTube URL: When prompted, paste the YouTube video URL you wish to transcribe.
Wait for the transcription: The script will download the audio, transcribe it, and save the transcription to transcription.txt.
Additional Notes
Model Selection: Whisper offers several models of different sizes (tiny, base, small, medium, large). Smaller models are faster but may be less accurate.
python
# For a smaller model
transcription = transcribe_audio(audio_filename, model_name="small")
Language Options: If the audio is not in English, Whisper can detect the language automatically. You can also specify the language:
python
result = model.transcribe(audio_filename, language='es') # For Spanish
Error Handling: The script includes basic error handling to catch and report issues during the download and transcription process.
Temporary Files: The downloaded audio file (downloaded_audio.mp3) will remain in the directory after the script finishes. You may want to delete it manually or modify the script to remove it after transcription.
Disclaimer
This script is intended for educational purposes and for transcribing content you have permission to use. Always respect copyright laws and the terms of service of platforms like YouTube.