Spaces:
No application file
No application file
| import subprocess | |
| import uuid | |
| from pathlib import Path | |
| class DockerSandbox: | |
| def __init__(self, project_dir="generated"): | |
| self.project_dir = Path(project_dir) | |
| def build_image(self): | |
| image_tag = f"ai_dev_{uuid.uuid4().hex[:8]}" | |
| cmd = [ | |
| "docker", | |
| "build", | |
| "-t", | |
| image_tag, | |
| str(self.project_dir) | |
| ] | |
| result = subprocess.run( | |
| cmd, | |
| capture_output=True, | |
| text=True | |
| ) | |
| if result.returncode != 0: | |
| return False, result.stderr | |
| return True, image_tag | |
| def run_container(self, image_tag, timeout=20): | |
| cmd = [ | |
| "docker", | |
| "run", | |
| "--rm", | |
| "--network", "none", # Disable internet | |
| "--memory", "512m", | |
| "--cpus", "1", | |
| image_tag | |
| ] | |
| result = subprocess.run( | |
| cmd, | |
| capture_output=True, | |
| text=True, | |
| timeout=timeout | |
| ) | |
| return result.returncode, result.stdout, result.stderr | |
| def cleanup_image(self, image_tag): | |
| subprocess.run( | |
| ["docker", "rmi", "-f", image_tag], | |
| capture_output=True | |
| ) | |