File size: 24,079 Bytes
44cb2cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
import tempfile
from pathlib import Path
import time
import gc
from PIL import Image, ImageOps
import io
import json
from moviepy.editor import VideoFileClip, concatenate_videoclips

from ai_video_analyzer import VideoAnalyzer
from code_generator import VideoCodeGenerator
from video_executor import VideoExecutor

# Page config
st.set_page_config(
    page_title="AI Video Editor V2",
    page_icon="πŸ€–",
    layout="wide"
)

# Custom CSS
st.markdown("""

<style>

    .main-header {

        font-size: 3rem;

        font-weight: 700;

        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);

        -webkit-background-clip: text;

        -webkit-text-fill-color: transparent;

        text-align: center;

        margin-bottom: 1rem;

    }

    .sub-header {

        text-align: center;

        color: #666;

        font-size: 1.2rem;

        margin-bottom: 2rem;

    }

    .stButton>button {

        width: 100%;

        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);

        color: white;

        border: none;

        padding: 0.75rem 1.5rem;

        font-size: 1rem;

        font-weight: 600;

        border-radius: 8px;

        transition: all 0.3s;

    }

    .stButton>button:hover {

        transform: translateY(-2px);

        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);

    }

    .segment-card {

        background: #f8f9fa;

        border-radius: 10px;

        padding: 1.5rem;

        margin: 1rem 0;

        border: 2px solid #e9ecef;

    }

    .video-container {

        border-radius: 15px;

        overflow: hidden;

        box-shadow: 0 10px 30px rgba(0,0,0,0.2);

    }

    .api-key-box {

        background: #fff3cd;

        border: 2px solid #ffc107;

        border-radius: 8px;

        padding: 1rem;

        margin: 1rem 0;

    }

</style>

""", unsafe_allow_html=True)

TARGET_SIZE = (1080, 1920)  # 9:16 aspect ratio

def init_session_state():
    """Initialize session state variables"""
    defaults = {
        'video_ready': False,
        'output_path': None,
        'analysis': None,
        'segments': [],
        'current_segment': 0,
        'approved_clips': [],
        'user_images_paths': [],
        'reference_video_path': None,
        'audio_path': None,
        'current_code': None,
        'preview_path': None,
        'api_key_valid': False
    }
    
    for key, value in defaults.items():
        if key not in st.session_state:
            st.session_state[key] = value

def process_image_to_portrait(image_file):
    """Fix phone orientation and force resize to 9:16 (1080x1920)"""
    try:
        image_bytes = image_file.getvalue()
        img = Image.open(io.BytesIO(image_bytes))
        
        if img.mode != 'RGB':
            img = img.convert('RGB')
        
        # Fix orientation using EXIF
        img = ImageOps.exif_transpose(img)
        
        # Force 9:16 aspect ratio
        target_width, target_height = TARGET_SIZE
        target_ratio = target_width / target_height
        current_width, current_height = img.size
        current_ratio = current_width / current_height
        
        if current_ratio > target_ratio:
            # Crop width
            new_width = int(target_ratio * current_height)
            left = (current_width - new_width) // 2
            img = img.crop((left, 0, left + new_width, current_height))
        else:
            # Crop height
            new_height = int(current_width / target_ratio)
            top = (current_height - new_height) // 2
            img = img.crop((0, top, current_width, top + new_height))
        
        # Resize to exact dimensions
        img = img.resize(TARGET_SIZE, Image.Resampling.LANCZOS)
        
        return img
    except Exception as e:
        st.warning(f"⚠️ Error processing image: {str(e)}")
        return None

def save_uploaded_images(uploaded_images):
    """Save and process uploaded images"""
    temp_dir = tempfile.mkdtemp()
    image_paths = []
    
    for idx, img_file in enumerate(uploaded_images):
        processed_img = process_image_to_portrait(img_file)
        if processed_img:
            try:
                path = os.path.join(temp_dir, f"img_{idx:03d}.jpg")
                processed_img.save(path, 'JPEG', quality=95, optimize=True)
                image_paths.append(path)
                processed_img.close()
            except Exception as e:
                st.warning(f"⚠️ Could not save image {idx+1}: {str(e)}")
        
        if idx % 5 == 0:
            gc.collect()
    
    return image_paths

def extract_audio_from_video(video_path):
    """Extract audio from video file"""
    try:
        video = VideoFileClip(video_path)
        audio_path = os.path.join(tempfile.gettempdir(), "reference_audio.mp3")
        
        if video.audio is not None:
            video.audio.write_audiofile(audio_path, logger=None)
            video.close()
            return audio_path
        else:
            video.close()
            st.warning("⚠️ Reference video has no audio")
            return None
    except Exception as e:
        st.error(f"Error extracting audio: {e}")
        return None

def main():
    init_session_state()
    
    # Header
    st.markdown('<div class="main-header">πŸ€– AI Video Editor V2</div>', unsafe_allow_html=True)
    st.markdown('<div class="sub-header">Transform any reel with AI-powered video generation</div>', unsafe_allow_html=True)
    
    # API Key input in sidebar - REQUIRED FOR USER INPUT
    with st.sidebar:
        st.markdown("### πŸ”‘ API Configuration")
        
        st.markdown("""

        <div class="api-key-box">

        <strong>⚠️ API Key Required</strong><br>

        Get your <strong>FREE</strong> Gemini API key from:<br>

        <a href="https://aistudio.google.com/apikey" target="_blank">

        https://aistudio.google.com/apikey

        </a>

        </div>

        """, unsafe_allow_html=True)
        
        api_key = st.text_input(
            "Enter Your Gemini API Key", 
            type="password",
            help="Your API key is never stored. It's only used for this session.",
            placeholder="Enter your API key here..."
        )
        
        if not api_key:
            st.error("⚠️ Please enter your API key to use the app")
            st.info("""

            **Free Tier Limits:**

            - βœ… 10 requests/minute

            - βœ… 250 requests/day

            - βœ… 250K tokens/minute

            - βœ… Completely FREE

            """)
        else:
            st.success("βœ… API Key configured")
            st.session_state.api_key_valid = True
        
        st.markdown("---")
        st.markdown("### πŸ“Š Progress")
        if st.session_state.segments:
            progress = st.session_state.current_segment / len(st.session_state.segments)
            st.progress(progress)
            st.metric("Segments Approved", f"{len(st.session_state.approved_clips)}/{len(st.session_state.segments)}")
        
        st.markdown("---")
        st.markdown("### πŸ’‘ How It Works")
        st.markdown("""

        1. Upload reference video & photos

        2. AI analyzes video structure

        3. Review each 3-second segment

        4. Approve or regenerate

        5. Download final video

        """)
    
    # Main content - only show if API key is provided
    if not api_key:
        st.warning("πŸ‘ˆ Please enter your Gemini API key in the sidebar to get started")
        
        # Show demo/instructions
        st.markdown("## 🎬 How This Works")
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.markdown("### 1️⃣ Upload")
            st.info("Upload a reference reel and your photos")
        
        with col2:
            st.markdown("### 2️⃣ AI Analysis")
            st.info("AI analyzes transitions, timing, and effects")
        
        with col3:
            st.markdown("### 3️⃣ Generate")
            st.info("Review and approve each segment")
        
        st.markdown("---")
        st.markdown("### πŸ†“ Free Tier Benefits")
        st.success("""

        With Gemini 2.5 Flash free tier, you can:

        - Create 3-4 complete videos per day

        - Analyze videos up to 60 seconds

        - Generate 20-30 segments per video

        - **100% FREE - No credit card required**

        """)
        
        return
    
    # Main tabs
    tab1, tab2, tab3, tab4 = st.tabs(["πŸ“€ Upload", "πŸ” Analysis", "🎬 Generation", "⬇️ Download"])
    
    with tab1:
        upload_section(api_key)
    
    with tab2:
        analysis_section()
    
    with tab3:
        generation_section(api_key)
    
    with tab4:
        download_section()

def upload_section(api_key):
    """Upload reference video and user images"""
    st.markdown("## πŸ“€ Upload Your Content")
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("### πŸŽ₯ Reference Video")
        st.markdown("Upload the reel/video you want to recreate")
        reference_video = st.file_uploader(
            "Upload reference video",
            type=['mp4', 'mov', 'avi', 'mkv'],
            help="This video will be analyzed for transitions, timing, and effects"
        )
        
        if reference_video:
            st.video(reference_video)
    
    with col2:
        st.markdown("### πŸ“Έ Your Photos")
        st.markdown("Upload photos to use in your video")
        user_images = st.file_uploader(
            "Upload your photos",
            type=['jpg', 'jpeg', 'png'],
            accept_multiple_files=True,
            help="Upload 5-20 photos for best results"
        )
        
        if user_images:
            st.info(f"βœ… {len(user_images)} photos uploaded")
            # Show thumbnail grid
            cols = st.columns(5)
            for idx, img in enumerate(user_images[:10]):
                with cols[idx % 5]:
                    st.image(img, use_container_width=True)
            if len(user_images) > 10:
                st.caption(f"...and {len(user_images) - 10} more")
    
    st.markdown("---")
    
    if reference_video and user_images:
        if st.button("πŸš€ Analyze Video & Start Generation", width=200):
            with st.spinner("πŸ” Analyzing reference video..."):
                try:
                    # Save reference video
                    with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_video:
                        tmp_video.write(reference_video.read())
                        video_path = tmp_video.name
                    
                    st.session_state.reference_video_path = video_path
                    
                    # Extract audio
                    audio_path = extract_audio_from_video(video_path)
                    st.session_state.audio_path = audio_path
                    
                    # Process and save user images
                    with st.spinner("πŸ“Έ Processing your photos..."):
                        image_paths = save_uploaded_images(user_images)
                        st.session_state.user_images_paths = image_paths
                    
                    # Analyze video
                    with st.spinner("πŸ€– AI is analyzing the video structure..."):
                        analyzer = VideoAnalyzer(api_key)
                        analysis = analyzer.analyze_reference_video(video_path)
                        st.session_state.analysis = analysis
                        st.session_state.segments = analysis['segments']
                    
                    st.success("βœ… Analysis complete! Go to 'Analysis' tab to review")
                    st.balloons()
                    
                except Exception as e:
                    st.error(f"❌ Error during analysis: {str(e)}")
                    st.exception(e)
    else:
        if not reference_video:
            st.info("πŸ‘† Upload a reference video to begin")
        elif not user_images:
            st.info("πŸ‘† Upload your photos to continue")

def analysis_section():
    """Display video analysis results"""
    if not st.session_state.analysis:
        st.info("πŸ‘ˆ Upload and analyze a video first in the Upload tab")
        return
    
    st.markdown("## πŸ” Video Analysis Results")
    
    analysis = st.session_state.analysis
    
    # Summary metrics
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("Duration", f"{analysis['duration']:.1f}s")
    with col2:
        st.metric("Segments", len(analysis['segments']))
    with col3:
        st.metric("FPS", analysis.get('fps', 30))
    with col4:
        st.metric("Style", analysis.get('style', 'Modern'))
    
    st.markdown("---")
    
    # Detailed segment breakdown
    st.markdown("### πŸ“‹ Segment Breakdown")
    
    for idx, segment in enumerate(analysis['segments']):
        with st.expander(f"Segment {idx + 1}: {segment['start_time']:.1f}s - {segment['end_time']:.1f}s"):
            col1, col2 = st.columns(2)
            
            with col1:
                st.markdown(f"**Duration:** {segment['duration']:.2f}s")
                st.markdown(f"**Transition In:** {segment['transition_in']}")
                st.markdown(f"**Transition Out:** {segment['transition_out']}")
            
            with col2:
                st.markdown(f"**Camera Movement:** {segment['camera_movement']}")
                st.markdown(f"**Zoom Level:** {segment['zoom_level']}")
                st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
    
    st.markdown("---")
    
    # Start generation button
    if st.button("✨ Start Video Generation", use_container_width=True):
        st.session_state.current_segment = 0
        st.session_state.approved_clips = []
        st.info("πŸ‘‰ Go to 'Generation' tab to create your video!")
        st.rerun()

def generation_section(api_key):
    """Iterative segment generation with human-in-the-loop"""
    if not st.session_state.segments:
        st.info("πŸ‘ˆ Analyze a video first in the Analysis tab")
        return
    
    current_idx = st.session_state.current_segment
    total_segments = len(st.session_state.segments)
    
    if current_idx >= total_segments:
        st.success("πŸŽ‰ All segments completed! Go to Download tab to render final video")
        return
    
    st.markdown(f"## 🎬 Segment {current_idx + 1} / {total_segments}")
    
    segment = st.session_state.segments[current_idx]
    
    # Segment info card
    st.markdown('<div class="segment-card">', unsafe_allow_html=True)
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("Time", f"{segment['start_time']:.1f}s - {segment['end_time']:.1f}s")
    with col2:
        st.metric("Duration", f"{segment['duration']:.2f}s")
    with col3:
        st.metric("Transition", segment['transition_in'])
    
    st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
    st.markdown(f"**Camera:** {segment['camera_movement']}")
    st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # Generate button
    col1, col2 = st.columns([3, 1])
    with col1:
        if st.button("🎬 Generate This Segment", use_container_width=True):
            generate_segment(api_key, segment, current_idx)
    
    with col2:
        if st.button("⏭️ Skip", use_container_width=True):
            st.session_state.current_segment += 1
            st.rerun()
    
    # Show preview if generated
    if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
        st.markdown("### πŸŽ₯ Preview")
        st.markdown('<div class="video-container">', unsafe_allow_html=True)
        st.video(st.session_state.preview_path)
        st.markdown('</div>', unsafe_allow_html=True)
        
        # Show generated code
        if st.session_state.current_code:
            with st.expander("πŸ“ View Generated Code"):
                st.code(st.session_state.current_code, language='python')
        
        st.markdown("---")
        
        # Approval actions
        st.markdown("### βœ… Review & Approve")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            if st.button("βœ… Approve & Continue", use_container_width=True, type="primary"):
                st.session_state.approved_clips.append(st.session_state.preview_path)
                st.session_state.current_segment += 1
                st.session_state.preview_path = None
                st.session_state.current_code = None
                st.success("Segment approved!")
                time.sleep(0.5)
                st.rerun()
        
        with col2:
            feedback = st.text_input("What needs improvement?", key=f"feedback_{current_idx}")
            if st.button("πŸ”„ Regenerate", use_container_width=True) and feedback:
                regenerate_segment(api_key, segment, current_idx, feedback)
        
        with col3:
            if st.button("❌ Discard & Skip", use_container_width=True):
                if os.path.exists(st.session_state.preview_path):
                    os.remove(st.session_state.preview_path)
                st.session_state.current_segment += 1
                st.session_state.preview_path = None
                st.session_state.current_code = None
                st.rerun()

def generate_segment(api_key, segment, segment_idx):
    """Generate code and video for a segment"""
    try:
        with st.spinner("πŸ€– Generating code..."):
            generator = VideoCodeGenerator(api_key)
            
            # Get previous code for context
            previous_code = st.session_state.current_code if segment_idx > 0 else None
            
            # Generate code
            code = generator.generate_segment_code(
                segment,
                st.session_state.user_images_paths,
                st.session_state.audio_path or st.session_state.reference_video_path,
                segment_idx,
                previous_code
            )
            
            st.session_state.current_code = code
        
        with st.spinner("🎬 Rendering video..."):
            # Execute code
            executor = VideoExecutor()
            video_path = executor.execute_code(
                code,
                st.session_state.user_images_paths,
                st.session_state.audio_path or st.session_state.reference_video_path,
                segment_idx
            )
            
            st.session_state.preview_path = video_path
            st.success("βœ… Segment generated!")
            st.rerun()
            
    except Exception as e:
        st.error(f"❌ Error generating segment: {str(e)}")
        with st.expander("πŸ› Error Details"):
            st.exception(e)

def regenerate_segment(api_key, segment, segment_idx, feedback):
    """Regenerate segment based on user feedback"""
    try:
        with st.spinner(f"πŸ”„ Regenerating with feedback: '{feedback}'..."):
            generator = VideoCodeGenerator(api_key)
            
            # Regenerate with feedback
            new_code = generator.regenerate_segment(
                segment,
                feedback,
                st.session_state.current_code,
                segment_idx
            )
            
            st.session_state.current_code = new_code
        
        with st.spinner("🎬 Rendering updated video..."):
            executor = VideoExecutor()
            video_path = executor.execute_code(
                new_code,
                st.session_state.user_images_paths,
                st.session_state.audio_path or st.session_state.reference_video_path,
                segment_idx
            )
            
            # Remove old preview
            if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
                os.remove(st.session_state.preview_path)
            
            st.session_state.preview_path = video_path
            st.success("βœ… Segment regenerated!")
            st.rerun()
            
    except Exception as e:
        st.error(f"❌ Error regenerating segment: {str(e)}")
        st.exception(e)

def download_section():
    """Render and download final video"""
    if not st.session_state.approved_clips:
        st.info("πŸ‘ˆ Generate and approve segments first in the Generation tab")
        return
    
    st.markdown("## ⬇️ Final Video")
    
    total_segments = len(st.session_state.segments)
    approved_count = len(st.session_state.approved_clips)
    
    col1, col2 = st.columns(2)
    with col1:
        st.metric("Total Segments", total_segments)
    with col2:
        st.metric("Approved Segments", approved_count)
    
    if approved_count < total_segments:
        st.warning(f"⚠️ You have only approved {approved_count}/{total_segments} segments. Continue to Generation tab to complete all segments.")
    
    st.markdown("---")
    
    if st.button("πŸŽ₯ Render Final Video", use_container_width=True, type="primary"):
        render_final_video()
    
    # Show final video if already rendered
    if st.session_state.output_path and os.path.exists(st.session_state.output_path):
        st.markdown("### πŸŽ‰ Your Final Video")
        st.markdown('<div class="video-container">', unsafe_allow_html=True)
        st.video(st.session_state.output_path)
        st.markdown('</div>', unsafe_allow_html=True)
        
        # Download button
        with open(st.session_state.output_path, 'rb') as f:
            video_bytes = f.read()
            st.download_button(
                label="πŸ“₯ Download Video",
                data=video_bytes,
                file_name="ai_generated_video.mp4",
                mime="video/mp4",
                use_container_width=True
            )

def render_final_video():
    """Combine all approved segments into final video"""
    try:
        with st.spinner("🎬 Combining segments..."):
            clips = []
            for path in st.session_state.approved_clips:
                if os.path.exists(path):
                    clip = VideoFileClip(path)
                    clips.append(clip)
            
            if not clips:
                st.error("❌ No valid clips to combine")
                return
            
            # Concatenate clips
            final_clip = concatenate_videoclips(clips, method="compose")
            
            # Output path
            output_path = os.path.join(tempfile.gettempdir(), "final_ai_video.mp4")
            
            # Write final video
            final_clip.write_videofile(
                output_path,
                fps=30,
                codec="libx264",
                audio_codec="aac",
                threads=4,
                logger=None
            )
            
            # Cleanup
            for clip in clips:
                clip.close()
            final_clip.close()
            
            st.session_state.output_path = output_path
            st.session_state.video_ready = True
            
            st.success("βœ… Final video rendered successfully!")
            st.balloons()
            st.rerun()
            
    except Exception as e:
        st.error(f"❌ Error rendering final video: {str(e)}")
        st.exception(e)

if __name__ == "__main__":
    main()