Write me a script where i can feed it a whole bunch of youtube video links, and it can generate for me one giant text file with all their transcripts , in the script below i'm using tdrz but i wanna do it all in one go using whisper.cpp
sooo yeah last one looked like that , but i wanna incorporate it all in one script that i put INSIDE the git clone https://github.com/ggerganov/whisper.cpp cd whisper.cpp folder i'm in
Certainly! Below is a comprehensive Python script that automates the entire process of downloading YouTube videos, converting them to the appropriate audio format, transcribing them using whisper.cpp, and compiling all transcripts into a single text file. This script assumes you're running it inside the whisper.cpp directory and that you've already built the whisper.cpp executable (./main) and downloaded the required model (medium.en).
Prerequisites
Clone whisper.cpp Repository:
bash
git clone https://github.com/ggerganov/whisper.cpp
cd whisper.cpp
Build whisper.cpp:
bash
make
Download the Whisper Model:
bash
./models/download-ggml-model.sh medium.en
Install Python Dependencies:
Ensure you have Python 3 installed. Then, install the required Python packages:
bash
pip install yt-dlp
Install FFmpeg:
Make sure ffmpeg is installed on your system. You can install it using:
Save the following script as transcribe_youtube.py inside the whisper.cpp directory.
python
import yt_dlp
import subprocess
import os
import sys
import shutil
# Define the list of YouTube URLs
URLS = [
"https://www.youtube.com/watch?v=4YWAZEcYeMQ", # Tilek Mamutov
"https://www.youtube.com/watch?v=NdgPOXWU864", # Mikael Koivukangas
"https://www.youtube.com/watch?v=R3_vh00p-x8", # Alexander Campbell
"https://www.youtube.com/watch?v=lt4vR6XQk-o", # George Hotz Spaces on X
"https://www.youtube.com/watch?v=dTQb6N3_zu8", # Robin Hanson
"https://www.youtube.com/watch?v=f71yn1j5Uyc" # Beff Jezos Spaces on X
]
# Configuration
AUDIO_DIR = "audio_files"
TRANSCRIPTS_DIR = "transcripts"
FINAL_TRANSCRIPT_FILE = "all_transcripts.txt"
WHISPER_EXECUTABLE = "./main" # Ensure this path is correct
WHISPER_MODEL = "models/ggml-medium.en.bin" # Update if using a different model
TRANSCRIBE_ARGS = [
# Add any additional default args if needed
]
# Ensure required directories exist
os.makedirs(AUDIO_DIR, exist_ok=True)
os.makedirs(TRANSCRIPTS_DIR, exist_ok=True)
# Initialize the final transcript file
with open(FINAL_TRANSCRIPT_FILE, 'w', encoding='utf-8') as f:
f.write("All Transcripts\n")
f.write("====================\n\n")
def sanitize_filename(name):
"""Sanitize the filename to remove or replace problematic characters."""
return "".join(c if c.isalnum() or c in " .-_()" else "_" for c in name)
def download_and_convert(url):
"""Download audio from YouTube and convert to 16kHz mono WAV."""
try:
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'wav',
'preferredquality': '192',
}],
'outtmpl': os.path.join(AUDIO_DIR, '%(title)s.%(ext)s'),
'quiet': True,
'noprogress': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
title = info.get('title', 'unknown_title')
sanitized_title = sanitize_filename(title)
original_filename = ydl.prepare_filename(info)
wav_filename = os.path.splitext(original_filename)[0] + ".wav"
# Convert to 16kHz mono WAV
converted_filename = os.path.join(
AUDIO_DIR, f"{sanitized_title}_16khz_mono.wav"
)
cmd = [
"ffmpeg",
"-y", # Overwrite if exists
"-i", wav_filename,
"-ar", "16000",
"-ac", "1",
"-c:a", "pcm_s16le",
converted_filename
]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Remove the original WAV file to save space
os.remove(wav_filename)
print(f"✅ Downloaded and converted: {sanitized_title}")
return converted_filename, sanitized_title
except Exception as e:
print(f"❌ Error processing {url}: {e}")
return None, None
def transcribe_audio(audio_path, transcript_path):
"""Transcribe the given audio file using whisper.cpp."""
try:
cmd = [
WHISPER_EXECUTABLE,
"-m", WHISPER_MODEL,
"-f", audio_path,
"-otxt",
"-of", transcript_path,
"-pc", # Enable per-chunk processing (optional)
"-fa", # Format annotations (optional)
"-t", "48" # Number of threads (adjust as needed)
]
# Execute the transcription
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"✅ Transcribed: {os.path.basename(audio_path)}")
except subprocess.CalledProcessError as e:
print(f"❌ Transcription failed for {audio_path}: {e}")
def append_transcript(final_file, transcript_file, title):
"""Append the content of a transcript file to the final transcript."""
try:
with open(transcript_file, 'r', encoding='utf-8') as src, \
open(final_file, 'a', encoding='utf-8') as dest:
dest.write(f"Title: {title}\n")
dest.write(f"{'-'*50}\n")
shutil.copyfileobj(src, dest)
dest.write(f"\n{'='*100}\n\n")
except Exception as e:
print(f"❌ Failed to append {transcript_file} to {final_file}: {e}")
def main():
for url in URLS:
audio_path, title = download_and_convert(url)
if audio_path and title:
transcript_filename = f"{title}.txt"
transcript_path = os.path.join(TRANSCRIPTS_DIR, transcript_filename)
transcribe_audio(audio_path, transcript_path)
append_transcript(FINAL_TRANSCRIPT_FILE, transcript_path, title)
# Optionally, remove individual transcript files to save space
os.remove(transcript_path)
print(f"\n🎉 All videos processed! Transcripts compiled in '{FINAL_TRANSCRIPT_FILE}'.")
if __name__ == "__main__":
# Check if whisper executable exists
if not os.path.isfile(WHISPER_EXECUTABLE):
print(f"❌ Whisper executable not found at '{WHISPER_EXECUTABLE}'. Please build whisper.cpp first.")
sys.exit(1)
# Check if model exists
if not os.path.isfile(WHISPER_MODEL):
print(f"❌ Whisper model not found at '{WHISPER_MODEL}'. Please download the model first.")
sys.exit(1)
main()
Script Breakdown
Imports and Configuration:
yt_dlp: Used for downloading YouTube videos.
subprocess: To run shell commands (ffmpeg and whisper.cpp).
os, sys, shutil: For file and directory operations.
Configuration Variables: Define directories for audio files and transcripts, the final transcript file name, the path to the whisper.cpp executable, and the Whisper model path.
Utility Functions:
sanitize_filename: Cleans the video title to create a valid filename by replacing or removing problematic characters.
download_and_convert: Downloads the audio from YouTube, converts it to a 16kHz mono WAV file using ffmpeg, and saves it in the designated directory.
transcribe_audio: Runs the whisper.cpp executable on the converted audio file to generate a transcript.
append_transcript: Appends each individual transcript to the final consolidated transcript file with appropriate headers for clarity.
Main Execution Flow:
Iterates over each YouTube URL.
Downloads and converts the audio.
Transcribes the audio.
Appends the transcript to the final transcript file.
Cleans up individual transcript files to save space (optional).
Pre-run Checks:
Ensures that the whisper.cpp executable exists.
Checks if the Whisper model has been downloaded.
Running the Script
Ensure You're in the whisper.cpp Directory:
bash
cd path/to/whisper.cpp
Make the Script Executable (Optional):
bash
chmod +x transcribe_youtube.py
Run the Script:
bash
python transcribe_youtube.py
Or, if you've made it executable:
bash
./transcribe_youtube.py
Output
Audio Files: Stored in the audio_files directory.
Individual Transcripts: Stored temporarily in the transcripts directory and then appended to all_transcripts.txt.
Final Transcript: A single text file named all_transcripts.txt containing all the transcripts, separated by titles and delimiters for clarity.
Notes
Performance Optimization:
Threads (-t): You can adjust the number of threads (-t) based on your CPU cores for faster transcription.
CUDA Support: If you have a GPU and have built whisper.cpp with CUDA support, you can modify the WHISPER_EXECUTABLE path or add environment variables to utilize the GPU.
Error Handling:
The script includes basic error handling. However, for large-scale or critical applications, consider enhancing logging and error recovery mechanisms.
Extensibility:
You can expand the URLS list or modify the script to read URLs from an external file for flexibility.
Cleaning Up:
Currently, the script removes individual transcript files after appending them to the final transcript. If you'd like to keep them, comment out or remove the os.remove(transcript_path) line.
Conclusion
This script automates the entire workflow, making it seamless to download, convert, transcribe, and compile transcripts from multiple YouTube videos using whisper.cpp. Ensure all dependencies are correctly installed and paths are appropriately set. Happy transcribing!