import streamlit as st import openai import os import requests from bs4 import BeautifulSoup from urllib.parse import urljoin, urlparse import re from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.units import inch import io # Page configuration st.set_page_config( page_title="AI Video Script Generator Pro", page_icon="🎬", layout="wide", initial_sidebar_state="collapsed" ) # Custom CSS for better styling st.markdown(""" """, unsafe_allow_html=True) # Initialize OpenAI API key @st.cache_resource def setup_openai(): api_key = os.getenv("OPENAI_API_KEY") if not api_key: st.error("Please set your OPENAI_API_KEY environment variable") return False openai.api_key = api_key return True openai_ready = setup_openai() # Website analysis functions def scrape_website(url, max_pages=3): """Scrape website content for business information""" if not url.startswith("http"): url = f"https://{url}" visited = set() to_visit = [url] all_content = [] scrape_successful = False while to_visit and len(visited) < max_pages: current_url = to_visit.pop(0) if current_url in visited: continue try: response = requests.get(current_url, timeout=10, headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }) response.raise_for_status() soup = BeautifulSoup(response.content, "html.parser") visited.add(current_url) scrape_successful = True # Extract meaningful content title = soup.find("title") if title: all_content.append(f"Title: {title.get_text(strip=True)}") meta_description = soup.find("meta", {"name": "description"}) if meta_description and meta_description.get("content"): all_content.append(f"Description: {meta_description['content']}") # Extract headings for heading in soup.find_all(["h1", "h2", "h3"])[:10]: all_content.append(f"Heading: {heading.get_text(strip=True)}") # Extract paragraphs paragraphs = soup.find_all("p")[:15] for para in paragraphs: text = para.get_text(strip=True) if len(text) > 20: # Only meaningful paragraphs all_content.append(text) # Look for about/services pages links = soup.find_all("a", href=True) for link in links[:10]: href = link.get("href", "").lower() if any(keyword in href for keyword in ["about", "service", "what-we-do", "our-story"]): full_url = urljoin(current_url, link["href"]) if full_url not in visited and url in full_url: to_visit.append(full_url) except Exception as e: continue return " ".join(all_content[:2000]), scrape_successful # Limit content length def search_business_info(url_or_name): """Search for business information using web search""" try: if not openai_ready: return "Unable to search - OpenAI not configured" domain = urlparse(url_or_name).netloc if url_or_name.startswith('http') else url_or_name response = openai.ChatCompletion.create( model="gpt-4", messages=[ { "role": "system", "content": "You are a business research assistant. Based on a website URL or business name, provide information about what the business does, what problems they solve, their target audience, and their unique value proposition. If you don't have specific information, make reasonable inferences based on the domain name or business name." }, { "role": "user", "content": f"Research this business: {domain}. Provide information about: 1) What they do, 2) Problems they solve, 3) Target audience, 4) Services/products, 5) What makes them unique. Be specific and practical." } ], temperature=0.3 ) return response["choices"][0]["message"]["content"] except Exception as e: return f"Unable to research business information: {str(e)}" def extract_business_info(content): """Extract structured business information from website content or research""" try: if not openai_ready: return {} response = openai.ChatCompletion.create( model="gpt-4", messages=[ { "role": "system", "content": """You are a business analyst. Extract key business information from website content and return it in a structured format. Extract: 1. Business description (what they do) 2. Problems they solve for customers 3. Main services/products (2-3 key offerings) 4. Unique value proposition 5. Business name 6. Target audience (be specific) Return the information in this exact format: BUSINESS_DESCRIPTION: [description] PROBLEM_SOLVED: [problem] SERVICES: [services] UNIQUE_VALUE: [unique aspects] BUSINESS_NAME: [name] TARGET_AUDIENCE: [audience] If any information is unclear, make reasonable inferences based on available context.""" }, { "role": "user", "content": f"Extract business information from this content: {content[:1500]}" # Limit content } ], temperature=0.3 ) result = response["choices"][0]["message"]["content"] # Parse the structured response info = {} lines = result.split('\n') for line in lines: if ':' in line: key, value = line.split(':', 1) key = key.strip() value = value.strip() if key == "BUSINESS_DESCRIPTION": info['business'] = value elif key == "PROBLEM_SOLVED": info['problem'] = value elif key == "SERVICES": info['services'] = value elif key == "UNIQUE_VALUE": info['unique'] = value elif key == "BUSINESS_NAME": info['name'] = value elif key == "TARGET_AUDIENCE": info['audience'] = value return info except Exception as e: return {} def analyze_website(url): """Main function to analyze website and extract business information""" if not url: return {} # First, try to scrape the website content, scrape_successful = scrape_website(url) if not scrape_successful or len(content) < 100: # If scraping failed, try searching for business information content = search_business_info(url) # Extract structured information business_info = extract_business_info(content) return business_info # Function to generate PDF def create_pdf(script_content, business_name, platform, video_type): buffer = io.BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter, topMargin=1*inch) # Define styles styles = getSampleStyleSheet() title_style = ParagraphStyle( 'CustomTitle', parent=styles['Heading1'], fontSize=18, textColor='#1f4e79', alignment=1, # Center alignment spaceAfter=30 ) content_style = ParagraphStyle( 'CustomContent', parent=styles['Normal'], fontSize=12, leading=18, spaceAfter=12 ) # Create content story = [] # Title story.append(Paragraph(f"Video Script for {business_name}", title_style)) story.append(Spacer(1, 20)) # Details story.append(Paragraph(f"Platform: {platform}", content_style)) story.append(Paragraph(f"Video Type: {video_type}", content_style)) story.append(Spacer(1, 20)) # Script content story.append(Paragraph("Script:", content_style)) story.append(Spacer(1, 10)) # Clean and format script content script_paragraphs = script_content.split('\n') for paragraph in script_paragraphs: if paragraph.strip(): story.append(Paragraph(paragraph.strip(), content_style)) # Build PDF doc.build(story) buffer.seek(0) return buffer # Function to generate script with enhanced prompting def generate_video_script(prompt_data): if not openai_ready: return None try: # Get platform-specific requirements platform_reqs = get_platform_requirements(prompt_data['platform']) hook_strategy = get_hook_strategy(prompt_data['hook_type']) storytelling_framework = get_storytelling_framework(prompt_data['storytelling']) system_message = f""" You are an expert video marketing strategist who creates compelling promotional scripts that convert viewers into customers. Your scripts are based on 2024-2025 research showing that authenticity beats polish, and that 93% of marketers see good ROI from video marketing. CRITICAL REQUIREMENTS: - Hook viewers in the first 3-5 seconds using psychological triggers - Create authentic, conversational content that blends with organic social media - Address specific customer pain points with empathy and understanding - Use proven storytelling frameworks for maximum engagement - Include strong, specific call-to-actions that drive conversions - Optimize for platform-specific requirements and audience behaviors - Write ONLY the words to be spoken - no directions or stage notes Platform Requirements: {platform_reqs} Hook Strategy: {hook_strategy} Storytelling Framework: {storytelling_framework} The script should feel natural, authentic, and valuable to the viewer even if they don't buy anything. """ user_message = f""" Create a promotional video script with these details: BUSINESS INFO: - Business: {prompt_data['business']} - Problem Solved: {prompt_data['problem']} - Services/Products: {prompt_data['services']} - Unique Value: {prompt_data['unique']} - Business Name: {prompt_data['name']} - Target Audience: {prompt_data['audience']} VIDEO SPECIFICATIONS: - Platform: {prompt_data['platform']} - Video Type: {prompt_data['video_type']} - Script Length: Maximum {prompt_data['length']} words - Tone: {prompt_data['tone']} - Hook Type: {prompt_data['hook_type']} - Storytelling Framework: {prompt_data['storytelling']} - Call to Action: {prompt_data['cta']} PSYCHOLOGICAL TRIGGERS TO INCLUDE: - {prompt_data['psychological_triggers']} Follow this structure: 1. HOOK (0-5 seconds): Use {prompt_data['hook_type']} approach to stop scrolling 2. PROBLEM/CONTEXT (5-15 seconds): Address the specific pain point with empathy 3. SOLUTION/VALUE (15-45 seconds): Present your solution using {prompt_data['storytelling']} framework 4. CALL-TO-ACTION (45-60 seconds): Clear, specific action with urgency Make it authentic, conversational, and optimized for {prompt_data['platform']} consumption patterns. """ response = openai.ChatCompletion.create( model="gpt-4", messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": user_message} ], temperature=0.8 ) return response["choices"][0]["message"]["content"] except Exception as e: st.error(f"Error generating script: {str(e)}") return None def get_platform_requirements(platform): platform_specs = { "Instagram Reels": "Vertical 9:16 format, 15-90 seconds optimal, trending audio integration crucial, captions required for 75% silent viewing, hook in first 3 seconds critical for algorithm", "TikTok": "31-60 seconds optimal (42.7s average), vertical format essential, completion rate prioritized by algorithm, native feel crucial, trending sounds boost reach", "YouTube Shorts": "Up to 3 minutes allowed, vertical 9:16 format, mobile-first consumption, separate Shorts feed optimization, focus on educational value", "LinkedIn": "30 seconds to 2 minutes, professional educational tone, business relevance essential, native uploads preferred, B2B audience focus", "Facebook": "Native uploads over shared links, 74% watched without sound (captions essential), meaningful social interactions prioritized, 1-3 minutes optimal", "Twitter/X": "15 seconds or less optimal for completion, 2:20 maximum, real-time trending integration valuable, concise messaging essential", "Email Marketing": "1-2 minutes maximum, static thumbnail with play button, clear value proposition in preview, fallback content for unsupported clients" } return platform_specs.get(platform, "General social media optimization") def get_hook_strategy(hook_type): hook_strategies = { "Question Hook": "Start with a compelling question that addresses a specific pain point or desire, creating curiosity gaps that compel continued viewing", "Movement Hook": "Begin with dynamic visual action - phone in hand, grabbing props, or physical movement that creates pattern interrupts", "Direct Call-out": "Use attention-grabbing phrases like 'Stop scrolling!' combined with specific audience targeting for immediate relevance", "Problem Statement": "Open by identifying a relatable, frustrating situation your audience experiences daily", "Curiosity Gap": "Hint at valuable information without revealing everything, using phrases like 'What if I told you...'", "Negative Hook": "Address mistakes or problems using loss aversion psychology - 'Stop making this mistake that's costing you...'", "Statistical Hook": "Lead with surprising or compelling data that challenges assumptions or reveals insights", "Story Hook": "Begin with a relatable personal anecdote or customer story that draws viewers into a narrative" } return hook_strategies.get(hook_type, "Create an attention-grabbing opening") def get_storytelling_framework(framework): frameworks = { "Problem-Solution": "Identify specific problem (0-15s) → Agitate consequences (15-30s) → Present solution (30-45s) → Show results (45-60s)", "Before-After": "Show current frustrating situation → Reveal transformation process → Demonstrate improved outcomes with specific benefits", "Hero's Journey": "Position customer as hero facing challenge → Guide them through transformation → Show achieved success state", "Pixar Framework": "Character in routine → Disruption occurs → Consequences unfold → Development happens → Resolution achieved → Clear moral", "Educational Value": "Promise valuable learning → Deliver actionable insights → Demonstrate application → Provide next steps", "Testimonial Story": "Customer introduction → Specific problem → Solution application → Tangible results achieved", "Behind-the-Scenes": "Show authentic process → Reveal human elements → Build trust through transparency → Connect with audience values" } return frameworks.get(framework, "Structure content for maximum engagement") # Initialize session state if 'generated_script' not in st.session_state: st.session_state.generated_script = "" if 'show_form' not in st.session_state: st.session_state.show_form = True if 'script_metadata' not in st.session_state: st.session_state.script_metadata = {} if 'website_analyzed' not in st.session_state: st.session_state.website_analyzed = False if 'extracted_info' not in st.session_state: st.session_state.extracted_info = {} # Header st.markdown('
Create authentic promotional videos that convert viewers into customers using 2024-2025 research insights
', unsafe_allow_html=True) # Benefits section st.markdown("""• 93% of marketers report good ROI from video marketing
• Videos increase engagement by 1200% compared to text
• 34% higher conversion rates with video content
• Authenticity beats production value in 2024-2025
• Platform-optimized scripts for maximum reach!
🎬 Ready to create videos that convert? This tool uses 2024-2025 research insights to maximize your video marketing ROI!