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('

🎬 AI Video Script Generator Pro

', unsafe_allow_html=True) st.markdown('

Create authentic promotional videos that convert viewers into customers using 2024-2025 research insights

', unsafe_allow_html=True) # Benefits section st.markdown("""

📈 Why This Approach Works

• 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!

""", unsafe_allow_html=True) if st.session_state.show_form: # Website URL Analysis Section st.markdown('

🌐 Quick Business Analysis

', unsafe_allow_html=True) col1, col2 = st.columns([3, 1]) with col1: website_url = st.text_input( "Enter your website URL (optional - we'll auto-fill details):", placeholder="e.g., https://yourwebsite.com or yourwebsite.com", help="We'll analyze your website to pre-fill business information" ) with col2: st.markdown("
", unsafe_allow_html=True) # Add spacing if st.button("🔍 Analyze Website", use_container_width=True): if website_url: with st.spinner("🔍 Analyzing your website..."): extracted_info = analyze_website(website_url) st.session_state.extracted_info = extracted_info st.session_state.website_analyzed = True if extracted_info: st.success("✅ Website analyzed! Information has been pre-filled below.") else: st.warning("⚠️ Could not extract all information. Please fill in the details manually.") st.rerun() # Input form - consolidated to 8 key inputs st.markdown('

📝 Video Details (8 Quick Steps)

', unsafe_allow_html=True) # Get pre-filled values from website analysis extracted = st.session_state.extracted_info # Step 1: Business Description business_description = st.text_area( "1️⃣ What does your business do?", value=extracted.get('business', ''), placeholder="e.g., We're a local coffee shop that roasts our own beans and creates custom blends for coffee lovers.", height=80, help="Describe your business in simple terms" ) # Step 2: Problem + Solution Combined col1, col2 = st.columns(2) with col1: problem_solved = st.text_input( "2️⃣ What problem do you solve?", value=extracted.get('problem', ''), placeholder="e.g., Busy professionals need great coffee fast", help="The main pain point you address" ) with col2: services_offered = st.text_input( "3️⃣ Main services/products?", value=extracted.get('services', ''), placeholder="e.g., Custom blends, catering, subscriptions", help="2-3 key offerings to highlight" ) # Step 3: Business Name + Unique Value col1, col2 = st.columns(2) with col1: name_to_include = st.text_input( "4️⃣ Business name:", value=extracted.get('name', ''), placeholder="e.g., Downtown Coffee Co.", help="How to reference your business" ) with col2: unique_aspects = st.text_input( "5️⃣ What makes you unique?", value=extracted.get('unique', ''), placeholder="e.g., Only shop with daily on-site roasting", help="Your key differentiator" ) # Step 4: Target + Platform Combined col1, col2 = st.columns(2) with col1: # Determine target audience from extracted info or provide options audience_options = [ "Local Community", "Young Professionals (25-35)", "Small Business Owners", "Families with Children", "Seniors (55+)", "Students", "Health-Conscious Consumers", "Industry Professionals", "Budget-Conscious Shoppers", "Luxury Market" ] # Try to match extracted audience to options default_audience = 0 extracted_audience = extracted.get('audience', '').lower() for i, option in enumerate(audience_options): if any(keyword in extracted_audience for keyword in option.lower().split()): default_audience = i break target_audience = st.selectbox( "6️⃣ Target audience:", audience_options, index=default_audience, help="Who are you trying to reach?" ) with col2: platform = st.selectbox( "7️⃣ Primary platform:", [ "Instagram Reels", "TikTok", "YouTube Shorts", "LinkedIn", "Facebook", "Twitter/X", "Email Marketing" ], help="Where will you post this video?" ) # Step 5: Call to Action call_to_action = st.text_input( "8️⃣ What should viewers do next?", placeholder="e.g., Visit us at 123 Main Street or order online", help="One clear, specific action" ) # Advanced Options (Collapsible) with st.expander("🎯 Advanced Options (Optional)"): col1, col2, col3 = st.columns(3) with col1: video_type = st.selectbox( "Video Type:", [ "Product/Service Showcase", "Problem-Solution Focused", "Educational/How-To", "Behind-the-Scenes", "Customer Success Story", "Brand Awareness", "Promotional Offer" ] ) tone = st.selectbox( "Tone:", [ "Friendly & Conversational", "Professional & Trustworthy", "Exciting & Energetic", "Warm & Personal", "Educational & Expert", "Authentic & Real" ] ) with col2: hook_type = st.selectbox( "Hook Strategy:", [ "Question Hook", "Problem Statement", "Curiosity Gap", "Direct Call-out", "Statistical Hook", "Story Hook" ] ) storytelling_framework = st.selectbox( "Story Structure:", [ "Problem-Solution", "Before-After", "Educational Value", "Testimonial Story", "Behind-the-Scenes" ] ) with col3: psychological_triggers = st.multiselect( "Psychological Triggers:", [ "Social Proof", "Scarcity/FOMO", "Authority", "Curiosity", "Empathy" ], default=["Social Proof", "Curiosity"] ) script_length = st.slider( "Length (words):", min_value=50, max_value=300, value=150, step=25 ) # Platform-specific tips platform_tips = { "Instagram Reels": "📱 Vertical format • 15-90 seconds • Use trending audio • Captions required", "TikTok": "🎵 31-60 seconds optimal • Completion rate crucial • Native feel important", "YouTube Shorts": "📺 Up to 3 minutes • Educational content performs well • Mobile-first", "LinkedIn": "💼 Professional tone • 30 seconds-2 minutes • Business value focus", "Facebook": "👥 Native uploads preferred • 74% watch without sound • Captions essential", "Twitter/X": "⚡ 15 seconds optimal • Real-time relevance • Concise messaging", "Email Marketing": "📧 1-2 minutes max • Clear thumbnail • Value-focused preview" } st.markdown(f"""
📋 {platform} Tips: {platform_tips.get(platform, "General optimization")}
""", unsafe_allow_html=True) # Generate button st.markdown("
", unsafe_allow_html=True) col1, col2, col3 = st.columns([1, 2, 1]) with col2: if st.button("🚀 Generate My Optimized Video Script", use_container_width=True): # Validation - only require essential fields required_fields = [business_description, problem_solved, services_offered, name_to_include, call_to_action] if not all(required_fields): st.error("⚠️ Please fill in the required fields (1-5 and 8) to generate your script.") else: with st.spinner("🎬 Crafting your conversion-optimized video script..."): # Set defaults for advanced options if not specified if 'video_type' not in locals(): video_type = "Product/Service Showcase" if 'tone' not in locals(): tone = "Friendly & Conversational" if 'hook_type' not in locals(): hook_type = "Question Hook" if 'storytelling_framework' not in locals(): storytelling_framework = "Problem-Solution" if 'psychological_triggers' not in locals(): psychological_triggers = ["Social Proof", "Curiosity"] if 'script_length' not in locals(): script_length = 150 prompt_data = { 'business': business_description, 'problem': problem_solved, 'services': services_offered, 'unique': unique_aspects, 'name': name_to_include, 'cta': call_to_action, 'length': script_length, 'tone': tone, 'platform': platform, 'video_type': video_type, 'audience': target_audience, 'hook_type': hook_type, 'storytelling': storytelling_framework, 'psychological_triggers': ", ".join(psychological_triggers) if isinstance(psychological_triggers, list) else psychological_triggers } script = generate_video_script(prompt_data) if script: st.session_state.generated_script = script st.session_state.script_metadata = { 'business_name': name_to_include, 'platform': platform, 'video_type': video_type, 'length': script_length, 'tone': tone, 'hook_type': hook_type, 'storytelling': storytelling_framework } st.session_state.show_form = False st.rerun() # Display generated script if st.session_state.generated_script and not st.session_state.show_form: st.markdown('

🎬 Your Optimized Video Script is Ready!

', unsafe_allow_html=True) # Script metadata display metadata = st.session_state.script_metadata col1, col2, col3 = st.columns(3) with col1: st.metric("Platform", metadata.get('platform', 'N/A')) with col2: st.metric("Hook Strategy", metadata.get('hook_type', 'N/A')) with col3: st.metric("Length", f"{metadata.get('length', 'N/A')} words") # Script display formatted_script = st.session_state.generated_script.replace('\n', '
') st.markdown(f"""

📜 Your Promotional Video Script

{formatted_script}
""", unsafe_allow_html=True) # Action buttons col1, col2, col3, col4 = st.columns([1, 1, 1, 1]) with col1: st.download_button( label="📥 Download TXT", data=st.session_state.generated_script, file_name=f"video_script_{metadata.get('business_name', 'business').replace(' ', '_').lower()}.txt", mime="text/plain", use_container_width=True ) with col2: # PDF download button if st.button("📄 Download PDF", use_container_width=True): pdf_buffer = create_pdf( st.session_state.generated_script, metadata.get('business_name', 'Your Business'), metadata.get('platform', 'General'), metadata.get('video_type', 'Promotional') ) st.download_button( label="📄 Download PDF", data=pdf_buffer.getvalue(), file_name=f"video_script_{metadata.get('business_name', 'business').replace(' ', '_').lower()}.pdf", mime="application/pdf", use_container_width=True, key="pdf_download" ) with col3: if st.button("✏️ Edit Details", use_container_width=True): st.session_state.show_form = True st.rerun() with col4: if st.button("🔄 Generate New Script", use_container_width=True): st.session_state.generated_script = "" st.session_state.script_metadata = {} st.session_state.show_form = True st.rerun() # Platform-specific tips for recording platform_recording_tips = { "Instagram Reels": "• Record in vertical format (9:16) • Use trending audio or original sound • Add captions for accessibility • Post when your audience is most active • Use relevant hashtags", "TikTok": "• Keep it authentic and native-looking • Use trending sounds when possible • Focus on completion rate • Engage with comments quickly • Post consistently", "YouTube Shorts": "• Create compelling thumbnails • Use YouTube Shorts hashtag • Focus on educational value • Optimize title and description • Create playlist for shorts", "LinkedIn": "• Professional backdrop and attire • Focus on business value • Use industry-relevant hashtags • Tag relevant connections • Post during business hours", "Facebook": "• Upload natively to Facebook • Include captions for silent viewing • Use Facebook's video features • Cross-post to appropriate groups • Encourage meaningful comments", "Twitter/X": "• Keep it concise and punchy • Use relevant trending hashtags • Tweet at optimal times • Engage with replies • Consider Twitter Spaces for longer content", "Email Marketing": "• Create compelling thumbnail image • Include clear play button • Have fallback text for unsupported clients • Keep file size under 10MB • Test across email clients" } current_platform = metadata.get('platform', 'General') recording_tips = platform_recording_tips.get(current_platform, "• Practice reading the script 2-3 times • Speak clearly and at moderate pace • Maintain eye contact with camera • Use good lighting • Keep background simple") st.markdown(f"""

🎯 Recording Tips for {current_platform}:

{recording_tips}

Universal Best Practices:
• Test your setup before final recording
• Record multiple takes and choose the best
• Ensure good audio quality
• Review for authenticity and energy
""", unsafe_allow_html=True) # Performance optimization tips st.markdown("""

📊 Maximize Your Video Performance:

• Post when your audience is most active
• Respond to comments within the first hour
• Use platform-specific features (polls, stickers, etc.)
• Track completion rates and engagement metrics
• A/B test different hooks and CTAs
• Repurpose successful content across platforms
""", unsafe_allow_html=True) # Footer st.markdown("

", unsafe_allow_html=True) st.markdown("""

🎬 Ready to create videos that convert? This tool uses 2024-2025 research insights to maximize your video marketing ROI!

""", unsafe_allow_html=True)