To create a Python script that downloads a YouTube video as an MP3 file and then transcribes it into a text file, you'll need pytube to handle the video downloading and a speech recognition package to transcribe the audio content. You also need to install some additional libraries for audio processing.
Here are the steps involved:
- Download the YouTube video as an MP3 file.
- Convert the MP3 file to text using speech recognition.
Prerequisites
Make sure to install the required libraries first. You can do this by running:
pip install pytube moviepy SpeechRecognition pydub
You'll also need to have ffmpeg installed on your system, as it is required for converting media files. You can download it from FFmpeg's official website.
Python Script
Here's a sample Python script that performs the tasks:
import os
from pytube import YouTube
from moviepy.editor import AudioFileClip
import speech_recognition as sr
def download_youtube_audio(url, output_path='downloaded_audio.mp4'):
print("Downloading audio...")
yt = YouTube(url)
audio_stream = yt.streams.filter(only_audio=True).first()
audio_file = audio_stream.download(output_path=output_path)
# Rename to mp3
base, ext = os.path.splitext(audio_file)
mp3_file = base + '.mp3'
os.rename(audio_file, mp3_file)
print(f"Downloaded and converted to MP3: {mp3_file}")
return mp3_file
def transcribe_audio_to_text(mp3_file, output_text_file='transcription.txt'):
print("Transcribing audio...")
recognizer = sr.Recognizer()
# Load the audio file into SpeechRecognition
audio_clip = sr.AudioFile(mp3_file)
with audio_clip as source:
audio_data = recognizer.record(source) # read the entire audio file
try:
# Recognize the speech in the audio file
transcription = recognizer.recognize_google(audio_data)
print("Transcription complete.")
# Write transcription to a text file
with open(output_text_file, 'w') as f:
f.write(transcription)
print(f"Transcription saved to {output_text_file}")
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio.")
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
if __name__ == "__main__":
youtube_url = input("Enter the YouTube video URL: ")
mp3_filename = download_youtube_audio(youtube_url)
transcribe_audio_to_text(mp3_filename)
Instructions to Use
-
Copy the script into a Python file, say youtube_transcriber.py.
-
Run the script using Python:
python youtube_transcriber.py
-
Input the YouTube URL when prompted.
Important Notes
- Ensure that the YouTube video you want to download complies with copyright laws.
- Speech recognition works best with clear audio, so the quality of the transcription may depend on the quality of the video’s audio track.
- The transcription service used here is Google's Speech Recognition API, and it requires an internet connection to function.
- Modify the output filenames as needed, and ensure you have write permissions to the respective directories.