Spaces:
Sleeping
Sleeping
| 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(""" | |
| <style> | |
| .main-header { | |
| text-align: center; | |
| color: #1f4e79; | |
| font-size: 3rem; | |
| font-weight: bold; | |
| margin-bottom: 0.5rem; | |
| } | |
| .sub-header { | |
| text-align: center; | |
| color: #666; | |
| font-size: 1.2rem; | |
| margin-bottom: 2rem; | |
| } | |
| .section-header { | |
| color: #1f4e79; | |
| font-size: 1.5rem; | |
| font-weight: bold; | |
| margin-top: 2rem; | |
| margin-bottom: 1rem; | |
| border-bottom: 2px solid #e0e0e0; | |
| padding-bottom: 0.5rem; | |
| } | |
| .highlight-box { | |
| background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| padding: 2rem; | |
| border-radius: 15px; | |
| color: white; | |
| margin: 2rem 0; | |
| } | |
| .feature-box { | |
| background: #f8f9fa; | |
| padding: 1.5rem; | |
| border-radius: 10px; | |
| border-left: 4px solid #667eea; | |
| margin: 1rem 0; | |
| } | |
| .script-output { | |
| background: #ffffff; | |
| padding: 2rem; | |
| border-radius: 15px; | |
| border: 2px solid #e0e0e0; | |
| box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); | |
| margin: 2rem 0; | |
| } | |
| .stButton > button { | |
| background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| color: white; | |
| border: none; | |
| padding: 0.75rem 2rem; | |
| border-radius: 25px; | |
| font-weight: bold; | |
| font-size: 1.1rem; | |
| transition: all 0.3s ease; | |
| } | |
| .stButton > button:hover { | |
| transform: translateY(-2px); | |
| box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); | |
| } | |
| .platform-tips { | |
| background: #e8f4fd; | |
| padding: 1rem; | |
| border-radius: 8px; | |
| border-left: 4px solid #2196F3; | |
| margin: 1rem 0; | |
| font-size: 0.9rem; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # Initialize OpenAI API key | |
| 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"<b>Platform:</b> {platform}", content_style)) | |
| story.append(Paragraph(f"<b>Video Type:</b> {video_type}", content_style)) | |
| story.append(Spacer(1, 20)) | |
| # Script content | |
| story.append(Paragraph("<b>Script:</b>", 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('<h1 class="main-header">π¬ AI Video Script Generator Pro</h1>', unsafe_allow_html=True) | |
| st.markdown('<p class="sub-header">Create authentic promotional videos that convert viewers into customers using 2024-2025 research insights</p>', unsafe_allow_html=True) | |
| # Benefits section | |
| st.markdown(""" | |
| <div class="highlight-box"> | |
| <h3>π Why This Approach Works</h3> | |
| <p>β’ 93% of marketers report good ROI from video marketing<br> | |
| β’ Videos increase engagement by 1200% compared to text<br> | |
| β’ 34% higher conversion rates with video content<br> | |
| β’ Authenticity beats production value in 2024-2025<br> | |
| β’ Platform-optimized scripts for maximum reach!</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| if st.session_state.show_form: | |
| # Website URL Analysis Section | |
| st.markdown('<h2 class="section-header">π Quick Business Analysis</h2>', 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("<br>", 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('<h2 class="section-header">π Video Details (8 Quick Steps)</h2>', 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""" | |
| <div class="platform-tips"> | |
| <strong>π {platform} Tips:</strong> {platform_tips.get(platform, "General optimization")} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Generate button | |
| st.markdown("<br>", 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('<h2 class="section-header">π¬ Your Optimized Video Script is Ready!</h2>', 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', '<br>') | |
| st.markdown(f""" | |
| <div class="script-output"> | |
| <h3 style="color: #1f4e79; margin-bottom: 1rem;">π Your Promotional Video Script</h3> | |
| <div style="font-size: 1.1rem; line-height: 1.6; color: #333;"> | |
| {formatted_script} | |
| </div> | |
| </div> | |
| """, 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""" | |
| <div class="feature-box"> | |
| <h4>π― Recording Tips for {current_platform}:</h4> | |
| {recording_tips}<br><br> | |
| <strong>Universal Best Practices:</strong><br> | |
| β’ Test your setup before final recording<br> | |
| β’ Record multiple takes and choose the best<br> | |
| β’ Ensure good audio quality<br> | |
| β’ Review for authenticity and energy | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Performance optimization tips | |
| st.markdown(""" | |
| <div class="feature-box"> | |
| <h4>π Maximize Your Video Performance:</h4> | |
| β’ Post when your audience is most active<br> | |
| β’ Respond to comments within the first hour<br> | |
| β’ Use platform-specific features (polls, stickers, etc.)<br> | |
| β’ Track completion rates and engagement metrics<br> | |
| β’ A/B test different hooks and CTAs<br> | |
| β’ Repurpose successful content across platforms | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Footer | |
| st.markdown("<br><br>", unsafe_allow_html=True) | |
| st.markdown(""" | |
| <div style="text-align: center; color: #666; padding: 2rem;"> | |
| <p>π¬ Ready to create videos that convert? This tool uses 2024-2025 research insights to maximize your video marketing ROI!</p> | |
| </div> | |
| """, unsafe_allow_html=True) |