File size: 3,087 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
import os
import sys
import tempfile
from pathlib import Path
import traceback

class VideoExecutor:
    def __init__(self):
        """Initialize video code executor"""
        self.temp_dir = tempfile.gettempdir()

    def execute_code(self, code, images, audio_path, segment_number):
        """Execute generated code safely and return video path"""

        print(f"⚙️ Executing segment {segment_number} code...")

        # Create execution environment
        exec_globals = {
            '__builtins__': __builtins__,
            'images': images,
            'audio_path': audio_path,
        }

        # Import necessary modules into execution environment
        exec("""

from moviepy.editor import *

import numpy as np

import cv2

from PIL import Image

import random

""", exec_globals)

        try:
            # Execute the generated code
            exec(code, exec_globals)

            # Find the segment creation function
            func_name = f'create_segment_{segment_number}'

            if func_name not in exec_globals:
                raise ValueError(f"❌ Function '{func_name}' not found in generated code")

            # Call the function
            segment_func = exec_globals[func_name]
            clip = segment_func(images, audio_path)

            if clip is None:
                raise ValueError("❌ Function returned None instead of a clip")

            # Render to temp file
            output_path = os.path.join(self.temp_dir, f"segment_{segment_number}_{os.urandom(4).hex()}.mp4")

            print(f"🎬 Rendering segment to: {output_path}")

            clip.write_videofile(
                output_path,
                fps=30,
                codec="libx264",
                audio_codec="aac",
                preset='medium',
                threads=4,
                logger=None
            )

            # Cleanup
            clip.close()

            print(f"✅ Segment {segment_number} rendered successfully")

            return output_path

        except Exception as e:
            print(f"❌ Error executing code: {str(e)}")
            print("Traceback:")
            traceback.print_exc()
            raise e

    def validate_code(self, code):
        """Basic validation of generated code"""

        # Check for dangerous operations
        dangerous_patterns = [
            'os.system',
            'subprocess',
            'eval(',
            '__import__',
            'open(',
            'file(',
        ]

        for pattern in dangerous_patterns:
            if pattern in code:
                raise ValueError(f"⚠️ Potentially dangerous operation detected: {pattern}")

        # Check for required imports
        required_patterns = [
            'from moviepy',
            'def create_segment_',
            'return '
        ]

        for pattern in required_patterns:
            if pattern not in code:
                raise ValueError(f"⚠️ Required pattern missing: {pattern}")