Spaces:
Runtime error
Runtime error
| from youtube_transcript_api import YouTubeTranscriptApi | |
| from urllib.parse import urlparse, parse_qs | |
| from transformers import pipeline | |
| import gradio as gr | |
| # 1. Helper: extract ID | |
| def get_video_id(url): | |
| parsed = urlparse(url) | |
| if parsed.hostname == "youtu.be": | |
| return parsed.path[1:] | |
| elif parsed.hostname in ["www.youtube.com", "youtube.com"]: | |
| if parsed.path == "/watch": | |
| return parse_qs(parsed.query)["v"][0] | |
| elif parsed.path.startswith("/embed/") or parsed.path.startswith("/v/"): | |
| return parsed.path.split("/")[2] | |
| raise ValueError("Invalid YouTube URL") | |
| # 2. Helper: get transcript | |
| def get_transcript(video_id, lang="en"): | |
| try: | |
| transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) | |
| transcript = transcript_list.find_transcript([lang]) | |
| lines = transcript.fetch() | |
| return " ".join([line.text for line in lines]) | |
| except Exception as e: | |
| return f"Error: {e}" | |
| # 3. Load model | |
| summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6") | |
| # 4. Summarize in chunks | |
| def local_summarize_text(text, max_chunk_words=400): | |
| words = text.split() | |
| chunks = [words[i:i+max_chunk_words] for i in range(0, len(words), max_chunk_words)] | |
| summaries = [] | |
| for chunk in chunks: | |
| chunk_text = " ".join(chunk) | |
| result = summarizer( | |
| chunk_text, | |
| max_length=min(130, int(len(chunk_text.split()) * 0.8)), | |
| min_length=20, | |
| do_sample=False | |
| ) | |
| summaries.append(result[0]["summary_text"]) | |
| return "\n\n".join(summaries) | |
| # 5. Gradio interface function | |
| def gradio_summarizer(youtube_url): | |
| try: | |
| video_id = get_video_id(youtube_url) | |
| except Exception as e: | |
| return f"❌ Error extracting video ID: {e}" | |
| transcript = get_transcript(video_id) | |
| if not transcript or transcript.startswith("Error"): | |
| return f"❌ Failed to fetch transcript. Reason: {transcript}" | |
| summary = local_summarize_text(transcript) | |
| return summary | |
| # 6. Launch | |
| iface = gr.Interface( | |
| fn=gradio_summarizer, | |
| inputs=gr.Textbox(label="YouTube Video URL"), | |
| outputs=gr.Textbox(label="Summary"), | |
| title="YouTube Video Summarizer", | |
| description="Enter a YouTube link (with subtitles). The app fetches and summarizes the transcript." | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |