Spaces:
Sleeping
Sleeping
Commit
·
aa9714c
1
Parent(s):
f757484
Fix: Correctly configure sandbox scope for code execution
Browse files
tools.py
CHANGED
|
@@ -106,24 +106,28 @@ def run_python_code_on_dataframe(df: pd.DataFrame, python_code: str) -> str:
|
|
| 106 |
"""
|
| 107 |
output_stream = io.StringIO()
|
| 108 |
|
| 109 |
-
# ---
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
'df': df,
|
| 112 |
'pd': pd,
|
| 113 |
're': re,
|
| 114 |
-
'plt': plt,
|
| 115 |
-
'sns': sns,
|
| 116 |
-
'np': np,
|
| 117 |
-
'LinearRegression': LinearRegression,
|
| 118 |
-
'io': io,
|
| 119 |
-
'base64': base64
|
|
|
|
| 120 |
}
|
| 121 |
|
| 122 |
try:
|
| 123 |
with redirect_stdout(output_stream):
|
| 124 |
-
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
# After execution, close any open matplotlib plots to free up memory
|
| 127 |
plt.close('all')
|
| 128 |
|
| 129 |
result = output_stream.getvalue()
|
|
@@ -132,5 +136,5 @@ def run_python_code_on_dataframe(df: pd.DataFrame, python_code: str) -> str:
|
|
| 132 |
return result
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
-
plt.close('all')
|
| 136 |
return f"Error executing code: {type(e).__name__}: {e}\n---\nCode that failed:\n{python_code}"
|
|
|
|
| 106 |
"""
|
| 107 |
output_stream = io.StringIO()
|
| 108 |
|
| 109 |
+
# --- THIS IS THE CORRECTED SANDBOX SETUP ---
|
| 110 |
+
# Create a single dictionary to serve as the global and local scope.
|
| 111 |
+
# This ensures that all libraries are accessible everywhere inside the exec'd code.
|
| 112 |
+
execution_scope = {
|
| 113 |
'df': df,
|
| 114 |
'pd': pd,
|
| 115 |
're': re,
|
| 116 |
+
'plt': plt,
|
| 117 |
+
'sns': sns,
|
| 118 |
+
'np': np,
|
| 119 |
+
'LinearRegression': LinearRegression,
|
| 120 |
+
'io': io,
|
| 121 |
+
'base64': base64,
|
| 122 |
+
'__builtins__': __builtins__ # Ensure basic built-ins are available
|
| 123 |
}
|
| 124 |
|
| 125 |
try:
|
| 126 |
with redirect_stdout(output_stream):
|
| 127 |
+
# Pass the scope dictionary as the 'globals' argument.
|
| 128 |
+
# This makes 'pd', 're', etc. globally available to the script.
|
| 129 |
+
exec(python_code, execution_scope)
|
| 130 |
|
|
|
|
| 131 |
plt.close('all')
|
| 132 |
|
| 133 |
result = output_stream.getvalue()
|
|
|
|
| 136 |
return result
|
| 137 |
|
| 138 |
except Exception as e:
|
| 139 |
+
plt.close('all')
|
| 140 |
return f"Error executing code: {type(e).__name__}: {e}\n---\nCode that failed:\n{python_code}"
|