Spaces:
Sleeping
Sleeping
Commit Β·
66ed707
1
Parent(s): 864646f
Switch to subprocess execution (Docker-in-Docker not supported on HF)
Browse files123456789101112131415161718192021222 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""Docker-Based Sandbox Executor for Hugging Face SpacesSecure code execution using Docker containers"""from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport subprocessimport tempfileimport osimport timeimport base64from typing import Optionalimport dockerfrom pathlib import Pathapp = FastAPI(title="Docker Sandbox Executor")# Enable CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Initialize Docker clienttry:docker_client = docker.from_env()DOCKER_AVAILABLE = Trueprint("β Docker client initialized successfully")except Exception as e:DOCKER_AVAILABLE = Falseprint(f"β οΈ Docker not available: {e}")class CodeExecutionRequest(BaseModel):language: strcode: strtimeout: Optional[int] = 30class SandboxDockerExecutor:"""Execute code in isolated Docker containers"""def __init__(self):self.execution_count = 0def execute_in_docker(self, language: str, code: str, timeout: int = 30):"""Execute code in Docker container"""self.execution_count += 1start_time = time.time()try:if language.lower() == "python":return self._execute_python_docker(code, timeout)elif language.lower() == "react":return self._execute_react_docker(code, timeout)elif language.lower() == "html":return self._execute_html_docker(code, timeout)elif language.lower() == "javascript":return self._execute_javascript_docker(code, timeout)else:return False, "", f"β Unsupported language: {language}"except Exception as e:return False, "", f"β Docker execution error: {str(e)}"def _execute_python_docker(self, code: str, timeout: int):"""Execute Python in Docker"""container = Nonetry:# Create container with resource limitscontainer = docker_client.containers.run("python:3.11-alpine",f"python -c '{code}'",detach=True,mem_limit="256m",cpu_period=100000,cpu_quota=50000, # 50% CPUnetwork_mode="none", # No network accessremove=True)# Wait for completion with timeoutresult = container.wait(timeout=timeout)logs = container.logs().decode('utf-8')success = result['StatusCode'] == 0return success, logs, "" if success else logsexcept docker.errors.ContainerError as e:return False, "", str(e)except Exception as e:return False, "", f"Container error: {str(e)}"finally:if container:try:container.remove(force=True)except:passdef _execute_react_docker(self, code: str, timeout: int):"""Execute React (generate HTML for client-side rendering)"""html_content = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>React Sandbox #{self.execution_count}</title><script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/@babel/standalone/babel.min.js"></script><style>body {{margin: 0;padding: 0;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;}}#root {{width: 100%;min-height: 100vh;}}</style></head><body><div id="root"></div><script type="text/babel">{code}</script></body></html>"""return True, html_content, ""def _execute_html_docker(self, code: str, timeout: int):"""Execute HTML"""if not code.strip().startswith('<!DOCTYPE') and not code.strip().startswith('<html'):code = f"<!DOCTYPE html>\n{code}"return True, code, ""def _execute_javascript_docker(self, code: str, timeout: int):"""Execute JavaScript in Docker"""container = Nonetry:container = docker_client.containers.run("node:18-alpine",f"node -e '{code}'",detach=True,mem_limit="256m",cpu_period=100000,cpu_quota=50000,network_mode="none",remove=True)result = container.wait(timeout=timeout)logs = container.logs().decode('utf-8')success = result['StatusCode'] == 0return success, logs, "" if success else logsexcept Exception as e:return False, "", f"Container error: {str(e)}"finally:if container:try:container.remove(force=True)except:pass# Global executorexecutor = SandboxDockerExecutor()def format_terminal_html(language: str, success: bool, stdout: str, stderr: str,execution_time: float, exec_id: int) -> str:"""Format terminal output as HTML"""import html as html_modulestatus_color = "#00ff00" if success else "#ff4444"status_text = "β SUCCESS" if success else "β FAILED"stdout_escaped = html_module.escape(stdout) if stdout else ""stderr_escaped = html_module.escape(stderr) if stderr else ""return f"""<!DOCTYPE html><html><head><meta charset="UTF-8"><title>π³ Docker Sandbox Terminal #{exec_id}</title><style>* {{ margin: 0; padding: 0; box-sizing: border-box; }}body {{background: #000;color: #00ff00;font-family: 'Courier New', monospace;padding: 20px;line-height: 1.6;}}.header {{border-bottom: 2px solid #00ff00;padding-bottom: 15px;margin-bottom: 20px;}}h1 {{ color: #00ff00; font-size: 24px; margin-bottom: 10px; }}.info {{display: grid;grid-template-columns: 150px 1fr;gap: 10px;margin-bottom: 20px;font-size: 14px;}}.info-label {{ color: #888; }}.info-value {{ color: #00ff00; }}.status {{ color: {status_color}; font-weight: bold; font-size: 18px; }}.output-section {{ margin: 20px 0; }}.output-title {{color: #00aaff;font-size: 16px;margin-bottom: 10px;border-bottom: 1px solid #00aaff;padding-bottom: 5px;}}.output-content {{background: #111;padding: 15px;border-left: 3px solid #00ff00;white-space: pre-wrap;word-wrap: break-word;max-height: 400px;overflow-y: auto;}}.stderr {{ color: #ff6666; border-left-color: #ff4444; }}.empty {{ color: #666; font-style: italic; }}::-webkit-scrollbar {{ width: 10px; }}::-webkit-scrollbar-track {{ background: #111; }}::-webkit-scrollbar-thumb {{ background: #00ff00; border-radius: 5px; }}</style></head><body><div class="header"><h1>π³ DOCKER SANDBOX TERMINAL</h1></div><div class="info"><div class="info-label">Execution ID:</div><div class="info-value">#{exec_id}</div><div class="info-label">Language:</div><div class="info-value">{language.upper()}</div><div class="info-label">Execution Time:</div><div class="info-value">{execution_time:.3f}s</div><div class="info-label">Status:</div><div class="status">{status_text}</div></div><div class="output-section"><div class="output-title">π€ STDOUT</div><div class="output-content {'empty' if not stdout_escaped else ''}">{stdout_escaped if stdout_escaped else '(no output)'}</div></div>{f'<div class="output-section"><div class="output-title">β οΈ STDERR</div><div class="output-content stderr">{stderr_escaped}</div></div>' if stderr_escaped else ''}</body></html>"""@app.post("/execute")async def execute_code(request: CodeExecutionRequest):"""Execute code in Docker sandbox"""if not DOCKER_AVAILABLE:raise HTTPException(status_code=503, detail="Docker not available in this environment")start_time = time.time()# Execute in Dockersuccess, stdout, stderr = executor.execute_in_docker(request.language,request.code,request.timeout)execution_time = time.time() - start_time# Generate terminal viewterminal_html = format_terminal_html(request.language,success,stdout,stderr,execution_time,executor.execution_count)# Encode as data URLsterminal_b64 = base64.b64encode(terminal_html.encode('utf-8')).decode('utf-8')terminal_url = f"data:text/html;base64,{terminal_b64}"# For HTML/React, use stdout as previewpreview_url = Noneif request.language.lower() in ["html", "react"]:preview_b64 = base64.b64encode(stdout.encode('utf-8')).decode('utf-8')preview_url = f"data:text/html;base64,{preview_b64}"return {"status": "success" if success else "error","preview_url": preview_url,"terminal_view_url": terminal_url,"execution_time": execution_time,"docker_enabled": True}@app.get("/health")async def health_check():"""Health check endpoint"""return {"status": "healthy","docker_available": DOCKER_AVAILABLE}@app.get("/")async def root():"""Root endpoint"""return {"message": "π³ Docker Sandbox Executor API","docker_enabled": DOCKER_AVAILABLE,"endpoints": {"/execute": "POST - Execute code in Docker sandbox","/health": "GET - Health check"}}if __name__ == "__main__":import uvicorn1234567891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972"""FastAPI Universal Code Execution Sandbox for Hugging Face SpacesSupports: HTML, React, Python, Node.js, Java, Ruby, PHP, Go, Rust, C++, C#, Swift, Kotlin, and more!"""from fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, StreamingResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport osimport asyncioimport shutilapp = FastAPI()# Enable CORS for iframe embeddingapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Language configurationsLANGUAGE_CONFIG = {"python": {"extension": ".py","command": lambda file: ["python3", file],"runtime_check": "python3"},"node": {"extension": ".mjs","command": lambda file: ["node", file],"runtime_check": "node"},"java": {"extension": ".java","compile": lambda file: ["javac", file],"command": lambda: ["java", "-cp", "/tmp", "Main"],"runtime_check": "javac","needs_compile": True},"ruby": {"extension": ".rb","command": lambda file: ["ruby", file],"runtime_check": "ruby"},"php": {"extension": ".php","command": lambda file: ["php", file],"runtime_check": "php"},"go": {"extension": ".go","command": lambda file: ["go", "run", file],"runtime_check": "go"},"rust": {"extension": ".rs","compile": lambda file: ["rustc", file, "-o", "/tmp/rust_output"],"command": lambda: ["/tmp/rust_output"],"runtime_check": "rustc","needs_compile": True},"cpp": {"extension": ".cpp","compile": lambda file: ["g++", file, "-o", "/tmp/cpp_output"],"command": lambda: ["/tmp/cpp_output"],"runtime_check": "g++","needs_compile": True},"c": {"extension": ".c","compile": lambda file: ["gcc", file, "-o", "/tmp/c_output"],"command": lambda: ["/tmp/c_output"],"runtime_check": "gcc","needs_compile": True},"csharp": {"extension": ".cs","compile": lambda file: ["mcs", file, "-out:/tmp/csharp_output.exe"],"command": lambda: ["mono", "/tmp/csharp_output.exe"],"runtime_check": "mcs","needs_compile": True},"swift": {"extension": ".swift","command": lambda file: ["swift", file],"runtime_check": "swift"},"kotlin": {"extension": ".kt","compile": lambda file: ["kotlinc", file, "-include-runtime", "-d", "/tmp/kotlin_output.jar"],"command": lambda: ["java", "-jar", "/tmp/kotlin_output.jar"],"runtime_check": "kotlinc","needs_compile": True},"perl": {"extension": ".pl","command": lambda file: ["perl", file],"runtime_check": "perl"},"lua": {"extension": ".lua","command": lambda file: ["lua", file],"runtime_check": "lua"},"bash": {"extension": ".sh","command": lambda file: ["bash", file],"runtime_check": "bash"},"r": {"extension": ".r","command": lambda file: ["Rscript", file],"runtime_check": "Rscript"},"scala": {"extension": ".scala","command": lambda file: ["scala", file],"runtime_check": "scala"}}@app.get("/health")async def health():"""Health check for pre-warming the Space"""return {"status": "ok"}@app.get("/capabilities")async def capabilities():"""Check which language runtimes are available"""caps = {}for lang, config in LANGUAGE_CONFIG.items():runtime = config.get("runtime_check")caps[lang] = shutil.which(runtime) is not Nonereturn caps@app.get("/languages")async def list_languages():"""List all supported languages with availability"""result = []for lang, config in LANGUAGE_CONFIG.items():runtime = config.get("runtime_check")available = shutil.which(runtime) is not Noneresult.append({"language": lang,"available": available,"extension": config["extension"],"needs_compile": config.get("needs_compile", False)})return {"languages": result}async def stream_execution(language: str, code: str):"""Execute code for any supported language and stream output"""config = LANGUAGE_CONFIG.get(language)if not config:yield f"Error: Unsupported language '{language}'\n"yield "done\n"return# Check runtime availabilityruntime = config.get("runtime_check")if not shutil.which(runtime):yield f"Error: {language} runtime not available\n"yield "done\n"return# Determine filenameif language == "java":code_path = "/tmp/Main.java"else:code_path = f"/tmp/code{config['extension']}"# Write code to filetry:with open(code_path, "w") as f:f.write(code)except Exception as e:yield f"Error writing code: {e}\n"yield "done\n"returntry:# Compile if neededif config.get("needs_compile"):compile_cmd = config["compile"](code_path)compile_process = await asyncio.create_subprocess_exec(*compile_cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT)# Stream compilation outputwhile True:line = await compile_process.stdout.readline()if not line:breakyield line.decode('utf-8', errors='replace')exit_code = await compile_process.wait()if exit_code != 0:yield f"Compilation failed with exit code {exit_code}\n"yield "done\n"return# Executeif config.get("needs_compile") and callable(config["command"]):run_cmd = config["command"]()else:run_cmd = config["command"](code_path)run_process = await asyncio.create_subprocess_exec(*run_cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT)# Stream execution outputwhile True:line = await run_process.stdout.readline()if not line:breakyield line.decode('utf-8', errors='replace')await run_process.wait()yield "done\n"except Exception as e:yield f"Execution error: {e}\n"yield "done\n"finally:# Clean uptry:os.remove(code_path)# Clean up compiled outputsif language == "java":os.remove("/tmp/Main.class")elif language == "rust":os.remove("/tmp/rust_output")elif language == "cpp":os.remove("/tmp/cpp_output")elif language == "c":os.remove("/tmp/c_output")elif language == "csharp":os.remove("/tmp/csharp_output.exe")elif language == "kotlin":os.remove("/tmp/kotlin_output.jar")except Exception:pass# Schedule exitasyncio.create_task(delayed_exit())async def delayed_exit():"""Exit the process after a short delay"""await asyncio.sleep(0.5)os._exit(0)@app.post("/run")async def run_code(request: Request):"""Execute code in any supported language and stream output"""body = await request.json()language = body.get("language", "").lower()code = body.get("code", "")if not code:return JSONResponse({"error": "NO_CODE"}, status_code=400)if language not in LANGUAGE_CONFIG:return JSONResponse({"error": f"UNSUPPORTED_LANGUAGE: {language}"},status_code=400)# Check if runtime is availableconfig = LANGUAGE_CONFIG[language]runtime = config.get("runtime_check")if not shutil.which(runtime):return JSONResponse({"error": f"{language.upper()}_NOT_AVAILABLE"},status_code=503)return StreamingResponse(stream_execution(language, code),media_type="text/plain")@app.get("/", response_class=HTMLResponse)async def root():"""Serve the HTML UI with multi-language support"""html_content = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Universal Code Sandbox</title><!-- CDN Scripts --><script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script><script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script><script src="https://unpkg.com/@babel/standalone/babel.min.js"></script><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;background: #1e1e1e;color: #d4d4d4;height: 100vh;overflow: hidden;display: flex;flex-direction: column;}.app-container {display: flex;flex-direction: column;height: 100vh;padding: 20px;gap: 15px;}h1 {color: #4ec9b0;font-size: 28px;margin: 0;}.controls {display: flex;gap: 10px;align-items: center;flex-wrap: wrap;flex-shrink: 0;}label {color: #9cdcfe;font-weight: bold;}select, button {background: #252526;color: #d4d4d4;border: 1px solid #3c3c3c;padding: 10px 15px;border-radius: 4px;font-family: inherit;font-size: 14px;cursor: pointer;transition: all 0.2s;}select:hover {border-color: #007acc;}select:focus, button:focus {outline: none;border-color: #007acc;}button {background: #007acc;color: white;border: none;font-weight: bold;padding: 10px 20px;}button:hover:not(:disabled) {background: #005a9e;transform: translateY(-1px);}button:active:not(:disabled) {transform: translateY(0);}button:disabled {background: #3c3c3c;cursor: not-allowed;opacity: 0.6;}.workspace {flex: 1;display: grid;grid-template-rows: minmax(250px, 1fr) minmax(250px, 1fr);gap: 15px;min-height: 0;overflow: hidden;}.editor-panel {display: flex;flex-direction: column;min-height: 0;}.panel-label {color: #9cdcfe;font-weight: bold;margin-bottom: 8px;font-size: 13px;text-transform: uppercase;letter-spacing: 1px;}textarea {flex: 1;background: #252526;color: #d4d4d4;border: 1px solid #3c3c3c;border-radius: 4px;padding: 15px;font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;font-size: 14px;line-height: 1.6;resize: none;outline: none;min-height: 0;}textarea:focus {border-color: #007acc;}.output-panel {display: flex;flex-direction: column;min-height: 0;position: relative;}#output {flex: 1;background: #0c0c0c;color: #00ff00;border: 1px solid #00ff00;border-radius: 4px;padding: 15px;overflow-y: auto;font-size: 13px;line-height: 1.6;white-space: pre-wrap;word-wrap: break-word;font-family: 'Courier New', monospace;min-height: 0;}#html-preview, #react-root {flex: 1;background: white;border: 1px solid #3c3c3c;border-radius: 4px;overflow: auto;min-height: 0;}#html-preview {border: 1px solid #3c3c3c;}.error { color: #f48771; }.success { color: #4ec9b0; }.info { color: #9cdcfe; }.badge {display: inline-block;padding: 3px 8px;border-radius: 3px;font-size: 11px;margin-left: 5px;font-weight: bold;}.badge-available { background: #4ec9b0; color: #000; }.badge-unavailable { background: #f48771; color: #000; }/* Scrollbar styling */::-webkit-scrollbar {width: 10px;height: 10px;}::-webkit-scrollbar-track {background: #1e1e1e;}::-webkit-scrollbar-thumb {background: #3c3c3c;border-radius: 5px;}::-webkit-scrollbar-thumb:hover {background: #007acc;}@media (max-width: 768px) {.workspace {grid-template-rows: 300px 1fr;}h1 {font-size: 20px;}}</style></head><body><div class="app-container"><h1>🚀 Universal Code Sandbox</h1><div class="controls"><label for="language">Language:</label><select id="language" onchange="switchLanguage()"><optgroup label="Client-Side"><option value="html">HTML</option><option value="react">React/JSX</option></optgroup><optgroup label="Scripting Languages"><option value="python">Python</option><option value="node">Node.js/JavaScript</option><option value="ruby">Ruby</option><option value="php">PHP</option><option value="perl">Perl</option><option value="lua">Lua</option><option value="bash">Bash</option><option value="r">R</option></optgroup><optgroup label="Compiled Languages"><option value="java">Java</option><option value="cpp">C++</option><option value="c">C</option><option value="go">Go</option><option value="rust">Rust</option><option value="csharp">C#</option><option value="swift">Swift</option><option value="kotlin">Kotlin</option><option value="scala">Scala</option></optgroup></select><button id="runBtn" onclick="runCode()">▶ Run</button><button onclick="checkAvailability()">🔍 Check Available</button><span id="status" class="info"></span></div><div class="workspace"><div class="editor-panel"><div class="panel-label">◆ Code Editor</div><textarea id="editor" placeholder="Enter your code here..." spellcheck="false"></textarea></div><div class="output-panel"><div class="panel-label">◆ Output / Preview</div><pre id="output" style="display: none;"></pre><iframe id="html-preview" style="display: none;" sandbox="allow-scripts"></iframe><div id="react-root" style="display: none;"></div></div></div></div><script>const editor = document.getElementById('editor');const output = document.getElementById('output');const htmlPreview = document.getElementById('html-preview');const reactRoot = document.getElementById('react-root');const languageSelect = document.getElementById('language');const runBtn = document.getElementById('runBtn');const status = document.getElementById('status');let capabilities = {};// Fetch capabilities on loadfetch('/capabilities').then(res => res.json()).then(data => {capabilities = data;updateLanguageSelector();});function updateLanguageSelector() {const options = languageSelect.querySelectorAll('option');options.forEach(opt => {const lang = opt.value;if (lang === 'html' || lang === 'react') {return; // Client-side always available}if (capabilities[lang] !== undefined) {const badge = capabilities[lang] ?'<span class="badge badge-available">β</span>' :'<span class="badge badge-unavailable">β</span>';opt.innerHTML = opt.innerHTML.split('<')[0] + ' ' + (capabilities[lang] ? 'β' : 'β');}});}async function checkAvailability() {status.textContent = 'π Checking...';status.className = 'info';const response = await fetch('/languages');const data = await response.json();output.style.display = 'block';htmlPreview.style.display = 'none';reactRoot.style.display = 'none';output.textContent = 'Available Languages:\\n\\n';data.languages.forEach(lang => {const badge = lang.available ? 'β ' : 'β';output.textContent += `${badge} ${lang.language.toUpperCase()} (${lang.extension})\\n`;});status.textContent = 'β Check complete';status.className = 'success';}const examples = {python: `# Python exampleprint("Hello from Python!")for i in range(5):print(f"Number: {i + 1}")print("Done!")`,node: `// Node.js exampleconsole.log('Hello from Node.js!');for (let i = 0; i < 5; i++) {console.log('Step ' + (i + 1));await new Promise(r => setTimeout(r, 200));}console.log('Done!');`,java: `public class Main {public static void main(String[] args) {System.out.println("Hello from Java!");for (int i = 0; i < 5; i++) {System.out.println("Step " + (i + 1));}System.out.println("Done!");}}`,ruby: `# Ruby exampleputs "Hello from Ruby!"5.times do |i|puts "Step #{i + 1}"endputs "Done!"`,php: `<?phpecho "Hello from PHP!\\n";for ($i = 1; $i <= 5; $i++) {echo "Step $i\\n";}echo "Done!\\n";?>`,go: `package mainimport "fmt"func main() {fmt.Println("Hello from Go!")for i := 1; i <= 5; i++ {fmt.Printf("Step %d\\n", i)}fmt.Println("Done!")}`,rust: `fn main() {println!("Hello from Rust!");for i in 1..=5 {println!("Step {}", i);}println!("Done!");}`,cpp: `#include <iostream>using namespace std;int main() {cout << "Hello from C++!" << endl;for (int i = 1; i <= 5; i++) {cout << "Step " << i << endl;}cout << "Done!" << endl;return 0;}`,c: `#include <stdio.h>int main() {printf("Hello from C!\\n");for (int i = 1; i <= 5; i++) {printf("Step %d\\n", i);}printf("Done!\\n");return 0;}`,csharp: `using System;class Program {static void Main() {Console.WriteLine("Hello from C#!");for (int i = 1; i <= 5; i++) {Console.WriteLine($"Step {i}");}Console.WriteLine("Done!");}}`,swift: `print("Hello from Swift!")for i in 1...5 {print("Step \\(i)")}print("Done!")`,kotlin: `fun main() {println("Hello from Kotlin!")for (i in 1..5) {println("Step $i")}println("Done!")}`,perl: `# Perl exampleprint "Hello from Perl!\\n";for my $i (1..5) {print "Step $i\\n";}print "Done!\\n";`,lua: `-- Lua exampleprint("Hello from Lua!")for i = 1, 5 doprint("Step " .. i)endprint("Done!")`,bash: `#!/bin/bashecho "Hello from Bash!"for i in {1..5}; doecho "Step $i"doneecho "Done!"`,r: `# R exampleprint("Hello from R!")for (i in 1:5) {print(paste("Step", i))}print("Done!")`,scala: `object Main extends App {println("Hello from Scala!")for (i <- 1 to 5) {println(s"Step $i")}println("Done!")}`,html: `<!DOCTYPE html><html><head><style>body { font-family: Arial; padding: 20px; }h1 { color: #007acc; }</style></head><body><h1>Hello from HTML!</h1><p>This is rendered client-side.</p><button onclick="alert('Clicked!')">Click Me</button></body></html>`,react: `function App() {const [count, setCount] = React.useState(0);return (<div style={{padding: '20px', fontFamily: 'Arial'}}><h1>Hello from React!</h1><p>Count: {count}</p><button onClick={() => setCount(count + 1)}>Increment</button></div>);}ReactDOM.createRoot(document.getElementById('react-root')).render(<App />);`};function switchLanguage() {const lang = languageSelect.value;editor.value = examples[lang] || '';// Hide all output areasoutput.style.display = 'none';htmlPreview.style.display = 'none';reactRoot.style.display = 'none';// Show appropriate output areaif (lang === 'html') {htmlPreview.style.display = 'block';} else if (lang === 'react') {reactRoot.style.display = 'block';} else {output.style.display = 'block';}output.textContent = '';status.textContent = '';}async function runCode() {const lang = languageSelect.value;const code = editor.value.trim();if (!code) {status.textContent = 'β οΈ No code to run';status.className = 'error';return;}output.textContent = '';status.textContent = 'π Running...';status.className = 'info';if (lang === 'html') {runHTML(code);} else if (lang === 'react') {runReact(code);} else {await runServerSide(lang, code);}}function runHTML(code) {try {const clean = DOMPurify.sanitize(code);htmlPreview.srcdoc = clean;status.textContent = 'β Rendered';status.className = 'success';} catch (error) {output.style.display = 'block';htmlPreview.style.display = 'none';output.textContent = 'Error: ' + error.message;status.textContent = 'β Error';status.className = 'error';}}function runReact(code) {try {reactRoot.innerHTML = '';const transformed = Babel.transform(code, {presets: ['react']}).code;eval(transformed);status.textContent = 'β Rendered';status.className = 'success';} catch (error) {reactRoot.innerHTML = '<div style="padding: 20px; color: red; font-family: monospace;">' +'<strong>Error:</strong><br>' + error.message + '</div>';status.textContent = 'β Error';status.className = 'error';}}async function runServerSide(lang, code) {runBtn.disabled = true;editor.disabled = true;output.textContent = '';try {const response = await fetch('/run', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ language: lang, code: code })});if (!response.ok) {const error = await response.json();output.textContent = 'Error: ' + (error.error || 'Unknown error');status.textContent = 'β Error';status.className = 'error';runBtn.disabled = false;editor.disabled = false;return;}const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { value, done } = await reader.read();if (done) break;const chunk = decoder.decode(value, { stream: true });output.textContent += chunk;output.scrollTop = output.scrollHeight;if (chunk.includes('done')) {status.textContent = 'β Complete (Space restarting...)';status.className = 'success';}}} catch (error) {output.textContent += '\\n\\nConnection error: ' + error.message;status.textContent = 'β Error';status.className = 'error';} finally {runBtn.disabled = false;editor.disabled = false;}}// Tab key supporteditor.addEventListener('keydown', (e) => {if (e.key === 'Tab') {e.preventDefault();const start = editor.selectionStart;const end = editor.selectionEnd;editor.value = editor.value.substring(0, start) + ' ' + editor.value.substring(end);editor.selectionStart = editor.selectionEnd = start + 4;}});// Ctrl+Enter to runeditor.addEventListener('keydown', (e) => {if (e.ctrlKey && e.key === 'Enter') {e.preventDefault();runCode();}});// InitializeswitchLanguage();</script></body></html>"""return HTMLResponse(content=html_content)if __name__ == "__main__":import uvicorn
app.py+918-275