File size: 36,382 Bytes
cac9eab
6198ee8
bd97fba
6198ee8
 
 
 
043548d
 
 
 
 
24b72ba
bd97fba
 
043548d
bd97fba
 
 
 
1e560ed
bd97fba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
043548d
 
 
 
 
 
 
 
bd97fba
 
f2703c6
6198ee8
043548d
6198ee8
043548d
 
 
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
043548d
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
043548d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
6198ee8
bd97fba
 
1c8ff11
043548d
 
 
 
 
bd97fba
043548d
 
 
 
 
 
 
 
 
 
bd97fba
043548d
 
 
 
 
bd97fba
 
 
 
 
043548d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
043548d
bd97fba
 
6198ee8
bd97fba
862456a
bd97fba
 
 
 
1c8ff11
bd97fba
6198ee8
bd97fba
1c8ff11
bd97fba
862456a
 
043548d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
 
 
 
 
043548d
 
6198ee8
 
 
 
84e2e78
bd97fba
043548d
 
862456a
bd97fba
 
 
043548d
 
bd97fba
043548d
 
 
bd97fba
 
862456a
bd97fba
6198ee8
 
bd97fba
6198ee8
bd97fba
6198ee8
 
 
 
bd97fba
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
6198ee8
 
 
 
bd97fba
6198ee8
 
bd97fba
6198ee8
 
 
 
bd97fba
6198ee8
 
 
 
bd97fba
6198ee8
 
bd97fba
6198ee8
 
 
 
 
 
 
 
 
bd97fba
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
6198ee8
 
 
 
 
bd97fba
 
 
043548d
6198ee8
043548d
 
 
 
 
 
 
 
 
6198ee8
043548d
6198ee8
 
 
 
 
 
 
 
 
 
 
043548d
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
043548d
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267080d
bd97fba
 
 
 
043548d
6198ee8
 
bd97fba
 
6198ee8
bd97fba
043548d
6198ee8
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
 
 
 
 
 
 
 
 
043548d
bd97fba
043548d
 
 
6198ee8
bd97fba
 
 
 
 
043548d
 
 
 
 
 
 
 
 
bd97fba
 
84e2e78
bd97fba
 
043548d
 
 
 
 
 
 
 
 
 
 
bd97fba
 
80defbf
bd97fba
 
 
 
80defbf
bd97fba
 
 
 
 
043548d
bd97fba
 
 
043548d
bd97fba
043548d
bd97fba
 
 
 
 
043548d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
 
 
 
043548d
bd97fba
 
043548d
bd97fba
 
 
043548d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd97fba
 
043548d
 
 
 
 
 
 
bd97fba
 
dfc0d11
bd97fba
 
 
 
043548d
bd97fba
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
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
@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"<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)