Update app.py
Browse files
app.py
CHANGED
@@ -14,6 +14,7 @@ import re
|
|
14 |
warnings.filterwarnings('ignore')
|
15 |
MAX_DASHBOARD_PLOTS = 10
|
16 |
CSS = """
|
|
|
17 |
#app-title { text-align: center; font-weight: 800; font-size: 2.5rem; color: #f9fafb; padding-top: 10px; }
|
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); }
|
@@ -36,35 +37,44 @@ class DataExplorerApp:
|
|
36 |
with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="AI Data Explorer Pro") as demo:
|
37 |
state_var = gr.State({})
|
38 |
|
39 |
-
# Component Definition
|
40 |
cockpit_btn = gr.Button("π Data Cockpit", elem_classes="selected", elem_id="cockpit")
|
41 |
deep_dive_btn = gr.Button("π Deep Dive Builder", elem_id="deep_dive")
|
42 |
copilot_btn = gr.Button("π€ Chief Data Scientist", elem_id="co-pilot")
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
status_output = gr.Markdown("Status: Awaiting data...")
|
45 |
api_key_input = gr.Textbox(label="π Gemini API Key", type="password", placeholder="Enter key to enable AI...")
|
46 |
suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary", interactive=False)
|
|
|
47 |
rows_stat, cols_stat = gr.Textbox("0", interactive=False, show_label=False), gr.Textbox("0", interactive=False, show_label=False)
|
48 |
quality_stat, time_cols_stat = gr.Textbox("0%", interactive=False, show_label=False), gr.Textbox("0", interactive=False, show_label=False)
|
49 |
suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
|
|
|
50 |
plot_type_dd = gr.Dropdown(['histogram', 'bar', 'scatter', 'box'], label="Plot Type", value='histogram')
|
51 |
x_col_dd = gr.Dropdown([], label="X-Axis / Column", interactive=False)
|
52 |
y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)", visible=False, interactive=False)
|
53 |
add_plot_btn, clear_plots_btn = gr.Button("Add to Dashboard", variant="primary", interactive=False), gr.Button("Clear Dashboard", interactive=False)
|
54 |
dashboard_plots = [gr.Plot(visible=False) for _ in range(MAX_DASHBOARD_PLOTS)]
|
|
|
55 |
chatbot = gr.Chatbot(height=500, label="Conversation", show_copy_button=True, avatar_images=(None, "bot.png"))
|
56 |
copilot_explanation, copilot_code = gr.Markdown(visible=False, elem_classes="explanation-block"), gr.Code(language="python", visible=False, label="Executed Code")
|
57 |
copilot_plot, copilot_table = gr.Plot(visible=False, label="Generated Visualization"), gr.Dataframe(visible=False, label="Generated Table", wrap=True)
|
58 |
chat_input, chat_submit_btn = gr.Textbox(label="Your Question", placeholder="e.g., 'What is the relationship between age and salary?'", scale=4), gr.Button("Ask AI", variant="primary", interactive=False)
|
59 |
|
60 |
-
# Layout Arrangement
|
61 |
with gr.Row():
|
62 |
with gr.Column(scale=1, elem_classes="sidebar"):
|
63 |
gr.Markdown("## π AI Explorer Pro", elem_id="app-title"); cockpit_btn; deep_dive_btn; copilot_btn; gr.Markdown("---")
|
64 |
file_input; status_output; gr.Markdown("---"); api_key_input; suggestion_btn
|
65 |
with gr.Column(scale=4):
|
66 |
welcome_page, cockpit_page, deep_dive_page, copilot_page = [gr.Column(visible=i==0) for i in range(4)]
|
67 |
-
with welcome_page: 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.")
|
68 |
with cockpit_page:
|
69 |
gr.Markdown("## π Data Cockpit: At-a-Glance Overview")
|
70 |
with gr.Row():
|
@@ -81,7 +91,7 @@ class DataExplorerApp:
|
|
81 |
with gr.Accordion("AI's Detailed Response", open=True): copilot_explanation; copilot_code; copilot_plot; copilot_table
|
82 |
with gr.Row(): chat_input; chat_submit_btn
|
83 |
|
84 |
-
# Event Handlers Registration
|
85 |
pages, nav_buttons = [welcome_page, cockpit_page, deep_dive_page, copilot_page], [cockpit_btn, deep_dive_btn, copilot_btn]
|
86 |
for i, btn in enumerate(nav_buttons):
|
87 |
btn.click(lambda id=btn.elem_id: self._switch_page(id, pages), outputs=pages).then(
|
@@ -107,7 +117,6 @@ class DataExplorerApp:
|
|
107 |
|
108 |
def launch(self): self.demo.launch(debug=True)
|
109 |
|
110 |
-
# --- Backend Logic Methods ---
|
111 |
def _switch_page(self, page_id: str, all_pages: List) -> List[gr.update]:
|
112 |
visibility = {"welcome":0, "cockpit":1, "deep_dive":2, "co-pilot":3}
|
113 |
return [gr.update(visible=i == visibility.get(page_id, 0)) for i in range(len(all_pages))]
|
@@ -115,20 +124,39 @@ class DataExplorerApp:
|
|
115 |
def _update_plot_controls(self, plot_type: str) -> gr.update: return gr.update(visible=plot_type in ['scatter', 'box'])
|
116 |
|
117 |
def load_and_process_file(self, file_obj: Any) -> Tuple[Any, ...]:
|
|
|
118 |
try:
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
metadata = self._extract_dataset_metadata(df)
|
121 |
state = {'df': df, 'metadata': metadata, 'dashboard_plots': []}
|
122 |
rows, cols, quality = metadata['shape'][0], metadata['shape'][1], metadata['data_quality']
|
123 |
page_updates = self._switch_page("cockpit", [0,1,2,3])
|
124 |
-
return (state, f"β
**{os.path.basename(
|
125 |
gr.update(choices=metadata['columns'], interactive=True), gr.update(choices=metadata['columns'], interactive=True), gr.update(interactive=True))
|
126 |
except Exception as e:
|
127 |
gr.Error(f"File Load Error: {e}"); page_updates = self._switch_page("welcome", [0,1,2,3]);
|
128 |
return {}, f"β Error: {e}", *page_updates, "0", "0", "0%", "0", gr.update(choices=[], interactive=False), gr.update(choices=[], interactive=False), gr.update(interactive=False)
|
129 |
|
130 |
def _extract_dataset_metadata(self, df: pd.DataFrame) -> Dict[str, Any]:
|
131 |
-
rows, cols
|
|
|
132 |
return {'shape': (rows, cols), 'columns': df.columns.tolist(), 'numeric_cols': df.select_dtypes(include=np.number).columns.tolist(),
|
133 |
'categorical_cols': df.select_dtypes(include=['object', 'category']).columns.tolist(), 'datetime_cols': df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist(),
|
134 |
'dtypes_head': df.head(3).to_string(), 'data_quality': quality}
|
@@ -171,10 +199,7 @@ class DataExplorerApp:
|
|
171 |
return *self._switch_page("co-pilot", [0,1,2,3]), question
|
172 |
|
173 |
def _sanitize_and_parse_json(self, raw_text: str) -> Dict:
|
174 |
-
"""Cleans and parses a JSON string from an LLM response."""
|
175 |
-
# Remove markdown code blocks
|
176 |
clean_text = re.sub(r'```json\n?|```', '', raw_text).strip()
|
177 |
-
# Escape single backslashes that are not already escaped
|
178 |
clean_text = re.sub(r'(?<!\\)\\(?!["\\/bfnrtu])', r'\\\\', clean_text)
|
179 |
return json.loads(clean_text)
|
180 |
|
@@ -185,22 +210,14 @@ class DataExplorerApp:
|
|
185 |
|
186 |
history.append((user_message, "Thinking... π€")); yield history, *[gr.update(visible=False)]*4
|
187 |
|
188 |
-
metadata
|
189 |
-
prompt = f"""You are 'Chief Data Scientist', an expert AI analyst
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
3. **Code:** Write Python code. Use `fig` for plots (`template='plotly_dark'`) and `result_df` for tables.
|
194 |
-
4. **Insight:** Provide a one-sentence business insight.
|
195 |
-
5. **Respond ONLY with a single JSON object with keys: "plan", "code", "insight".**
|
196 |
-
**Metadata:** {dtypes_head}
|
197 |
-
**User Question:** "{user_message}"
|
198 |
"""
|
199 |
try:
|
200 |
-
genai.configure(api_key=api_key)
|
201 |
-
# CRITICAL FIX: Use the new sanitizer function
|
202 |
-
response_json = self._sanitize_and_parse_json(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text)
|
203 |
-
|
204 |
plan, code, insight = response_json.get("plan"), response_json.get("code"), response_json.get("insight")
|
205 |
stdout, fig, df_result, error = self._safe_exec(code, {'df': state['df'], 'px': px, 'pd': pd})
|
206 |
|
|
|
14 |
warnings.filterwarnings('ignore')
|
15 |
MAX_DASHBOARD_PLOTS = 10
|
16 |
CSS = """
|
17 |
+
/* --- Phoenix UI Professional Dark CSS --- */
|
18 |
#app-title { text-align: center; font-weight: 800; font-size: 2.5rem; color: #f9fafb; padding-top: 10px; }
|
19 |
.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; }
|
20 |
.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); }
|
|
|
37 |
with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="AI Data Explorer Pro") as demo:
|
38 |
state_var = gr.State({})
|
39 |
|
40 |
+
# --- Component Definition ---
|
41 |
cockpit_btn = gr.Button("π Data Cockpit", elem_classes="selected", elem_id="cockpit")
|
42 |
deep_dive_btn = gr.Button("π Deep Dive Builder", elem_id="deep_dive")
|
43 |
copilot_btn = gr.Button("π€ Chief Data Scientist", elem_id="co-pilot")
|
44 |
+
|
45 |
+
# UPDATED: File input now accepts multiple types
|
46 |
+
file_input = gr.File(
|
47 |
+
label="π Upload Data File",
|
48 |
+
file_types=[".csv", ".txt", ".xls", ".xlsx"]
|
49 |
+
)
|
50 |
+
|
51 |
status_output = gr.Markdown("Status: Awaiting data...")
|
52 |
api_key_input = gr.Textbox(label="π Gemini API Key", type="password", placeholder="Enter key to enable AI...")
|
53 |
suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary", interactive=False)
|
54 |
+
|
55 |
rows_stat, cols_stat = gr.Textbox("0", interactive=False, show_label=False), gr.Textbox("0", interactive=False, show_label=False)
|
56 |
quality_stat, time_cols_stat = gr.Textbox("0%", interactive=False, show_label=False), gr.Textbox("0", interactive=False, show_label=False)
|
57 |
suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
|
58 |
+
|
59 |
plot_type_dd = gr.Dropdown(['histogram', 'bar', 'scatter', 'box'], label="Plot Type", value='histogram')
|
60 |
x_col_dd = gr.Dropdown([], label="X-Axis / Column", interactive=False)
|
61 |
y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)", visible=False, interactive=False)
|
62 |
add_plot_btn, clear_plots_btn = gr.Button("Add to Dashboard", variant="primary", interactive=False), gr.Button("Clear Dashboard", interactive=False)
|
63 |
dashboard_plots = [gr.Plot(visible=False) for _ in range(MAX_DASHBOARD_PLOTS)]
|
64 |
+
|
65 |
chatbot = gr.Chatbot(height=500, label="Conversation", show_copy_button=True, avatar_images=(None, "bot.png"))
|
66 |
copilot_explanation, copilot_code = gr.Markdown(visible=False, elem_classes="explanation-block"), gr.Code(language="python", visible=False, label="Executed Code")
|
67 |
copilot_plot, copilot_table = gr.Plot(visible=False, label="Generated Visualization"), gr.Dataframe(visible=False, label="Generated Table", wrap=True)
|
68 |
chat_input, chat_submit_btn = gr.Textbox(label="Your Question", placeholder="e.g., 'What is the relationship between age and salary?'", scale=4), gr.Button("Ask AI", variant="primary", interactive=False)
|
69 |
|
70 |
+
# --- Layout Arrangement ---
|
71 |
with gr.Row():
|
72 |
with gr.Column(scale=1, elem_classes="sidebar"):
|
73 |
gr.Markdown("## π AI Explorer Pro", elem_id="app-title"); cockpit_btn; deep_dive_btn; copilot_btn; gr.Markdown("---")
|
74 |
file_input; status_output; gr.Markdown("---"); api_key_input; suggestion_btn
|
75 |
with gr.Column(scale=4):
|
76 |
welcome_page, cockpit_page, deep_dive_page, copilot_page = [gr.Column(visible=i==0) for i in range(4)]
|
77 |
+
with welcome_page: gr.Markdown("# Welcome to the AI Data Explorer Pro\n> Please **upload a CSV, TXT, or Excel file** and **enter your Gemini API key** to begin your analysis.")
|
78 |
with cockpit_page:
|
79 |
gr.Markdown("## π Data Cockpit: At-a-Glance Overview")
|
80 |
with gr.Row():
|
|
|
91 |
with gr.Accordion("AI's Detailed Response", open=True): copilot_explanation; copilot_code; copilot_plot; copilot_table
|
92 |
with gr.Row(): chat_input; chat_submit_btn
|
93 |
|
94 |
+
# --- Event Handlers Registration ---
|
95 |
pages, nav_buttons = [welcome_page, cockpit_page, deep_dive_page, copilot_page], [cockpit_btn, deep_dive_btn, copilot_btn]
|
96 |
for i, btn in enumerate(nav_buttons):
|
97 |
btn.click(lambda id=btn.elem_id: self._switch_page(id, pages), outputs=pages).then(
|
|
|
117 |
|
118 |
def launch(self): self.demo.launch(debug=True)
|
119 |
|
|
|
120 |
def _switch_page(self, page_id: str, all_pages: List) -> List[gr.update]:
|
121 |
visibility = {"welcome":0, "cockpit":1, "deep_dive":2, "co-pilot":3}
|
122 |
return [gr.update(visible=i == visibility.get(page_id, 0)) for i in range(len(all_pages))]
|
|
|
124 |
def _update_plot_controls(self, plot_type: str) -> gr.update: return gr.update(visible=plot_type in ['scatter', 'box'])
|
125 |
|
126 |
def load_and_process_file(self, file_obj: Any) -> Tuple[Any, ...]:
|
127 |
+
"""Intelligently loads data from CSV, TXT, or Excel files."""
|
128 |
try:
|
129 |
+
filename = file_obj.name
|
130 |
+
extension = os.path.splitext(filename)[1].lower()
|
131 |
+
|
132 |
+
if extension == '.csv':
|
133 |
+
df = pd.read_csv(filename)
|
134 |
+
elif extension == '.txt':
|
135 |
+
# Use sep=None to auto-detect the delimiter (tabs, spaces, etc.)
|
136 |
+
df = pd.read_csv(filename, sep=None, engine='python')
|
137 |
+
elif extension in ['.xls', '.xlsx']:
|
138 |
+
df = pd.read_excel(filename)
|
139 |
+
else:
|
140 |
+
raise ValueError(f"Unsupported file type: {extension}")
|
141 |
+
|
142 |
+
# Continue with processing once the DataFrame is loaded
|
143 |
+
for col in df.select_dtypes(include=['object']).columns:
|
144 |
+
try: df[col] = pd.to_datetime(df[col], errors='raise')
|
145 |
+
except (ValueError, TypeError): continue
|
146 |
+
|
147 |
metadata = self._extract_dataset_metadata(df)
|
148 |
state = {'df': df, 'metadata': metadata, 'dashboard_plots': []}
|
149 |
rows, cols, quality = metadata['shape'][0], metadata['shape'][1], metadata['data_quality']
|
150 |
page_updates = self._switch_page("cockpit", [0,1,2,3])
|
151 |
+
return (state, f"β
**{os.path.basename(filename)}** loaded.", *page_updates, f"{rows:,}", f"{cols}", f"{quality}%", f"{len(metadata['datetime_cols'])}",
|
152 |
gr.update(choices=metadata['columns'], interactive=True), gr.update(choices=metadata['columns'], interactive=True), gr.update(interactive=True))
|
153 |
except Exception as e:
|
154 |
gr.Error(f"File Load Error: {e}"); page_updates = self._switch_page("welcome", [0,1,2,3]);
|
155 |
return {}, f"β Error: {e}", *page_updates, "0", "0", "0%", "0", gr.update(choices=[], interactive=False), gr.update(choices=[], interactive=False), gr.update(interactive=False)
|
156 |
|
157 |
def _extract_dataset_metadata(self, df: pd.DataFrame) -> Dict[str, Any]:
|
158 |
+
rows, cols = df.shape
|
159 |
+
quality = round((df.notna().sum().sum() / df.size) * 100, 1) if df.size > 0 else 0
|
160 |
return {'shape': (rows, cols), 'columns': df.columns.tolist(), 'numeric_cols': df.select_dtypes(include=np.number).columns.tolist(),
|
161 |
'categorical_cols': df.select_dtypes(include=['object', 'category']).columns.tolist(), 'datetime_cols': df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist(),
|
162 |
'dtypes_head': df.head(3).to_string(), 'data_quality': quality}
|
|
|
199 |
return *self._switch_page("co-pilot", [0,1,2,3]), question
|
200 |
|
201 |
def _sanitize_and_parse_json(self, raw_text: str) -> Dict:
|
|
|
|
|
202 |
clean_text = re.sub(r'```json\n?|```', '', raw_text).strip()
|
|
|
203 |
clean_text = re.sub(r'(?<!\\)\\(?!["\\/bfnrtu])', r'\\\\', clean_text)
|
204 |
return json.loads(clean_text)
|
205 |
|
|
|
210 |
|
211 |
history.append((user_message, "Thinking... π€")); yield history, *[gr.update(visible=False)]*4
|
212 |
|
213 |
+
metadata = state.get('metadata', {}); dtypes_head = metadata.get('dtypes_head', 'No metadata available.')
|
214 |
+
prompt = f"""You are 'Chief Data Scientist', an expert AI analyst...
|
215 |
+
Respond ONLY with a single JSON object with keys: "plan", "code", "insight".
|
216 |
+
Metadata: {dtypes_head}
|
217 |
+
User Question: "{user_message}"
|
|
|
|
|
|
|
|
|
|
|
218 |
"""
|
219 |
try:
|
220 |
+
genai.configure(api_key=api_key); response_json = self._sanitize_and_parse_json(genai.GenerativeModel('gemini-1.5-flash').generate_content(prompt).text)
|
|
|
|
|
|
|
221 |
plan, code, insight = response_json.get("plan"), response_json.get("code"), response_json.get("insight")
|
222 |
stdout, fig, df_result, error = self._safe_exec(code, {'df': state['df'], 'px': px, 'pd': pd})
|
223 |
|