Spaces:
Sleeping
Sleeping
Download app/services/code_executor.py from baljot07/studiq-backend: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/app/services/code_executor.py
- Command line
-
hf download hf://spaces/baljot07/studiq-backend/app/services/code_executor.py
-
curl -L -o code_executor.py https://huggingface.co/spaces/baljot07/studiq-backend/resolve/main/app/services/code_executor.py
8.21 kB
| """Code Sandbox Executor — compiles and runs programming snippets using Piston API. | |
| Supports Python, JavaScript, C++, C, Java, and SQL out of the box with zero local overhead. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import logging | |
| from typing import Any, Optional | |
| import httpx | |
| logger = logging.getLogger(__name__) | |
| PISTON_BASE_URL = "https://emkc.org/api/v2/piston" | |
| # Shared, connection-pooled client for Piston calls — `execute()` runs once | |
| # per test case, and exercise_service.py calls it in a loop for multi-test-case | |
| # submissions, so a fresh TCP+TLS handshake per call compounds fast. | |
| _piston_client: Optional[httpx.AsyncClient] = None | |
| _piston_client_lock = asyncio.Lock() | |
| async def _get_piston_client() -> httpx.AsyncClient: | |
| global _piston_client | |
| if _piston_client is None: | |
| async with _piston_client_lock: | |
| if _piston_client is None: | |
| _piston_client = httpx.AsyncClient( | |
| limits=httpx.Limits(max_keepalive_connections=10, max_connections=20), | |
| ) | |
| return _piston_client | |
| async def close_piston_client() -> None: | |
| global _piston_client | |
| if _piston_client is not None: | |
| await _piston_client.aclose() | |
| _piston_client = None | |
| # Shorthand mapping of common file extensions and language nicknames to Piston identifiers | |
| LANGUAGE_MAP = { | |
| "py": "python", | |
| "python": "python", | |
| "js": "javascript", | |
| "javascript": "javascript", | |
| "ts": "typescript", | |
| "typescript": "typescript", | |
| "cpp": "c++", | |
| "c++": "c++", | |
| "c": "c", | |
| "java": "java", | |
| "sql": "sqlite3", | |
| "sqlite": "sqlite3", | |
| "sqlite3": "sqlite3", | |
| "go": "go", | |
| "rust": "rust", | |
| "rs": "rust", | |
| "bash": "bash", | |
| "sh": "bash", | |
| } | |
| # Fallback versions in case dynamic fetching fails | |
| FALLBACK_VERSIONS = { | |
| "python": "3.10.0", | |
| "javascript": "18.15.0", | |
| "typescript": "5.0.3", | |
| "c++": "10.2.0", | |
| "c": "10.2.0", | |
| "java": "15.0.2", | |
| "sqlite3": "3.36.0", | |
| "go": "1.16.2", | |
| "rust": "1.68.2", | |
| "bash": "5.2.0", | |
| } | |
| class CodeExecutor: | |
| """Manages secure sandbox execution of code snippets via the Piston API.""" | |
| _runtimes_cache: dict[str, str] = {} # maps language identifier -> latest version | |
| async def _fetch_latest_versions(cls) -> dict[str, str]: | |
| """Fetch all available runtimes from Piston and cache the latest version for each language.""" | |
| if cls._runtimes_cache: | |
| return cls._runtimes_cache | |
| try: | |
| client = await _get_piston_client() | |
| resp = await client.get(f"{PISTON_BASE_URL}/runtimes", timeout=5.0) | |
| if resp.status_code == 200: | |
| runtimes = resp.json() | |
| new_cache: dict[str, str] = {} | |
| for r in runtimes: | |
| lang = r.get("language") | |
| version = r.get("version") | |
| if lang and version: | |
| # Keep the highest version if multiple exist | |
| if lang not in new_cache or version > new_cache[lang]: | |
| new_cache[lang] = version | |
| cls._runtimes_cache = new_cache | |
| logger.info("Successfully fetched and cached %d Piston language runtimes.", len(cls._runtimes_cache)) | |
| return cls._runtimes_cache | |
| except Exception as exc: | |
| logger.warning("Failed to fetch dynamic Piston runtimes, falling back to static map. Error: %s", exc) | |
| return FALLBACK_VERSIONS | |
| def get_filename(cls, language: str) -> str: | |
| """Get standard entrypoint filename for the given language.""" | |
| exts = { | |
| "python": "main.py", | |
| "javascript": "index.js", | |
| "typescript": "index.ts", | |
| "c++": "main.cpp", | |
| "c": "main.c", | |
| "java": "Main.java", | |
| "sqlite3": "query.sql", | |
| "go": "main.go", | |
| "rust": "main.rs", | |
| "bash": "script.sh", | |
| } | |
| return exts.get(language, "main.txt") | |
| async def execute( | |
| cls, | |
| language_or_alias: str, | |
| code: str, | |
| stdin: Optional[str] = None, | |
| args: Optional[list[str]] = None, | |
| ) -> dict[str, Any]: | |
| """Send a code snippet to the Piston API and return execution stdout/stderr and status metrics.""" | |
| # Standardize language identifier | |
| alias = language_or_alias.lower().strip() | |
| piston_lang = LANGUAGE_MAP.get(alias, alias) | |
| # Get language version | |
| runtimes = await cls._fetch_latest_versions() | |
| version = runtimes.get(piston_lang) or FALLBACK_VERSIONS.get(piston_lang, "*") | |
| filename = cls.get_filename(piston_lang) | |
| payload = { | |
| "language": piston_lang, | |
| "version": version, | |
| "files": [ | |
| { | |
| "name": filename, | |
| "content": code, | |
| } | |
| ], | |
| "stdin": stdin or "", | |
| "args": args or [], | |
| } | |
| try: | |
| client = await _get_piston_client() | |
| resp = await client.post(f"{PISTON_BASE_URL}/execute", json=payload, timeout=15.0) | |
| if resp.status_code == 200: | |
| res = resp.json() | |
| run_result = res.get("run", {}) | |
| compile_result = res.get("compile", {}) | |
| # Extract exit code and output | |
| exit_code = run_result.get("code", 0) | |
| stdout = run_result.get("stdout", "") | |
| stderr = run_result.get("stderr", "") | |
| signal = run_result.get("signal") | |
| # If compiling failed, prioritize compilation errors | |
| compile_stderr = compile_result.get("stderr", "") | |
| if compile_stderr: | |
| stderr = compile_stderr + ("\n" + stderr if stderr else "") | |
| exit_code = compile_result.get("code", exit_code) | |
| return { | |
| "success": exit_code == 0 and not stderr, | |
| "stdout": stdout, | |
| "stderr": stderr, | |
| "exit_code": exit_code, | |
| "language": piston_lang, | |
| "version": res.get("version", version), | |
| "run": { | |
| "stdout": stdout, | |
| "stderr": stderr, | |
| "code": exit_code, | |
| "signal": signal, | |
| } | |
| } | |
| else: | |
| err_msg = f"Execution server returned HTTP status {resp.status_code}: {resp.text}" | |
| return { | |
| "success": False, | |
| "stdout": "", | |
| "stderr": err_msg, | |
| "exit_code": -1, | |
| "language": piston_lang, | |
| "version": version, | |
| "run": { | |
| "stdout": "", | |
| "stderr": err_msg, | |
| "code": -1, | |
| "signal": None, | |
| } | |
| } | |
| except httpx.TimeoutException: | |
| timeout_msg = "Execution timed out (sandbox limit reached)." | |
| return { | |
| "success": False, | |
| "stdout": "", | |
| "stderr": timeout_msg, | |
| "exit_code": -2, | |
| "language": piston_lang, | |
| "version": version, | |
| "run": { | |
| "stdout": "", | |
| "stderr": timeout_msg, | |
| "code": -2, | |
| "signal": None, | |
| } | |
| } | |
| except Exception as exc: | |
| fail_msg = f"Failed to execute code: {str(exc)}" | |
| return { | |
| "success": False, | |
| "stdout": "", | |
| "stderr": fail_msg, | |
| "exit_code": -3, | |
| "language": piston_lang, | |
| "version": version, | |
| "run": { | |
| "stdout": "", | |
| "stderr": fail_msg, | |
| "code": -3, | |
| "signal": None, | |
| } | |
| } | |