File size: 9,704 Bytes
b671043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8421e1e
 
 
 
 
 
 
fe02574
 
8421e1e
 
fe02574
8421e1e
 
 
 
 
 
 
 
 
 
 
 
fe02574
8b8897f
8421e1e
 
 
 
 
 
 
 
b671043
 
 
 
 
 
 
 
 
 
fe02574
 
b671043
 
 
159d213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b671043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe02574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b671043
 
 
fe02574
 
b671043
fe02574
b671043
 
 
 
 
 
 
fe02574
b671043
 
 
fe02574
b671043
 
 
 
fe02574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b671043
fe02574
 
 
 
 
 
 
b671043
 
 
 
 
 
 
fe02574
b671043
fe02574
b671043
 
fe02574
 
 
b671043
 
 
 
 
 
 
 
 
 
 
8421e1e
 
b671043
 
 
 
 
 
 
 
 
 
b7dcfcb
b671043
 
 
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
import gradio as gr
import tempfile
from pathlib import Path
import subprocess
import sys
import os
import shutil
import uuid
import json
import io
import zipfile
import time

from run_script_venv import main as run_in_venv

code="""
import os
import base64
from io import BytesIO
from PIL import Image
import json

# input_path = os.environ["SCRIPT_INPUT"]
# output_path = os.environ["SCRIPT_OUTPUT"]

# Load JSON input
with open("input.txt", "r") as f:
    data = json.load(f)
    img_b64 = data["img"]

# Decode base64 to image
img_bytes = base64.b64decode(img_b64)
img = Image.open(BytesIO(img_bytes))
img.load()  # ⬅️ Ensure image is fully loaded before processing

# Flip image horizontally
flipped = img.transpose(Image.FLIP_LEFT_RIGHT)

# Save output
# flipped.save(os.path.join(output_path, "flipped.png"))
flipped.save("flipped.png")
print("Image flipped and saved as flipped.png.")
"""

input="""
{
  "img": "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC"
}
"""

def cleanup_old_runs(base_dir: Path, max_age: int):
    now = time.time()
    for d in base_dir.glob("run_*/"):
        if d.is_dir() and now - d.stat().st_mtime > max_age:
            shutil.rmtree(d, ignore_errors=True)

def zip_artifacts(output_dir: Path, zip_path: Path):
    with zipfile.ZipFile(zip_path, "w") as zf:
        for file in output_dir.iterdir():
            if "output.zip" not in file.name:
                zf.write(file, arcname=file.name)


def run_script(code: str, user_input: str = "", cleanup_enabled: bool = True, cleanup_after: int = 600):
    """
    Executes a user-provided self contained Python script inside an isolated virtual environment with automatic dependency management.

    This function is intended to serve as a backend execution engine in a Model Context Protocol (MCP) server setting,
    where a language model may submit scripts for evaluation. It creates a secure workspace, detects dependencies,
    installs them using `uv`, executes the script, captures its output (including stdout and generated files), and
    returns all relevant results. 

    ⚠️ Limitations & Guidance for LLM-based Use:
    - Scripts should be self-contained, avoid system-level access, and primarily focus on data processing, text generation,
      visualization, or machine learning tasks.
    - The code can output logs, JSON, images, CSVs, or any other files, which are returned as artifacts.
    - Avoid infinite loops or long-running background processes. Timeout support can be added externally.

    Args:
        code (str): The Python script to execute. Should include all import statements and logic. 
            Example:
                ```python
                import json
                import os
                input_path = os.environ["SCRIPT_INPUT"]
                with open(input_path) as f:
                    data = json.load(f)
                print("Processed:", data["name"])
                ```

        user_input (str, optional): A string input available to the script via the SCRIPT_INPUT environment variable. 
            Can be plain text, JSON, Markdown, or even base64-encoded images.
            Example:
                ```json
                {"img": "base64string..."}
                ```

        cleanup_enabled (bool, optional): 
            Whether to automatically delete old execution directories.

        cleanup_after (int, optional): 
            Number of seconds after which completed runs should be deleted, if cleanup is enabled.

    Returns:
        Tuple[str, Dict[str, str], str]:
            - logs (str): Full stdout and stderr logs of the executed script.
            - artifacts (Dict[str, str]): A dictionary of output files with their names and summaries or indicators 
              (e.g., image or CSV placeholders). Includes a "__workdir__" key pointing to the working directory.
            - zip_path (str): Path to a ZIP archive containing all output artifacts for download.
    """

    
    base_dir = Path("./script_runs")
    base_dir.mkdir(exist_ok=True)
    if cleanup_enabled:
        cleanup_old_runs(base_dir, cleanup_after)

    run_id = uuid.uuid4().hex[:8]
    run_dir = base_dir / f"run_{run_id}"
    run_dir.mkdir()
    script_path = run_dir / "script.py"
    input_path = run_dir / "input.txt"
    output_path = run_dir / "output"
    output_path.mkdir()

    # Save the user's code
    script_path.write_text(code)

    # Always create input file
    input_path.write_text(user_input or "")


    # Redirect stdout/stderr
    with tempfile.TemporaryFile(mode="w+") as output:
        orig_stdout = sys.stdout
        orig_stderr = sys.stderr
        sys.stdout = sys.stderr = output

        # try:
        #     sys.argv = [
        #         "run_script_venv.py",
        #         str(script_path),
        #         "--keep-workdir",
        #         "--extra", "pandas",  # safe default dependency for common data handling
        #     ]
        #     os.environ["SCRIPT_INPUT"] = str(input_path)
        #     os.environ["SCRIPT_OUTPUT"] = str(output_path)
        #     run_in_venv()
        # except SystemExit:
        #     pass
        # finally:
        #     sys.stdout = orig_stdout
        #     sys.stderr = orig_stderr

        # Set working directory so user script writes to run_dir
        old_cwd = os.getcwd()
        os.chdir(run_dir)

        try:
            sys.argv = [
                "run_script_venv.py",
                # str(script_path),
                "script.py",
                "--keep-workdir",
                "--extra", "pandas",
            ]
            os.environ["SCRIPT_INPUT"] = str(input_path)
            os.environ["SCRIPT_OUTPUT"] = str(output_path)
            run_in_venv()
        except SystemExit:
            pass
        finally:
            os.chdir(old_cwd)
            sys.stdout = orig_stdout
            sys.stderr = orig_stderr


        output.seek(0)
        logs = output.read()


    # # Collect output artifacts
    # artifacts = {}
    # for item in output_path.iterdir():
    #     if item.suffix in {".txt", ".csv", ".json", ".md"}:
    #         artifacts[item.name] = item.read_text()
    #     elif item.suffix.lower() in {".png", ".jpg", ".jpeg"}:
    #         artifacts[item.name] = f"[image file: {item.name}]"
    #     else:
    #         artifacts[item.name] = f"[file saved: {item.name}]"

    # # Create zip
    # zip_path = run_dir / "output.zip"
    # zip_artifacts(output_path, zip_path)
    # artifacts["Download All (ZIP)"] = str(zip_path)
    # artifacts["__workdir__"] = str(run_dir)
    
    # Collect output artifacts (from output/ and run_dir/)
    artifacts = {}
    # ignored = {"script.py", "input.txt", "output.zip"}
    ignored = {"output.zip"}
    for item in run_dir.iterdir():
        if item.name in ignored or item.name.startswith(".venv"):
            continue
        if item.is_dir():
            continue  # Skip subdirectories except output
        if item.suffix in {".txt", ".csv", ".json", ".md"}:
            artifacts[item.name] = item.read_text()
        elif item.suffix.lower() in {".png", ".jpg", ".jpeg"}:
            artifacts[item.name] = f"[image file: {item.name}]"
        else:
            artifacts[item.name] = f"[file saved: {item.name}]"

    # Still allow zipped output/ as a bonus
    zip_path = run_dir / "output.zip"
    zip_artifacts(run_dir, zip_path)
    artifacts["Download All (ZIP)"] = str(zip_path)
    artifacts["__workdir__"] = str(run_dir)

    
    
    return logs, artifacts, str(zip_path)


def launch_ui():
    with gr.Blocks() as app:
        gr.Markdown("# 🚀 Run My Script")
        run_btn = gr.Button("Run My Script")
        with gr.Row():
            cleanup_toggle = gr.Checkbox(label="Enable Auto Cleanup", value=True)
            cleanup_seconds = gr.Number(label="Cleanup After (seconds)", value=600, precision=0)
        with gr.Row():
            editor = gr.Code(label="Your Python Script", value=code, language="python")
            user_input = gr.Textbox(label="Optional Input", value=input, lines=4, placeholder="Text, JSON, Markdown...")
        with gr.Row():
            output_log = gr.Textbox(label="Terminal Output", lines=3)
            output_files = gr.JSON(label="Output Artifacts")
        zip_file = gr.File(label="Download All Artifacts")
        run_btn.click(
            fn=run_script,
            inputs=[editor, user_input, cleanup_toggle, cleanup_seconds],
            outputs=[output_log, output_files, zip_file]
        )

    app.launch(mcp_server=True)

if __name__ == "__main__":
    launch_ui()