Spaces:
Build error
Build error
File size: 5,609 Bytes
650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 650c99a da5b525 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
#!/usr/bin/env python3
"""
Simplified Ubuntu Sandbox - Core Functionality Only
"""
import gradio as gr
import subprocess
import os
import json
from typing import Dict, List, Any
import psutil
import time
from datetime import datetime
# Initialize workspace
WORKSPACE_PATH = "/home/user/workspace"
os.makedirs(WORKSPACE_PATH, exist_ok=True)
class SimpleSandbox:
def __init__(self):
self.sessions = {}
def execute_command(self, command: str, session_id: str = "default") -> str:
"""Execute command safely"""
if not command.strip():
return "Empty command"
try:
# Simple command execution
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=10,
cwd=WORKSPACE_PATH
)
output = f"Command: {command}\n"
output += f"Exit Code: {result.returncode}\n"
if result.stdout:
output += f"Output:\n{result.stdout}"
if result.stderr:
output += f"Error:\n{result.stderr}"
output += f"\nTimestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
return output
except subprocess.TimeoutExpired:
return f"Command timed out: {command}"
except Exception as e:
return f"Error executing command: {str(e)}"
def get_system_info(self) -> str:
"""Get system information"""
try:
info = {
"CPU": f"{psutil.cpu_count()} cores",
"Memory": f"{psutil.virtual_memory().total / (1024**3):.1f} GB",
"Disk": f"{psutil.disk_usage('/').free / (1024**3):.1f} GB free",
"Uptime": f"{time.time() - psutil.boot_time():.0f} seconds"
}
return json.dumps(info, indent=2)
except Exception as e:
return f"Error getting system info: {str(e)}"
def list_files(self, path: str = "/home/user/workspace") -> str:
"""List files in workspace"""
try:
if not os.path.exists(path):
return f"Path does not exist: {path}"
files = []
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
files.append(f"[DIR] {item}")
else:
size = os.path.getsize(item_path)
files.append(f"[FILE] {item} ({size} bytes)")
return "\n".join(files) if files else "No files found"
except Exception as e:
return f"Error listing files: {str(e)}"
# Create sandbox instance
sandbox = SimpleSandbox()
def terminal_interface():
"""Create Gradio interface"""
with gr.Blocks(title="Ubuntu Sandbox v2.0", theme=gr.themes.Soft()) as demo:
gr.Markdown("# π Ubuntu Sandbox v2.0 - AI Development Environment")
gr.Markdown("A minimal, secure environment for AI models to execute commands and manage files.")
with gr.Tabs():
with gr.Tab("π» Terminal"):
command = gr.Textbox(
label="Enter Command",
placeholder="e.g., ls, pwd, python --version, echo 'Hello AI!'"
)
output = gr.Textbox(
label="Output",
lines=10,
max_lines=20,
info="Command execution results will appear here"
)
gr.Button("βΆοΈ Execute", variant="primary").click(
fn=sandbox.execute_command,
inputs=[command],
outputs=[output]
)
with gr.Tab("π System Info"):
system_output = gr.Textbox(
label="System Information",
lines=8,
info="Current system status and resources"
)
gr.Button("π Refresh Info", variant="secondary").click(
fn=sandbox.get_system_info,
inputs=[],
outputs=[system_output]
)
with gr.Tab("π File Browser"):
file_path = gr.Textbox(
label="Directory Path",
value="/home/user/workspace",
info="Enter path to list files"
)
files_output = gr.Textbox(
label="Files and Directories",
lines=10,
info="Directory contents will be listed here"
)
gr.Button("π List Files", variant="secondary").click(
fn=sandbox.list_files,
inputs=[file_path],
outputs=[files_output]
)
gr.Markdown("## π§ API Endpoints")
gr.Markdown("""
- **GET** `/health` - Health check
- **POST** `/api/execute` - Execute command
- **GET** `/api/system` - Get system info
- **GET** `/api/files` - List files
""")
return demo
if __name__ == "__main__":
print("π Starting Ubuntu Sandbox v2.0...")
app = terminal_interface()
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True
)
|