Spaces:
Sleeping
Sleeping
File size: 1,226 Bytes
f73646a | 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 | import pandas as pd
import numpy as np
import traceback
def execute_generated_code(code: str, df: pd.DataFrame):
"""
Safely execute LLM-generated pandas code.
Only df, pd, np are available.
"""
# SAFE GLOBAL ENVIRONMENT
safe_globals = {
"__builtins__": {
"len": len,
"range": range,
"min": min,
"max": max,
"sum": sum,
"print": print,
"list": list,
"dict": dict,
},
"pd": pd,
"np": np,
"df": df.copy()
}
# LOCAL STORAGE FOR RESULTS
safe_locals = {}
try:
# EXECUTE CODE
exec(code, safe_globals, safe_locals)
# Try to extract result
if "result" in safe_locals:
return safe_locals["result"]
if "output" in safe_locals:
return safe_locals["output"]
# fallback: return last modified df or summary
if isinstance(df, pd.DataFrame):
return df.head(5)
return safe_locals
except Exception as e:
return {
"error": str(e),
"trace": traceback.format_exc()
} |