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
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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import gradio as gr
import sys
import io
import traceback
import subprocess
import os
import json
import base64
from pathlib import Path
import tempfile
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# Create workspace directory
WORKSPACE_DIR = Path("/tmp/code_workspace")
WORKSPACE_DIR.mkdir(exist_ok=True)

class CodeInterpreter:
    def __init__(self):
        self.session_vars = {}
        self.installed_packages = set()
        
    def install_package(self, package_name):
        """Install a Python package dynamically"""
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package_name, "-q"])
            self.installed_packages.add(package_name)
            return f"βœ… Successfully installed: {package_name}"
        except Exception as e:
            return f"❌ Failed to install {package_name}: {str(e)}"
    
    def execute_code(self, code, maintain_session=True):
        """Execute Python code with proper output capture"""
        stdout_capture = io.StringIO()
        stderr_capture = io.StringIO()
        
        # Save current stdout/stderr
        old_stdout = sys.stdout
        old_stderr = sys.stderr
        
        try:
            # Redirect output
            sys.stdout = stdout_capture
            sys.stderr = stderr_capture
            
            # Prepare execution environment
            exec_globals = {
                '__builtins__': __builtins__,
                'WORKSPACE': str(WORKSPACE_DIR),
                'workspace_path': str(WORKSPACE_DIR),
            }
            
            if maintain_session:
                exec_globals.update(self.session_vars)
            
            # Execute code
            exec(code, exec_globals)
            
            # Update session variables
            if maintain_session:
                self.session_vars.update({
                    k: v for k, v in exec_globals.items() 
                    if not k.startswith('__') and k not in ['WORKSPACE', 'workspace_path']
                })
            
            # Get output
            stdout_output = stdout_capture.getvalue()
            stderr_output = stderr_capture.getvalue()
            
            result = {
                'success': True,
                'stdout': stdout_output,
                'stderr': stderr_output,
                'error': None
            }
            
        except Exception as e:
            result = {
                'success': False,
                'stdout': stdout_capture.getvalue(),
                'stderr': stderr_capture.getvalue(),
                'error': f"{type(e).__name__}: {str(e)}\n\n{traceback.format_exc()}"
            }
        finally:
            # Restore stdout/stderr
            sys.stdout = old_stdout
            sys.stderr = old_stderr
            
        return result
    
    def reset_session(self):
        """Clear session variables"""
        self.session_vars.clear()
        plt.close('all')
        return "Session reset successfully"
    
    def list_workspace_files(self):
        """List files in workspace"""
        files = list(WORKSPACE_DIR.glob("*"))
        if not files:
            return "Workspace is empty"
        return "\n".join([f"πŸ“„ {f.name}" for f in files if f.is_file()])

# Initialize interpreter
interpreter = CodeInterpreter()

def run_code(code, maintain_session):
    """Main function to run code and return formatted output"""
    if not code.strip():
        return "⚠️ Please enter some code to execute"
    
    result = interpreter.execute_code(code, maintain_session)
    
    output_parts = []
    
    if result['stdout']:
        output_parts.append("πŸ“€ OUTPUT:\n" + "=" * 50 + "\n" + result['stdout'])
    
    if result['stderr']:
        output_parts.append("⚠️ WARNINGS:\n" + "=" * 50 + "\n" + result['stderr'])
    
    if result['error']:
        output_parts.append("❌ ERROR:\n" + "=" * 50 + "\n" + result['error'])
    
    if result['success'] and not result['stdout'] and not result['stderr']:
        output_parts.append("βœ… Code executed successfully (no output)")
    
    # Check for generated plots
    plot_files = list(WORKSPACE_DIR.glob("*.png")) + list(WORKSPACE_DIR.glob("*.jpg"))
    if plot_files:
        output_parts.append(f"\nπŸ“Š Generated {len(plot_files)} plot(s) - check Files tab")
    
    return "\n\n".join(output_parts)

def install_package_handler(package_name):
    """Handle package installation"""
    if not package_name.strip():
        return "⚠️ Please enter a package name"
    return interpreter.install_package(package_name.strip())

def reset_session_handler():
    """Handle session reset"""
    return interpreter.reset_session()

def list_files_handler():
    """Handle file listing"""
    return interpreter.list_workspace_files()

def upload_file_handler(files):
    """Handle file uploads"""
    if not files:
        return "No files uploaded"
    
    uploaded = []
    for file in files:
        try:
            file_path = Path(file.name)
            dest_path = WORKSPACE_DIR / file_path.name
            
            # Copy file to workspace
            with open(file.name, 'rb') as src:
                with open(dest_path, 'wb') as dst:
                    dst.write(src.read())
            
            uploaded.append(f"βœ… {file_path.name}")
        except Exception as e:
            uploaded.append(f"❌ {file_path.name}: {str(e)}")
    
    return "Uploaded files:\n" + "\n".join(uploaded)

def get_workspace_files():
    """Get list of files in workspace for download"""
    files = list(WORKSPACE_DIR.glob("*"))
    return [str(f) for f in files if f.is_file()]

# Example code snippets
EXAMPLES = {
    "Hello World": """print("Hello from Code Interpreter!")
print("Python version:", sys.version)""",
    
    "Data Analysis": """import pandas as pd
import numpy as np

# Create sample data
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 35, 28],
    'Score': [85, 92, 78, 95]
}

df = pd.DataFrame(data)
print("DataFrame:")
print(df)
print(f"\\nAverage Score: {df['Score'].mean():.2f}")""",
    
    "Visualization": """import matplotlib.pyplot as plt
import numpy as np

# Create data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='sin(x)', linewidth=2)
plt.plot(x, y2, label='cos(x)', linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine and Cosine Functions')
plt.legend()
plt.grid(True, alpha=0.3)

# Save plot
plt.savefig(f'{WORKSPACE}/trigonometric.png', dpi=150, bbox_inches='tight')
print("βœ… Plot saved to workspace as 'trigonometric.png'")
plt.close()""",
    
    "File Operations": """import os

# Create a text file
with open(f'{WORKSPACE}/sample.txt', 'w') as f:
    f.write("Hello from Code Interpreter!\\n")
    f.write("This is a sample file.\\n")

# Read it back
with open(f'{WORKSPACE}/sample.txt', 'r') as f:
    content = f.read()

print("File content:")
print(content)

# List workspace files
files = os.listdir(WORKSPACE)
print(f"\\nWorkspace files: {files}")""",

    "Machine Learning": """from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Load dataset
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.2, random_state=42
)

# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Evaluate
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)

print(f"Model Accuracy: {accuracy:.2%}")
print(f"\\nFeature Importances:")
for name, importance in zip(iris.feature_names, model.feature_importances_):
    print(f"  {name}: {importance:.3f}")"""
}

def load_example(example_name):
    """Load example code"""
    return EXAMPLES.get(example_name, "")

# Custom CSS for better UI
custom_css = """
#code-input textarea {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
    font-size: 14px !important;
}
#output-display textarea {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
    font-size: 13px !important;
}
.gradio-container {
    max-width: 1400px !important;
}
"""

# Build Gradio Interface
with gr.Blocks(css=custom_css, title="πŸš€ Code Interpreter Pro", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # πŸš€ Code Interpreter Pro - HuggingFace Edition
    
    A powerful Python code execution sandbox with:
    - ✨ **Real-time code execution** with session management
    - πŸ“¦ **Dynamic package installation** 
    - πŸ“Š **Data visualization** (matplotlib, plotly, seaborn)
    - πŸ“ **File upload/download** capabilities
    - πŸ”„ **Persistent session** (variables maintained across runs)
    - 🎯 **Better than basic sandboxes** - Full-featured development environment
    """)
    
    with gr.Tabs():
        # Main Code Editor Tab
        with gr.Tab("πŸ’» Code Editor"):
            with gr.Row():
                with gr.Column(scale=2):
                    code_input = gr.Code(
                        label="Python Code Editor",
                        language="python",
                        lines=20,
                        elem_id="code-input"
                    )
                    
                    with gr.Row():
                        run_btn = gr.Button("▢️ Run Code", variant="primary", size="lg")
                        maintain_session_check = gr.Checkbox(
                            label="Maintain Session (keep variables)", 
                            value=True
                        )
                    
                    with gr.Row():
                        example_dropdown = gr.Dropdown(
                            choices=list(EXAMPLES.keys()),
                            label="πŸ“š Load Example",
                            value=None
                        )
                        load_example_btn = gr.Button("Load", size="sm")
                
                with gr.Column(scale=2):
                    output_display = gr.Textbox(
                        label="Output",
                        lines=20,
                        max_lines=30,
                        elem_id="output-display"
                    )
        
        # Package Manager Tab
        with gr.Tab("πŸ“¦ Package Manager"):
            gr.Markdown("### Install Python Packages")
            gr.Markdown("Install any package from PyPI (e.g., pandas, numpy, requests)")
            
            with gr.Row():
                package_input = gr.Textbox(
                    label="Package Name",
                    placeholder="e.g., pandas, requests, beautifulsoup4"
                )
                install_btn = gr.Button("Install", variant="primary")
            
            install_output = gr.Textbox(label="Installation Output", lines=5)
            
            gr.Markdown("""
            ### Pre-installed Packages
            - numpy, pandas, matplotlib
            - scikit-learn, scipy
            - requests, beautifulsoup4
            - And more...
            """)
        
        # File Manager Tab
        with gr.Tab("πŸ“ File Manager"):
            gr.Markdown("### Workspace File Manager")
            gr.Markdown(f"Files are stored in: `{WORKSPACE_DIR}`")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("#### Upload Files")
                    file_upload = gr.File(
                        label="Select files to upload",
                        file_count="multiple"
                    )
                    upload_btn = gr.Button("Upload to Workspace", variant="primary")
                    upload_output = gr.Textbox(label="Upload Status", lines=3)
                
                with gr.Column():
                    gr.Markdown("#### Workspace Files")
                    list_files_btn = gr.Button("πŸ”„ Refresh File List", variant="secondary")
                    files_list = gr.Textbox(label="Files in Workspace", lines=10)
                    
                    gr.Markdown("#### Download Files")
                    workspace_files = gr.File(
                        label="Download files from workspace",
                        file_count="multiple",
                        type="filepath",
                        interactive=False
                    )
        
        # Session Manager Tab
        with gr.Tab("πŸ”„ Session Manager"):
            gr.Markdown("### Session Management")
            gr.Markdown("Control your execution session and view session state")
            
            reset_btn = gr.Button("πŸ—‘οΈ Reset Session", variant="stop")
            reset_output = gr.Textbox(label="Status", lines=2)
            
            gr.Markdown("""
            ### Session Info
            - **Maintain Session ON**: Variables persist between code executions
            - **Maintain Session OFF**: Fresh environment for each execution
            - **Reset Session**: Clear all variables and start fresh
            """)
        
        # Help Tab
        with gr.Tab("❓ Help & Tips"):
            gr.Markdown("""
            ## 🎯 Quick Start Guide
            
            ### Basic Usage
            1. Write or paste Python code in the editor
            2. Click "▢️ Run Code" to execute
            3. View output in the right panel
            
            ### Advanced Features
            
            #### πŸ“Š Creating Visualizations
            ```python
            import matplotlib.pyplot as plt
            
            plt.figure(figsize=(10, 6))
            plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
            plt.savefig(f'{WORKSPACE}/my_plot.png')
            print("Plot saved!")
            ```
            
            #### πŸ“ Working with Files
            ```python
            # Access workspace directory
            print(f"Workspace: {WORKSPACE}")
            
            # Save data
            with open(f'{WORKSPACE}/data.txt', 'w') as f:
                f.write("Hello World!")
            
            # Read data
            with open(f'{WORKSPACE}/data.txt', 'r') as f:
                print(f.read())
            ```
            
            #### πŸ“¦ Installing Packages
            Go to "Package Manager" tab and install any PyPI package!
            
            ### Tips
            - Use `maintain_session=True` to keep variables between runs
            - Save plots to workspace to download them
            - Upload CSV/JSON files to analyze data
            - Install packages dynamically as needed
            
            ### Advantages over e2b.dev
            - βœ… Free and open-source
            - βœ… Integrated file management
            - βœ… Visual package manager
            - βœ… Session persistence
            - βœ… Better UI/UX
            - βœ… Hosted on HuggingFace (reliable infrastructure)
            """)
    
    # Event handlers
    run_btn.click(
        fn=run_code,
        inputs=[code_input, maintain_session_check],
        outputs=output_display
    )
    
    load_example_btn.click(
        fn=load_example,
        inputs=example_dropdown,
        outputs=code_input
    )
    
    install_btn.click(
        fn=install_package_handler,
        inputs=package_input,
        outputs=install_output
    )
    
    upload_btn.click(
        fn=upload_file_handler,
        inputs=file_upload,
        outputs=upload_output
    )
    
    list_files_btn.click(
        fn=list_files_handler,
        outputs=files_list
    )
    
    reset_btn.click(
        fn=reset_session_handler,
        outputs=reset_output
    )

if __name__ == "__main__":
    demo.launch()