import os import time from serpapi import GoogleSearch from langchain_google_genai import ChatGoogleGenerativeAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate def generate_script(prompt, video_length, creativity, api_key): # Setup Google (Gemini) using the provided API key chat = ChatGoogleGenerativeAI( model="gemini-1.5-flash", google_api_key=api_key, temperature=creativity # Adjust creativity level using temperature ) # Prompt template for generating video title title_template = PromptTemplate( input_variables=["topic"], template="Generate a YouTube video title based on the following topic: {topic}" ) title_chain = LLMChain(llm=chat, prompt=title_template, verbose=True) # Generate the title from the input prompt title = title_chain.run({"topic": prompt}) # Use SerpAPI to get search data search_params = { "q": prompt, "api_key": os.getenv('SERPAPI_API_KEY') # Make sure your API key is stored in the .env file } search = GoogleSearch(search_params) # Correct way to use SerpAPI search_data = search.get_dict() # This returns the search data in dictionary format # Ensure that the search data is in the correct format if "organic_results" in search_data: search_data = search_data["organic_results"] else: search_data = [] # Organize the script into sections script = f"**Generated Script for Topic: {prompt}**\n\n" script += f"**Video Title:** {title}\n\n" script += f"**Introduction:**\n" script += f"Host: 'Hey there, welcome to our channel! In today's video, we're diving into {title}. Let’s get started!'\n\n" # Add key points to the script based on the search data script += f"**Key Points to Discuss:**\n" if search_data: for index, result in enumerate(search_data[:5]): # Taking top 5 results for a concise script title_result = result.get('title', 'No title available') snippet_result = result.get('snippet', 'No description available') # Ensure that the search data has valid title and snippet if title_result and snippet_result: script += f"{index + 1}. {title_result}.\n" script += f" - Key Insights: {snippet_result}\n\n" # Fixed: correctly closed string here else: script += f"{index + 1}. No valid data available.\n" else: script += "No search data available to generate key points.\n" # Add a conclusion to the script script += f"**Conclusion:**\n" script += f"Host: 'We hope you found these tips helpful! Don’t forget to like, share, and subscribe for more content. See you in the next video!'\n" return title, script, search_data