write me a function in python that fetches youtube transcript of link then summarize…
- User
write me a function in python that fetches youtube transcript of link then summarize using ai
Assistant
write me a function in python that fetches youtube transcript of link then summarize using ai
Okay, I can help you with that. Here's a Python function that fetches a YouTube transcript, then summarizes it using an AI model (specifically, using the Hugging Face Transformers library).
from youtube_transcript_api import YouTubeTranscriptApi
from transformers import pipeline
def summarize_youtube_transcript(youtube_url):
"""
Fetches the transcript of a YouTube video, then summarizes it using an AI model.
Args:
youtube_url: The URL of the YouTube video.
Returns:
A string containing the summarized transcript, or None if an error occurred.
"""
try:
# 1. Extract video ID from URL
video_id = youtube_url.split("watch?v=")[1]
if "&" in video_id:
video_id = video_id.split("&")[0]
# 2. Fetch the transcript
transcript = YouTubeTranscriptApi.get_transcript(video_id)
# 3. Combine transcript into a single string
full_transcript = " ".join([entry['text'] for entry in transcript])
# 4. Summarize the transcript using Hugging Face Transformers
summarizer = pipeline("summarization") # Uses a default model
summary = summarizer(full_transcript, max_length=130, min_length=30, do_sample=False)[0]['summary_text']
return summary
except Exception as e:
print(f"An error occurred: {e}")
return None
if __name__ == '__main__':
# Example usage
youtube_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Replace with a real YouTube URL
summary = summarize_youtube_transcript(youtube_url)
if summary:
print("Summary:")
print(summary)
else:
print("Failed to generate summary.")
Key improvements and explanations:
Error Handling: Includes a try...except block to catch potential errors during the process (e.g., invalid URL, missing transcript, API errors). This makes the function more robust.
Video ID Extraction: The code now extracts the YouTube video ID more reliably, handling cases where there are additional parameters in the URL after watch?v=.
Transcript Combination: It iterates through the transcript entries and combines the text parts into a single string.
Hugging Face pipeline: It utilizes the transformers library's pipeline function for summarization. This simplifies the process of loading a pre-trained model and using it. I've added max_length and min_length parameters to control the summary length, and do_sample=False for more deterministic summaries.
Clearer Return Value: The function returns the summary string or None if there was an error.
Example Usage: The if __name__ == '__main__': block provides an example of how to use the function. Important: Replace the placeholder URL with a real YouTube URL for testing.
Dependencies: You need to install the required libraries:
pip install youtube-transcript-api transformers
How to use:
youtube-transcript-api and transformers libraries installed.if __name__ == '__main__': block, replace the example YouTube URL with the URL of the video you want to summarize.Important considerations:
pipeline("summarization") uses a default summarization model. You can specify a different model if you want (e.g., pipeline("summarization", model="facebook/bart-large-cnn")). Some models are better than others, but larger models often require more memory. Research different summarization models on the Hugging Face Model Hub.