File size: 2,390 Bytes
9202158 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | import gradio as gr
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
from pytube import YouTube
import tempfile
import whisper
import os
def extract_video_id(url):
if "watch?v=" in url:
return url.split("watch?v=")[-1].split("&")[0]
elif "youtu.be/" in url:
return url.split("youtu.be/")[-1].split("?")[0]
return None
def fetch_transcript(video_id):
try:
transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
full_text = ""
for entry in transcript_list:
full_text += f"[{entry['start']:.2f}s - {entry['start'] + entry['duration']:.2f}s]: {entry['text']}\n"
return full_text, "YouTube Captions"
except (TranscriptsDisabled, NoTranscriptFound):
return None, "Transcript Not Found"
def download_audio(video_url):
yt = YouTube(video_url)
stream = yt.streams.filter(only_audio=True).first()
temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
stream.download(filename=temp_audio.name)
return temp_audio.name
def transcribe_with_whisper(audio_path):
model = whisper.load_model("base") # "tiny", "base", "small", "medium", "large"
result = model.transcribe(audio_path)
return result['text']
def get_video_text(youtube_url):
video_id = extract_video_id(youtube_url)
if not video_id:
return "Invalid YouTube URL. Please paste the full video link.", None
transcript, source = fetch_transcript(video_id)
if transcript:
return f"โ
Transcript Source: {source}\n\n{transcript}", source
# If no transcript found, use Whisper AI
audio_file = download_audio(youtube_url)
transcript = transcribe_with_whisper(audio_file)
os.remove(audio_file)
return f"๐ง Transcript Source: OpenAI Whisper\n\n{transcript}", "Whisper AI"
# Gradio Interface
iface = gr.Interface(
fn=get_video_text,
inputs=gr.Textbox(label="Paste YouTube Video URL here", placeholder="https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
outputs=gr.Textbox(label="๐ Transcript (Full with Timestamps)", lines=20),
title="๐ฅ YouTube Video Transcript Extractor",
description="Fetch full video content as text using YouTube captions or OpenAI Whisper AI fallback. Works on most public videos with or without captions.",
)
if __name__ == "__main__":
iface.launch()
|