sanjaystarc commited on
Commit
20ed955
·
verified ·
1 Parent(s): 8757353

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -6
app.py CHANGED
@@ -5,6 +5,7 @@ import numpy as np
5
  import requests
6
  import json
7
  import time # Ensure time is imported for backoff
 
8
 
9
  # --- CONFIG ---
10
  # Note: GEMINI_API_KEY is retrieved from environment variables/secrets.
@@ -41,7 +42,7 @@ SYSTEM_INSTRUCTION = (
41
  "2. **Code:** If the question requires calculation, aggregation, or visualization, you MUST generate Python code to execute against the 'df' DataFrame. "
42
  " - The DataFrame is already loaded as a variable named 'df'. Do NOT redefine it. "
43
  " - Use Streamlit functions for output: `st.dataframe(...)` for results, `st.bar_chart()`, `st.line_chart()`, or `st.pyplot()` for plots. "
44
- " - Use `import matplotlib.pyplot as plt` if creating custom plots. "
45
  " - Ensure the code is self-contained and ready to execute."
46
  )
47
 
@@ -91,7 +92,7 @@ def chat_with_gemini(prompt, context):
91
  raise e
92
 
93
  # --- UI ---
94
- st.title("✨ Perfect Data Analyst Agent (Code Execution Enabled)")
95
  st.write("Upload a CSV file and ask natural language questions. The agent now generates and executes Python code to provide precise data analysis and visualizations.")
96
 
97
  # State variable to hold the DataFrame, initialized once
@@ -122,7 +123,8 @@ if uploaded:
122
  df = st.session_state.df # Local variable for code execution context
123
 
124
  # Summarize dataset for context sent to the LLM
125
- context = f"Dataset Columns: {', '.join(df.columns.astype(str))}\n\nFirst 5 rows of data:\n{df.head(5).to_markdown(index=False)}"
 
126
 
127
  st.markdown("---")
128
  st.subheader("🤖 Analysis Steps")
@@ -151,12 +153,13 @@ if uploaded:
151
  try:
152
  # 2. Execute the generated Python code safely
153
 
154
- # IMPORTANT: Create a local scope with necessary variables (df, st)
155
  local_scope = {
156
  'df': df,
157
  'st': st,
158
  'pd': pd,
159
  'np': np,
 
160
  }
161
  # Executing the code within the local scope
162
  exec(code, globals(), local_scope)
@@ -164,5 +167,12 @@ if uploaded:
164
  st.success("Code execution complete. Results are displayed above.")
165
 
166
  except Exception as e:
167
- st.error(f"Step 2 Failed (Code Execution Error): The agent generated invalid code.")
168
- st.exception(e)
 
 
 
 
 
 
 
 
5
  import requests
6
  import json
7
  import time # Ensure time is imported for backoff
8
+ import matplotlib.pyplot as plt # Explicitly import matplotlib.pyplot here for use in exec() scope
9
 
10
  # --- CONFIG ---
11
  # Note: GEMINI_API_KEY is retrieved from environment variables/secrets.
 
42
  "2. **Code:** If the question requires calculation, aggregation, or visualization, you MUST generate Python code to execute against the 'df' DataFrame. "
43
  " - The DataFrame is already loaded as a variable named 'df'. Do NOT redefine it. "
44
  " - Use Streamlit functions for output: `st.dataframe(...)` for results, `st.bar_chart()`, `st.line_chart()`, or `st.pyplot()` for plots. "
45
+ " - If you need custom plotting, you can assume `import matplotlib.pyplot as plt` is available and use `plt.figure()`, `plt.bar()`, etc., followed by `st.pyplot(plt)` to display the plot. "
46
  " - Ensure the code is self-contained and ready to execute."
47
  )
48
 
 
92
  raise e
93
 
94
  # --- UI ---
95
+ st.title("✨Data Analyst Agent (Code Execution Enabled)")
96
  st.write("Upload a CSV file and ask natural language questions. The agent now generates and executes Python code to provide precise data analysis and visualizations.")
97
 
98
  # State variable to hold the DataFrame, initialized once
 
123
  df = st.session_state.df # Local variable for code execution context
124
 
125
  # Summarize dataset for context sent to the LLM
126
+ # FIX: Using to_string() instead of to_markdown() to avoid the 'tabulate' dependency error.
127
+ context = f"Dataset Columns: {', '.join(df.columns.astype(str))}\n\nFirst 5 rows of data:\n{df.head(5).to_string(index=False)}"
128
 
129
  st.markdown("---")
130
  st.subheader("🤖 Analysis Steps")
 
153
  try:
154
  # 2. Execute the generated Python code safely
155
 
156
+ # IMPORTANT: Create a local scope with necessary variables
157
  local_scope = {
158
  'df': df,
159
  'st': st,
160
  'pd': pd,
161
  'np': np,
162
+ 'plt': plt, # Explicitly include pyplot here
163
  }
164
  # Executing the code within the local scope
165
  exec(code, globals(), local_scope)
 
167
  st.success("Code execution complete. Results are displayed above.")
168
 
169
  except Exception as e:
170
+ st.error(f"Step 2 Failed (Code Execution Error): The agent generated invalid code. Check the console for full traceback.")
171
+ st.exception(e)
172
+ else:
173
+ st.info("No code was generated, as the question was purely informational.")
174
+ else:
175
+ st.info("The uploaded CSV file appears to be empty.")
176
+
177
+ else:
178
+ st.info("👆 Upload a CSV file to begin the full analysis experience.")