import yt_dlp
import subprocess
import os
import sys
# ==================== Configuration ====================
# List of YouTube URLs to process
YOUTUBE_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
]
# Path configurations
WHISPER_CPP_REPO = "whisper.cpp"
WHISPER_CPP_EXE = os.path.join(WHISPER_CPP_REPO, "main") # Executable
MODEL_NAME = "ggml-medium.en.bin" # Change to desired model
MODEL_URL_SCRIPT = os.path.join(WHISPER_CPP_REPO, "models", "download-ggml-model.sh")
MODEL_PATH = os.path.join(WHISPER_CPP_REPO, "models", MODEL_NAME)
OUTPUT_TRANSCRIPT = "all_transcripts.txt"
# Whisper.cpp transcription settings
WHISPER_ARGS = [
"-otxt", # Output format: text
"-pc", # Print progress
"-fa", # Alignment (optional, adjust as needed)
"-t", "48" # Number of threads (adjust based on your CPU)
]
# ========================================================
def clone_whisper_cpp():
"""Clone the whisper.cpp repository if it doesn't exist."""
if not os.path.isdir(WHISPER_CPP_REPO):
print(f"Cloning {WHISPER_CPP_REPO} repository...")
subprocess.run(["git", "clone", "https://github.com/ggerganov/whisper.cpp.git"], check=True)
else:
print(f"Repository '{WHISPER_CPP_REPO}' already exists.")
def build_whisper_cpp():
"""Build the whisper.cpp executable."""
print("Building whisper.cpp...")
subprocess.run(["make", "-C", WHISPER_CPP_REPO], check=True)
print("whisper.cpp built successfully.")
def download_whisper_model():
"""Download the specified Whisper model."""
if not os.path.isfile(MODEL_PATH):
print(f"Downloading model '{MODEL_NAME}'...")
subprocess.run(["bash", MODEL_URL_SCRIPT, "medium.en"], check=True, cwd=WHISPER_CPP_REPO)
print(f"Model '{MODEL_NAME}' downloaded.")
else:
print(f"Model '{MODEL_NAME}' already exists.")
def download_and_convert_audio(url):
"""Download audio from YouTube and convert it to 16kHz mono WAV."""
try:
# Setup yt-dlp options
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': '%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'wav',
}],
'quiet': True,
'noplaylist': True
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=True)
title = info_dict.get('title', 'Untitled')
downloaded_file = ydl.prepare_filename(info_dict).replace('.webm', '.wav').replace('.m4a', '.wav').replace('.mp4', '.wav')
# Convert to 16kHz mono
converted_file = f"{os.path.splitext(downloaded_file)[0]}_16khz_mono.wav"
cmd_ffmpeg = [
"ffmpeg",
"-y", # Overwrite if exists
"-i", downloaded_file,
"-ar", "16000", # Set sample rate to 16kHz
"-ac", "1", # Convert to mono
"-c:a", "pcm_s16le", # Set codec
converted_file
]
subprocess.run(cmd_ffmpeg, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
# Remove the original downloaded file to save space
os.remove(downloaded_file)
print(f"✅ Downloaded and converted: {converted_file}")
return converted_file, title
except Exception as e:
print(f"❌ Failed to download/convert {url}: {e}")
return None, None
def transcribe_audio(audio_path, title):
"""Transcribe audio using whisper.cpp and append to the main transcript."""
try:
transcript_file = f"{os.path.splitext(audio_path)[0]}.txt"
cmd_whisper = [
WHISPER_CPP_EXE,
"-m", MODEL_PATH,
"-f", audio_path
] + WHISPER_ARGS
subprocess.run(cmd_whisper, check=True, cwd=WHISPER_CPP_REPO)
# Read the generated transcript
with open(transcript_file, 'r', encoding='utf-8') as tf:
transcript = tf.read()
# Append to the main transcript file with a header
with open(OUTPUT_TRANSCRIPT, 'a', encoding='utf-8') as out_f:
out_f.write(f"--- Transcript for: {title} ---\n")
out_f.write(transcript)
out_f.write("\n\n")
print(f"✅ Transcribed and appended: {title}")
# Optional: Clean up individual transcript and audio files
os.remove(transcript_file)
os.remove(audio_path)
except subprocess.CalledProcessError as e:
print(f"❌ Transcription failed for {audio_path}: {e}")
except Exception as e:
print(f"❌ Error processing {audio_path}: {e}")
def main():
# Step 1: Clone the repository
clone_whisper_cpp()
# Step 2: Build whisper.cpp
build_whisper_cpp()
# Step 3: Download the Whisper model
download_whisper_model()
# Step 4: Process each YouTube URL
# Clear the main transcript file if it exists
if os.path.exists(OUTPUT_TRANSCRIPT):
os.remove(OUTPUT_TRANSCRIPT)
for url in YOUTUBE_URLS:
print(f"Processing URL: {url}")
audio_file, title = download_and_convert_audio(url)
if audio_file:
transcribe_audio(audio_file, title)
else:
print(f"Skipping transcription for URL: {url}")
print(f"\n🎉 All transcripts have been compiled into '{OUTPUT_TRANScript}'.")
if __name__ == "__main__":
main()