Srevarshan1502 commited on
Commit
605b91b
·
1 Parent(s): e65d68f
Files changed (7) hide show
  1. Dockerfile +47 -0
  2. README.md +5 -4
  3. app.py +552 -0
  4. docker-compose.yml +29 -0
  5. index.html +243 -0
  6. requirements.txt +3 -0
  7. test.py +114 -0
Dockerfile ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use official Python runtime as base image
2
+ FROM python:3.9-slim
3
+
4
+ # Set working directory in container
5
+ WORKDIR /app
6
+
7
+ # Set environment variables
8
+ ENV PYTHONUNBUFFERED=1
9
+ ENV PYTHONDONTWRITEBYTECODE=1
10
+ ENV FASTAPI_SERVER_NAME=0.0.0.0
11
+ ENV FASTAPI_SERVER_PORT=7860
12
+
13
+ # Install build dependencies for some Python packages (like uvicorn, fastapi)
14
+ # and for the signal handling
15
+ RUN apt-get update && apt-get install -y \
16
+ gcc \
17
+ g++ \
18
+ && rm -rf /var/lib/apt/lists/*
19
+
20
+ # Copy requirements.txt and install Python dependencies
21
+ COPY requirements.txt .
22
+ RUN pip install --no-cache-dir --upgrade pip && \
23
+ pip install --no-cache-dir -r requirements.txt
24
+
25
+ # --- Diagnostic step: List contents of /app before copying index.html ---
26
+ # This command will output the contents of the /app directory in the build logs.
27
+ # It can help diagnose if an unexpected 'file' is already present.
28
+ RUN echo "Contents of /app before copying index.html:"
29
+ RUN ls -la /app
30
+ # --- End Diagnostic step ---
31
+
32
+ # Copy the application files
33
+ COPY app.py .
34
+ # Explicitly copy index.html to /app/index.html to avoid any ambiguity with '.'
35
+ # This is the primary change to address "cannot copy to non-directory: .../app/file"
36
+ COPY index.html /app/index.html
37
+
38
+ # Create a non-root user for security
39
+ RUN useradd --create-home --shell /bin/bash app && \
40
+ chown -R app:app /app
41
+ USER app
42
+
43
+ # Expose the port FastAPI will run on
44
+ EXPOSE 7860
45
+
46
+ # Command to run the FastAPI application using Uvicorn
47
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,11 @@
1
  ---
2
- title: Python Server
3
- emoji: 🌖
4
- colorFrom: pink
5
- colorTo: green
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Collaborative Python Executor
3
+ emoji: 🐨
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
  sdk: docker
7
  pinned: false
8
+ license: artistic-2.0
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import io
3
+ import traceback
4
+ import ast
5
+ import time
6
+ import json
7
+ import os
8
+ from contextlib import redirect_stdout, redirect_stderr
9
+ from typing import Dict, Any, Optional
10
+ import threading
11
+ import asyncio
12
+ import signal
13
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
14
+ from pydantic import BaseModel
15
+ from starlette.responses import HTMLResponse
16
+
17
+ # Set up proper signal handling for Docker
18
+ def signal_handler(signum, frame):
19
+ print(f"Received signal {signum}, shutting down gracefully...")
20
+ sys.exit(0)
21
+
22
+ signal.signal(signal.SIGTERM, signal_handler)
23
+ signal.signal(signal.SIGINT, signal_handler)
24
+
25
+ # --- Custom IO Redirection for Interactive Execution ---
26
+
27
+ class WebSocketInputOutput:
28
+ """
29
+ Redirects stdin/stdout/stderr to/from a WebSocket connection.
30
+ Handles interactive input by waiting for messages from the client.
31
+ """
32
+ def __init__(self, websocket: WebSocket):
33
+ self.websocket = websocket
34
+ self.input_queue = asyncio.Queue()
35
+ self.output_buffer = io.StringIO()
36
+ self.error_buffer = io.StringIO()
37
+ self.closed = False
38
+
39
+ async def write(self, s: str):
40
+ """Writes to stdout/stderr and sends to WebSocket."""
41
+ self.output_buffer.write(s)
42
+ try:
43
+ # Send output in chunks or lines to prevent large messages
44
+ await self.websocket.send_text(json.dumps({"type": "output", "content": s}))
45
+ except WebSocketDisconnect:
46
+ self.closed = True
47
+ print("WebSocket disconnected during write.")
48
+ except Exception as e:
49
+ print(f"Error sending output over WebSocket: {e}")
50
+ self.closed = True
51
+
52
+ def flush(self):
53
+ """Flushes the buffer (no-op for now, as we send immediately)."""
54
+ pass
55
+
56
+ async def readline(self) -> str:
57
+ """Reads a line from stdin, waiting for input from WebSocket."""
58
+ try:
59
+ await self.websocket.send_text(json.dumps({"type": "input_request"}))
60
+ line = await self.input_queue.get() # Wait for input from client
61
+ return line
62
+ except WebSocketDisconnect:
63
+ self.closed = True
64
+ print("WebSocket disconnected during readline.")
65
+ raise EOFError("Input stream closed due to WebSocket disconnect")
66
+ except Exception as e:
67
+ print(f"Error requesting input over WebSocket: {e}")
68
+ self.closed = True
69
+ raise EOFError(f"Input stream error: {e}")
70
+
71
+ # For compatibility with sys.stdin, which expects a file-like object
72
+ def _get_input_line(self):
73
+ """Synchronous wrapper for readline for use with exec."""
74
+ # This is a bit tricky: exec is synchronous, but WebSocket is async.
75
+ # We need to bridge this. A simple way is to run the async part
76
+ # in the event loop, but it's usually better to refactor the executor
77
+ # to be fully async if input() is truly interactive.
78
+ # For this example, we'll use a blocking call to asyncio.run
79
+ # which is generally discouraged in a running event loop,
80
+ # but works for simple cases or if the exec is in a separate thread.
81
+ # A more robust solution involves a custom Future/Event loop integration.
82
+ try:
83
+ # This will block the current thread until input is available
84
+ return asyncio.run(self.readline())
85
+ except Exception as e:
86
+ print(f"Synchronous input wrapper error: {e}")
87
+ raise
88
+
89
+ def read(self, n=-1):
90
+ """Reads n characters. For simplicity, we'll treat it as readline."""
91
+ return self._get_input_line() # Or implement more complex buffering
92
+
93
+ def __getattr__(self, name):
94
+ """Delegate other attributes if needed, or raise AttributeError."""
95
+ # This is a placeholder; real implementation would be more robust
96
+ # For now, we only need write, flush, and readline.
97
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
98
+
99
+
100
+ # --- Python Syntax Validation FSM (unchanged) ---
101
+
102
+ class PythonSyntaxFSM:
103
+ """Finite State Machine for Python syntax validation"""
104
+
105
+ def __init__(self):
106
+ self.reset()
107
+
108
+ def reset(self):
109
+ self.state = 'normal'
110
+ self.bracket_stack = []
111
+ self.in_string = False
112
+ self.string_delimiter = None
113
+ self.line_number = 0
114
+ self.errors = []
115
+ self.warnings = []
116
+
117
+ def validate_code(self, code: str) -> Dict[str, Any]:
118
+ """Validate Python code using FSM approach"""
119
+ self.reset()
120
+
121
+ if not code or not code.strip():
122
+ return {
123
+ 'valid': False,
124
+ 'errors': [{'line': 0, 'message': 'Empty code input', 'type': 'input_error'}],
125
+ 'warnings': [],
126
+ 'total_issues': 1
127
+ }
128
+
129
+ lines = code.split('\n')
130
+
131
+ for i, line in enumerate(lines):
132
+ self.line_number = i + 1
133
+ self.validate_line(line)
134
+
135
+ # Check for unclosed brackets at end
136
+ if self.bracket_stack:
137
+ self.errors.append({
138
+ 'line': self.line_number,
139
+ 'type': 'syntax_error',
140
+ 'message': f'Unclosed bracket: {self.bracket_stack[-1]}',
141
+ 'severity': 'error'
142
+ })
143
+
144
+ return {
145
+ 'valid': len(self.errors) == 0,
146
+ 'errors': self.errors,
147
+ 'warnings': self.warnings,
148
+ 'total_issues': len(self.errors) + len(self.warnings)
149
+ }
150
+
151
+ def validate_line(self, line: str):
152
+ """Validate a single line using FSM logic"""
153
+ if not line.strip():
154
+ return
155
+
156
+ # Check indentation
157
+ leading_spaces = len(line) - len(line.lstrip())
158
+ if leading_spaces % 4 != 0 and line.strip():
159
+ self.warnings.append({
160
+ 'line': self.line_number,
161
+ 'type': 'style_warning',
162
+ 'message': 'Inconsistent indentation (PEP 8 recommends 4 spaces)',
163
+ 'severity': 'warning'
164
+ })
165
+
166
+ # Process character by character for brackets and strings
167
+ i = 0
168
+ while i < len(line):
169
+ char = line[i]
170
+
171
+ # Handle string states
172
+ if self.in_string:
173
+ if char == self.string_delimiter and (i == 0 or line[i-1] != '\\'):
174
+ self.in_string = False
175
+ self.string_delimiter = None
176
+ i += 1
177
+ continue
178
+
179
+ # Handle comment detection
180
+ if char == '#':
181
+ break # Rest of line is comment
182
+
183
+ # Handle string detection
184
+ if char in ['"', "'"]:
185
+ # Check for triple quotes
186
+ if i + 2 < len(line) and line[i:i+3] == char * 3:
187
+ self.string_delimiter = char * 3
188
+ i += 3
189
+ else:
190
+ self.string_delimiter = char
191
+ i += 1
192
+ self.in_string = True
193
+ continue
194
+
195
+ # Handle brackets
196
+ if char in '([{':
197
+ self.bracket_stack.append(char)
198
+ elif char in ')]}':
199
+ if not self.bracket_stack:
200
+ self.errors.append({
201
+ 'line': self.line_number,
202
+ 'type': 'syntax_error',
203
+ 'message': f'Unmatched closing bracket: {char}',
204
+ 'severity': 'error'
205
+ })
206
+ else:
207
+ expected = {'(': ')', '[': ']', '{': '}'}
208
+ last_open = self.bracket_stack[-1]
209
+ if expected[last_open] != char:
210
+ self.errors.append({
211
+ 'line': self.line_number,
212
+ 'type': 'syntax_error',
213
+ 'message': f'Mismatched brackets: expected {expected[last_open]}, got {char}',
214
+ 'severity': 'error'
215
+ })
216
+ else:
217
+ self.bracket_stack.pop()
218
+
219
+ i += 1
220
+
221
+ # Check Python syntax patterns
222
+ stripped = line.strip()
223
+ control_keywords = ['def ', 'class ', 'if ', 'elif ', 'for ', 'while ', 'try:', 'except']
224
+
225
+ for keyword in control_keywords:
226
+ if stripped.startswith(keyword):
227
+ if not stripped.endswith(':') and keyword != 'except':
228
+ self.errors.append({
229
+ 'line': self.line_number,
230
+ 'type': 'syntax_error',
231
+ 'message': f'{keyword.strip()} statement must end with colon',
232
+ 'severity': 'error'
233
+ })
234
+ break
235
+
236
+ # --- Secure Python Executor (modified for WebSockets) ---
237
+
238
+ class SecurePythonExecutor:
239
+ """Secure Python code executor with sandboxing and timeout, now interactive."""
240
+
241
+ def __init__(self, timeout: int = 10):
242
+ self.timeout = timeout
243
+ self.restricted_modules = {
244
+ 'os', 'sys', 'subprocess', 'socket', 'urllib', 'requests',
245
+ 'shutil', 'glob', 'pickle', 'marshal', 'shelve', 'dbm',
246
+ 'sqlite3', 'threading', 'multiprocessing', 'ctypes', 'importlib',
247
+ 'builtins', '__builtin__', 'imp', 'zipimport'
248
+ }
249
+
250
+ # Create safe builtins
251
+ # IMPORTANT: 'input' is now included and will be redirected!
252
+ self.safe_builtins = {
253
+ 'print': print,
254
+ 'len': len,
255
+ 'range': range,
256
+ 'str': str,
257
+ 'int': int,
258
+ 'float': float,
259
+ 'bool': bool,
260
+ 'list': list,
261
+ 'dict': dict,
262
+ 'tuple': tuple,
263
+ 'set': set,
264
+ 'frozenset': frozenset,
265
+ 'abs': abs,
266
+ 'max': max,
267
+ 'min': min,
268
+ 'sum': sum,
269
+ 'sorted': sorted,
270
+ 'reversed': reversed,
271
+ 'enumerate': enumerate,
272
+ 'zip': zip,
273
+ 'map': map,
274
+ 'filter': filter,
275
+ 'all': all,
276
+ 'any': any,
277
+ 'type': type,
278
+ 'isinstance': isinstance,
279
+ 'hasattr': hasattr,
280
+ 'getattr': getattr,
281
+ 'setattr': setattr,
282
+ 'delattr': delattr,
283
+ 'round': round,
284
+ 'pow': pow,
285
+ 'divmod': divmod,
286
+ 'chr': chr,
287
+ 'ord': ord,
288
+ 'hex': hex,
289
+ 'oct': oct,
290
+ 'bin': bin,
291
+ 'format': format,
292
+ 'repr': repr,
293
+ 'ascii': ascii,
294
+ 'iter': iter,
295
+ 'next': next,
296
+ 'slice': slice,
297
+ 'callable': callable,
298
+ 'id': id,
299
+ 'hash': hash,
300
+ 'vars': vars,
301
+ 'dir': dir,
302
+ 'help': help,
303
+ 'Exception': Exception,
304
+ 'ValueError': ValueError,
305
+ 'TypeError': TypeError,
306
+ 'IndexError': IndexError,
307
+ 'KeyError': KeyError,
308
+ 'AttributeError': AttributeError,
309
+ 'NameError': NameError,
310
+ 'ZeroDivisionError': ZeroDivisionError,
311
+ 'input': input # Now included for interactive use
312
+ }
313
+
314
+ async def execute_code(self, code: str, websocket_io: WebSocketInputOutput) -> Dict[str, Any]:
315
+ """Execute Python code in a secure environment with WebSocket IO."""
316
+ start_time = time.time()
317
+
318
+ # Input validation
319
+ if not code or not code.strip():
320
+ error_msg = 'No code provided'
321
+ await websocket_io.write(f"Error: {error_msg}\n")
322
+ return {
323
+ 'success': False,
324
+ 'output': '',
325
+ 'error': error_msg,
326
+ 'execution_time': 0,
327
+ 'validation': {
328
+ 'valid': False,
329
+ 'errors': [{'message': error_msg, 'line': 0}],
330
+ 'warnings': [],
331
+ 'total_issues': 1
332
+ }
333
+ }
334
+
335
+ # Pre-execution validation
336
+ fsm = PythonSyntaxFSM()
337
+ validation_result = fsm.validate_code(code)
338
+
339
+ # Check for restricted imports
340
+ restricted_check = self.check_restricted_imports(code)
341
+ if not restricted_check['allowed']:
342
+ error_msg = f"Security violation: Restricted module '{restricted_check['module']}' is not allowed"
343
+ await websocket_io.write(f"Error: {error_msg}\n")
344
+ return {
345
+ 'success': False,
346
+ 'output': '',
347
+ 'error': error_msg,
348
+ 'execution_time': 0,
349
+ 'validation': validation_result
350
+ }
351
+
352
+ # Execute code with timeout
353
+ result = await self.run_with_timeout(code, websocket_io) # Pass websocket_io
354
+ execution_time = time.time() - start_time
355
+
356
+ return {
357
+ 'success': result['success'],
358
+ 'output': result['output'],
359
+ 'error': result['error'],
360
+ 'execution_time': round(execution_time, 3),
361
+ 'validation': validation_result
362
+ }
363
+
364
+ def check_restricted_imports(self, code: str) -> Dict[str, Any]:
365
+ """Check for restricted module imports"""
366
+ try:
367
+ tree = ast.parse(code)
368
+ for node in ast.walk(tree):
369
+ if isinstance(node, ast.Import):
370
+ for alias in node.names:
371
+ if alias.name.split('.')[0] in self.restricted_modules:
372
+ return {'allowed': False, 'module': alias.name}
373
+ elif isinstance(node, ast.ImportFrom):
374
+ if node.module and node.module.split('.')[0] in self.restricted_modules:
375
+ return {'allowed': False, 'module': node.module}
376
+ return {'allowed': True, 'module': None}
377
+ except Exception:
378
+ return {'allowed': True, 'module': None} # If parsing fails, let execution handle it
379
+
380
+ async def run_with_timeout(self, code: str, websocket_io: WebSocketInputOutput) -> Dict[str, Any]:
381
+ """Run code with timeout protection, interacting via WebSocketIO."""
382
+ result = {'success': False, 'output': '', 'error': ''}
383
+
384
+ # Store original stdin/stdout/stderr
385
+ original_stdin = sys.stdin
386
+ original_stdout = sys.stdout
387
+ original_stderr = sys.stderr
388
+
389
+ # Use a threading.Event to signal completion from the execution thread
390
+ execution_finished_event = threading.Event()
391
+
392
+ def target():
393
+ nonlocal result
394
+ try:
395
+ # Redirect sys.stdin, sys.stdout, sys.stderr for this thread
396
+ sys.stdin = websocket_io
397
+ sys.stdout = websocket_io
398
+ sys.stderr = websocket_io
399
+
400
+ # Create restricted execution environment
401
+ restricted_globals = {
402
+ '__builtins__': self.safe_builtins,
403
+ '__name__': '__main__',
404
+ '__doc__': None,
405
+ }
406
+
407
+ # Execute the code
408
+ exec(code, restricted_globals)
409
+ result['success'] = True
410
+
411
+ except EOFError as e:
412
+ # This happens if the WebSocket disconnects during input()
413
+ result['error'] = f"Input stream closed: {str(e)}"
414
+ result['success'] = False
415
+ except Exception as e:
416
+ error_msg = f"{type(e).__name__}: {str(e)}\n{traceback.format_exc()}"
417
+ # Write error to WebSocket and internal buffer
418
+ try:
419
+ asyncio.run(websocket_io.write(f"Error: {error_msg}\n"))
420
+ except Exception as write_e:
421
+ print(f"Failed to write error to WebSocket: {write_e}")
422
+ websocket_io.error_buffer.write(error_msg)
423
+ result['success'] = False
424
+ finally:
425
+ # Restore original stdin/stdout/stderr for the thread pool (if applicable)
426
+ sys.stdin = original_stdin
427
+ sys.stdout = original_stdout
428
+ sys.stderr = original_stderr
429
+ execution_finished_event.set() # Signal completion
430
+
431
+ # Run the execution in a separate thread to allow for timeout
432
+ thread = threading.Thread(target=target)
433
+ thread.daemon = True # Allow the program to exit even if thread is running
434
+ thread.start()
435
+
436
+ # Wait for the thread to finish or timeout
437
+ thread.join(timeout=self.timeout)
438
+
439
+ if thread.is_alive():
440
+ result['error'] = f"Code execution timed out after {self.timeout} seconds"
441
+ result['success'] = False
442
+ # Attempt to send timeout message to client
443
+ try:
444
+ await websocket_io.write(f"Error: {result['error']}\n")
445
+ except Exception:
446
+ pass # Ignore if websocket is already closed
447
+ else:
448
+ # Execution finished within timeout
449
+ result['output'] = websocket_io.output_buffer.getvalue()
450
+ if websocket_io.error_buffer.getvalue():
451
+ result['error'] = websocket_io.error_buffer.getvalue()
452
+ result['success'] = False
453
+ else:
454
+ result['success'] = True
455
+
456
+ # Send a final message to the client indicating execution is complete
457
+ try:
458
+ await websocket_io.send_text(json.dumps({"type": "execution_complete", "result": result}))
459
+ except WebSocketDisconnect:
460
+ pass # Ignore if websocket is already closed
461
+ except Exception as e:
462
+ print(f"Error sending execution_complete message: {e}")
463
+
464
+ return result
465
+
466
+
467
+ # Initialize the executor
468
+ executor = SecurePythonExecutor(timeout=10)
469
+
470
+ # Initialize FastAPI app
471
+ app = FastAPI(
472
+ title="Interactive Python Code Executor API",
473
+ description="A secure WebSocket API for executing Python code interactively.",
474
+ version="1.0.0",
475
+ )
476
+
477
+ # Serve the HTML frontend
478
+ @app.get("/", response_class=HTMLResponse)
479
+ async def get_index():
480
+ """Serves the interactive frontend."""
481
+ # This assumes index.html is in the same directory as app.py
482
+ with open("index.html", "r") as f:
483
+ return HTMLResponse(content=f.read())
484
+
485
+ # WebSocket endpoint for interactive execution
486
+ @app.websocket("/ws")
487
+ async def websocket_endpoint(websocket: WebSocket):
488
+ await websocket.accept()
489
+ websocket_io = WebSocketInputOutput(websocket)
490
+ print(f"WebSocket connection established: {websocket.client}")
491
+
492
+ try:
493
+ while True:
494
+ message = await websocket.receive_text()
495
+ data = json.loads(message)
496
+
497
+ if data["type"] == "code":
498
+ code = data["content"]
499
+ print(f"Received code from {websocket.client}: {code[:50]}...")
500
+ # Execute code asynchronously in the background
501
+ asyncio.create_task(executor.execute_code(code, websocket_io))
502
+ elif data["type"] == "input":
503
+ user_input = data["content"]
504
+ print(f"Received input from {websocket.client}: {user_input.strip()[:50]}...")
505
+ await websocket_io.input_queue.put(user_input + "\n") # Add newline for readline
506
+ elif data["type"] == "ping":
507
+ # Respond to pings to keep connection alive
508
+ await websocket.send_text(json.dumps({"type": "pong"}))
509
+ else:
510
+ await websocket_io.write(f"Unknown message type: {data['type']}\n")
511
+
512
+ except WebSocketDisconnect:
513
+ print(f"WebSocket disconnected: {websocket.client}")
514
+ except json.JSONDecodeError:
515
+ print(f"Received invalid JSON from {websocket.client}: {message}")
516
+ except Exception as e:
517
+ print(f"WebSocket error for {websocket.client}: {e}")
518
+ finally:
519
+ websocket_io.closed = True
520
+ # Clean up any pending input requests if the client disconnects
521
+ while not websocket_io.input_queue.empty():
522
+ try:
523
+ websocket_io.input_queue.get_nowait()
524
+ except asyncio.QueueEmpty:
525
+ pass
526
+ print(f"WebSocket connection closed for {websocket.client}")
527
+
528
+ # This block is for local development using `uvicorn`
529
+ # Hugging Face Spaces will use `uvicorn` directly via the Dockerfile CMD
530
+ if __name__ == "__main__":
531
+ import uvicorn
532
+ print("Starting Interactive Python Code Executor API (FastAPI)...")
533
+ print(f"Python version: {sys.version}")
534
+ print(f"Working directory: {os.getcwd()}")
535
+
536
+ server_name = os.getenv('FASTAPI_SERVER_NAME', '0.0.0.0')
537
+ server_port = int(os.getenv('FASTAPI_SERVER_PORT', 7860))
538
+
539
+ print(f"Starting server on {server_name}:{server_port}")
540
+
541
+ try:
542
+ uvicorn.run(
543
+ "app:app", # app:app means the `app` object in `app.py`
544
+ host=server_name,
545
+ port=server_port,
546
+ reload=False, # Set to True for local dev to auto-reload on code changes
547
+ log_level="info"
548
+ )
549
+ except Exception as e:
550
+ print(f"Failed to start server: {e}")
551
+ sys.exit(1)
552
+
docker-compose.yml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ python-executor:
5
+ build: .
6
+ ports:
7
+ - "7860:7860"
8
+ environment:
9
+ - GRADIO_SERVER_NAME=0.0.0.0
10
+ - GRADIO_SERVER_PORT=7860
11
+ - PYTHONUNBUFFERED=1
12
+ volumes:
13
+ # Optional: Mount for development
14
+ - ./app.py:/app/app.py:ro
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "curl", "-f", "http://localhost:7860/health"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 60s
22
+ deploy:
23
+ resources:
24
+ limits:
25
+ memory: 512M
26
+ cpus: '0.5'
27
+ reservations:
28
+ memory: 256M
29
+ cpus: '0.25'
index.html ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Interactive Python Executor</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
9
+ <style>
10
+ body {
11
+ font-family: 'Inter', sans-serif;
12
+ background-color: #1a202c; /* Dark background */
13
+ color: #e2e8f0; /* Light text */
14
+ display: flex;
15
+ justify-content: center;
16
+ align-items: flex-start;
17
+ min-height: 100vh;
18
+ padding: 2rem;
19
+ box-sizing: border-box;
20
+ }
21
+ .container {
22
+ background-color: #2d3748; /* Slightly lighter dark for container */
23
+ border-radius: 0.75rem; /* rounded-xl */
24
+ box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2); /* shadow-xl */
25
+ padding: 2rem;
26
+ max-width: 900px;
27
+ width: 100%;
28
+ display: flex;
29
+ flex-direction: column;
30
+ gap: 1.5rem;
31
+ }
32
+ textarea, input[type="text"] {
33
+ background-color: #1a202c; /* Even darker for input fields */
34
+ color: #e2e8f0;
35
+ border: 1px solid #4a5568; /* border-gray-600 */
36
+ border-radius: 0.5rem; /* rounded-lg */
37
+ padding: 0.75rem 1rem;
38
+ font-family: 'Fira Code', 'Cascadia Code', 'Consolas', monospace; /* Monospace for code */
39
+ font-size: 0.9rem;
40
+ resize: vertical;
41
+ }
42
+ button {
43
+ padding: 0.75rem 1.5rem;
44
+ border-radius: 0.5rem; /* rounded-lg */
45
+ font-weight: 600; /* font-semibold */
46
+ transition: background-color 0.2s, transform 0.1s;
47
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
48
+ }
49
+ button:hover {
50
+ transform: translateY(-1px);
51
+ }
52
+ .btn-primary {
53
+ background-color: #4299e1; /* blue-500 */
54
+ color: white;
55
+ }
56
+ .btn-primary:hover {
57
+ background-color: #3182ce; /* blue-600 */
58
+ }
59
+ .btn-secondary {
60
+ background-color: #a0aec0; /* gray-400 */
61
+ color: #2d3748;
62
+ }
63
+ .btn-secondary:hover {
64
+ background-color: #718096; /* gray-500 */
65
+ }
66
+ .terminal-output {
67
+ background-color: #000; /* Black for terminal */
68
+ color: #0f0; /* Green text for terminal */
69
+ border-radius: 0.5rem;
70
+ padding: 1rem;
71
+ min-height: 200px;
72
+ max-height: 400px;
73
+ overflow-y: auto;
74
+ white-space: pre-wrap; /* Preserve whitespace and wrap text */
75
+ font-family: 'Fira Code', 'Cascadia Code', 'Consolas', monospace;
76
+ font-size: 0.85rem;
77
+ border: 1px solid #4a5568;
78
+ }
79
+ .input-area {
80
+ display: flex;
81
+ gap: 0.5rem;
82
+ margin-top: 1rem;
83
+ }
84
+ .hidden {
85
+ display: none;
86
+ }
87
+ .status-message {
88
+ font-size: 0.8rem;
89
+ color: #cbd5e0;
90
+ margin-top: 0.5rem;
91
+ }
92
+ </style>
93
+ </head>
94
+ <body class="antialiased">
95
+ <div class="container">
96
+ <h1 class="text-3xl font-bold text-center mb-4 text-blue-300">Interactive Python Interpreter</h1>
97
+ <p class="text-center text-gray-400 mb-6">Enter Python code and interact with it in real-time.</p>
98
+
99
+ <div class="flex flex-col gap-4">
100
+ <label for="code-input" class="text-lg font-semibold text-gray-200">Python Code:</label>
101
+ <textarea id="code-input" rows="15" class="focus:ring-blue-500 focus:border-blue-500">
102
+ # Example: Interactive input
103
+ n = int(input("Enter a number: "))
104
+ if n % 2 == 0:
105
+ print("Even")
106
+ else:
107
+ print("Odd")
108
+
109
+ # Example: Multiple inputs
110
+ name = input("What is your name? ")
111
+ age = int(input("How old are you? "))
112
+ print(f"Hello, {name}! You are {age} years old.")
113
+ </textarea>
114
+ <button id="run-button" class="btn-primary">Run Code</button>
115
+ </div>
116
+
117
+ <div class="flex flex-col gap-4">
118
+ <label for="terminal-output" class="text-lg font-semibold text-gray-200">Terminal Output:</label>
119
+ <div id="terminal-output" class="terminal-output"></div>
120
+ <div id="input-prompt-area" class="input-area hidden">
121
+ <input type="text" id="user-input" class="flex-grow" placeholder="Enter input here...">
122
+ <button id="send-input-button" class="btn-primary">Send Input</button>
123
+ </div>
124
+ <p id="status-message" class="status-message">Status: Not connected</p>
125
+ </div>
126
+ </div>
127
+
128
+ <script>
129
+ const codeInput = document.getElementById('code-input');
130
+ const runButton = document.getElementById('run-button');
131
+ const terminalOutput = document.getElementById('terminal-output');
132
+ const inputPromptArea = document.getElementById('input-prompt-area');
133
+ const userInput = document.getElementById('user-input');
134
+ const sendInputButton = document.getElementById('send-input-button');
135
+ const statusMessage = document.getElementById('status-message');
136
+
137
+ let ws;
138
+ let isAwaitingInput = false;
139
+
140
+ function connectWebSocket() {
141
+ let wsUrl;
142
+ if (window.location.protocol === 'https:') {
143
+ // For Hugging Face Spaces, always use wss:// when the page is loaded over HTTPS
144
+ // window.location.hostname is safer as it never includes the port
145
+ wsUrl = `wss://${window.location.hostname}/ws`;
146
+ } else {
147
+ // For local development (http://localhost:7860)
148
+ wsUrl = `ws://${window.location.host}/ws`;
149
+ }
150
+
151
+ console.log('Attempting to connect WebSocket to:', wsUrl);
152
+ console.log('Current page protocol:', window.location.protocol);
153
+ console.log('Current page hostname:', window.location.hostname);
154
+ console.log('Current page host (includes port):', window.location.host);
155
+
156
+
157
+ ws = new WebSocket(wsUrl);
158
+
159
+ ws.onopen = () => {
160
+ statusMessage.textContent = 'Status: Connected';
161
+ runButton.disabled = false;
162
+ console.log('WebSocket connected');
163
+ };
164
+
165
+ ws.onmessage = (event) => {
166
+ const data = JSON.parse(event.data);
167
+ if (data.type === 'output') {
168
+ terminalOutput.textContent += data.content;
169
+ terminalOutput.scrollTop = terminalOutput.scrollHeight; // Auto-scroll
170
+ } else if (data.type === 'input_request') {
171
+ isAwaitingInput = true;
172
+ inputPromptArea.classList.remove('hidden');
173
+ userInput.focus();
174
+ terminalOutput.scrollTop = terminalOutput.scrollHeight; // Auto-scroll
175
+ } else if (data.type === 'execution_complete') {
176
+ isAwaitingInput = false;
177
+ inputPromptArea.classList.add('hidden');
178
+ userInput.value = '';
179
+ statusMessage.textContent = 'Status: Execution complete.';
180
+ console.log('Execution complete:', data.result);
181
+ } else if (data.type === 'pong') {
182
+ // console.log('Pong received');
183
+ }
184
+ };
185
+
186
+ ws.onclose = (event) => {
187
+ statusMessage.textContent = `Status: Disconnected (Code: ${event.code}, Reason: ${event.reason})`;
188
+ runButton.disabled = true;
189
+ inputPromptArea.classList.add('hidden');
190
+ console.log('WebSocket disconnected:', event);
191
+ // Attempt to reconnect after a delay
192
+ setTimeout(connectWebSocket, 3000);
193
+ };
194
+
195
+ ws.onerror = (error) => {
196
+ statusMessage.textContent = 'Status: Connection error';
197
+ console.error('WebSocket error:', error);
198
+ };
199
+ }
200
+
201
+ runButton.addEventListener('click', () => {
202
+ if (ws && ws.readyState === WebSocket.OPEN) {
203
+ terminalOutput.textContent = ''; // Clear previous output
204
+ statusMessage.textContent = 'Status: Running code...';
205
+ isAwaitingInput = false;
206
+ inputPromptArea.classList.add('hidden'); // Hide input area initially
207
+ userInput.value = ''; // Clear input field
208
+
209
+ const code = codeInput.value;
210
+ ws.send(JSON.stringify({ type: 'code', content: code }));
211
+ } else {
212
+ statusMessage.textContent = 'Status: Not connected. Please wait or refresh.';
213
+ }
214
+ });
215
+
216
+ sendInputButton.addEventListener('click', () => {
217
+ if (isAwaitingInput && ws && ws.readyState === WebSocket.OPEN) {
218
+ const inputContent = userInput.value;
219
+ ws.send(JSON.stringify({ type: 'input', content: inputContent }));
220
+ userInput.value = ''; // Clear input field after sending
221
+ inputPromptArea.classList.add('hidden'); // Hide input area until next prompt
222
+ isAwaitingInput = false;
223
+ }
224
+ });
225
+
226
+ userInput.addEventListener('keypress', (event) => {
227
+ if (event.key === 'Enter') {
228
+ sendInputButton.click();
229
+ }
230
+ });
231
+
232
+ // Start WebSocket connection when the page loads
233
+ document.addEventListener('DOMContentLoaded', connectWebSocket);
234
+
235
+ // Optional: Send a ping every 30 seconds to keep the WebSocket connection alive
236
+ setInterval(() => {
237
+ if (ws && ws.readyState === WebSocket.OPEN) {
238
+ ws.send(JSON.stringify({ type: 'ping' }));
239
+ }
240
+ }, 30000); // 30 seconds
241
+ </script>
242
+ </body>
243
+ </html>
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn==0.24.0
3
+ pydantic==2.5.0
test.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import websockets
3
+ import json
4
+
5
+ # Replace with your actual Space URL
6
+ # For Hugging Face Spaces, use wss://<your-space-id>.hf.space/ws
7
+ WS_URL = "wss://Srevarshan1502-collaborative-python-executor.hf.space/ws"
8
+
9
+ async def run_python_code(code_to_execute: str):
10
+ try:
11
+ async with websockets.connect(WS_URL) as websocket:
12
+ print("Connected to WebSocket.")
13
+
14
+ # Send the Python code
15
+ await websocket.send(json.dumps({"type": "code", "content": code_to_execute}))
16
+ print(f"Sent code:\n---\n{code_to_execute}\n---")
17
+
18
+ full_output = ""
19
+ execution_complete = False
20
+
21
+ while not execution_complete:
22
+ try:
23
+ # Keep waiting for messages until execution_complete
24
+ # Increased timeout to 60 seconds as per your last script
25
+ message = await asyncio.wait_for(websocket.recv(), timeout=60)
26
+ data = json.loads(message)
27
+
28
+ if data["type"] == "output":
29
+ full_output += data["content"]
30
+ print(f"Received output chunk: {data['content'].strip()}")
31
+ elif data["type"] == "input_request":
32
+ print("\n--- Input Requested ---")
33
+ user_input = input("Please enter input for the script: ")
34
+ # IMPORTANT: Add newline character for the server's readline() to process it as a complete line
35
+ await websocket.send(json.dumps({"type": "input", "content": user_input + "\n"}))
36
+ print(f"Sent input: {user_input}")
37
+ elif data["type"] == "execution_complete":
38
+ print("\n--- Execution Complete ---")
39
+ # The 'result' field from the server's execution_complete message
40
+ server_result = data['result']
41
+ print(f"Result details from server: {server_result}")
42
+
43
+ # Consolidate output from the server_result as well
44
+ if server_result.get('output'):
45
+ full_output += server_result['output']
46
+ if server_result.get('error'):
47
+ # Prepend "Error:" if it's the first error message
48
+ if "Error from server:" not in full_output:
49
+ full_output += "\nError from server:\n"
50
+ full_output += server_result['error']
51
+
52
+ execution_complete = True
53
+ elif data["type"] == "pong":
54
+ # print("Received pong.") # Optional: uncomment to see pongs
55
+ pass
56
+ else:
57
+ print(f"Received unknown message type: {data['type']} - {data.get('content')}")
58
+
59
+ except asyncio.TimeoutError:
60
+ print("Timeout: No message received from server for 60 seconds. Disconnecting.")
61
+ break
62
+ except websockets.exceptions.ConnectionClosedOK:
63
+ print("Connection closed by server (OK).")
64
+ # If it closes OK before execution_complete, it's an issue
65
+ if not execution_complete:
66
+ print("WARNING: Connection closed OK before execution_complete message was received!")
67
+ break
68
+ except websockets.exceptions.ConnectionClosedError as e:
69
+ print(f"Connection closed with error: {e}")
70
+ break
71
+ except json.JSONDecodeError:
72
+ print(f"Received invalid JSON: {message}")
73
+ break
74
+ except Exception as e:
75
+ print(f"An unexpected error occurred during message reception: {e}")
76
+ break
77
+
78
+ print("\n--- Final Consolidated Output ---")
79
+ print(full_output)
80
+ return full_output
81
+
82
+ except websockets.exceptions.InvalidURI as e:
83
+ print(f"Invalid WebSocket URI: {e}")
84
+ except ConnectionRefusedError:
85
+ print("Connection refused. Is the server running and accessible?")
86
+ except Exception as e:
87
+ print(f"Could not connect to WebSocket: {e}")
88
+ return None
89
+
90
+ if __name__ == "__main__":
91
+ # Test 1: Simple print statement (Matches the current app.py test 1)
92
+ print("\n=== Running Test 1: Simple Print ===")
93
+ asyncio.run(run_python_code(code_to_execute = "print('Hello, Space!')"))
94
+
95
+ # Test 2: Code with interactive input (corrected syntax)
96
+ print("\n=== Running Test 2: Interactive Input ===")
97
+ interactive_code = """
98
+ name = input("Enter your name: ")
99
+ age = int(input("How old are you? "))
100
+ print(f"Hello, {name}! You are {age} years old.")
101
+ """
102
+ # For app.py's Test 2 (where exec is not yet active)
103
+ # asyncio.run(run_python_code(code_to_execute="DUMMY_CODE_FOR_TESTING_SYS_REDIRECTION"))
104
+
105
+ # Once app.py has Test 3 (with exec) uncomment this:
106
+ asyncio.run(run_python_code(interactive_code))
107
+
108
+ # Test 3: Code with error (uncomment when full exec is working)
109
+ # print("\n=== Running Test 3: Code with Error ===")
110
+ # asyncio.run(run_python_code("print(1/0)"))
111
+
112
+ # Test 4: Long-running code (will hit timeout if not finished, uncomment when full exec is working)
113
+ # print("\n=== Running Test 4: Long Running Code ===")
114
+ # asyncio.run(run_python_code("import time\nfor i in range(5):\n print(f'Counting: {i}')\n time.sleep(1)"))