Spaces:
Build error
Build error
Delete execution_programs.py
Browse files- execution_programs.py +0 -224
execution_programs.py
DELETED
|
@@ -1,224 +0,0 @@
|
|
| 1 |
-
import io
|
| 2 |
-
import contextlib
|
| 3 |
-
import streamlit as st
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import matplotlib.pyplot as plt
|
| 6 |
-
import seaborn as sns
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
import re
|
| 9 |
-
from io import StringIO
|
| 10 |
-
import plotly.graph_objects as go
|
| 11 |
-
from llm_models import text_llm
|
| 12 |
-
from prompt_models import prompt_analyze
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def analyze_code_execution(code: str, execution_result: dict, df: pd.DataFrame) -> str:
|
| 16 |
-
"""
|
| 17 |
-
Analyze only the execution results (output and variables) to provide focused insights.
|
| 18 |
-
|
| 19 |
-
Args:
|
| 20 |
-
code: The Python code that was executed
|
| 21 |
-
execution_result: The dictionary containing execution results
|
| 22 |
-
df: The DataFrame being analyzed (for context only)
|
| 23 |
-
|
| 24 |
-
Returns:
|
| 25 |
-
str: Natural language analysis focused on the execution results
|
| 26 |
-
"""
|
| 27 |
-
# Extract relevant information from execution_result
|
| 28 |
-
output = execution_result.get('stdout', 'Tidak ada output teks')
|
| 29 |
-
variables = execution_result.get('variables', {})
|
| 30 |
-
error = execution_result.get('error', None)
|
| 31 |
-
|
| 32 |
-
# Prepare variable summaries
|
| 33 |
-
var_summaries = []
|
| 34 |
-
for var_name, var_value in variables.items():
|
| 35 |
-
if isinstance(var_value, (pd.DataFrame, pd.Series)):
|
| 36 |
-
var_summaries.append(f"- {var_name}: {type(var_value).__name__} dengan bentuk {var_value.shape}")
|
| 37 |
-
elif isinstance(var_value, (plt.Figure, sns.axisgrid.Grid)):
|
| 38 |
-
var_summaries.append(f"- {var_name}: Visualisasi plot")
|
| 39 |
-
else:
|
| 40 |
-
var_summaries.append(f"- {var_name}: {type(var_value).__name__}")
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
prompt = prompt_analyze(output, var_summaries, df, error)
|
| 44 |
-
# Get analysis from the text model
|
| 45 |
-
response = text_llm(prompt)
|
| 46 |
-
|
| 47 |
-
# Clear thinking output
|
| 48 |
-
clean_response = re.sub(r'<\s*think\s*>.*?<\s*/\s*think\s*>', '', response, flags=re.DOTALL | re.IGNORECASE)
|
| 49 |
-
|
| 50 |
-
return clean_response
|
| 51 |
-
|
| 52 |
-
# =======================
|
| 53 |
-
def execute_code(code: str, df: pd.DataFrame):
|
| 54 |
-
"""Execute Python code safely and return outputs"""
|
| 55 |
-
# Extract Python code from markdown blocks
|
| 56 |
-
if "```python" in code:
|
| 57 |
-
clean_code = code.split("```python")[1].split("```")[0].strip()
|
| 58 |
-
else:
|
| 59 |
-
clean_code = code.strip()
|
| 60 |
-
|
| 61 |
-
# Add required imports if missing
|
| 62 |
-
required_imports = [
|
| 63 |
-
"import pandas as pd",
|
| 64 |
-
"import matplotlib.pyplot as plt",
|
| 65 |
-
"import seaborn as sns",
|
| 66 |
-
"import plotly.express as px",
|
| 67 |
-
"import plotly.graph_objects as go"
|
| 68 |
-
]
|
| 69 |
-
|
| 70 |
-
for imp in required_imports:
|
| 71 |
-
if imp not in clean_code:
|
| 72 |
-
clean_code = imp + "\n" + clean_code
|
| 73 |
-
|
| 74 |
-
# Prepare execution environment
|
| 75 |
-
local_vars = {
|
| 76 |
-
'df': df,
|
| 77 |
-
'plt': plt,
|
| 78 |
-
'sns': sns,
|
| 79 |
-
'pd': pd
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
# Capture outputs
|
| 83 |
-
stdout = io.StringIO()
|
| 84 |
-
stderr = io.StringIO()
|
| 85 |
-
|
| 86 |
-
try:
|
| 87 |
-
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
| 88 |
-
exec(clean_code, local_vars)
|
| 89 |
-
|
| 90 |
-
# Deteksi plot Plotly
|
| 91 |
-
plotly_figs = []
|
| 92 |
-
for var_name, var_value in local_vars.items():
|
| 93 |
-
if isinstance(var_value, go.Figure):
|
| 94 |
-
plotly_figs.append(var_value)
|
| 95 |
-
|
| 96 |
-
return {
|
| 97 |
-
'code': clean_code,
|
| 98 |
-
'stdout': stdout.getvalue(),
|
| 99 |
-
'stderr': stderr.getvalue(),
|
| 100 |
-
'figure': plotly_figs,
|
| 101 |
-
'success': True,
|
| 102 |
-
'variables': {k: v for k, v in local_vars.items()
|
| 103 |
-
if not k.startswith('_') and k not in ['df', 'plt', 'sns', 'pd']}
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
except Exception as e:
|
| 107 |
-
return {
|
| 108 |
-
'code': clean_code,
|
| 109 |
-
'error': str(e),
|
| 110 |
-
'stderr': stderr.getvalue(),
|
| 111 |
-
'success': False
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
def add_to_history(execution_result):
|
| 115 |
-
"""Add execution result to history with timestamp"""
|
| 116 |
-
history_item = {
|
| 117 |
-
**execution_result,
|
| 118 |
-
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 119 |
-
}
|
| 120 |
-
st.session_state.execution_history.append(history_item)
|
| 121 |
-
|
| 122 |
-
# Generate explanation for successful executions
|
| 123 |
-
if execution_result['success']:
|
| 124 |
-
with st.spinner("Analyzing results..."):
|
| 125 |
-
df_to_analyze = st.session_state.df_cleaned if 'df_cleaned' in st.session_state else st.session_state.df
|
| 126 |
-
|
| 127 |
-
analysis = analyze_code_execution(
|
| 128 |
-
code=execution_result['code'],
|
| 129 |
-
execution_result=execution_result,
|
| 130 |
-
df=df_to_analyze # Only used for context, not analyzed
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
history_item['explanation'] = f"""
|
| 134 |
-
**Analisis Hasil Eksekusi:**
|
| 135 |
-
{analysis}
|
| 136 |
-
"""
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# =======================
|
| 141 |
-
# Display Functions
|
| 142 |
-
# =======================
|
| 143 |
-
|
| 144 |
-
def display_code_with_highlight(code: str):
|
| 145 |
-
"""Display formatted Python code using Streamlit's built-in code block"""
|
| 146 |
-
st.code(code, language='python')
|
| 147 |
-
|
| 148 |
-
def display_history():
|
| 149 |
-
"""Display all execution history items"""
|
| 150 |
-
st.markdown("### Execution History")
|
| 151 |
-
|
| 152 |
-
if not st.session_state.execution_history:
|
| 153 |
-
st.info("No executions yet. Run some code to see results here.")
|
| 154 |
-
return
|
| 155 |
-
|
| 156 |
-
for i, item in enumerate(reversed(st.session_state.execution_history)):
|
| 157 |
-
with st.container():
|
| 158 |
-
st.markdown(f"### Execution #{len(st.session_state.execution_history)-i}")
|
| 159 |
-
st.caption(f"Executed at {item['timestamp']}")
|
| 160 |
-
|
| 161 |
-
# Display code
|
| 162 |
-
with st.expander("View Code", expanded=False):
|
| 163 |
-
display_code_with_highlight(item['code'])
|
| 164 |
-
|
| 165 |
-
# Display outputs
|
| 166 |
-
if item['success']:
|
| 167 |
-
if 'explanation' in item:
|
| 168 |
-
with st.expander("See Explanation"):
|
| 169 |
-
st.markdown("**Explanation:**")
|
| 170 |
-
st.info(item['explanation'])
|
| 171 |
-
|
| 172 |
-
if item['stdout']:
|
| 173 |
-
with st.expander("View Output", expanded=False):
|
| 174 |
-
st.markdown("**Output:**")
|
| 175 |
-
lines = item['stdout'].split('\n')
|
| 176 |
-
text_content = []
|
| 177 |
-
table_data = []
|
| 178 |
-
header_detected = False
|
| 179 |
-
|
| 180 |
-
for idx, line in enumerate(lines):
|
| 181 |
-
cleaned_line = line.strip()
|
| 182 |
-
if not cleaned_line:
|
| 183 |
-
continue
|
| 184 |
-
|
| 185 |
-
if not header_detected:
|
| 186 |
-
if re.match(r"^[\w\s_]+$", cleaned_line) and len(cleaned_line.split()) > 1:
|
| 187 |
-
if (idx + 1 < len(lines)) and re.match(r"^\d+\s+[\d\.e+-]+", lines[idx+1].strip()):
|
| 188 |
-
header_detected = True
|
| 189 |
-
table_data = lines[idx:]
|
| 190 |
-
break
|
| 191 |
-
else:
|
| 192 |
-
text_content.append(cleaned_line)
|
| 193 |
-
else:
|
| 194 |
-
text_content.append(cleaned_line)
|
| 195 |
-
|
| 196 |
-
if text_content:
|
| 197 |
-
st.write("\n".join(text_content))
|
| 198 |
-
|
| 199 |
-
if table_data:
|
| 200 |
-
try:
|
| 201 |
-
clean_table = [line.strip() for line in table_data if line.strip()]
|
| 202 |
-
df = pd.read_csv(StringIO("\n".join(clean_table)), sep=r"\s+", engine="python")
|
| 203 |
-
st.dataframe(df)
|
| 204 |
-
except Exception as e:
|
| 205 |
-
st.write("\n".join(table_data))
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
if item['figure']:
|
| 209 |
-
st.markdown("**Visualisasi Interaktif:**")
|
| 210 |
-
for fig in item['figure']:
|
| 211 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
if item['variables']:
|
| 215 |
-
with st.expander("Created Variables"):
|
| 216 |
-
st.json({k: str(type(v)) for k, v in item['variables'].items()})
|
| 217 |
-
else:
|
| 218 |
-
st.error("Execution failed")
|
| 219 |
-
st.error(item['error'])
|
| 220 |
-
if item['stderr']:
|
| 221 |
-
st.text("Error details:")
|
| 222 |
-
st.text(item['stderr'])
|
| 223 |
-
|
| 224 |
-
st.markdown("---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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