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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import sys
3
+ import io
4
+ import traceback
5
+ import subprocess
6
+ import os
7
+ import json
8
+ import base64
9
+ from pathlib import Path
10
+ import tempfile
11
+ import matplotlib
12
+ matplotlib.use('Agg')
13
+ import matplotlib.pyplot as plt
14
+
15
+ # Create workspace directory
16
+ WORKSPACE_DIR = Path("/tmp/code_workspace")
17
+ WORKSPACE_DIR.mkdir(exist_ok=True)
18
+
19
+ class CodeInterpreter:
20
+ def __init__(self):
21
+ self.session_vars = {}
22
+ self.installed_packages = set()
23
+
24
+ def install_package(self, package_name):
25
+ """Install a Python package dynamically"""
26
+ try:
27
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package_name, "-q"])
28
+ self.installed_packages.add(package_name)
29
+ return f"βœ… Successfully installed: {package_name}"
30
+ except Exception as e:
31
+ return f"❌ Failed to install {package_name}: {str(e)}"
32
+
33
+ def execute_code(self, code, maintain_session=True):
34
+ """Execute Python code with proper output capture"""
35
+ stdout_capture = io.StringIO()
36
+ stderr_capture = io.StringIO()
37
+
38
+ # Save current stdout/stderr
39
+ old_stdout = sys.stdout
40
+ old_stderr = sys.stderr
41
+
42
+ try:
43
+ # Redirect output
44
+ sys.stdout = stdout_capture
45
+ sys.stderr = stderr_capture
46
+
47
+ # Prepare execution environment
48
+ exec_globals = {
49
+ '__builtins__': __builtins__,
50
+ 'WORKSPACE': str(WORKSPACE_DIR),
51
+ 'workspace_path': str(WORKSPACE_DIR),
52
+ }
53
+
54
+ if maintain_session:
55
+ exec_globals.update(self.session_vars)
56
+
57
+ # Execute code
58
+ exec(code, exec_globals)
59
+
60
+ # Update session variables
61
+ if maintain_session:
62
+ self.session_vars.update({
63
+ k: v for k, v in exec_globals.items()
64
+ if not k.startswith('__') and k not in ['WORKSPACE', 'workspace_path']
65
+ })
66
+
67
+ # Get output
68
+ stdout_output = stdout_capture.getvalue()
69
+ stderr_output = stderr_capture.getvalue()
70
+
71
+ result = {
72
+ 'success': True,
73
+ 'stdout': stdout_output,
74
+ 'stderr': stderr_output,
75
+ 'error': None
76
+ }
77
+
78
+ except Exception as e:
79
+ result = {
80
+ 'success': False,
81
+ 'stdout': stdout_capture.getvalue(),
82
+ 'stderr': stderr_capture.getvalue(),
83
+ 'error': f"{type(e).__name__}: {str(e)}\n\n{traceback.format_exc()}"
84
+ }
85
+ finally:
86
+ # Restore stdout/stderr
87
+ sys.stdout = old_stdout
88
+ sys.stderr = old_stderr
89
+
90
+ return result
91
+
92
+ def reset_session(self):
93
+ """Clear session variables"""
94
+ self.session_vars.clear()
95
+ plt.close('all')
96
+ return "Session reset successfully"
97
+
98
+ def list_workspace_files(self):
99
+ """List files in workspace"""
100
+ files = list(WORKSPACE_DIR.glob("*"))
101
+ if not files:
102
+ return "Workspace is empty"
103
+ return "\n".join([f"πŸ“„ {f.name}" for f in files if f.is_file()])
104
+
105
+ # Initialize interpreter
106
+ interpreter = CodeInterpreter()
107
+
108
+ def run_code(code, maintain_session):
109
+ """Main function to run code and return formatted output"""
110
+ if not code.strip():
111
+ return "⚠️ Please enter some code to execute"
112
+
113
+ result = interpreter.execute_code(code, maintain_session)
114
+
115
+ output_parts = []
116
+
117
+ if result['stdout']:
118
+ output_parts.append("πŸ“€ OUTPUT:\n" + "=" * 50 + "\n" + result['stdout'])
119
+
120
+ if result['stderr']:
121
+ output_parts.append("⚠️ WARNINGS:\n" + "=" * 50 + "\n" + result['stderr'])
122
+
123
+ if result['error']:
124
+ output_parts.append("❌ ERROR:\n" + "=" * 50 + "\n" + result['error'])
125
+
126
+ if result['success'] and not result['stdout'] and not result['stderr']:
127
+ output_parts.append("βœ… Code executed successfully (no output)")
128
+
129
+ # Check for generated plots
130
+ plot_files = list(WORKSPACE_DIR.glob("*.png")) + list(WORKSPACE_DIR.glob("*.jpg"))
131
+ if plot_files:
132
+ output_parts.append(f"\nπŸ“Š Generated {len(plot_files)} plot(s) - check Files tab")
133
+
134
+ return "\n\n".join(output_parts)
135
+
136
+ def install_package_handler(package_name):
137
+ """Handle package installation"""
138
+ if not package_name.strip():
139
+ return "⚠️ Please enter a package name"
140
+ return interpreter.install_package(package_name.strip())
141
+
142
+ def reset_session_handler():
143
+ """Handle session reset"""
144
+ return interpreter.reset_session()
145
+
146
+ def list_files_handler():
147
+ """Handle file listing"""
148
+ return interpreter.list_workspace_files()
149
+
150
+ def upload_file_handler(files):
151
+ """Handle file uploads"""
152
+ if not files:
153
+ return "No files uploaded"
154
+
155
+ uploaded = []
156
+ for file in files:
157
+ try:
158
+ file_path = Path(file.name)
159
+ dest_path = WORKSPACE_DIR / file_path.name
160
+
161
+ # Copy file to workspace
162
+ with open(file.name, 'rb') as src:
163
+ with open(dest_path, 'wb') as dst:
164
+ dst.write(src.read())
165
+
166
+ uploaded.append(f"βœ… {file_path.name}")
167
+ except Exception as e:
168
+ uploaded.append(f"❌ {file_path.name}: {str(e)}")
169
+
170
+ return "Uploaded files:\n" + "\n".join(uploaded)
171
+
172
+ def get_workspace_files():
173
+ """Get list of files in workspace for download"""
174
+ files = list(WORKSPACE_DIR.glob("*"))
175
+ return [str(f) for f in files if f.is_file()]
176
+
177
+ # Example code snippets
178
+ EXAMPLES = {
179
+ "Hello World": """print("Hello from Code Interpreter!")
180
+ print("Python version:", sys.version)""",
181
+
182
+ "Data Analysis": """import pandas as pd
183
+ import numpy as np
184
+
185
+ # Create sample data
186
+ data = {
187
+ 'Name': ['Alice', 'Bob', 'Charlie', 'David'],
188
+ 'Age': [25, 30, 35, 28],
189
+ 'Score': [85, 92, 78, 95]
190
+ }
191
+
192
+ df = pd.DataFrame(data)
193
+ print("DataFrame:")
194
+ print(df)
195
+ print(f"\\nAverage Score: {df['Score'].mean():.2f}")""",
196
+
197
+ "Visualization": """import matplotlib.pyplot as plt
198
+ import numpy as np
199
+
200
+ # Create data
201
+ x = np.linspace(0, 10, 100)
202
+ y1 = np.sin(x)
203
+ y2 = np.cos(x)
204
+
205
+ # Create plot
206
+ plt.figure(figsize=(10, 6))
207
+ plt.plot(x, y1, label='sin(x)', linewidth=2)
208
+ plt.plot(x, y2, label='cos(x)', linewidth=2)
209
+ plt.xlabel('x')
210
+ plt.ylabel('y')
211
+ plt.title('Sine and Cosine Functions')
212
+ plt.legend()
213
+ plt.grid(True, alpha=0.3)
214
+
215
+ # Save plot
216
+ plt.savefig(f'{WORKSPACE}/trigonometric.png', dpi=150, bbox_inches='tight')
217
+ print("βœ… Plot saved to workspace as 'trigonometric.png'")
218
+ plt.close()""",
219
+
220
+ "File Operations": """import os
221
+
222
+ # Create a text file
223
+ with open(f'{WORKSPACE}/sample.txt', 'w') as f:
224
+ f.write("Hello from Code Interpreter!\\n")
225
+ f.write("This is a sample file.\\n")
226
+
227
+ # Read it back
228
+ with open(f'{WORKSPACE}/sample.txt', 'r') as f:
229
+ content = f.read()
230
+
231
+ print("File content:")
232
+ print(content)
233
+
234
+ # List workspace files
235
+ files = os.listdir(WORKSPACE)
236
+ print(f"\\nWorkspace files: {files}")""",
237
+
238
+ "Machine Learning": """from sklearn.datasets import load_iris
239
+ from sklearn.model_selection import train_test_split
240
+ from sklearn.ensemble import RandomForestClassifier
241
+ from sklearn.metrics import accuracy_score
242
+
243
+ # Load dataset
244
+ iris = load_iris()
245
+ X_train, X_test, y_train, y_test = train_test_split(
246
+ iris.data, iris.target, test_size=0.2, random_state=42
247
+ )
248
+
249
+ # Train model
250
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
251
+ model.fit(X_train, y_train)
252
+
253
+ # Evaluate
254
+ predictions = model.predict(X_test)
255
+ accuracy = accuracy_score(y_test, predictions)
256
+
257
+ print(f"Model Accuracy: {accuracy:.2%}")
258
+ print(f"\\nFeature Importances:")
259
+ for name, importance in zip(iris.feature_names, model.feature_importances_):
260
+ print(f" {name}: {importance:.3f}")"""
261
+ }
262
+
263
+ def load_example(example_name):
264
+ """Load example code"""
265
+ return EXAMPLES.get(example_name, "")
266
+
267
+ # Custom CSS for better UI
268
+ custom_css = """
269
+ #code-input textarea {
270
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
271
+ font-size: 14px !important;
272
+ }
273
+ #output-display textarea {
274
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
275
+ font-size: 13px !important;
276
+ }
277
+ .gradio-container {
278
+ max-width: 1400px !important;
279
+ }
280
+ """
281
+
282
+ # Build Gradio Interface
283
+ with gr.Blocks(css=custom_css, title="πŸš€ Code Interpreter Pro", theme=gr.themes.Soft()) as demo:
284
+ gr.Markdown("""
285
+ # πŸš€ Code Interpreter Pro - HuggingFace Edition
286
+
287
+ A powerful Python code execution sandbox with:
288
+ - ✨ **Real-time code execution** with session management
289
+ - πŸ“¦ **Dynamic package installation**
290
+ - πŸ“Š **Data visualization** (matplotlib, plotly, seaborn)
291
+ - πŸ“ **File upload/download** capabilities
292
+ - πŸ”„ **Persistent session** (variables maintained across runs)
293
+ - 🎯 **Better than basic sandboxes** - Full-featured development environment
294
+ """)
295
+
296
+ with gr.Tabs():
297
+ # Main Code Editor Tab
298
+ with gr.Tab("πŸ’» Code Editor"):
299
+ with gr.Row():
300
+ with gr.Column(scale=2):
301
+ code_input = gr.Code(
302
+ label="Python Code Editor",
303
+ language="python",
304
+ lines=20,
305
+ elem_id="code-input"
306
+ )
307
+
308
+ with gr.Row():
309
+ run_btn = gr.Button("▢️ Run Code", variant="primary", size="lg")
310
+ maintain_session_check = gr.Checkbox(
311
+ label="Maintain Session (keep variables)",
312
+ value=True
313
+ )
314
+
315
+ with gr.Row():
316
+ example_dropdown = gr.Dropdown(
317
+ choices=list(EXAMPLES.keys()),
318
+ label="πŸ“š Load Example",
319
+ value=None
320
+ )
321
+ load_example_btn = gr.Button("Load", size="sm")
322
+
323
+ with gr.Column(scale=2):
324
+ output_display = gr.Textbox(
325
+ label="Output",
326
+ lines=20,
327
+ max_lines=30,
328
+ elem_id="output-display"
329
+ )
330
+
331
+ # Package Manager Tab
332
+ with gr.Tab("πŸ“¦ Package Manager"):
333
+ gr.Markdown("### Install Python Packages")
334
+ gr.Markdown("Install any package from PyPI (e.g., pandas, numpy, requests)")
335
+
336
+ with gr.Row():
337
+ package_input = gr.Textbox(
338
+ label="Package Name",
339
+ placeholder="e.g., pandas, requests, beautifulsoup4"
340
+ )
341
+ install_btn = gr.Button("Install", variant="primary")
342
+
343
+ install_output = gr.Textbox(label="Installation Output", lines=5)
344
+
345
+ gr.Markdown("""
346
+ ### Pre-installed Packages
347
+ - numpy, pandas, matplotlib
348
+ - scikit-learn, scipy
349
+ - requests, beautifulsoup4
350
+ - And more...
351
+ """)
352
+
353
+ # File Manager Tab
354
+ with gr.Tab("πŸ“ File Manager"):
355
+ gr.Markdown("### Workspace File Manager")
356
+ gr.Markdown(f"Files are stored in: `{WORKSPACE_DIR}`")
357
+
358
+ with gr.Row():
359
+ with gr.Column():
360
+ gr.Markdown("#### Upload Files")
361
+ file_upload = gr.File(
362
+ label="Select files to upload",
363
+ file_count="multiple"
364
+ )
365
+ upload_btn = gr.Button("Upload to Workspace", variant="primary")
366
+ upload_output = gr.Textbox(label="Upload Status", lines=3)
367
+
368
+ with gr.Column():
369
+ gr.Markdown("#### Workspace Files")
370
+ list_files_btn = gr.Button("πŸ”„ Refresh File List", variant="secondary")
371
+ files_list = gr.Textbox(label="Files in Workspace", lines=10)
372
+
373
+ gr.Markdown("#### Download Files")
374
+ workspace_files = gr.File(
375
+ label="Download files from workspace",
376
+ file_count="multiple",
377
+ type="filepath",
378
+ interactive=False
379
+ )
380
+
381
+ # Session Manager Tab
382
+ with gr.Tab("πŸ”„ Session Manager"):
383
+ gr.Markdown("### Session Management")
384
+ gr.Markdown("Control your execution session and view session state")
385
+
386
+ reset_btn = gr.Button("πŸ—‘οΈ Reset Session", variant="stop")
387
+ reset_output = gr.Textbox(label="Status", lines=2)
388
+
389
+ gr.Markdown("""
390
+ ### Session Info
391
+ - **Maintain Session ON**: Variables persist between code executions
392
+ - **Maintain Session OFF**: Fresh environment for each execution
393
+ - **Reset Session**: Clear all variables and start fresh
394
+ """)
395
+
396
+ # Help Tab
397
+ with gr.Tab("❓ Help & Tips"):
398
+ gr.Markdown("""
399
+ ## 🎯 Quick Start Guide
400
+
401
+ ### Basic Usage
402
+ 1. Write or paste Python code in the editor
403
+ 2. Click "▢️ Run Code" to execute
404
+ 3. View output in the right panel
405
+
406
+ ### Advanced Features
407
+
408
+ #### πŸ“Š Creating Visualizations
409
+ ```python
410
+ import matplotlib.pyplot as plt
411
+
412
+ plt.figure(figsize=(10, 6))
413
+ plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
414
+ plt.savefig(f'{WORKSPACE}/my_plot.png')
415
+ print("Plot saved!")
416
+ ```
417
+
418
+ #### πŸ“ Working with Files
419
+ ```python
420
+ # Access workspace directory
421
+ print(f"Workspace: {WORKSPACE}")
422
+
423
+ # Save data
424
+ with open(f'{WORKSPACE}/data.txt', 'w') as f:
425
+ f.write("Hello World!")
426
+
427
+ # Read data
428
+ with open(f'{WORKSPACE}/data.txt', 'r') as f:
429
+ print(f.read())
430
+ ```
431
+
432
+ #### πŸ“¦ Installing Packages
433
+ Go to "Package Manager" tab and install any PyPI package!
434
+
435
+ ### Tips
436
+ - Use `maintain_session=True` to keep variables between runs
437
+ - Save plots to workspace to download them
438
+ - Upload CSV/JSON files to analyze data
439
+ - Install packages dynamically as needed
440
+
441
+ ### Advantages over e2b.dev
442
+ - βœ… Free and open-source
443
+ - βœ… Integrated file management
444
+ - βœ… Visual package manager
445
+ - βœ… Session persistence
446
+ - βœ… Better UI/UX
447
+ - βœ… Hosted on HuggingFace (reliable infrastructure)
448
+ """)
449
+
450
+ # Event handlers
451
+ run_btn.click(
452
+ fn=run_code,
453
+ inputs=[code_input, maintain_session_check],
454
+ outputs=output_display
455
+ )
456
+
457
+ load_example_btn.click(
458
+ fn=load_example,
459
+ inputs=example_dropdown,
460
+ outputs=code_input
461
+ )
462
+
463
+ install_btn.click(
464
+ fn=install_package_handler,
465
+ inputs=package_input,
466
+ outputs=install_output
467
+ )
468
+
469
+ upload_btn.click(
470
+ fn=upload_file_handler,
471
+ inputs=file_upload,
472
+ outputs=upload_output
473
+ )
474
+
475
+ list_files_btn.click(
476
+ fn=list_files_handler,
477
+ outputs=files_list
478
+ )
479
+
480
+ reset_btn.click(
481
+ fn=reset_session_handler,
482
+ outputs=reset_output
483
+ )
484
+
485
+ if __name__ == "__main__":
486
+ demo.launch()