Update app.py
Browse files
app.py
CHANGED
@@ -2,258 +2,280 @@ import gradio as gr
|
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
4 |
import plotly.express as px
|
5 |
-
import plotly.graph_objects as go
|
6 |
-
from plotly.subplots import make_subplots
|
7 |
import io
|
8 |
import json
|
9 |
import warnings
|
10 |
import google.generativeai as genai
|
11 |
import os
|
12 |
-
from
|
13 |
|
14 |
-
# --- Configuration ---
|
15 |
warnings.filterwarnings('ignore')
|
16 |
|
17 |
-
# --- Expert-Crafted Dark Theme CSS ---
|
18 |
CSS = """
|
19 |
-
/* --- Phoenix UI
|
20 |
-
|
21 |
-
.stat-card {
|
22 |
-
|
23 |
-
padding: 20px !important;
|
24 |
-
background: #1f2937 !important; /* Dark blue-gray background */
|
25 |
-
border: 1px solid #374151 !important;
|
26 |
-
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
27 |
-
text-align: center;
|
28 |
-
}
|
29 |
.stat-card-title { font-size: 16px; font-weight: 500; color: #9ca3af !important; margin-bottom: 8px; }
|
30 |
.stat-card-value { font-size: 32px; font-weight: 700; color: #f9fafb !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
.gr-button { box-shadow: 0 1px 2px 0 rgba(0,0,0,0.05); }
|
35 |
|
36 |
-
|
37 |
-
.
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
min-height: 100vh;
|
42 |
-
}
|
43 |
-
.sidebar .gr-button {
|
44 |
-
width: 100%;
|
45 |
-
text-align: left !important;
|
46 |
-
background: none !important;
|
47 |
-
border: none !important;
|
48 |
-
box-shadow: none !important;
|
49 |
-
color: #d1d5db !important; /* Light gray text for readability */
|
50 |
-
font-size: 16px !important;
|
51 |
-
padding: 12px 10px !important;
|
52 |
-
margin-bottom: 8px !important;
|
53 |
-
border-radius: 8px !important;
|
54 |
-
}
|
55 |
-
.sidebar .gr-button:hover { background-color: #374151 !important; } /* Hover state */
|
56 |
-
.sidebar .gr-button.selected { background-color: #4f46e5 !important; font-weight: 600 !important; color: white !important; } /* Selected state with primary color */
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
.
|
61 |
-
|
62 |
-
|
63 |
-
padding: 12px;
|
64 |
-
color: #e5e7eb !important;
|
65 |
-
}
|
66 |
-
"""
|
67 |
|
68 |
-
# ---
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
-
def
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
if not state_dict: return "Upload data first.", *[gr.update(visible=False)]*5
|
106 |
-
metadata, prompt = state_dict['metadata'], f"Based on metadata... generate 3-5 questions... Return ONLY JSON list of strings."
|
107 |
-
try:
|
108 |
-
genai.configure(api_key=api_key)
|
109 |
-
model = genai.GenerativeModel('gemini-1.5-flash')
|
110 |
-
suggestions = json.loads(model.generate_content(prompt).text)
|
111 |
-
buttons = [gr.Button(s, variant="secondary", visible=True) for s in suggestions] + [gr.Button(visible=False)] * (5 - len(suggestions))
|
112 |
-
return gr.update(visible=False), *buttons
|
113 |
-
except Exception as e: return f"Could not generate suggestions: {e}", *[gr.update(visible=False)]*5
|
114 |
|
115 |
-
|
116 |
-
|
|
|
|
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
elif plot_type == 'bar':
|
128 |
-
counts = df[x_col].value_counts().nlargest(20)
|
129 |
-
fig = px.bar(counts, x=counts.index, y=counts.values, title=f"Top 20 Categories for {x_col}", labels={'index': x_col, 'y': 'Count'})
|
130 |
-
if fig:
|
131 |
-
fig.update_layout(template="plotly_dark")
|
132 |
-
state_dict['dashboard_plots'].append(fig)
|
133 |
-
return state_dict, state_dict['dashboard_plots']
|
134 |
-
except Exception as e:
|
135 |
-
gr.Warning(f"Plotting Error: {e}")
|
136 |
-
return state_dict, state_dict.get('dashboard_plots', [])
|
137 |
|
138 |
-
def
|
139 |
-
|
140 |
-
|
141 |
|
142 |
-
|
143 |
-
if not api_key or not state_dict:
|
144 |
-
msg = "I need a Gemini API key and a dataset to work."
|
145 |
-
history.append((user_message, msg)); return history, *[gr.update(visible=False)]*4
|
146 |
-
history.append((user_message, None)); metadata = state_dict['metadata']
|
147 |
-
prompt = f"You are 'Phoenix Co-pilot'... IMPORTANT: add `template='plotly_dark'` to all figures... User Question: '{user_message}'"
|
148 |
-
try:
|
149 |
-
genai.configure(api_key=api_key)
|
150 |
-
response_json = json.loads(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text.strip().replace("```json", "").replace("```", ""))
|
151 |
-
thought, code_to_run, explanation = response_json.get("thought", "Thinking..."), response_json.get("code", ""), response_json.get("explanation", "Here is the result.")
|
152 |
-
stdout, fig_result, df_result, error = safe_exec(code_to_run, {'df': state_dict['df'], 'px': px, 'pd': pd, 'np': np})
|
153 |
-
history[-1] = (user_message, f"🤔 **Thought:** *{thought}*")
|
154 |
-
output_updates = [gr.update(visible=False, value=None)] * 4
|
155 |
-
if explanation: output_updates[0] = gr.update(visible=True, value=f"**Phoenix Co-pilot:** {explanation}")
|
156 |
-
if code_to_run: output_updates[1] = gr.update(visible=True, value=code_to_run)
|
157 |
-
if fig_result: output_updates[2] = gr.update(visible=True, value=fig_result)
|
158 |
-
if df_result is not None: output_updates[3] = gr.update(visible=True, value=df_result)
|
159 |
-
if stdout:
|
160 |
-
new_explanation = (output_updates[0]['value'] if output_updates[0]['visible'] else "") + f"\n\n**Console Output:**\n```\n{stdout}\n```"
|
161 |
-
output_updates[0] = gr.update(visible=True, value=new_explanation)
|
162 |
-
if error: output_updates[0] = gr.update(visible=True, value=f"**Phoenix Co-pilot:** I encountered an error:\n\n`{error}`")
|
163 |
-
return history, *output_updates
|
164 |
-
except Exception as e:
|
165 |
-
history[-1] = (user_message, f"A critical error occurred: {e}."); return history, *[gr.update(visible=False)]*4
|
166 |
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
with gr.Column(scale=1, elem_classes="sidebar"):
|
201 |
-
gr.Markdown("## 🚀 Phoenix UI"); cockpit_btn; deep_dive_btn; copilot_btn; gr.Markdown("---")
|
202 |
-
file_input; status_output; gr.Markdown("---"); api_key_input; suggestion_btn
|
203 |
-
with gr.Column(scale=4):
|
204 |
-
with gr.Column(visible=True) as welcome_page:
|
205 |
-
gr.Markdown("# Welcome to the AI Data Explorer (Phoenix UI)\n Please **upload a CSV file** and **enter your Gemini API key** to begin.")
|
206 |
-
gr.Image(value="workflow.png", show_label=False, show_download_button=False, container=False)
|
207 |
-
with gr.Column(visible=False) as cockpit_page:
|
208 |
-
gr.Markdown("## 📊 Data Cockpit")
|
209 |
-
with gr.Row():
|
210 |
-
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Rows</div>"); rows_stat
|
211 |
-
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Columns</div>"); cols_stat
|
212 |
-
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Data Quality</div>"); quality_stat
|
213 |
-
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Date/Time Cols</div>"); time_cols_stat
|
214 |
-
suggestion_status;
|
215 |
-
with gr.Accordion(label="✨ AI Smart Suggestions", open=True): [btn for btn in suggestion_buttons]
|
216 |
-
with gr.Column(visible=False) as deep_dive_page:
|
217 |
-
gr.Markdown("## 🔍 Deep Dive Dashboard Builder"); gr.Markdown("Create a custom dashboard by adding plots to the gallery.")
|
218 |
-
with gr.Row(): plot_type_dd; x_col_dd; y_col_dd
|
219 |
-
with gr.Row(): add_plot_btn; clear_plots_btn
|
220 |
-
dashboard_gallery
|
221 |
-
with gr.Column(visible=False) as copilot_page:
|
222 |
-
gr.Markdown("## 🤖 AI Co-pilot"); chatbot
|
223 |
-
with gr.Accordion("Co-pilot's Response Details", open=True): copilot_explanation; copilot_code; copilot_plot; copilot_table
|
224 |
-
with gr.Row(): chat_input; chat_submit_btn
|
225 |
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
240 |
|
241 |
-
|
242 |
|
243 |
-
|
244 |
-
|
245 |
-
.then(lambda: (gr.update(elem_classes=""), gr.update(elem_classes=""), gr.update(elem_classes="selected")), outputs=nav_buttons)
|
246 |
|
247 |
-
|
248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
|
|
|
|
|
|
|
|
|
|
254 |
|
255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
256 |
|
257 |
if __name__ == "__main__":
|
258 |
-
app =
|
259 |
-
app.launch(
|
|
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
4 |
import plotly.express as px
|
|
|
|
|
5 |
import io
|
6 |
import json
|
7 |
import warnings
|
8 |
import google.generativeai as genai
|
9 |
import os
|
10 |
+
from typing import List, Dict, Any, Tuple, Optional
|
11 |
|
12 |
+
# --- Configuration & Constants ---
|
13 |
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; }
|
21 |
.stat-card-value { font-size: 32px; font-weight: 700; color: #f9fafb !important; }
|
22 |
+
.sidebar { background-color: #111827 !important; padding: 15px; border-right: 1px solid #374151 !important; min-height: 100vh; }
|
23 |
+
.sidebar .gr-button { width: 100%; text-align: left !important; background: none !important; border: none !important; box-shadow: none !important; color: #d1d5db !important; font-size: 16px !important; padding: 12px 10px !important; margin-bottom: 8px !important; border-radius: 8px !important; transition: background-color 0.2s ease; }
|
24 |
+
.sidebar .gr-button:hover { background-color: #374151 !important; }
|
25 |
+
.sidebar .gr-button.selected { background-color: #4f46e5 !important; font-weight: 600 !important; color: white !important; }
|
26 |
+
.explanation-block { background-color: #1e3a8a !important; border-left: 4px solid #3b82f6 !important; padding: 12px; color: #e5e7eb !important; border-radius: 4px; }
|
27 |
+
"""
|
28 |
|
29 |
+
class DataExplorerApp:
|
30 |
+
"""A professional-grade, AI-powered data exploration application."""
|
|
|
31 |
|
32 |
+
def __init__(self):
|
33 |
+
"""Initializes the application state and builds the UI."""
|
34 |
+
self.state: Dict[str, Any] = {}
|
35 |
+
self.demo = self._create_layout()
|
36 |
+
self._register_event_handlers()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
+
def _create_layout(self) -> gr.Blocks:
|
39 |
+
"""Defines all UI components and arranges them in the layout."""
|
40 |
+
with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="Professional AI Data Explorer") as demo:
|
41 |
+
# --- State Management ---
|
42 |
+
self.state_var = gr.State({})
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
# --- Component Definition ---
|
45 |
+
# Sidebar
|
46 |
+
self.cockpit_btn = gr.Button("📊 Data Cockpit", elem_classes="selected", elem_id="cockpit")
|
47 |
+
self.deep_dive_btn = gr.Button("🔍 Deep Dive Builder", elem_id="deep_dive")
|
48 |
+
self.copilot_btn = gr.Button("🤖 Chief Data Scientist", elem_id="co-pilot")
|
49 |
+
self.file_input = gr.File(label="📁 Upload CSV File", file_types=[".csv"])
|
50 |
+
self.status_output = gr.Markdown("Status: Awaiting data...")
|
51 |
+
self.api_key_input = gr.Textbox(label="🔑 Gemini API Key", type="password", placeholder="Enter key to enable AI...")
|
52 |
+
self.suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary", interactive=False)
|
53 |
+
|
54 |
+
# Cockpit
|
55 |
+
self.rows_stat = gr.Textbox("0", interactive=False, elem_classes="stat-card-value")
|
56 |
+
self.cols_stat = gr.Textbox("0", interactive=False, elem_classes="stat-card-value")
|
57 |
+
self.quality_stat = gr.Textbox("0%", interactive=False, elem_classes="stat-card-value")
|
58 |
+
self.time_cols_stat = gr.Textbox("0", interactive=False, elem_classes="stat-card-value")
|
59 |
+
self.suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
|
60 |
+
|
61 |
+
# Deep Dive
|
62 |
+
self.plot_type_dd = gr.Dropdown(['histogram', 'bar', 'scatter', 'box'], label="Plot Type", value='histogram')
|
63 |
+
self.x_col_dd = gr.Dropdown([], label="X-Axis / Column", interactive=False)
|
64 |
+
self.y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)", visible=False, interactive=False)
|
65 |
+
self.add_plot_btn = gr.Button("Add to Dashboard", variant="primary", interactive=False)
|
66 |
+
self.clear_plots_btn = gr.Button("Clear Dashboard")
|
67 |
+
self.dashboard_gallery = gr.Gallery(label="📊 Your Custom Dashboard", height="auto", columns=2, preview=True)
|
68 |
|
69 |
+
# Co-pilot
|
70 |
+
self.chatbot = gr.Chatbot(height=500, label="Conversation", show_copy_button=True)
|
71 |
+
self.copilot_explanation = gr.Markdown(visible=False, elem_classes="explanation-block")
|
72 |
+
self.copilot_code = gr.Code(language="python", visible=False, label="Executed Code")
|
73 |
+
self.copilot_plot = gr.Plot(visible=False, label="Generated Visualization")
|
74 |
+
self.copilot_table = gr.Dataframe(visible=False, label="Generated Table", wrap=True)
|
75 |
+
self.chat_input = gr.Textbox(label="Your Question", placeholder="e.g., 'What is the relationship between age and salary?'", scale=4)
|
76 |
+
self.chat_submit_btn = gr.Button("Ask AI", variant="primary")
|
77 |
+
|
78 |
+
# --- Layout Arrangement ---
|
79 |
+
with gr.Row():
|
80 |
+
with gr.Column(scale=1, elem_classes="sidebar"):
|
81 |
+
gr.Markdown("## 🚀 AI Explorer Pro")
|
82 |
+
self.cockpit_btn; self.deep_dive_btn; self.copilot_btn; gr.Markdown("---")
|
83 |
+
self.file_input; self.status_output; gr.Markdown("---"); self.api_key_input; self.suggestion_btn
|
84 |
+
with gr.Column(scale=4):
|
85 |
+
self.welcome_page = gr.Column(visible=True)
|
86 |
+
with self.welcome_page:
|
87 |
+
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.")
|
88 |
+
self.cockpit_page = gr.Column(visible=False)
|
89 |
+
with self.cockpit_page:
|
90 |
+
gr.Markdown("## 📊 Data Cockpit: At-a-Glance Overview")
|
91 |
+
with gr.Row():
|
92 |
+
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Rows</div>"); self.rows_stat
|
93 |
+
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Columns</div>"); self.cols_stat
|
94 |
+
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Data Quality</div>"); self.quality_stat
|
95 |
+
with gr.Column(elem_classes="stat-card"): gr.Markdown("<div class='stat-card-title'>Date/Time Cols</div>"); self.time_cols_stat
|
96 |
+
with gr.Accordion(label="✨ AI Smart Suggestions", open=True): [btn for btn in self.suggestion_buttons]
|
97 |
+
self.deep_dive_page = gr.Column(visible=False)
|
98 |
+
with self.deep_dive_page:
|
99 |
+
gr.Markdown("## 🔍 Deep Dive: Manual Dashboard Builder"); gr.Markdown("Construct your own visualizations to investigate specific relationships.")
|
100 |
+
with gr.Row(): self.plot_type_dd; self.x_col_dd; self.y_col_dd
|
101 |
+
with gr.Row(): self.add_plot_btn; self.clear_plots_btn
|
102 |
+
self.dashboard_gallery
|
103 |
+
self.copilot_page = gr.Column(visible=False)
|
104 |
+
with self.copilot_page:
|
105 |
+
gr.Markdown("## 🤖 Chief Data Scientist: Your AI Partner"); self.chatbot
|
106 |
+
with gr.Accordion("AI's Detailed Response", open=True): self.copilot_explanation; self.copilot_code; self.copilot_plot; self.copilot_table
|
107 |
+
with gr.Row(): self.chat_input; self.chat_submit_btn
|
108 |
+
return demo
|
109 |
|
110 |
+
def _register_event_handlers(self):
|
111 |
+
"""Connects UI components to their backend logic functions."""
|
112 |
+
# Navigation
|
113 |
+
nav_buttons = [self.cockpit_btn, self.deep_dive_btn, self.copilot_btn]
|
114 |
+
pages = [self.cockpit_page, self.deep_dive_page, self.copilot_page]
|
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 Upload
|
123 |
+
self.file_input.upload(self.load_and_process_file, inputs=[self.file_input], outputs=[
|
124 |
+
self.state_var, self.status_output, self.welcome_page, self.cockpit_page,
|
125 |
+
self.rows_stat, self.cols_stat, self.quality_stat, self.time_cols_stat,
|
126 |
+
self.x_col_dd, self.y_col_dd, self.add_plot_btn
|
127 |
+
]).then(lambda: self._switch_page("cockpit"), outputs=pages) \
|
128 |
+
.then(lambda: [gr.update(elem_classes="selected"), gr.update(elem_classes=""), gr.update(elem_classes="")], outputs=nav_buttons)
|
129 |
|
130 |
+
# API Key Input
|
131 |
+
self.api_key_input.change(lambda x: gr.update(interactive=bool(x)), inputs=[self.api_key_input], outputs=[self.suggestion_btn])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
+
# Deep Dive Page Logic
|
134 |
+
self.plot_type_dd.change(self._update_plot_controls, inputs=[self.plot_type_dd], outputs=[self.y_col_dd])
|
135 |
+
self.add_plot_btn.click(self.add_plot_to_dashboard, inputs=[self.state_var, self.x_col_dd, self.y_col_dd, self.plot_type_dd], outputs=[self.state_var, self.dashboard_gallery])
|
136 |
+
self.clear_plots_btn.click(self.clear_dashboard, inputs=[self.state_var], outputs=[self.state_var, self.dashboard_gallery])
|
137 |
|
138 |
+
# Co-pilot & Suggestions
|
139 |
+
self.suggestion_btn.click(self.get_ai_suggestions, inputs=[self.state_var, self.api_key_input], outputs=self.suggestion_buttons)
|
140 |
+
for btn in self.suggestion_buttons:
|
141 |
+
btn.click(self.handle_suggestion_click, inputs=[btn], outputs=[self.cockpit_page, self.deep_dive_page, self.copilot_page, self.chat_input]) \
|
142 |
+
.then(lambda: self._switch_page("co-pilot"), outputs=pages) \
|
143 |
+
.then(lambda: (gr.update(elem_classes=""), gr.update(elem_classes=""), gr.update(elem_classes="selected")), outputs=nav_buttons)
|
144 |
+
|
145 |
+
self.chat_submit_btn.click(self.respond_to_chat, [self.state_var, self.api_key_input, self.chat_input, self.chatbot], [self.chatbot, self.copilot_explanation, self.copilot_code, self.copilot_plot, self.copilot_table]).then(lambda: "", outputs=[self.chat_input])
|
146 |
+
self.chat_input.submit(self.respond_to_chat, [self.state_var, self.api_key_input, self.chat_input, self.chatbot], [self.chatbot, self.copilot_explanation, self.copilot_code, self.copilot_plot, self.copilot_table]).then(lambda: "", outputs=[self.chat_input])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
|
148 |
+
def launch(self):
|
149 |
+
"""Launches the Gradio application."""
|
150 |
+
self.demo.launch(debug=True)
|
151 |
|
152 |
+
# --- Backend Logic Methods ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
|
154 |
+
def _switch_page(self, page_id: str) -> Tuple[gr.update, ...]:
|
155 |
+
return gr.update(visible=page_id=="cockpit"), gr.update(visible=page_id=="deep_dive"), gr.update(visible=page_id=="co-pilot")
|
156 |
+
|
157 |
+
def _update_plot_controls(self, plot_type: str) -> gr.update:
|
158 |
+
is_bivariate = plot_type in ['scatter', 'box']
|
159 |
+
return gr.update(visible=is_bivariate)
|
160 |
|
161 |
+
def load_and_process_file(self, file_obj: Any) -> Tuple[Any, ...]:
|
162 |
+
try:
|
163 |
+
df = pd.read_csv(file_obj.name, low_memory=False)
|
164 |
+
for col in df.select_dtypes(include=['object']).columns:
|
165 |
+
try: df[col] = pd.to_datetime(df[col], errors='raise')
|
166 |
+
except (ValueError, TypeError): continue
|
167 |
+
|
168 |
+
metadata = self._extract_dataset_metadata(df)
|
169 |
+
state = {'df': df, 'metadata': metadata, 'dashboard_plots': []}
|
170 |
+
status_msg = f"✅ **{os.path.basename(file_obj.name)}** loaded."
|
171 |
+
|
172 |
+
rows, cols, quality = metadata['shape'][0], metadata['shape'][1], metadata['data_quality']
|
173 |
+
|
174 |
+
return (state, status_msg, gr.update(visible=False), gr.update(visible=True),
|
175 |
+
f"{rows:,}", f"{cols}", f"{quality}%", f"{len(metadata['datetime_cols'])}",
|
176 |
+
gr.update(choices=metadata['columns'], interactive=True), gr.update(choices=metadata['columns'], interactive=True), gr.update(interactive=True))
|
177 |
+
except Exception as e:
|
178 |
+
gr.Error(f"File Load Error: {e}")
|
179 |
+
return {}, f"❌ Error: {e}", gr.update(visible=True), gr.update(visible=False), "0", "0", "0%", "0", gr.update(choices=[], interactive=False), gr.update(choices=[], interactive=False), gr.update(interactive=False)
|
180 |
|
181 |
+
def _extract_dataset_metadata(self, df: pd.DataFrame) -> Dict[str, Any]:
|
182 |
+
rows, cols = df.shape
|
183 |
+
quality = round((df.notna().sum().sum() / (rows * cols)) * 100, 1) if rows * cols > 0 else 0
|
184 |
+
return {'shape': (rows, cols), 'columns': df.columns.tolist(),
|
185 |
+
'numeric_cols': df.select_dtypes(include=np.number).columns.tolist(),
|
186 |
+
'categorical_cols': df.select_dtypes(include=['object', 'category']).columns.tolist(),
|
187 |
+
'datetime_cols': df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist(),
|
188 |
+
'dtypes_head': df.head().to_string()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
+
def add_plot_to_dashboard(self, state: Dict, x_col: str, y_col: str, plot_type: str) -> Tuple[Dict, List]:
|
191 |
+
if not x_col:
|
192 |
+
gr.Warning("Please select at least an X-axis column.")
|
193 |
+
return state, state.get('dashboard_plots', [])
|
194 |
+
df = state['df']
|
195 |
+
title = f"{plot_type.capitalize()}: {y_col} by {x_col}" if y_col else f"Distribution of {x_col}"
|
196 |
+
try:
|
197 |
+
if plot_type == 'histogram': fig = px.histogram(df, x=x_col, title=title)
|
198 |
+
elif plot_type == 'box': fig = px.box(df, x=x_col, y=y_col, title=title)
|
199 |
+
elif plot_type == 'scatter': fig = px.scatter(df, x=x_col, y=y_col, title=title, trendline="ols", trendline_color_override="red")
|
200 |
+
elif plot_type == 'bar':
|
201 |
+
counts = df[x_col].value_counts().nlargest(20)
|
202 |
+
fig = px.bar(counts, x=counts.index, y=counts.values, title=f"Top 20 Categories for {x_col}", labels={'index': x_col, 'y': 'Count'})
|
203 |
+
if fig:
|
204 |
+
fig.update_layout(template="plotly_dark")
|
205 |
+
state['dashboard_plots'].append(fig)
|
206 |
+
gr.Info(f"Added '{title}' to the dashboard.")
|
207 |
+
return state, state['dashboard_plots']
|
208 |
+
except Exception as e:
|
209 |
+
gr.Error(f"Plotting Error: {e}"); return state, state.get('dashboard_plots', [])
|
210 |
+
|
211 |
+
def clear_dashboard(self, state: Dict) -> Tuple[Dict, List]:
|
212 |
+
state['dashboard_plots'] = []
|
213 |
+
gr.Info("Dashboard cleared.")
|
214 |
+
return state, []
|
215 |
|
216 |
+
def get_ai_suggestions(self, state: Dict, api_key: str) -> List[gr.update]:
|
217 |
+
if not api_key: gr.Warning("API Key is required for suggestions."); return [gr.update(visible=False)]*5
|
218 |
+
if not state: gr.Warning("Please load data first."); return [gr.update(visible=False)]*5
|
219 |
+
metadata = state['metadata']
|
220 |
+
prompt = f"""Based on this metadata (columns: {metadata['columns']}), generate 4 impactful analytical questions. Return ONLY a JSON list of strings."""
|
221 |
+
try:
|
222 |
+
genai.configure(api_key=api_key)
|
223 |
+
suggestions = json.loads(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text)
|
224 |
+
return [gr.Button(s, visible=True) for s in suggestions] + [gr.Button(visible=False)] * (5 - len(suggestions))
|
225 |
+
except Exception as e: gr.Error(f"AI Suggestion Error: {e}"); return [gr.update(visible=False)]*5
|
226 |
+
|
227 |
+
def handle_suggestion_click(self, question: str) -> Tuple[gr.update, ...]:
|
228 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), question
|
229 |
+
|
230 |
+
def respond_to_chat(self, state: Dict, api_key: str, user_message: str, history: List) -> Tuple[List, ...]:
|
231 |
+
if not api_key or not state:
|
232 |
+
msg = "I need a Gemini API key and a dataset to work."
|
233 |
+
history.append((user_message, msg)); return history, *[gr.update(visible=False)]*4
|
234 |
|
235 |
+
history.append((user_message, "Thinking... 🤔")); yield history, *[gr.update(visible=False)]*4
|
236 |
|
237 |
+
metadata = state['metadata']
|
238 |
+
prompt = 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.
|
|
|
239 |
|
240 |
+
**Instructions:**
|
241 |
+
1. **Analyze the Request:** Understand the user's intent, even if it's vague.
|
242 |
+
2. **Choose the Best Method:** Decide if the answer is a table (e.g., `df.describe()`), a single value, or a visualization. If a plot is needed, choose the BEST plot type (e.g., 'histogram' for distribution, 'scatter' for two numerics, 'bar' for categorical counts).
|
243 |
+
3. **Formulate a Plan:** Briefly explain your plan of attack.
|
244 |
+
4. **Write Code:** Generate the Python code. Use pandas (`pd`), numpy (`np`), and plotly express (`px`).
|
245 |
+
- For plots, assign to `fig` and add `template='plotly_dark'`.
|
246 |
+
- For tables, assign the final DataFrame to `result_df`.
|
247 |
+
5. **Provide Insights:** After the result, give a one or two-sentence INSIGHT. What does the result mean? What is the business implication?
|
248 |
+
6. **Respond ONLY with a single JSON object with keys: "plan", "code", "insight".**
|
249 |
|
250 |
+
**DataFrame Metadata:** {metadata['dtypes_head']}
|
251 |
+
**User Question:** "{user_message}"
|
252 |
+
"""
|
253 |
+
try:
|
254 |
+
genai.configure(api_key=api_key)
|
255 |
+
response_json = json.loads(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text.strip().replace("```json", "").replace("```", ""))
|
256 |
+
plan, code_to_run, insight = response_json.get("plan"), response_json.get("code"), response_json.get("insight")
|
257 |
+
|
258 |
+
stdout, fig_result, df_result, error = self._safe_exec(code_to_run, {'df': state['df'], 'px': px, 'pd': pd, 'np': np})
|
259 |
|
260 |
+
history[-1] = (user_message, f"**Plan:** {plan}")
|
261 |
+
|
262 |
+
explanation = f"**Insight:** {insight}"
|
263 |
+
if stdout: explanation += f"\n\n**Console Output:**\n```\n{stdout}\n```"
|
264 |
+
if error: gr.Error(f"AI Code Execution Failed: {error}")
|
265 |
+
|
266 |
+
yield (history, gr.update(visible=bool(explanation)), gr.update(visible=bool(code_to_run), value=code_to_run),
|
267 |
+
gr.update(visible=bool(fig_result), value=fig_result), gr.update(visible=bool(df_result is not None), value=df_result))
|
268 |
+
except Exception as e:
|
269 |
+
history[-1] = (user_message, f"I'm sorry, I encountered an error. Please try rephrasing your question. (Error: {e})")
|
270 |
+
yield history, *[gr.update(visible=False)]*4
|
271 |
+
|
272 |
+
def _safe_exec(self, code_string: str, local_vars: Dict) -> Tuple[Any, ...]:
|
273 |
+
output_buffer = io.StringIO()
|
274 |
+
try:
|
275 |
+
with redirect_stdout(output_buffer): exec(code_string, globals(), local_vars)
|
276 |
+
return output_buffer.getvalue(), local_vars.get('fig'), local_vars.get('result_df'), None
|
277 |
+
except Exception as e: return None, None, None, f"Execution Error: {str(e)}"
|
278 |
|
279 |
if __name__ == "__main__":
|
280 |
+
app = DataExplorerApp()
|
281 |
+
app.launch()
|