To solve this problem, we'll create a Python script that fetches the transcript of a YouTube video and uses OpenAI's API to generate a concise summary. The solution involves three main steps: extracting the video ID from the URL, retrieving the transcript, and generating the summary via OpenAI.
Step-by-Step Explanation
- Extract Video ID: Parse the YouTube URL to get the unique video ID.
- Fetch Transcript: Use the
youtube-transcript-apilibrary to retrieve the video's transcript. - Generate Summary: Send the transcript to OpenAI's GPT-3.5-turbo model to get a concise summary.
Prerequisites
- Install required libraries:
pip install youtube-transcript-api openai - Set your OpenAI API key as an environment variable:
Linux/macOS:export OPENAI_API_KEY="your_api_key"
Windows:set OPENAI_API_KEY="your_api_key"
Python Script
import re
import os
import openai
from youtube_transcript_api import YouTubeTranscriptApi
def get_video_id(url: str) -> str:
"""Extract video ID from YouTube URL."""
patterns = [
r'(?:https?://)?(?:www\.)?youtube\.com/watch\?v=([^&]+)', # Standard URL
r'(?:https?://)?youtu\.be/([^?]+)', # Short URL
r'(?:https?://)?(?:www\.)?youtube\.com/shorts/([^?]+)' # Shorts URL
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1)
raise ValueError("Invalid YouTube URL: Could not extract video ID.")
def get_transcript(video_id: str, languages: list = ['en']) -> str:
"""Retrieve transcript for the given video ID."""
try:
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=languages)
return ' '.join([entry['text'] for entry in transcript])
except Exception as e:
raise Exception(f"Transcript error: {str(e)}")
def generate_summary(transcript: str, api_key: str) -> str:
"""Generate summary using OpenAI's GPT-3.5-turbo."""
openai.api_key = api_key
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a concise summarizer. Summarize the YouTube transcript, covering key points and takeaways."},
{"role": "user", "content": f"Transcript:\n{transcript}"}
],
temperature=0.3, # Low temperature for factual accuracy
max_tokens=500 # Adjust based on desired summary length
)
return response.choices[0].message['content'].strip()
except Exception as e:
raise Exception(f"OpenAI API error: {str(e)}")
def main():
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
print("Error: OPENAI_API_KEY environment variable not set.")
return
url = input("Enter YouTube video URL: ")
try:
video_id = get_video_id(url)
print(f"Extracted Video ID: {video_id}")
transcript = get_transcript(video_id)
print("Transcript fetched successfully.")
summary = generate_summary(transcript, api_key)
print("\nSummary:\n")
print(summary)
except Exception as e:
print(f"Error: {str(e)}")
if __name__ == "__main__":
main()
Key Features
- URL Handling: Supports standard, short, and Shorts YouTube URLs.
- Multilingual Transcripts: Defaults to English but can be extended to other languages (e.g.,
languages=['en', 'es']). - Error Handling: Catches invalid URLs, missing transcripts, and API errors.
- Concise Summaries: Uses GPT-3.5-turbo with low temperature for accurate, focused summaries.
Limitations & Improvements
- Long Transcripts: For transcripts exceeding the model's context window (4096 tokens), split the transcript into chunks and summarize each, then combine the results.
- Language Support: Add user input for preferred languages to fetch transcripts in non-English languages.
- Summary Length: Allow users to adjust the
max_tokensparameter for longer/shorter summaries.
This script provides a robust foundation for summarizing YouTube videos using AI, with room for customization based on specific needs.


作者声明:本文包含人工智能生成内容。