Spaces:
Sleeping

File size: 6,430 Bytes
f859d51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Purpose: CPU bypass for python code execution (sandbox, no LLM/GPU)
from __future__ import annotations

import ast
import io
import re
import sys
import time
import traceback
from contextlib import redirect_stdout, redirect_stderr
from typing import Optional

CODE_PREFIXES = ("/py", "/python", "/code", "/run")
BLOCK_RE = re.compile(r"```(?:python)?\s*(.*?)\s*```", re.DOTALL | re.IGNORECASE)

# blocked imports / calls
BLOCKED_NAMES = {
    "os", "sys", "subprocess", "socket", "shutil", "pathlib", "open",
    "eval", "exec", "compile", "__import__", "input", "exit", "quit",
}
BLOCKED_ATTRS = {"system", "popen", "remove", "rmdir", "unlink", "write", "call"}

MAX_OUTPUT = 4000
TIMEOUT_SEC = 3  # soft, we check elapsed during exec via timeout logic


def _extract_code(message: str) -> tuple[str, bool]:
    """Extract code from message. Returns (code, had_prefix)."""
    s = message.strip()
    low = s.lower()
    for p in CODE_PREFIXES:
        if low.startswith(p):
            body = s[len(p):].strip(" :\n")
            # if body wrapped in ```, extract
            m = BLOCK_RE.search(body)
            if m:
                body = m.group(1)
            return body.strip(), True
    # check for ```python block without prefix
    m = BLOCK_RE.search(s)
    if m:
        code = m.group(1).strip()
        # only treat as code if it looks like python (has def/class/import/print/for)
        if re.search(r"\b(def|class|import|print|for|while|if|return)\b", code):
            return code, True
    return s, False


def should_bypass_llm(message: str) -> bool:
    if not message or not message.strip():
        return False
    low = message.strip().lower()
    for p in CODE_PREFIXES:
        if low.startswith(p):
            return True
    if BLOCK_RE.search(message):
        code, _ = _extract_code(message)
        if code and len(code) < 2000:
            return True
    return False


def _is_safe(node: ast.AST) -> tuple[bool, str]:
    """Basic AST safety check. Returns (ok, reason)."""
    for n in ast.walk(node):
        if isinstance(n, ast.Import):
            for alias in n.names:
                if alias.name.split(".")[0] in BLOCKED_NAMES:
                    return False, f"blocked import {alias.name}"
        elif isinstance(n, ast.ImportFrom):
            if n.module and n.module.split(".")[0] in BLOCKED_NAMES:
                return False, f"blocked import from {n.module}"
        elif isinstance(n, ast.Call):
            # check for open(), eval(), etc.
            if isinstance(n.func, ast.Name) and n.func.id in BLOCKED_NAMES:
                return False, f"blocked call {n.func.id}"
            if isinstance(n.func, ast.Attribute) and n.func.attr in BLOCKED_ATTRS:
                return False, f"blocked attr {n.func.attr}"
        elif isinstance(n, ast.Attribute):
            if n.attr in {"__subclasses__", "__bases__", "__mro__"}:
                return False, "blocked dunder"
    return True, ""


def solve(query: str) -> str:
    """Execute python code and return output. Never raises."""
    code, had_prefix = _extract_code(query)
    if not code:
        return "code: empty"
    # if query was prefix-like but code empty, try original
    if len(code) > 3000:
        return "code: too long (max 3000 chars)"

    # safety check via AST
    try:
        tree = ast.parse(code)
    except SyntaxError as e:
        return f"code SyntaxError: {e}"

    ok, reason = _is_safe(tree)
    if not ok:
        return f"code blocked: {reason} (sandbox)"

    # prepare sandbox globals
    safe_builtins = {
        "print": print,
        "len": len, "range": range, "enumerate": enumerate, "zip": zip,
        "map": map, "filter": filter, "sorted": sorted, "sum": sum, "min": min, "max": max,
        "abs": abs, "round": round, "pow": pow, "divmod": divmod,
        "int": int, "float": float, "str": str, "bool": bool, "list": list, "dict": dict,
        "set": set, "tuple": tuple, "any": any, "all": all,
        "math": __import__("math"),
        "random": __import__("random"),
        "datetime": __import__("datetime"),
        "re": __import__("re"),
        "json": __import__("json"),
        "collections": __import__("collections"),
        "itertools": __import__("itertools"),
    }
    # provide sympy/z3 if available but not required
    try:
        import sympy
        safe_builtins["sympy"] = sympy
    except Exception:
        pass

    out_buf = io.StringIO()
    err_buf = io.StringIO()
    start = time.time()
    try:
        with redirect_stdout(out_buf), redirect_stderr(err_buf):
            # exec with timeout check via simple elapsed
            # need to handle both expression and statements
            # try eval for single expression
            try:
                # if single expression, eval and print
                if len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr):
                    val = eval(compile(ast.Expression(tree.body[0].value), "<calc>", "eval"), {"__builtins__": safe_builtins}, {})
                    if val is not None:
                        print(repr(val))
                else:
                    exec(compile(tree, "<calc>", "exec"), {"__builtins__": safe_builtins}, {})
            except Exception:
                raise
            if time.time() - start > TIMEOUT_SEC:
                return "code timeout (>3s)"
    except Exception:
        tb = traceback.format_exc()
        # truncate
        if len(tb) > MAX_OUTPUT:
            tb = tb[:MAX_OUTPUT] + "\n... truncated"
        return f"code error:\n{tb}"

    out = out_buf.getvalue()
    err = err_buf.getvalue()
    combined = (out + ("\n[stderr]\n" + err if err else "")).strip()
    if not combined:
        combined = "(no output)"
    if len(combined) > MAX_OUTPUT:
        combined = combined[:MAX_OUTPUT] + "\n... truncated"
    elapsed = time.time() - start
    return f"🐍 [py · CPU bypass · {elapsed:.3f}s]\n{combined}"


def try_solve(message: str) -> Optional[str]:
    if not should_bypass_llm(message):
        return None
    if len(message) > 8000:
        return None
    res = solve(message)
    # if blocked or error, still return (don't fallback to LLM) if prefix was explicit
    _, had_prefix = _extract_code(message)
    if had_prefix:
        return res
    # for block without prefix, only return if success
    if "blocked" in res or "SyntaxError" in res:
        return None
    return res