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
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
"""
Advanced Code Interpreter Sandbox
A powerful code execution environment with advanced features
"""

import gradio as gr
import subprocess
import sys
import io
import os
import traceback
import json
import tempfile
import shutil
from datetime import datetime
from pathlib import Path
import ast
import signal
import time

# Global variables
session_state = {
    "files": {},
    "history": [],
    "packages": set(),
    "cwd": tempfile.mkdtemp(prefix="code_sandbox_"),
    "start_time": time.time()
}

# Initialize workspace
os.makedirs(session_state["cwd"], exist_ok=True)
os.chdir(session_state["cwd"])

class CodeExecutor:
    """Secure code execution with proper sandboxing"""

    def __init__(self, timeout=10, memory_limit=512):
        self.timeout = timeout
        self.memory_limit = memory_limit

    def install_package(self, package_name):
        """Install package using pip"""
        try:
            result = subprocess.run(
                [sys.executable, "-m", "pip", "install", package_name, "-q"],
                capture_output=True,
                text=True,
                timeout=60
            )
            if result.returncode == 0:
                session_state["packages"].add(package_name)
                return f"βœ… Successfully installed {package_name}"
            else:
                return f"❌ Failed to install {package_name}\n{result.stderr}"
        except Exception as e:
            return f"❌ Error installing package: {str(e)}"

    def execute_code(self, code, use_file=False, filename=""):
        """Execute Python code safely"""
        output = []
        error_output = []

        # Create a custom stdout/stderr capture
        old_stdout = sys.stdout
        old_stderr = sys.stderr
        sys.stdout = io.StringIO()
        sys.stderr = io.StringIO()

        try:
            # Set up environment
            env = {
                "__name__": "__main__",
                "__builtins__": __builtins__,
                "session_files": session_state["files"],
                "session_state": session_state,
                "os": os,
                "sys": sys,
                "json": json,
                "pathlib": __import__("pathlib")
            }

            # If using file mode, write code to file
            if use_file and filename:
                filepath = os.path.join(session_state["cwd"], filename)
                with open(filepath, 'w') as f:
                    f.write(code)

                # Execute file
                with open(filepath, 'r') as f:
                    code_obj = compile(f.read(), filename, 'exec')
                    exec(code_obj, env)
            else:
                # Direct code execution
                try:
                    # Try to parse and execute
                    code_obj = compile(code, '<input>', 'exec')
                    exec(code_obj, env)
                except SyntaxError as e:
                    # Try as expression
                    try:
                        result = eval(code, env)
                        if result is not None:
                            output.append(str(result))
                    except:
                        raise

            # Get captured output
            stdout_val = sys.stdout.getvalue()
            stderr_val = sys.stderr.getvalue()

            if stdout_val:
                output.append(stdout_val)
            if stderr_val:
                error_output.append(stderr_val)

        except Exception as e:
            error_output.append(traceback.format_exc())

        finally:
            # Restore stdout/stderr
            sys.stdout = old_stdout
            sys.stderr = old_stderr

        return "\n".join(output), "\n".join(error_output)

# Initialize executor
executor = CodeExecutor()

# Custom CSS for better UX
CUSTOM_CSS = """
.gradio-container {
    max-width: 1400px !important;
    margin: auto !important;
}

.code-editor {
    font-family: 'Courier New', monospace;
    font-size: 14px;
}

.output-box {
    background-color: #1e1e1e;
    color: #d4d4d4;
    font-family: 'Courier New', monospace;
    padding: 10px;
    border-radius: 5px;
}

.file-item {
    padding: 8px;
    margin: 4px 0;
    background-color: #2d2d2d;
    border-radius: 4px;
    cursor: pointer;
}

.file-item:hover {
    background-color: #3d3d3d;
}

.tab-button {
    padding: 10px 20px;
    margin: 5px;
    background-color: #007acc;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.tab-button.active {
    background-color: #005a9e;
}
"""

def run_code(code, output_mode="both"):
    """Run code and return output"""
    stdout, stderr = executor.execute_code(code)

    if output_mode == "stdout":
        return stdout
    elif output_mode == "stderr":
        return stderr
    else:
        result = ""
        if stdout:
            result += f"πŸ“€ STDOUT:\n{stdout}\n"
        if stderr:
            result += f"⚠️ STDERR:\n{stderr}\n"
        return result if result else "Code executed successfully with no output."

def upload_file(file):
    """Handle file upload"""
    if file is None:
        return "No file uploaded"

    try:
        # Get file info
        file_name = os.path.basename(file.name)
        file_size = os.path.getsize(file.name)

        # Copy to workspace
        dest_path = os.path.join(session_state["cwd"], file_name)
        shutil.copy2(file.name, dest_path)

        # Store in session
        session_state["files"][file_name] = {
            "path": dest_path,
            "size": file_size,
            "uploaded_at": datetime.now().isoformat()
        }

        return f"βœ… Uploaded: {file_name} ({file_size} bytes)"
    except Exception as e:
        return f"❌ Upload failed: {str(e)}"

def list_files():
    """List all files in workspace"""
    if not session_state["files"]:
        return "No files in workspace"

    file_list = []
    for name, info in session_state["files"].items():
        file_list.append(f"πŸ“„ {name} ({info['size']} bytes)")

    return "\n".join(file_list)

def read_file(filename):
    """Read file content"""
    if filename not in session_state["files"]:
        return f"File '{filename}' not found"

    try:
        with open(session_state["files"][filename]["path"], 'r') as f:
            return f.read()
    except Exception as e:
        return f"Error reading file: {str(e)}"

def delete_file(filename):
    """Delete file from workspace"""
    if filename not in session_state["files"]:
        return f"File '{filename}' not found"

    try:
        os.remove(session_state["files"][filename]["path"])
        del session_state["files"][filename]
        return f"βœ… Deleted: {filename}"
    except Exception as e:
        return f"❌ Delete failed: {str(e)}"

def install_packages(package_list):
    """Install multiple packages"""
    if not package_list:
        return "No packages specified"

    packages = [p.strip() for p in package_list.split(',')]
    results = []

    for package in packages:
        result = executor.install_package(package)
        results.append(result)

    return "\n".join(results)

def show_installed_packages():
    """Show installed packages"""
    if not session_state["packages"]:
        return "No custom packages installed"

    return "\n".join([f"πŸ“¦ {pkg}" for pkg in sorted(session_state["packages"])])

def get_session_info():
    """Get session information"""
    uptime = time.time() - session_state["start_time"]
    file_count = len(session_state["files"])

    return f"""
πŸ• Session Started: {datetime.fromtimestamp(session_state["start_time"]).strftime('%Y-%m-%d %H:%M:%S')}
⏱️ Uptime: {uptime:.1f} seconds
πŸ“ Files: {file_count}
πŸ“¦ Packages: {len(session_state["packages"])}
πŸ’Ύ Workspace: {session_state["cwd"]}
    """

# Create Gradio interface
def create_interface():
    """Create the main Gradio interface"""
    with gr.Blocks(css=CUSTOM_CSS, title="Code Interpreter Sandbox", theme=gr.themes.Soft()) as app:

        gr.Markdown(
            """
            # πŸš€ Advanced Code Interpreter Sandbox

            A powerful code execution environment with advanced features:
            - βœ… Secure code execution
            - πŸ“ File system access
            - πŸ“¦ Package installation
            - πŸ“Š Data visualization
            - πŸ’Ύ Session persistence
            - πŸ”„ Real-time output
            - πŸ“ Multi-file support
            """
        )

        with gr.Tab("πŸ”§ Code Executor"):
            with gr.Row():
                with gr.Column(scale=3):
                    code_input = gr.Code(
                        label="Python Code",
                        value="# Write your Python code here\nprint('Hello, World!')",
                        language="python",
                        elem_classes="code-editor"
                    )
                    with gr.Row():
                        run_btn = gr.Button("▢️ Run Code", variant="primary")
                        clear_btn = gr.Button("πŸ—‘οΈ Clear Output")
                    with gr.Row():
                        output_mode = gr.Radio(
                            ["both", "stdout", "stderr"],
                            value="both",
                            label="Output Mode"
                        )

                with gr.Column(scale=3):
                    output = gr.Textbox(
                        label="Output",
                        lines=20,
                        elem_classes="output-box"
                    )

            run_btn.click(
                fn=run_code,
                inputs=[code_input, output_mode],
                outputs=output
            )

            clear_btn.click(
                fn=lambda: "",
                outputs=output
            )

        with gr.Tab("πŸ“ File Manager"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Upload Files")
                    file_upload = gr.File(
                        label="Upload File",
                        file_count="single"
                    )
                    upload_btn = gr.Button("πŸ“€ Upload")
                    upload_status = gr.Textbox(label="Status", lines=5)

                with gr.Column():
                    gr.Markdown("### File Operations")
                    with gr.Row():
                        refresh_btn = gr.Button("πŸ”„ Refresh File List")
                        files_display = gr.Textbox(label="Files", lines=10, interactive=False)

                    file_selector = gr.Dropdown(
                        label="Select File",
                        choices=[],
                        value=None
                    )

            # Define refresh function
            def refresh_and_update():
                file_list = list_files()
                choices = list(session_state["files"].keys())
                return file_list, gr.update(choices=choices)

            # Update refresh button
            refresh_btn.click(
                fn=refresh_and_update,
                outputs=[files_display, file_selector]
            )

            # Update upload button
            upload_btn.click(
                fn=upload_file,
                inputs=file_upload,
                outputs=upload_status
            ).then(
                fn=refresh_and_update,
                outputs=[files_display, file_selector]
            )

            with gr.Row():
                read_btn = gr.Button("πŸ“– Read File")
                del_btn = gr.Button("πŸ—‘οΈ Delete File")

            file_content = gr.Textbox(label="File Content", lines=15)

            read_btn.click(
                fn=read_file,
                inputs=file_selector,
                outputs=file_content
            )

            del_status = gr.Textbox(label="Status", lines=5)

            del_btn.click(
                fn=delete_file,
                inputs=file_selector,
                outputs=del_status
            ).then(
                fn=refresh_and_update,
                outputs=[files_display, file_selector]
            )

        with gr.Tab("πŸ“¦ Package Manager"):
            gr.Markdown("### Install Packages")

            package_input = gr.Textbox(
                label="Package Names (comma-separated)",
                placeholder="numpy, pandas, matplotlib, plotly"
            )

            with gr.Row():
                install_btn = gr.Button("πŸ“₯ Install", variant="primary")
                show_btn = gr.Button("πŸ“‹ Show Installed")

            install_output = gr.Textbox(label="Installation Status", lines=10)
            installed_display = gr.Textbox(label="Installed Packages", lines=10)

            install_btn.click(
                fn=install_packages,
                inputs=package_input,
                outputs=install_output
            )

            show_btn.click(
                fn=show_installed_packages,
                outputs=installed_display
            )

        with gr.Tab("ℹ️ Session Info"):
            info_btn = gr.Button("πŸ“Š Get Session Info")
            session_info = gr.Textbox(label="Session Information", lines=15, interactive=False)

            info_btn.click(
                fn=get_session_info,
                outputs=session_info
            )

    return app

# Launch the app
if __name__ == "__main__":
    app = create_interface()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
        quiet=False
    )