Spaces:
Sleeping
Sleeping
File size: 5,805 Bytes
3b93525 | 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 164 165 166 167 168 169 170 171 172 173 174 175 | import os
import subprocess
import tempfile
import zipfile
from pathlib import Path
from .config import config
def execute_python_code(code: str, required_packages: str | None = None) -> str:
"""
Executes the given Python code in the Docker sandbox; note that created files stay in the sandbox and must be shared explicitly using `export_files`.
Args:
code (str): The Python code to execute.
required_packages (str | None, optional): A comma-separated string of Python package names that are required for the execution. Defaults to None.
Returns:
str: Standard output or "Executed successfully" if the execution succeeds; otherwise, a detailed error message.
"""
required_packages = (
[p.strip() for p in required_packages.split(",")]
if (required_packages and required_packages.strip())
else None
)
if required_packages:
pkg_tmp_file = tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
suffix=".py",
delete=False,
)
pkg_tmp_file.close()
try:
args = [
"uv",
"run",
"--with",
",".join(required_packages),
pkg_tmp_file.name,
]
result = subprocess.run(
args,
cwd=config.working_dir,
capture_output=True,
text=True,
timeout=config.pkg_timeout,
)
if result.returncode != 0:
return result.stderr
except subprocess.TimeoutExpired:
return "Package installation timeout."
except Exception as e:
return f"Package installation error: {str(e) or 'Unknown failure'}"
finally:
if pkg_tmp_file and os.path.exists(pkg_tmp_file.name):
try:
os.remove(pkg_tmp_file.name)
except Exception:
pass
code_tmp_file = tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
suffix=".py",
delete=False,
)
code_tmp_file.write(code)
code_tmp_file.close()
try:
args = (
[
"uv",
"run",
"--with",
",".join(required_packages),
code_tmp_file.name,
]
if required_packages
else [
"uv",
"run",
code_tmp_file.name,
]
)
result = subprocess.run(
args,
cwd=config.working_dir,
capture_output=True,
text=True,
timeout=config.code_timeout,
)
if result.returncode == 0:
return result.stdout if result.stdout else "Executed successfully."
return result.stderr
except subprocess.TimeoutExpired:
return "Code execution timeout."
except Exception as e:
return f"Code execution error: {str(e) or 'Unknown failure'}"
finally:
if code_tmp_file and os.path.exists(code_tmp_file.name):
try:
os.remove(code_tmp_file.name)
except Exception:
pass
def execute_shell_command(command: str) -> str:
"""
Executes the given shell command in the Docker sandbox; note that this is mostly intended to install system-level dependencies.
Args:
command (str): The shell command to execute.
Returns:
str: Standard output or "Executed successfully" if the execution succeeds; otherwise, a detailed error message.
"""
try:
result = subprocess.run(
command,
shell=True,
cwd=config.working_dir,
capture_output=True,
text=True,
timeout=config.command_timeout,
)
if result.returncode == 0:
return result.stdout if result.stdout else "Executed successfully."
return result.stderr
except subprocess.TimeoutExpired:
return "Command execution timeout."
except Exception as e:
return f"Command execution error: {str(e) or 'Unknown failure'}"
def export_files(file_paths: str, as_zip: bool = False) -> tuple[list[str], str | None]:
"""
Exports Docker sandbox files as download URLs to share with the user. Optionally bundles them into a ZIP archive.
Args:
file_paths (str): A comma-separated string of file paths to export.
as_zip (bool, optional): If True, bundles files as a ZIP archive before exporting. Defaults to False.
Returns:
tuple[list[str], str | None]: A list of download URLs and an error message, if any.
"""
paths = [Path(f.strip()) for f in file_paths.strip().split(",") if f.strip()]
for idx, path in enumerate(paths):
resolved = (
path.resolve()
if path.is_absolute()
else (config.working_dir / path).resolve()
)
try:
resolved.relative_to(config.working_dir)
except ValueError:
return [], f"Path '{resolved}' is outside the working directory."
paths[idx] = resolved
for path in paths:
if not path.exists():
return [], f"File '{path}' not found."
if not path.is_file():
return [], f"Expected a file, but '{path}' is a directory."
if as_zip:
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as zip_tmp_file:
with zipfile.ZipFile(zip_tmp_file.name, "w") as zip_file:
for path in paths:
zip_file.write(str(path), arcname=path.name)
return [zip_tmp_file.name], None
return [str(p) for p in paths], None
|