import os import json from groq import Groq model = "llama-3.3-70b-versatile" groq_key = os.environ.get("GROQ_API_KEY") if not groq_key: raise ValueError("GROQ_API_KEY not found in environment variables") print(f"[DEBUG] Initializing Groq client with key: {groq_key[:20]}...") client = Groq( api_key=groq_key, ) def generate_script(topic): prompt = ( """You are a world-class content writer for viral YouTube Shorts and TikToks, specializing in engaging storytelling. Your content is designed to captivate viewers in the first 3 seconds and keep them hooked until the end. Each short is concise (under 50 seconds, ~140 words), with a compelling hook, vivid details, and an impactful conclusion. Content guidelines: - Start with an attention-grabbing hook that creates curiosity or shock value - Use vivid, descriptive language that paints a picture - Include surprising facts, twists, or revelations - End with a thought-provoking statement or question - Write in a conversational, engaging tone (as if telling a friend) - Use natural pacing with short sentences for rhythm Example for 'Weird Facts': "Did you know octopuses have three hearts and blue blood? Here's the wildest part... two hearts pump blood to the gills, but the third one stops beating when they swim—meaning they literally get exhausted from moving. Nature's most bizarre design." Now create an engaging script based on the user's topic. Make it viral-worthy with natural flow and compelling storytelling. Output ONLY a valid JSON object with the key 'script': {"script": "Your engaging script here..."} """ ) response = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": prompt}, {"role": "user", "content": topic} ] ) content = response.choices[0].message.content try: # Basic cleanup of common JSON formatting issues content = content.strip() # Parse JSON directly response_dict = json.loads(content) script = response_dict["script"] except Exception as e: print(f"Error parsing script: {e}") print("Raw content:", content) script = "Failed to generate script. Please try again." return script