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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import tempfile
4
+ import os
5
+ import json
6
+ import docker
7
+ import time
8
+ from typing import Dict, List, Tuple
9
+ import black
10
+ import autopep8
11
+ import ast
12
+ import sys
13
+ from contextlib import redirect_stdout, redirect_stderr
14
+ from io import StringIO
15
+
16
+ class CodeRunner:
17
+ def __init__(self):
18
+ self.supported_languages = {
19
+ 'python': {'ext': '.py', 'cmd': ['python'], 'formatter': self.format_python},
20
+ 'javascript': {'ext': '.js', 'cmd': ['node'], 'formatter': self.format_javascript},
21
+ 'typescript': {'ext': '.ts', 'cmd': ['ts-node'], 'formatter': None},
22
+ 'go': {'ext': '.go', 'cmd': ['go', 'run'], 'formatter': None},
23
+ 'rust': {'ext': '.rs', 'cmd': ['rustc', '--edition=2021'], 'formatter': None},
24
+ 'c': {'ext': '.c', 'cmd': ['gcc', '-o', '/tmp/output'], 'formatter': None},
25
+ 'cpp': {'ext': '.cpp', 'cmd': ['g++', '-o', '/tmp/output'], 'formatter': None},
26
+ 'java': {'ext': '.java', 'cmd': ['javac'], 'formatter': None},
27
+ 'bash': {'ext': '.sh', 'cmd': ['bash'], 'formatter': None}
28
+ }
29
+
30
+ # Security restrictions
31
+ self.forbidden_imports = {
32
+ 'python': ['os', 'subprocess', 'sys', 'importlib', '__import__'],
33
+ 'javascript': ['fs', 'child_process', 'cluster', 'worker_threads'],
34
+ 'bash': ['rm', 'sudo', 'chmod', 'chown']
35
+ }
36
+
37
+ def run_code_sandboxed(self, code: str, language: str = "python", timeout: int = 10) -> Dict:
38
+ """
39
+ Safely execute code with multiple sandboxing layers
40
+ """
41
+ if language not in self.supported_languages:
42
+ return {
43
+ "success": False,
44
+ "output": f"Language '{language}' not supported. Available: {list(self.supported_languages.keys())}",
45
+ "execution_time": 0
46
+ }
47
+
48
+ # Security check
49
+ security_issues = self.check_security(code, language)
50
+ if security_issues:
51
+ return {
52
+ "success": False,
53
+ "output": f"Security violations detected: {', '.join(security_issues)}",
54
+ "execution_time": 0
55
+ }
56
+
57
+ start_time = time.time()
58
+
59
+ try:
60
+ # Method 1: Direct execution for Python (fastest)
61
+ if language == "python":
62
+ result = self._run_python_restricted(code, timeout)
63
+
64
+ # Method 2: Docker sandboxing for other languages
65
+ else:
66
+ result = self._run_in_docker(code, language, timeout)
67
+
68
+ execution_time = time.time() - start_time
69
+ result["execution_time"] = round(execution_time, 3)
70
+ return result
71
+
72
+ except Exception as e:
73
+ return {
74
+ "success": False,
75
+ "output": f"Execution error: {str(e)}",
76
+ "execution_time": time.time() - start_time
77
+ }
78
+
79
+ def _run_python_restricted(self, code: str, timeout: int) -> Dict:
80
+ """
81
+ Run Python code with restricted builtins and memory/time limits
82
+ """
83
+ # Create restricted environment
84
+ restricted_builtins = {
85
+ 'print': print,
86
+ 'len': len,
87
+ 'str': str,
88
+ 'int': int,
89
+ 'float': float,
90
+ 'list': list,
91
+ 'dict': dict,
92
+ 'tuple': tuple,
93
+ 'set': set,
94
+ 'range': range,
95
+ 'enumerate': enumerate,
96
+ 'zip': zip,
97
+ 'map': map,
98
+ 'filter': filter,
99
+ 'sorted': sorted,
100
+ 'sum': sum,
101
+ 'min': min,
102
+ 'max': max,
103
+ 'abs': abs,
104
+ 'round': round,
105
+ 'isinstance': isinstance,
106
+ 'type': type,
107
+ 'hasattr': hasattr,
108
+ 'getattr': getattr,
109
+ 'setattr': setattr,
110
+ }
111
+
112
+ # Capture output
113
+ stdout_buffer = StringIO()
114
+ stderr_buffer = StringIO()
115
+
116
+ try:
117
+ # Parse and validate AST
118
+ tree = ast.parse(code)
119
+
120
+ # Execute with restrictions
121
+ with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
122
+ exec(compile(tree, '<string>', 'exec'), {
123
+ '__builtins__': restricted_builtins,
124
+ '__name__': '__main__'
125
+ })
126
+
127
+ return {
128
+ "success": True,
129
+ "output": stdout_buffer.getvalue(),
130
+ "errors": stderr_buffer.getvalue()
131
+ }
132
+
133
+ except SyntaxError as e:
134
+ return {
135
+ "success": False,
136
+ "output": f"Syntax Error: {str(e)}"
137
+ }
138
+ except Exception as e:
139
+ return {
140
+ "success": False,
141
+ "output": f"Runtime Error: {str(e)}"
142
+ }
143
+
144
+ def _run_in_docker(self, code: str, language: str, timeout: int) -> Dict:
145
+ """
146
+ Run code in isolated Docker container (requires Docker daemon)
147
+ """
148
+ try:
149
+ client = docker.from_env()
150
+
151
+ # Language-specific Docker images
152
+ images = {
153
+ 'javascript': 'node:18-alpine',
154
+ 'typescript': 'node:18-alpine',
155
+ 'go': 'golang:1.21-alpine',
156
+ 'rust': 'rust:1.70-alpine',
157
+ 'c': 'gcc:latest',
158
+ 'cpp': 'gcc:latest',
159
+ 'java': 'openjdk:17-alpine',
160
+ 'bash': 'alpine:latest'
161
+ }
162
+
163
+ image = images.get(language, 'alpine:latest')
164
+ lang_config = self.supported_languages[language]
165
+
166
+ # Create temporary file
167
+ with tempfile.NamedTemporaryFile(mode='w', suffix=lang_config['ext'], delete=False) as f:
168
+ f.write(code)
169
+ temp_file = f.name
170
+
171
+ try:
172
+ # Run in container
173
+ result = client.containers.run(
174
+ image,
175
+ command=lang_config['cmd'] + [f'/tmp/code{lang_config["ext"]}'],
176
+ volumes={temp_file: {'bind': f'/tmp/code{lang_config["ext"]}', 'mode': 'ro'}},
177
+ mem_limit='128m',
178
+ cpu_quota=50000, # 50% CPU
179
+ network_disabled=True,
180
+ timeout=timeout,
181
+ remove=True,
182
+ capture_output=True,
183
+ text=True
184
+ )
185
+
186
+ return {
187
+ "success": True,
188
+ "output": result.decode('utf-8') if isinstance(result, bytes) else str(result)
189
+ }
190
+
191
+ finally:
192
+ os.unlink(temp_file)
193
+
194
+ except docker.errors.ContainerError as e:
195
+ return {"success": False, "output": f"Container error: {e.stderr.decode()}"}
196
+ except docker.errors.ImageNotFound:
197
+ return {"success": False, "output": f"Docker image not found for {language}"}
198
+ except Exception as e:
199
+ return {"success": False, "output": f"Docker execution failed: {str(e)}"}
200
+
201
+ def _run_with_subprocess(self, code: str, language: str, timeout: int) -> Dict:
202
+ """
203
+ Fallback: Run using subprocess with basic sandboxing
204
+ """
205
+ lang_config = self.supported_languages[language]
206
+
207
+ with tempfile.NamedTemporaryFile(mode='w', suffix=lang_config['ext'], delete=False) as f:
208
+ f.write(code)
209
+ temp_file = f.name
210
+
211
+ try:
212
+ result = subprocess.run(
213
+ lang_config['cmd'] + [temp_file],
214
+ stdout=subprocess.PIPE,
215
+ stderr=subprocess.PIPE,
216
+ text=True,
217
+ timeout=timeout,
218
+ cwd='/tmp', # Restrict to /tmp directory
219
+ env={'PATH': '/usr/bin:/bin'} # Minimal environment
220
+ )
221
+
222
+ return {
223
+ "success": result.returncode == 0,
224
+ "output": result.stdout,
225
+ "errors": result.stderr
226
+ }
227
+
228
+ except subprocess.TimeoutExpired:
229
+ return {"success": False, "output": f"Execution timed out after {timeout}s"}
230
+ except FileNotFoundError:
231
+ return {"success": False, "output": f"Language runtime not found for {language}"}
232
+ finally:
233
+ os.unlink(temp_file)
234
+
235
+ def check_security(self, code: str, language: str) -> List[str]:
236
+ """
237
+ Basic security checks for dangerous patterns
238
+ """
239
+ issues = []
240
+ forbidden = self.forbidden_imports.get(language, [])
241
+
242
+ code_lower = code.lower()
243
+
244
+ # Check forbidden imports/modules
245
+ for forbidden_item in forbidden:
246
+ if forbidden_item in code_lower:
247
+ issues.append(f"Forbidden: {forbidden_item}")
248
+
249
+ # Language-specific checks
250
+ if language == "python":
251
+ dangerous_patterns = ['eval(', 'exec(', '__import__', 'open(', 'file(']
252
+ for pattern in dangerous_patterns:
253
+ if pattern in code_lower:
254
+ issues.append(f"Dangerous pattern: {pattern}")
255
+
256
+ elif language == "bash":
257
+ dangerous_cmds = ['rm -rf', 'sudo', '> /dev/', 'curl', 'wget']
258
+ for cmd in dangerous_cmds:
259
+ if cmd in code_lower:
260
+ issues.append(f"Dangerous command: {cmd}")
261
+
262
+ return issues
263
+
264
+ def format_python(self, code: str) -> str:
265
+ """Format Python code using black and autopep8"""
266
+ try:
267
+ # First pass with autopep8
268
+ formatted = autopep8.fix_code(code)
269
+ # Second pass with black
270
+ formatted = black.format_str(formatted, mode=black.Mode())
271
+ return formatted
272
+ except Exception as e:
273
+ return f"Formatting error: {str(e)}"
274
+
275
+ def format_javascript(self, code: str) -> str:
276
+ """Basic JavaScript formatting (would use prettier in production)"""
277
+ # This is a simplified formatter - in production, use prettier
278
+ lines = code.split('\n')
279
+ formatted_lines = []
280
+ indent_level = 0
281
+
282
+ for line in lines:
283
+ stripped = line.strip()
284
+ if not stripped:
285
+ formatted_lines.append('')
286
+ continue
287
+
288
+ if stripped.endswith('{'):
289
+ formatted_lines.append(' ' * indent_level + stripped)
290
+ indent_level += 1
291
+ elif stripped.startswith('}'):
292
+ indent_level = max(0, indent_level - 1)
293
+ formatted_lines.append(' ' * indent_level + stripped)
294
+ else:
295
+ formatted_lines.append(' ' * indent_level + stripped)
296
+
297
+ return '\n'.join(formatted_lines)
298
+
299
+ def format_code(self, code: str, language: str = "python") -> str:
300
+ """Format code based on language"""
301
+ if language not in self.supported_languages:
302
+ return f"Formatting not supported for {language}"
303
+
304
+ formatter = self.supported_languages[language]['formatter']
305
+ if formatter:
306
+ return formatter(code)
307
+ else:
308
+ return f"No formatter available for {language}"
309
+
310
+ def analyze_code(self, code: str, language: str = "python") -> List[str]:
311
+ """Analyze code for potential issues"""
312
+ issues = []
313
+
314
+ # Security analysis
315
+ security_issues = self.check_security(code, language)
316
+ issues.extend([f"Security: {issue}" for issue in security_issues])
317
+
318
+ # Language-specific analysis
319
+ if language == "python":
320
+ try:
321
+ tree = ast.parse(code)
322
+
323
+ # Check for common issues
324
+ for node in ast.walk(tree):
325
+ if isinstance(node, ast.Global):
326
+ issues.append("Code Quality: Avoid global variables")
327
+ elif isinstance(node, ast.Import):
328
+ for alias in node.names:
329
+ if alias.name.startswith('_'):
330
+ issues.append(f"Style: Avoid importing private modules: {alias.name}")
331
+ elif isinstance(node, ast.FunctionDef):
332
+ if len(node.args.args) > 5:
333
+ issues.append(f"Code Quality: Function '{node.name}' has too many parameters")
334
+
335
+ except SyntaxError as e:
336
+ issues.append(f"Syntax Error: {str(e)}")
337
+
338
+ return issues if issues else ["No issues found"]
339
+
340
+ def generate_code(self, prompt: str, language: str = "python") -> str:
341
+ """Generate basic code templates based on prompt"""
342
+ templates = {
343
+ "python": {
344
+ "function": "def {name}():\n \"\"\"\n {description}\n \"\"\"\n pass",
345
+ "class": "class {name}:\n def __init__(self):\n pass",
346
+ "api": "import requests\n\ndef fetch_data(url):\n response = requests.get(url)\n return response.json()",
347
+ "file": "with open('file.txt', 'r') as f:\n content = f.read()\nprint(content)"
348
+ },
349
+ "javascript": {
350
+ "function": "function {name}() {\n // {description}\n return null;\n}",
351
+ "async": "async function {name}() {\n try {\n // {description}\n return await someAsyncOperation();\n } catch (error) {\n console.error(error);\n }\n}",
352
+ "api": "fetch('/api/data')\n .then(response => response.json())\n .then(data => console.log(data));"
353
+ }
354
+ }
355
+
356
+ prompt_lower = prompt.lower()
357
+ lang_templates = templates.get(language, {})
358
+
359
+ # Simple template matching
360
+ if "function" in prompt_lower:
361
+ template = lang_templates.get("function", f"// {prompt}")
362
+ return template.format(name="myFunction", description=prompt)
363
+ elif "class" in prompt_lower and language == "python":
364
+ template = lang_templates.get("class", f"# {prompt}")
365
+ return template.format(name="MyClass")
366
+ elif "api" in prompt_lower or "fetch" in prompt_lower:
367
+ return lang_templates.get("api", f"// API code for: {prompt}")
368
+ else:
369
+ return f"# Generated code for: {prompt}\n# TODO: Implement functionality"
370
+
371
+ # Initialize the CodeRunner
372
+ runner = CodeRunner()
373
+
374
+ # Gradio interface functions
375
+ def run_code_interface(code: str, language: str, timeout: int = 10):
376
+ result = runner.run_code_sandboxed(code, language.lower(), timeout)
377
+
378
+ output = []
379
+ output.append(f"βœ… Success: {result['success']}")
380
+ output.append(f"⏱️ Execution Time: {result.get('execution_time', 0)}s")
381
+ output.append(f"\nπŸ“€ Output:\n{result.get('output', '')}")
382
+
383
+ if result.get('errors'):
384
+ output.append(f"\n❌ Errors:\n{result['errors']}")
385
+
386
+ return "\n".join(output)
387
+
388
+ def format_code_interface(code: str, language: str):
389
+ return runner.format_code(code, language.lower())
390
+
391
+ def analyze_code_interface(code: str, language: str):
392
+ issues = runner.analyze_code(code, language.lower())
393
+ return "\n".join([f"β€’ {issue}" for issue in issues])
394
+
395
+ def generate_code_interface(prompt: str, language: str):
396
+ return runner.generate_code(prompt, language.lower())
397
+
398
+ # Create Gradio interfaces
399
+ with gr.Blocks(title="CodeRunner - Multi-Language Code Execution Tool") as demo:
400
+ gr.Markdown("# πŸš€ CodeRunner - Secure Multi-Language Code Execution")
401
+ gr.Markdown("Execute, format, analyze, and generate code in multiple programming languages with built-in security sandboxing.")
402
+
403
+ with gr.Tab("πŸƒ Run Code"):
404
+ with gr.Row():
405
+ with gr.Column(scale=2):
406
+ code_input = gr.Textbox(
407
+ label="Code",
408
+ lines=10,
409
+ placeholder="Enter your code here...",
410
+ value="print('Hello, World!')"
411
+ )
412
+ language_select = gr.Dropdown(
413
+ choices=list(runner.supported_languages.keys()),
414
+ value="python",
415
+ label="Language"
416
+ )
417
+ timeout_slider = gr.Slider(1, 30, value=10, label="Timeout (seconds)")
418
+
419
+ with gr.Column(scale=2):
420
+ output = gr.Textbox(label="Output", lines=12, max_lines=20)
421
+
422
+ run_btn = gr.Button("▢️ Run Code", variant="primary")
423
+ run_btn.click(
424
+ run_code_interface,
425
+ inputs=[code_input, language_select, timeout_slider],
426
+ outputs=output
427
+ )
428
+
429
+ with gr.Tab("✨ Format Code"):
430
+ with gr.Row():
431
+ with gr.Column():
432
+ format_input = gr.Textbox(label="Code to Format", lines=8)
433
+ format_lang = gr.Dropdown(choices=["python", "javascript"], value="python", label="Language")
434
+ format_btn = gr.Button("🎨 Format Code")
435
+
436
+ with gr.Column():
437
+ format_output = gr.Textbox(label="Formatted Code", lines=8)
438
+
439
+ format_btn.click(format_code_interface, inputs=[format_input, format_lang], outputs=format_output)
440
+
441
+ with gr.Tab("πŸ” Analyze Code"):
442
+ with gr.Row():
443
+ with gr.Column():
444
+ analyze_input = gr.Textbox(label="Code to Analyze", lines=8)
445
+ analyze_lang = gr.Dropdown(choices=list(runner.supported_languages.keys()), value="python", label="Language")
446
+ analyze_btn = gr.Button("πŸ” Analyze Code")
447
+
448
+ with gr.Column():
449
+ analyze_output = gr.Textbox(label="Analysis Results", lines=8)
450
+
451
+ analyze_btn.click(analyze_code_interface, inputs=[analyze_input, analyze_lang], outputs=analyze_output)
452
+
453
+ with gr.Tab("πŸ€– Generate Code"):
454
+ with gr.Row():
455
+ with gr.Column():
456
+ prompt_input = gr.Textbox(label="Describe what you want to generate", lines=3, placeholder="e.g., 'Create a function that calculates fibonacci numbers'")
457
+ generate_lang = gr.Dropdown(choices=["python", "javascript"], value="python", label="Language")
458
+ generate_btn = gr.Button("πŸš€ Generate Code")
459
+
460
+ with gr.Column():
461
+ generate_output = gr.Textbox(label="Generated Code", lines=10)
462
+
463
+ generate_btn.click(generate_code_interface, inputs=[prompt_input, generate_lang], outputs=generate_output)
464
+
465
+ with gr.Tab("πŸ“š API Documentation"):
466
+ gr.Markdown("""
467
+ ## API Endpoints
468
+
469
+ This CodeRunner can be used as a HuggingChat tool with the following functions:
470
+
471
+ ### 1. `run_code(code: str, language: str, timeout: int = 10)`
472
+ - Executes code safely in a sandboxed environment
473
+ - Supports: Python, JavaScript, TypeScript, Go, Rust, C, C++, Java, Bash
474
+ - Returns: execution result with output and timing
475
+
476
+ ### 2. `format_code(code: str, language: str)`
477
+ - Formats and prettifies code
478
+ - Currently supports: Python (black), JavaScript (basic)
479
+ - Returns: formatted code string
480
+
481
+ ### 3. `analyze_code(code: str, language: str)`
482
+ - Analyzes code for security issues and code quality
483
+ - Checks for dangerous patterns and common mistakes
484
+ - Returns: list of issues and recommendations
485
+
486
+ ### 4. `generate_code(prompt: str, language: str)`
487
+ - Generates basic code templates from natural language
488
+ - Supports common patterns: functions, classes, API calls
489
+ - Returns: generated code template
490
+
491
+ ## Security Features
492
+ - Restricted Python execution environment
493
+ - Docker containerization for other languages
494
+ - Memory and CPU limits
495
+ - Network isolation
496
+ - Forbidden imports/commands detection
497
+ """)
498
+
499
+ if __name__ == "__main__":
500
+ demo.launch(server_name="0.0.0.0", server_port=7860)