import gradio as gr from gradio_client import Client import json import time import threading import random from datetime import datetime # Backend engines BACKEND_ENGINES = [ "ChocoLaboratory/SANDBOXBACKEND2", "ChocoLaboratory/SANDBOX_BACKEND" ] class SandboxManager: def __init__(self): self.client = None self.current_engine = None self.is_connected = False self.last_status = "Disconnected" def select_random_engine(self): """Randomly select an engine""" self.current_engine = random.choice(BACKEND_ENGINES) return self.current_engine def connect(self): engine = self.select_random_engine() try: self.client = Client(engine) self.is_connected = True return f"✓ Connected to: {engine}", engine except Exception as e: self.is_connected = False self.current_engine = None return f"✗ Connection failed to {engine}: {str(e)}", "Not connected" def launch_sandbox(self, main_py_code, requirements_txt): if not self.is_connected: return "✗ Not connected to backend. Please connect first.", "" try: result = self.client.predict( code=main_py_code, requirements=requirements_txt, api_name="/launch_sandbox" ) return f"✓ Sandbox deployed successfully on {self.current_engine}\n\nResponse: {result}", self.get_status() except Exception as e: return f"✗ Deployment failed: {str(e)}", "" def fetch_logs(self): if not self.is_connected: return "✗ Not connected to backend" try: result = self.client.predict(api_name="/fetch_logs") timestamp = datetime.now().strftime("%H:%M:%S") return f"[{timestamp}] Logs from {self.current_engine}:\n\n{result}" except Exception as e: return f"[ERROR] Failed to fetch logs: {str(e)}" def kill_sandbox(self): if not self.is_connected: return "✗ Not connected to backend", "" try: result = self.client.predict(api_name="/kill_sandbox") return f"✓ Sandbox terminated on {self.current_engine}\n\nResponse: {result}", self.get_status() except Exception as e: return f"✗ Termination failed: {str(e)}", "" def get_status(self): if not self.is_connected: return "OFFLINE" try: result = self.client.predict(api_name="/status_sandbox") if "running" in str(result).lower(): return f"RUNNING - {result}" else: return f"IDLE - {result}" except Exception as e: return f"ERROR - {str(e)}" # Initialize sandbox manager sandbox = SandboxManager() # Professional code templates SAMPLE_MAIN_PY = """#!/usr/bin/env python3 \"\"\" Sandbox Compute Environment Enterprise Python Application Template \"\"\" import os import sys import json import logging from datetime import datetime, timezone # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def initialize_environment(): \"\"\"Initialize the compute environment\"\"\" logger.info("Initializing sandbox environment...") env_info = { "timestamp": datetime.now(timezone.utc).isoformat(), "python_version": sys.version, "platform": os.name, "working_directory": os.getcwd(), "environment_variables": dict(os.environ) } logger.info(f"Environment initialized: {env_info['timestamp']}") return env_info def execute_business_logic(): \"\"\"Main application business logic\"\"\" logger.info("Executing main application logic...") # Example: Data processing pipeline data_points = list(range(1, 101)) processed_data = [x ** 2 for x in data_points if x % 2 == 0] result = { "status": "success", "data_points_processed": len(processed_data), "sum_of_squares": sum(processed_data), "processing_time": datetime.now(timezone.utc).isoformat() } logger.info(f"Processing complete: {result}") return result def main(): \"\"\"Main application entry point\"\"\" try: print("=" * 60) print("SANDBOX COMPUTE ENVIRONMENT - PRODUCTION RUNTIME") print("=" * 60) # Initialize env_info = initialize_environment() print(f"Environment: {env_info['platform']}") print(f"Python: {env_info['python_version'].split()[0]}") print(f"Started: {env_info['timestamp']}") print("\\n" + "-" * 40) print("EXECUTING APPLICATION LOGIC") print("-" * 40) # Execute business logic result = execute_business_logic() # Output results print(f"\\nStatus: {result['status'].upper()}") print(f"Data Points: {result['data_points_processed']}") print(f"Computation Result: {result['sum_of_squares']}") print(f"Completed: {result['processing_time']}") print("\\n" + "=" * 60) print("APPLICATION EXECUTION COMPLETED SUCCESSFULLY") print("=" * 60) except Exception as e: logger.error(f"Application failed: {str(e)}") raise if __name__ == "__main__": main() """ SAMPLE_REQUIREMENTS_TXT = """# Enterprise Python Dependencies # Production-grade package specifications # Core utilities and date handling requests>=2.31.0,<3.0.0 python-dateutil>=2.8.2,<3.0.0 pytz>=2023.3 # Data processing and analysis numpy>=1.24.0,<2.0.0 pandas>=2.0.0,<3.0.0 # Logging and monitoring structlog>=23.1.0 prometheus-client>=0.17.0 # Configuration management pydantic>=2.0.0,<3.0.0 python-dotenv>=1.0.0 # Database connectivity (uncomment as needed) # sqlalchemy>=2.0.0,<3.0.0 # psycopg2-binary>=2.9.0 # redis>=4.5.0 # Web frameworks (uncomment as needed) # fastapi>=0.100.0,<1.0.0 # uvicorn[standard]>=0.23.0 # gunicorn>=21.0.0 # Scientific computing (uncomment as needed) # scipy>=1.11.0,<2.0.0 # scikit-learn>=1.3.0,<2.0.0 # matplotlib>=3.7.0,<4.0.0 # Development and testing (uncomment as needed) # pytest>=7.4.0,<8.0.0 # black>=23.0.0,<24.0.0 # mypy>=1.5.0,<2.0.0 # flake8>=6.0.0,<7.0.0 """ # Professional industrial CSS professional_css = """ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap'); :root { --primary-color: #2563eb; --primary-hover: #1d4ed8; --secondary-color: #64748b; --success-color: #059669; --warning-color: #d97706; --danger-color: #dc2626; --background: #f8fafc; --surface: #ffffff; --border: #e2e8f0; --text-primary: #1e293b; --text-secondary: #64748b; --text-muted: #94a3b8; } .gradio-container { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important; background-color: var(--background) !important; color: var(--text-primary) !important; min-height: 100vh; line-height: 1.5; } /* Professional Header */ .platform-header { background: linear-gradient(135deg, #1e293b 0%, #334155 100%) !important; color: white !important; padding: 16px 24px !important; border-bottom: 3px solid var(--primary-color) !important; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important; } .platform-title { font-size: 24px !important; font-weight: 700 !important; letter-spacing: -0.025em !important; } .platform-subtitle { font-size: 14px !important; opacity: 0.8 !important; margin-top: 4px !important; } /* Navigation */ .nav-breadcrumb { background-color: #f1f5f9 !important; padding: 12px 24px !important; font-size: 13px !important; color: var(--text-secondary) !important; border-bottom: 1px solid var(--border) !important; } /* Container System */ .enterprise-container { background-color: var(--surface) !important; border: 1px solid var(--border) !important; border-radius: 12px !important; margin: 20px !important; overflow: hidden !important; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06) !important; } .container-header { background: linear-gradient(to right, #f8fafc, #f1f5f9) !important; border-bottom: 1px solid var(--border) !important; padding: 16px 24px !important; font-weight: 600 !important; font-size: 16px !important; color: var(--text-primary) !important; display: flex !important; align-items: center !important; gap: 8px !important; } .container-content { padding: 24px !important; } /* Professional Buttons */ .btn-primary { background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%) !important; color: white !important; border: none !important; border-radius: 8px !important; padding: 12px 24px !important; font-size: 14px !important; font-weight: 500 !important; transition: all 0.2s ease !important; box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2) !important; } .btn-primary:hover { transform: translateY(-1px) !important; box-shadow: 0 4px 8px rgba(37, 99, 235, 0.3) !important; } .btn-secondary { background-color: var(--surface) !important; color: var(--text-primary) !important; border: 1px solid var(--border) !important; border-radius: 8px !important; padding: 12px 24px !important; font-size: 14px !important; font-weight: 500 !important; transition: all 0.2s ease !important; } .btn-secondary:hover { background-color: #f8fafc !important; border-color: var(--secondary-color) !important; } .btn-danger { background: linear-gradient(135deg, var(--danger-color) 0%, #b91c1c 100%) !important; color: white !important; border: none !important; border-radius: 8px !important; padding: 12px 24px !important; font-size: 14px !important; font-weight: 500 !important; transition: all 0.2s ease !important; box-shadow: 0 2px 4px rgba(220, 38, 38, 0.2) !important; } /* Status Indicators */ .status-online { background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%) !important; color: var(--success-color) !important; border: 1px solid #86efac !important; border-radius: 8px !important; padding: 16px !important; font-weight: 600 !important; text-align: center !important; } .status-offline { background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%) !important; color: var(--danger-color) !important; border: 1px solid #fca5a5 !important; border-radius: 8px !important; padding: 16px !important; font-weight: 600 !important; text-align: center !important; } .status-warning { background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%) !important; color: var(--warning-color) !important; border: 1px solid #fde68a !important; border-radius: 8px !important; padding: 16px !important; font-weight: 600 !important; text-align: center !important; } /* Code Editor */ .code-editor-professional { font-family: 'JetBrains Mono', 'SF Mono', Monaco, 'Cascadia Code', monospace !important; background: #1e1e1e !important; border: 2px solid var(--border) !important; border-radius: 8px !important; font-size: 14px !important; line-height: 1.5 !important; box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06) !important; } .requirements-editor { font-family: 'JetBrains Mono', monospace !important; background: #2d2d2d !important; border: 2px solid var(--border) !important; border-radius: 8px !important; font-size: 13px !important; line-height: 1.4 !important; } /* Logs Terminal */ .terminal-logs { font-family: 'JetBrains Mono', monospace !important; background: #0f172a !important; color: #e2e8f0 !important; border: 2px solid #334155 !important; border-radius: 8px !important; font-size: 13px !important; line-height: 1.6 !important; padding: 16px !important; } /* Sidebar */ .monitoring-panel { background-color: var(--surface) !important; border: 1px solid var(--border) !important; border-radius: 12px !important; overflow: hidden !important; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1) !important; height: fit-content !important; } .panel-header { background: linear-gradient(to right, #f1f5f9, #e2e8f0) !important; padding: 12px 16px !important; font-weight: 600 !important; font-size: 14px !important; color: var(--text-primary) !important; border-bottom: 1px solid var(--border) !important; } .panel-content { padding: 16px !important; } /* Form Elements */ .form-group { margin-bottom: 20px !important; } .form-label { font-size: 14px !important; font-weight: 500 !important; color: var(--text-primary) !important; margin-bottom: 6px !important; display: block !important; } .info-badge { background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%) !important; color: var(--primary-color) !important; border: 1px solid #93c5fd !important; border-radius: 6px !important; padding: 12px 16px !important; font-size: 13px !important; font-weight: 500 !important; } /* Metrics */ .metric-card { text-align: center !important; padding: 16px !important; border-right: 1px solid var(--border) !important; } .metric-card:last-child { border-right: none !important; } .metric-value { font-size: 28px !important; font-weight: 700 !important; color: var(--primary-color) !important; line-height: 1 !important; } .metric-label { font-size: 12px !important; color: var(--text-secondary) !important; margin-top: 4px !important; font-weight: 500 !important; text-transform: uppercase !important; letter-spacing: 0.025em !important; } /* Professional spacing */ .section-divider { height: 1px !important; background: var(--border) !important; margin: 24px 0 !important; } .mb-4 { margin-bottom: 16px !important; } .mt-4 { margin-top: 16px !important; } """ def auto_refresh_status(): return sandbox.get_status() def auto_refresh_logs(): return sandbox.fetch_logs() def load_sample_files(): """Load professional sample files""" return SAMPLE_MAIN_PY, SAMPLE_REQUIREMENTS_TXT # Build the professional interface with gr.Blocks(css=professional_css, title="Sandbox Compute Platform", theme=gr.themes.Default()) as demo: # Platform Header gr.HTML("""
Sandbox Compute Platform
Runtime Engines: SANDBOXBACKEND2, SANDBOX_BACKEND