mgbam commited on
Commit
5effbd3
Β·
verified Β·
1 Parent(s): 9940006

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -55
app.py CHANGED
@@ -14,7 +14,7 @@ warnings.filterwarnings('ignore')
14
 
15
  CSS = """
16
  /* --- Phoenix UI Professional Dark CSS --- */
17
- body { --body-background-fill: #111827; }
18
  .stat-card { border-radius: 12px !important; padding: 20px !important; background: #1f2937 !important; border: 1px solid #374151 !important; text-align: center; transition: all 0.3s ease; }
19
  .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05); }
20
  .stat-card-title { font-size: 16px; font-weight: 500; color: #9ca3af !important; margin-bottom: 8px; }
@@ -34,14 +34,10 @@ class DataExplorerApp:
34
  self.demo = self._build_ui()
35
 
36
  def _build_ui(self) -> gr.Blocks:
37
- """
38
- Defines all UI components, arranges them in the layout,
39
- and registers all event handlers within the same Blocks context.
40
- """
41
- with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="Professional AI Data Explorer") as demo:
42
- # --- State Management ---
43
  state_var = gr.State({})
44
-
45
  # --- Component Definition ---
46
  # Sidebar
47
  cockpit_btn = gr.Button("πŸ“Š Data Cockpit", elem_classes="selected", elem_id="cockpit")
@@ -53,8 +49,8 @@ class DataExplorerApp:
53
  suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary", interactive=False)
54
 
55
  # Cockpit
56
- rows_stat, cols_stat = gr.Textbox("0", interactive=False, elem_classes="stat-card-value"), gr.Textbox("0", interactive=False, elem_classes="stat-card-value")
57
- quality_stat, time_cols_stat = gr.Textbox("0%", interactive=False, elem_classes="stat-card-value"), gr.Textbox("0", interactive=False, elem_classes="stat-card-value")
58
  suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
59
 
60
  # Deep Dive
@@ -63,10 +59,10 @@ class DataExplorerApp:
63
  y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)", visible=False, interactive=False)
64
  add_plot_btn = gr.Button("Add to Dashboard", variant="primary", interactive=False)
65
  clear_plots_btn = gr.Button("Clear Dashboard")
66
- dashboard_gallery = gr.Gallery(label="πŸ“Š Your Custom Dashboard", height="auto", columns=2, preview=True)
67
 
68
  # Co-pilot
69
- chatbot = gr.Chatbot(height=500, label="Conversation", show_copy_button=True)
70
  copilot_explanation = gr.Markdown(visible=False, elem_classes="explanation-block")
71
  copilot_code = gr.Code(language="python", visible=False, label="Executed Code")
72
  copilot_plot = gr.Plot(visible=False, label="Generated Visualization")
@@ -77,13 +73,12 @@ class DataExplorerApp:
77
  # --- Layout Arrangement ---
78
  with gr.Row():
79
  with gr.Column(scale=1, elem_classes="sidebar"):
80
- gr.Markdown("## πŸš€ AI Explorer Pro"); cockpit_btn; deep_dive_btn; copilot_btn; gr.Markdown("---")
81
  file_input; status_output; gr.Markdown("---"); api_key_input; suggestion_btn
82
  with gr.Column(scale=4):
83
  welcome_page = gr.Column(visible=True)
84
  with welcome_page:
85
  gr.Markdown("# Welcome to the AI Data Explorer Pro\n> Please **upload a CSV file** and **enter your Gemini API key** to begin your analysis.")
86
- gr.Image("workflow.png", show_label=False, show_download_button=False, container=False)
87
 
88
  cockpit_page = gr.Column(visible=False)
89
  with cockpit_page:
@@ -108,35 +103,31 @@ class DataExplorerApp:
108
  with gr.Accordion("AI's Detailed Response", open=True): copilot_explanation; copilot_code; copilot_plot; copilot_table
109
  with gr.Row(): chat_input; chat_submit_btn
110
 
111
- # --- Event Handlers Registration (inside the 'with' block) ---
112
- pages = [cockpit_page, deep_dive_page, copilot_page]
113
  nav_buttons = [cockpit_btn, deep_dive_btn, copilot_btn]
114
 
115
  for i, btn in enumerate(nav_buttons):
116
- btn.click(
117
- lambda id=btn.elem_id: self._switch_page(id), outputs=pages
118
- ).then(
119
- lambda i=i: [gr.update(elem_classes="selected" if j==i else "") for j in range(len(nav_buttons))], outputs=nav_buttons
120
- )
121
 
122
  file_input.upload(self.load_and_process_file, inputs=[file_input], outputs=[
123
  state_var, status_output, welcome_page, cockpit_page,
124
  rows_stat, cols_stat, quality_stat, time_cols_stat,
125
  x_col_dd, y_col_dd, add_plot_btn
126
- ]).then(lambda: self._switch_page("cockpit"), outputs=pages) \
127
- .then(lambda: [gr.update(elem_classes="selected"), gr.update(elem_classes=""), gr.update(elem_classes="")], outputs=nav_buttons)
128
 
129
  api_key_input.change(lambda x: gr.update(interactive=bool(x)), inputs=[api_key_input], outputs=[suggestion_btn])
130
-
131
  plot_type_dd.change(self._update_plot_controls, inputs=[plot_type_dd], outputs=[y_col_dd])
132
  add_plot_btn.click(self.add_plot_to_dashboard, inputs=[state_var, x_col_dd, y_col_dd, plot_type_dd], outputs=[state_var, dashboard_gallery])
133
  clear_plots_btn.click(self.clear_dashboard, inputs=[state_var], outputs=[state_var, dashboard_gallery])
134
-
135
  suggestion_btn.click(self.get_ai_suggestions, inputs=[state_var, api_key_input], outputs=suggestion_buttons)
 
136
  for btn in suggestion_buttons:
137
- btn.click(self.handle_suggestion_click, inputs=[btn], outputs=[cockpit_page, deep_dive_page, copilot_page, chat_input]) \
138
- .then(lambda: self._switch_page("co-pilot"), outputs=pages) \
139
- .then(lambda: (gr.update(elem_classes=""), gr.update(elem_classes=""), gr.update(elem_classes="selected")), outputs=nav_buttons)
140
 
141
  chat_submit_btn.click(self.respond_to_chat, [state_var, api_key_input, chat_input, chatbot], [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]).then(lambda: "", outputs=[chat_input])
142
  chat_input.submit(self.respond_to_chat, [state_var, api_key_input, chat_input, chatbot], [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]).then(lambda: "", outputs=[chat_input])
@@ -144,12 +135,14 @@ class DataExplorerApp:
144
  return demo
145
 
146
  def launch(self):
147
- """Launches the Gradio application."""
148
  self.demo.launch(debug=True)
149
 
150
- # --- Backend Logic Methods ---
151
- def _switch_page(self, page_id: str) -> Tuple[gr.update, ...]:
152
- return gr.update(visible=page_id=="cockpit"), gr.update(visible=page_id=="deep_dive"), gr.update(visible=page_id=="co-pilot")
 
 
 
153
 
154
  def _update_plot_controls(self, plot_type: str) -> gr.update:
155
  return gr.update(visible=plot_type in ['scatter', 'box'])
@@ -157,16 +150,10 @@ class DataExplorerApp:
157
  def load_and_process_file(self, file_obj: Any) -> Tuple[Any, ...]:
158
  try:
159
  df = pd.read_csv(file_obj.name, low_memory=False)
160
- for col in df.select_dtypes(include=['object']).columns:
161
- try: df[col] = pd.to_datetime(df[col], errors='raise')
162
- except (ValueError, TypeError): continue
163
-
164
  metadata = self._extract_dataset_metadata(df)
165
  state = {'df': df, 'metadata': metadata, 'dashboard_plots': []}
166
- status_msg = f"βœ… **{os.path.basename(file_obj.name)}** loaded."
167
  rows, cols, quality = metadata['shape'][0], metadata['shape'][1], metadata['data_quality']
168
-
169
- return (state, status_msg, gr.update(visible=False), gr.update(visible=True),
170
  f"{rows:,}", f"{cols}", f"{quality}%", f"{len(metadata['datetime_cols'])}",
171
  gr.update(choices=metadata['columns'], interactive=True), gr.update(choices=metadata['columns'], interactive=True), gr.update(interactive=True))
172
  except Exception as e:
@@ -179,11 +166,11 @@ class DataExplorerApp:
179
  'numeric_cols': df.select_dtypes(include=np.number).columns.tolist(),
180
  'categorical_cols': df.select_dtypes(include=['object', 'category']).columns.tolist(),
181
  'datetime_cols': df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist(),
182
- 'dtypes_head': df.head().to_string()}
 
183
 
184
  def add_plot_to_dashboard(self, state: Dict, x_col: str, y_col: Optional[str], plot_type: str) -> Tuple[Dict, List]:
185
- if not x_col:
186
- gr.Warning("Please select at least an X-axis column."); return state, state.get('dashboard_plots', [])
187
  df = state['df']
188
  title = f"{plot_type.capitalize()}: {y_col} by {x_col}" if y_col and plot_type in ['box', 'scatter'] else f"Distribution of {x_col}"
189
  try:
@@ -196,17 +183,15 @@ class DataExplorerApp:
196
  if fig:
197
  fig.update_layout(template="plotly_dark"); state['dashboard_plots'].append(fig); gr.Info(f"Added '{title}' to the dashboard.")
198
  return state, state['dashboard_plots']
199
- except Exception as e:
200
- gr.Error(f"Plotting Error: {e}"); return state, state.get('dashboard_plots', [])
201
 
202
  def clear_dashboard(self, state: Dict) -> Tuple[Dict, List]:
203
  state['dashboard_plots'] = []; gr.Info("Dashboard cleared."); return state, []
204
 
205
  def get_ai_suggestions(self, state: Dict, api_key: str) -> List[gr.update]:
206
- if not api_key: gr.Warning("API Key is required for suggestions."); return [gr.update(visible=False)]*5
207
  if not state: gr.Warning("Please load data first."); return [gr.update(visible=False)]*5
208
- metadata = state['metadata']
209
- prompt = f"""Based on this metadata (columns: {metadata['columns']}), generate 4 impactful analytical questions. Return ONLY a JSON list of strings."""
210
  try:
211
  genai.configure(api_key=api_key)
212
  suggestions = json.loads(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text)
@@ -214,22 +199,22 @@ class DataExplorerApp:
214
  except Exception as e: gr.Error(f"AI Suggestion Error: {e}"); return [gr.update(visible=False)]*5
215
 
216
  def handle_suggestion_click(self, question: str) -> Tuple[gr.update, ...]:
217
- return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), question
218
 
219
  def respond_to_chat(self, state: Dict, api_key: str, user_message: str, history: List) -> Any:
 
220
  if not api_key or not state:
221
  msg = "I need a Gemini API key and a dataset to work."; history.append((user_message, msg)); return history, *[gr.update(visible=False)]*4
222
 
223
  history.append((user_message, "Thinking... πŸ€”")); yield history, *[gr.update(visible=False)]*4
224
 
225
- metadata, prompt = state['metadata'], f"""You are 'Chief Data Scientist', an expert AI analyst...
226
  **Instructions:**
227
- 1. **Analyze:** Understand the user's intent.
228
- 2. **Method:** Choose the best method (table, value, or plot). Infer the best plot type.
229
- 3. **Plan:** Briefly explain your plan.
230
- 4. **Code:** Write Python code. Use `fig` for plots (with `template='plotly_dark'`) and `result_df` for tables.
231
- 5. **Insight:** Provide a one-sentence business insight.
232
- 6. **Respond ONLY with a single JSON object with keys: "plan", "code", "insight".**
233
  **Metadata:** {metadata['dtypes_head']}
234
  **User Question:** "{user_message}"
235
  """
 
14
 
15
  CSS = """
16
  /* --- Phoenix UI Professional Dark CSS --- */
17
+ #app-title { text-align: center; font-weight: 800; font-size: 2.5rem; }
18
  .stat-card { border-radius: 12px !important; padding: 20px !important; background: #1f2937 !important; border: 1px solid #374151 !important; text-align: center; transition: all 0.3s ease; }
19
  .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05); }
20
  .stat-card-title { font-size: 16px; font-weight: 500; color: #9ca3af !important; margin-bottom: 8px; }
 
34
  self.demo = self._build_ui()
35
 
36
  def _build_ui(self) -> gr.Blocks:
37
+ """Defines, arranges, and connects all UI components and logic."""
38
+ with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="AI Data Explorer Pro") as demo:
 
 
 
 
39
  state_var = gr.State({})
40
+
41
  # --- Component Definition ---
42
  # Sidebar
43
  cockpit_btn = gr.Button("πŸ“Š Data Cockpit", elem_classes="selected", elem_id="cockpit")
 
49
  suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary", interactive=False)
50
 
51
  # Cockpit
52
+ rows_stat, cols_stat = gr.Textbox("0", interactive=False, elem_classes="stat-card-value", show_label=False), gr.Textbox("0", interactive=False, elem_classes="stat-card-value", show_label=False)
53
+ quality_stat, time_cols_stat = gr.Textbox("0%", interactive=False, elem_classes="stat-card-value", show_label=False), gr.Textbox("0", interactive=False, elem_classes="stat-card-value", show_label=False)
54
  suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
55
 
56
  # Deep Dive
 
59
  y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)", visible=False, interactive=False)
60
  add_plot_btn = gr.Button("Add to Dashboard", variant="primary", interactive=False)
61
  clear_plots_btn = gr.Button("Clear Dashboard")
62
+ dashboard_gallery = gr.Gallery(label="πŸ“Š Your Custom Dashboard", height="auto", columns=[1, 2], preview=True)
63
 
64
  # Co-pilot
65
+ chatbot = gr.Chatbot(height=500, label="Conversation", show_copy_button=True, avatar_images=("user.png", "bot.png"))
66
  copilot_explanation = gr.Markdown(visible=False, elem_classes="explanation-block")
67
  copilot_code = gr.Code(language="python", visible=False, label="Executed Code")
68
  copilot_plot = gr.Plot(visible=False, label="Generated Visualization")
 
73
  # --- Layout Arrangement ---
74
  with gr.Row():
75
  with gr.Column(scale=1, elem_classes="sidebar"):
76
+ gr.Markdown("## πŸš€ AI Explorer Pro", elem_id="app-title"); cockpit_btn; deep_dive_btn; copilot_btn; gr.Markdown("---")
77
  file_input; status_output; gr.Markdown("---"); api_key_input; suggestion_btn
78
  with gr.Column(scale=4):
79
  welcome_page = gr.Column(visible=True)
80
  with welcome_page:
81
  gr.Markdown("# Welcome to the AI Data Explorer Pro\n> Please **upload a CSV file** and **enter your Gemini API key** to begin your analysis.")
 
82
 
83
  cockpit_page = gr.Column(visible=False)
84
  with cockpit_page:
 
103
  with gr.Accordion("AI's Detailed Response", open=True): copilot_explanation; copilot_code; copilot_plot; copilot_table
104
  with gr.Row(): chat_input; chat_submit_btn
105
 
106
+ # --- Event Handlers Registration ---
107
+ pages = [welcome_page, cockpit_page, deep_dive_page, copilot_page]
108
  nav_buttons = [cockpit_btn, deep_dive_btn, copilot_btn]
109
 
110
  for i, btn in enumerate(nav_buttons):
111
+ btn.click(lambda id=btn.elem_id: self._switch_page(id, pages), outputs=pages).then(
112
+ lambda i=i: [gr.update(elem_classes="selected" if j==i else "") for j in range(len(nav_buttons))], outputs=nav_buttons)
 
 
 
113
 
114
  file_input.upload(self.load_and_process_file, inputs=[file_input], outputs=[
115
  state_var, status_output, welcome_page, cockpit_page,
116
  rows_stat, cols_stat, quality_stat, time_cols_stat,
117
  x_col_dd, y_col_dd, add_plot_btn
118
+ ]).then(lambda: self._switch_page("cockpit", pages), outputs=pages).then(
119
+ lambda: [gr.update(elem_classes="selected"), gr.update(elem_classes=""), gr.update(elem_classes="")], outputs=nav_buttons)
120
 
121
  api_key_input.change(lambda x: gr.update(interactive=bool(x)), inputs=[api_key_input], outputs=[suggestion_btn])
 
122
  plot_type_dd.change(self._update_plot_controls, inputs=[plot_type_dd], outputs=[y_col_dd])
123
  add_plot_btn.click(self.add_plot_to_dashboard, inputs=[state_var, x_col_dd, y_col_dd, plot_type_dd], outputs=[state_var, dashboard_gallery])
124
  clear_plots_btn.click(self.clear_dashboard, inputs=[state_var], outputs=[state_var, dashboard_gallery])
 
125
  suggestion_btn.click(self.get_ai_suggestions, inputs=[state_var, api_key_input], outputs=suggestion_buttons)
126
+
127
  for btn in suggestion_buttons:
128
+ btn.click(self.handle_suggestion_click, inputs=[btn], outputs=[welcome_page, cockpit_page, deep_dive_page, copilot_page, chat_input]) \
129
+ .then(lambda: self._switch_page("co-pilot", pages), outputs=pages) \
130
+ .then(lambda: (gr.update(elem_classes=""), gr.update(elem_classes=""), gr.update(elem_classes="selected")), outputs=nav_buttons)
131
 
132
  chat_submit_btn.click(self.respond_to_chat, [state_var, api_key_input, chat_input, chatbot], [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]).then(lambda: "", outputs=[chat_input])
133
  chat_input.submit(self.respond_to_chat, [state_var, api_key_input, chat_input, chatbot], [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]).then(lambda: "", outputs=[chat_input])
 
135
  return demo
136
 
137
  def launch(self):
 
138
  self.demo.launch(debug=True)
139
 
140
+ def _switch_page(self, page_id: str, all_pages: List) -> List[gr.update]:
141
+ visibility_updates = [gr.update(visible=False)] * len(all_pages)
142
+ if page_id == "cockpit": visibility_updates[1] = gr.update(visible=True)
143
+ elif page_id == "deep_dive": visibility_updates[2] = gr.update(visible=True)
144
+ elif page_id == "co-pilot": visibility_updates[3] = gr.update(visible=True)
145
+ return visibility_updates
146
 
147
  def _update_plot_controls(self, plot_type: str) -> gr.update:
148
  return gr.update(visible=plot_type in ['scatter', 'box'])
 
150
  def load_and_process_file(self, file_obj: Any) -> Tuple[Any, ...]:
151
  try:
152
  df = pd.read_csv(file_obj.name, low_memory=False)
 
 
 
 
153
  metadata = self._extract_dataset_metadata(df)
154
  state = {'df': df, 'metadata': metadata, 'dashboard_plots': []}
 
155
  rows, cols, quality = metadata['shape'][0], metadata['shape'][1], metadata['data_quality']
156
+ return (state, f"βœ… **{os.path.basename(file_obj.name)}** loaded.", gr.update(visible=False), gr.update(visible=True),
 
157
  f"{rows:,}", f"{cols}", f"{quality}%", f"{len(metadata['datetime_cols'])}",
158
  gr.update(choices=metadata['columns'], interactive=True), gr.update(choices=metadata['columns'], interactive=True), gr.update(interactive=True))
159
  except Exception as e:
 
166
  'numeric_cols': df.select_dtypes(include=np.number).columns.tolist(),
167
  'categorical_cols': df.select_dtypes(include=['object', 'category']).columns.tolist(),
168
  'datetime_cols': df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist(),
169
+ 'dtypes_head': df.head(3).to_string(),
170
+ 'data_quality': quality} # <--- CRITICAL FIX: KEY ADDED HERE
171
 
172
  def add_plot_to_dashboard(self, state: Dict, x_col: str, y_col: Optional[str], plot_type: str) -> Tuple[Dict, List]:
173
+ if not x_col: gr.Warning("Please select at least an X-axis column."); return state, state.get('dashboard_plots', [])
 
174
  df = state['df']
175
  title = f"{plot_type.capitalize()}: {y_col} by {x_col}" if y_col and plot_type in ['box', 'scatter'] else f"Distribution of {x_col}"
176
  try:
 
183
  if fig:
184
  fig.update_layout(template="plotly_dark"); state['dashboard_plots'].append(fig); gr.Info(f"Added '{title}' to the dashboard.")
185
  return state, state['dashboard_plots']
186
+ except Exception as e: gr.Error(f"Plotting Error: {e}"); return state, state.get('dashboard_plots', [])
 
187
 
188
  def clear_dashboard(self, state: Dict) -> Tuple[Dict, List]:
189
  state['dashboard_plots'] = []; gr.Info("Dashboard cleared."); return state, []
190
 
191
  def get_ai_suggestions(self, state: Dict, api_key: str) -> List[gr.update]:
192
+ if not api_key: gr.Warning("API Key is required."); return [gr.update(visible=False)]*5
193
  if not state: gr.Warning("Please load data first."); return [gr.update(visible=False)]*5
194
+ metadata, prompt = state['metadata'], f"From columns {metadata['columns']}, generate 4 impactful analytical questions. Return ONLY a JSON list of strings."
 
195
  try:
196
  genai.configure(api_key=api_key)
197
  suggestions = json.loads(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text)
 
199
  except Exception as e: gr.Error(f"AI Suggestion Error: {e}"); return [gr.update(visible=False)]*5
200
 
201
  def handle_suggestion_click(self, question: str) -> Tuple[gr.update, ...]:
202
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), question
203
 
204
  def respond_to_chat(self, state: Dict, api_key: str, user_message: str, history: List) -> Any:
205
+ if not user_message.strip(): gr.Warning("Message is empty."); return history, *[gr.update()]*4
206
  if not api_key or not state:
207
  msg = "I need a Gemini API key and a dataset to work."; history.append((user_message, msg)); return history, *[gr.update(visible=False)]*4
208
 
209
  history.append((user_message, "Thinking... πŸ€”")); yield history, *[gr.update(visible=False)]*4
210
 
211
+ metadata, prompt = state['metadata'], f"""You are 'Chief Data Scientist', an expert AI analyst. Your goal is to answer a user's question about a pandas DataFrame (`df`) by writing and executing Python code.
212
  **Instructions:**
213
+ 1. **Analyze:** Understand the user's intent. Infer the best plot type if not specified.
214
+ 2. **Plan:** Briefly explain your plan of attack.
215
+ 3. **Code:** Write Python code. Use `fig` for plots (with `template='plotly_dark'`) and `result_df` for tables.
216
+ 4. **Insight:** Provide a one-sentence business insight.
217
+ 5. **Respond ONLY with a single JSON object with keys: "plan", "code", "insight".**
 
218
  **Metadata:** {metadata['dtypes_head']}
219
  **User Question:** "{user_message}"
220
  """