File size: 2,335 Bytes
89c42ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Nástroje pro bezpečné spuštění a validaci Python skriptů.
"""
import io
import sys
from contextlib import redirect_stdout, redirect_stderr

def safe_execute_script(script_code, context=None):
    """
    Safely execute Python script with limited context
    Returns script output or error message
    """
    if context is None:
        context = {
            'video_path': None,
            'frame_data': None,
            'metadata': None
        }
    
    output = io.StringIO()
    error = io.StringIO()
    
    try:
        with redirect_stdout(output), redirect_stderr(error):
            exec_globals = {
                '__builtins__': {
                    'print': print,
                    'str': str,
                    'int': int,
                    'float': float,
                    'list': list,
                    'dict': dict,
                    'tuple': tuple,
                    'range': range,
                    'len': len,
                    'enumerate': enumerate,
                    'zip': zip,
                    'min': min,
                    'max': max,
                    'sum': sum,
                    'abs': abs,
                    'round': round
                },
                'context': context
            }
            
            exec(script_code, exec_globals)
        
        if error.getvalue():
            return f"Error: {error.getvalue()}"
        else:
            return output.getvalue()
        
    except Exception as e:
        return f"Error executing script: {str(e)}"


def validate_python_script(script_code):
    """
    Validate Python script syntax and restricted functions
    Returns (is_valid, error_message)
    """
    import ast
    
    try:
        tree = ast.parse(script_code)
        
        for node in ast.walk(tree):
            if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
                return (False, "Import statements are not allowed")
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
                if node.func.id in ['eval', 'exec', 'open', 'execfile']:
                    return (False, f"Function {node.func.id}() is not allowed")
        
        return (True, "Script is valid")
    except SyntaxError as e:
        return (False, f"Syntax error: {str(e)}")