OpenAI Layer Zip File: Download

lambda_handler function Source Code:
import json
import os
from openai import OpenAI
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api import CouldNotRetrieveTranscript, InvalidVideoId, NoTranscriptAvailable

def get_transcript(video_id):
    try:
        response = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
        transcript = ' '.join([chunk['text'] for chunk in response])
        return transcript
    except (CouldNotRetrieveTranscript, InvalidVideoId, NoTranscriptAvailable) as e:
        print(e)
        return None

def lambda_handler(event, context):
    try:
        openai_api_key = os.environ['OPENAI_API_KEY']
    except KeyError:
        return {
            'statusCode': 500,
            'body': 'OpenAI API key not found.'
        }
    
    client = OpenAI(api_key=openai_api_key)

    if 'queryStringParameters' not in event or 'video_id' not in event['queryStringParameters']:
        return {
            'statusCode': 400,
            'body': 'video_id not found in event data.'
        }

    video_id = event['queryStringParameters']['video_id']

    try:
        transcript = get_transcript(video_id)
        if transcript is None:
            return {
                'satatusCode': 400,
                'body': json.dumps('Unable to retrieve transcript')
            }

        prompt = 'Summarize the following transcript. Output the summary in bullet points, and be detailed.\n\nTranscript:\n' +  transcript
        response = client.Completion.create(
            model="gpt-3.5-turbo-instruct",
            prompt=prompt,
            temperature=0,
            max_tokens=512,
        )

        return {
            'statusCode': 200,
            'body': response.choices[0].text.strip()
        }
    except Exception as e:
        print(e)
        return {
            'statusCode': 500,
            'body': json.dumps('An error occurred while summarizing the transcript.')
        }