Skip to content
site logo mobile

Code Snippets Library >

YouTube Video To Blog Post

🔑 ID:

23850

👨‍💻

Python

🕒

05/02/2024
Free

Description:

This is a project that turns any youtube video into a blog post.

Code:

# Import necessary libraries
from youtube_transcript_api import YouTubeTranscriptApi
import openai
import re


#FUNCTIONS:


# Define a function to get the transcript of a YouTube video
def get_video_transcript(video_url):
    # Extract the video ID from the YouTube URL using regular expressions
    match = re.search(r"(?:youtube\.com\/watch\?v=|youtu\.be\/)(.*)", video_url)
    if match:
        video_id = match.group(1)
    else:
        # If the URL is invalid, raise an error
        raise ValueError("Invalid YouTube URL")


    # Fetch the transcript using the YouTubeTranscriptApi library
    transcript = YouTubeTranscriptApi.get_transcript(video_id)


    # Combine the text of the transcript into a single string
    transcript_text = ""
    for line in transcript:
        transcript_text += line["text"] + " "
    return transcript_text


# Define a function to generate text using OpenAI's GPT model
def openai_generate(user_prompt, selected_model):
    # Create a completion request to OpenAI with the provided prompt and model
    completion = openai.chat.completions.create(
        model=selected_model, messages=[{"role": "user", "content": user_prompt}]
    )
    # Return the generated text
    return completion.choices[0].message.content


# Template for the prompt to be sent to OpenAI
youtube_to_blog_post = """Act as a professional blog copywriter.
I'm going to give you a transcript of a YouTube video, and I want you
to generate s full compelling blog with a title for it.
Make sure you don't use complex vocabulary and only use the information from the transcript.
VIDEO TRANSCRIPT:{transcript}"""


#INPUTS:


openai.api_key = "Your API Key"  # Replace with your actual API key
youtube_url = "https://www.youtube.com/watch?v=gnCO6443kuk" # URL of the YouTube video
model = "gpt-3.5-turbo" # The model of OpenAI's GPT to use


# Get the transcript of the YouTube video
video_transcript = get_video_transcript(youtube_url)


# Format the prompt with the actual transcript
formatted_prompt = youtube_to_blog_post.format(transcript=video_transcript)


# Generate text using OpenAI's GPT model
generated_text = openai_generate(formatted_prompt, model)


print(generated_text)

 

Untitled design (82)

GitHub Link

✖️ Not Available

Untitled design (83)

Download File

✖️ Not Available

If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.