File size: 17,870 Bytes
c08faed
 
 
 
 
b5fce9d
 
 
 
 
 
c08faed
5bd4d74
c08faed
 
51fb89c
12ef31b
b5fce9d
51fb89c
b5fce9d
 
 
 
51fb89c
 
b5fce9d
 
 
51fb89c
 
b5fce9d
 
 
 
 
 
 
51fb89c
b5fce9d
51fb89c
b5fce9d
 
 
 
 
 
 
 
51fb89c
b5fce9d
 
 
 
 
51fb89c
 
b5fce9d
 
51fb89c
 
 
 
 
 
 
b5fce9d
c08faed
272b87c
b5fce9d
5bd4d74
 
 
 
 
 
b5fce9d
 
5bd4d74
 
 
b5fce9d
1aae43a
b5fce9d
 
 
1aae43a
 
b5fce9d
 
1aae43a
b5fce9d
 
 
 
 
 
 
1aae43a
 
b5fce9d
 
f72077b
f7b84f1
b5fce9d
 
 
 
 
 
1aae43a
 
1956035
b5fce9d
1aae43a
5bd4d74
b5fce9d
51fb89c
 
b5fce9d
 
272b87c
b5fce9d
 
 
 
 
 
 
f72077b
 
 
272b87c
f72077b
 
1aae43a
b5fce9d
 
1aae43a
 
 
b5fce9d
 
 
 
 
 
 
 
 
 
 
 
1aae43a
b5fce9d
1aae43a
b5fce9d
 
1aae43a
b5fce9d
 
 
1aae43a
1956035
b5fce9d
5bd4d74
272b87c
b5fce9d
 
 
 
5bd4d74
b5fce9d
5bd4d74
1aae43a
b5fce9d
5bd4d74
 
 
b5fce9d
 
5bd4d74
1aae43a
b5fce9d
5bd4d74
b5fce9d
 
 
1aae43a
5bd4d74
51fb89c
b5fce9d
 
 
 
 
f72077b
b5fce9d
 
1aae43a
b5fce9d
5bd4d74
272b87c
b5fce9d
1956035
b5fce9d
 
12ef31b
b5fce9d
1956035
272b87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1956035
272b87c
b5fce9d
51fb89c
272b87c
 
 
b5fce9d
272b87c
 
b5fce9d
272b87c
 
1956035
272b87c
1956035
b5fce9d
12ef31b
b5fce9d
272b87c
b5fce9d
 
 
272b87c
 
 
 
 
 
 
 
 
 
f72077b
272b87c
 
b5fce9d
 
 
1aae43a
1956035
272b87c
b5fce9d
272b87c
 
b5fce9d
 
 
272b87c
 
 
 
 
b5fce9d
272b87c
b5fce9d
 
c08faed
b5fce9d
272b87c
 
51fb89c
b5fce9d
1aae43a
 
 
 
 
 
1956035
51fb89c
f72077b
 
51fb89c
 
f72077b
1aae43a
 
b5fce9d
1aae43a
 
51fb89c
1aae43a
 
51fb89c
f7b84f1
b5fce9d
f7b84f1
c08faed
b5fce9d
1956035
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import gradio as gr
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import io
import json
import warnings
import google.generativeai as genai
import os
from contextlib import redirect_stdout

# --- Configuration ---
warnings.filterwarnings('ignore')

# --- Expert-Crafted Dark Theme CSS ---
CSS = """
/* --- Phoenix UI Custom Dark CSS --- */
/* Stat Card Styling */
.stat-card {
    border-radius: 12px !important;
    padding: 20px !important;
    background: #1f2937 !important; /* Dark blue-gray background */
    border: 1px solid #374151 !important;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    text-align: center;
}
.stat-card-title { font-size: 16px; font-weight: 500; color: #9ca3af !important; margin-bottom: 8px; }
.stat-card-value { font-size: 32px; font-weight: 700; color: #f9fafb !important; }

/* General Layout & Feel */
.gradio-container { font-family: 'Inter', sans-serif; }
.gr-button { box-shadow: 0 1px 2px 0 rgba(0,0,0,0.05); }

/* Sidebar Styling */
.sidebar {
    background-color: #111827 !important; /* Very dark blue-gray */
    padding: 15px;
    border-right: 1px solid #374151 !important;
    min-height: 100vh;
}
.sidebar .gr-button {
    width: 100%;
    text-align: left !important;
    background: none !important;
    border: none !important;
    box-shadow: none !important;
    color: #d1d5db !important; /* Light gray text for readability */
    font-size: 16px !important;
    padding: 12px 10px !important;
    margin-bottom: 8px !important;
    border-radius: 8px !important;
}
.sidebar .gr-button:hover { background-color: #374151 !important; } /* Hover state */
.sidebar .gr-button.selected { background-color: #4f46e5 !important; font-weight: 600 !important; color: white !important; } /* Selected state with primary color */

/* AI Co-pilot Styling */
.code-block { border: 1px solid #374151 !important; border-radius: 8px; }
.explanation-block {
    background-color: #1e3a8a !important; /* Dark blue background */
    border-left: 4px solid #3b82f6 !important; /* Brighter blue border */
    padding: 12px;
    color: #e5e7eb !important;
}
"""

# --- Helper and Core Functions (Unchanged) ---
def safe_exec(code_string: str, local_vars: dict):
    output_buffer = io.StringIO()
    try:
        with redirect_stdout(output_buffer):
            exec(code_string, globals(), local_vars)
        stdout = output_buffer.getvalue()
        fig = local_vars.get('fig')
        result_df = local_vars.get('result_df')
        return stdout, fig, result_df, None
    except Exception as e:
        return None, None, None, f"Execution Error: {str(e)}"

def load_and_process_file(file_obj, state_dict):
    if file_obj is None: return state_dict, "Please upload a file.", *[gr.update(visible=False)] * 4
    try:
        df = pd.read_csv(file_obj.name, low_memory=False)
        for col in df.select_dtypes(include=['object']).columns:
            try: df[col] = pd.to_datetime(df[col], errors='raise')
            except (ValueError, TypeError): continue
        
        metadata = extract_dataset_metadata(df)
        state_dict = {'df': df, 'metadata': metadata, 'filename': os.path.basename(file_obj.name), 'dashboard_plots': []}
        
        status_msg = f"βœ… **{state_dict['filename']}** loaded successfully."
        cockpit_update = gr.update(visible=True)
        welcome_update = gr.update(visible=False)
        rows, cols = metadata['shape']
        quality = metadata['data_quality']
        
        return (state_dict, status_msg, welcome_update, cockpit_update, gr.update(visible=False), gr.update(visible=False),
                gr.update(value=f"{rows:,}"), gr.update(value=cols), gr.update(value=f"{quality}%"), gr.update(value=f"{len(metadata['datetime_cols'])}"),
                gr.update(choices=metadata['columns']), gr.update(choices=metadata['columns']), gr.update(choices=metadata['columns']))
    except Exception as e:
        return state_dict, f"❌ **Error:** {e}", *[gr.update()] * 11

def extract_dataset_metadata(df: pd.DataFrame):
    rows, cols = df.shape
    numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
    categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
    datetime_cols = df.select_dtypes(include=['datetime64', 'datetime64[ns]']).columns.tolist()
    data_quality = round((df.notna().sum().sum() / (rows * cols)) * 100, 1) if rows * cols > 0 else 0
    return {'shape': (rows, cols), 'columns': df.columns.tolist(), 'numeric_cols': numeric_cols, 'categorical_cols': categorical_cols,
            'datetime_cols': datetime_cols, 'dtypes': df.dtypes.to_string(), 'head': df.head().to_string(), 'data_quality': data_quality}

def switch_page(page_name):
    return (gr.update(visible=page_name=="cockpit"), gr.update(visible=page_name=="deep_dive"), gr.update(visible=page_name=="co-pilot"))

def get_ai_suggestions(state_dict, api_key):
    if not api_key: return "Enter your Gemini API key to get suggestions.", *[gr.update(visible=False)]*5
    if not state_dict: return "Upload data first.", *[gr.update(visible=False)]*5
    metadata = state_dict['metadata']
    prompt = f"""
    Based on the following dataset metadata, generate 3 to 5 specific, actionable, and interesting analytical questions...
    Return ONLY a JSON list of strings. Example: ["What is the trend of sales over time?", "Which category has the highest average price?"]
    """
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel('gemini-1.5-flash')
        response = model.generate_content(prompt)
        suggestions = json.loads(response.text)
        buttons = [gr.Button(s, variant="secondary", visible=True) for s in suggestions]
        buttons += [gr.Button(visible=False)] * (5 - len(buttons))
        return gr.update(visible=False), *buttons
    except Exception as e: return f"Could not generate suggestions: {e}", *[gr.update(visible=False)]*5

def handle_suggestion_click(question_text):
    return (gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), question_text)

def add_plot_to_dashboard(state_dict, x_col, y_col, plot_type):
    if not x_col:
        gr.Warning("Please select at least an X-axis column.")
        return state_dict, state_dict.get('dashboard_plots', [])
    df = state_dict['df']
    title = f"{plot_type.capitalize()}: {y_col} by {x_col}" if y_col else f"Distribution of {x_col}"
    fig = None
    try:
        if plot_type == 'histogram': fig = px.histogram(df, x=x_col, title=title)
        elif plot_type == 'box': fig = px.box(df, x=x_col, y=y_col, title=title)
        elif plot_type == 'scatter': fig = px.scatter(df, x=x_col, y=y_col, title=title, trendline="ols")
        elif plot_type == 'bar': 
            counts = df[x_col].value_counts().nlargest(20)
            fig = px.bar(counts, x=counts.index, y=counts.values, title=f"Top 20 Categories for {x_col}")
            fig.update_xaxes(title=x_col)
        if fig:
            fig.update_layout(template="plotly_dark")
            state_dict['dashboard_plots'].append(fig)
        return state_dict, state_dict['dashboard_plots']
    except Exception as e:
        gr.Warning(f"Plotting Error: {e}")
        return state_dict, state_dict.get('dashboard_plots', [])

def clear_dashboard(state_dict):
    state_dict['dashboard_plots'] = []
    return state_dict, []

def respond_to_chat(user_message, history, state_dict, api_key):
    if not api_key:
        history.append((user_message, "I need a Gemini API key to function..."))
        return history, *[gr.update(visible=False)] * 4
    if not state_dict:
        history.append((user_message, "Please upload a dataset first."))
        return history, *[gr.update(visible=False)] * 4
    history.append((user_message, None))
    metadata = state_dict['metadata']
    prompt = f"""
    You are 'Phoenix Co-pilot', an expert AI data analyst... [Prompt remains the same]
    **User Question:** "{user_message}"
    **Your JSON Response:**
    """
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel('gemini-1.5-flash')
        response = model.generate_content(prompt)
        response_json = json.loads(response.text.strip().replace("```json", "").replace("```", ""))
        
        thought = response_json.get("thought", "Thinking...")
        code_to_run = response_json.get("code", "")
        explanation = response_json.get("explanation", "Here is the result.")
        stdout, fig_result, df_result, error = safe_exec(code_to_run, {'df': state_dict['df'], 'px': px, 'pd': pd, 'np': np})
        history[-1] = (user_message, f"πŸ€” **Thought:** *{thought}*")
        
        output_updates = [gr.update(visible=False, value=None)] * 4
        if explanation: output_updates[0] = gr.update(visible=True, value=f"**Phoenix Co-pilot:** {explanation}")
        if code_to_run: output_updates[1] = gr.update(visible=True, value=code_to_run)
        if fig_result: output_updates[2] = gr.update(visible=True, value=fig_result)
        if df_result is not None: output_updates[3] = gr.update(visible=True, value=df_result)
        if stdout:
            new_explanation = (output_updates[0]['value'] if output_updates[0]['visible'] else "") + f"\n\n**Console Output:**\n```\n{stdout}\n```"
            output_updates[0] = gr.update(visible=True, value=new_explanation)
        if error:
            output_updates[0] = gr.update(visible=True, value=f"**Phoenix Co-pilot:** I encountered an error. Here's the details:\n\n`{error}`")
        return history, *output_updates
    except Exception as e:
        history[-1] = (user_message, f"A critical error occurred: {e}.")
        return history, *[gr.update(visible=False)] * 4

# --- Gradio UI Definition ---
def create_gradio_interface():
    with gr.Blocks(theme=gr.themes.Glass(primary_hue="indigo", secondary_hue="blue"), css=CSS, title="Phoenix AI Data Explorer") as demo:
        global_state = gr.State({})

        # --- CORRECTED: "Define-Then-Place" Pattern ---
        # 1. DEFINE all interactive components first.
        
        # Sidebar components
        cockpit_btn = gr.Button("πŸ“Š Data Cockpit", elem_classes="selected")
        deep_dive_btn = gr.Button("πŸ” Deep Dive Builder")
        copilot_btn = gr.Button("πŸ€– AI Co-pilot")
        file_input = gr.File(label="πŸ“ Upload New CSV", file_types=[".csv"])
        status_output = gr.Markdown("Status: Awaiting data...")
        api_key_input = gr.Textbox(label="πŸ”‘ Gemini API Key", type="password", placeholder="Enter key here...")
        suggestion_btn = gr.Button("Get Smart Suggestions", variant="secondary")
        
        # Cockpit page components
        rows_stat = gr.Textbox("0", show_label=False, elem_classes="stat-card-value", interactive=False)
        cols_stat = gr.Textbox("0", show_label=False, elem_classes="stat-card-value", interactive=False)
        quality_stat = gr.Textbox("0%", show_label=False, elem_classes="stat-card-value", interactive=False)
        time_cols_stat = gr.Textbox("0", show_label=False, elem_classes="stat-card-value", interactive=False)
        suggestion_status = gr.Markdown(visible=True)
        suggestion_buttons = [gr.Button(visible=False) for _ in range(5)]
        
        # Deep Dive page components
        plot_type_dd = gr.Dropdown(['histogram', 'bar', 'scatter', 'box'], label="Plot Type", value='histogram')
        x_col_dd = gr.Dropdown([], label="X-Axis / Column")
        y_col_dd = gr.Dropdown([], label="Y-Axis (for Scatter/Box)")
        add_plot_btn = gr.Button("Add to Dashboard", variant="primary")
        clear_plots_btn = gr.Button("Clear Dashboard")
        dashboard_gallery = gr.Gallery(label="πŸ“Š Your Custom Dashboard", height="auto", columns=2, preview=True)

        # Co-pilot page components
        chatbot = gr.Chatbot(height=400, label="Conversation with Co-pilot", show_copy_button=True)
        copilot_explanation = gr.Markdown(visible=False, elem_classes="explanation-block")
        copilot_code = gr.Code(language="python", visible=False, label="Executed Python Code")
        copilot_plot = gr.Plot(visible=False, label="Generated Visualization")
        copilot_table = gr.Dataframe(visible=False, label="Generated Table", wrap=True)
        chat_input = gr.Textbox(label="Your Question", placeholder="e.g., 'What is the correlation between age and salary?'", scale=4)
        chat_submit_btn = gr.Button("Submit", variant="primary")
        
        # 2. PLACE the defined components into the layout.
        with gr.Row():
            # Sidebar Layout
            with gr.Column(scale=1, elem_classes="sidebar"):
                gr.Markdown("## πŸš€ Phoenix UI")
                cockpit_btn
                deep_dive_btn
                copilot_btn
                gr.Markdown("---")
                file_input
                status_output
                gr.Markdown("---")
                api_key_input
                suggestion_btn

            # Main Content Layout
            with gr.Column(scale=4):
                with gr.Column(visible=True) as welcome_page:
                    gr.Markdown("# Welcome to the AI Data Explorer (Phoenix UI)")
                    gr.Markdown("Please **upload a CSV file** and **enter your Gemini API key** in the sidebar to begin.")
                    gr.Image(value="workflow.png", show_label=False, show_download_button=False, container=False)

                with gr.Column(visible=False) as cockpit_page:
                    gr.Markdown("## πŸ“Š Data Cockpit")
                    with gr.Row():
                        with gr.Column(elem_classes="stat-card"):
                            gr.Markdown("<div class='stat-card-title'>Rows</div>"); rows_stat
                        with gr.Column(elem_classes="stat-card"):
                            gr.Markdown("<div class='stat-card-title'>Columns</div>"); cols_stat
                        with gr.Column(elem_classes="stat-card"):
                            gr.Markdown("<div class='stat-card-title'>Data Quality</div>"); quality_stat
                        with gr.Column(elem_classes="stat-card"):
                            gr.Markdown("<div class='stat-card-title'>Date/Time Cols</div>"); time_cols_stat
                    suggestion_status
                    with gr.Accordion(label="✨ AI Smart Suggestions", open=True):
                        for btn in suggestion_buttons:
                            btn

                with gr.Column(visible=False) as deep_dive_page:
                    gr.Markdown("## πŸ” Deep Dive Dashboard Builder")
                    gr.Markdown("Create a custom dashboard by adding multiple plots to the gallery below.")
                    with gr.Row():
                        plot_type_dd; x_col_dd; y_col_dd
                    with gr.Row():
                        add_plot_btn; clear_plots_btn
                    dashboard_gallery

                with gr.Column(visible=False) as copilot_page:
                    gr.Markdown("## πŸ€– AI Co-pilot")
                    chatbot
                    with gr.Accordion("Co-pilot's Response Details", open=True):
                        copilot_explanation; copilot_code; copilot_plot; copilot_table
                    with gr.Row():
                        chat_input; chat_submit_btn

        # 3. DEFINE all event handlers. Now all component variables are guaranteed to exist.
        pages = [cockpit_page, deep_dive_page, copilot_page]
        nav_buttons = [cockpit_btn, deep_dive_btn, copilot_btn]
        
        for i, btn in enumerate(nav_buttons):
            page_name = btn.value.lower().replace(" ", "_").split(" ")[-1]
            btn.click(lambda name=page_name: switch_page(name), outputs=pages) \
               .then(lambda i=i: [gr.update(elem_classes="selected" if j==i else "") for j in range(len(nav_buttons))], outputs=nav_buttons)

        file_input.upload(load_and_process_file, [file_input, global_state],
                          [global_state, status_output, welcome_page, cockpit_page, deep_dive_page, copilot_page,
                           rows_stat, cols_stat, quality_stat, time_cols_stat,
                           x_col_dd, y_col_dd, plot_type_dd]) \
            .then(lambda: switch_page("cockpit"), outputs=pages) \
            .then(lambda: [gr.update(elem_classes="selected"), gr.update(elem_classes=""), gr.update(elem_classes="")], outputs=nav_buttons)
        
        suggestion_btn.click(get_ai_suggestions, [global_state, api_key_input], [suggestion_status, *suggestion_buttons])
        
        for btn in suggestion_buttons:
            btn.click(handle_suggestion_click, inputs=[btn], outputs=[cockpit_page, deep_dive_page, copilot_page, chat_input]) \
               .then(lambda: (gr.update(elem_classes=""), gr.update(elem_classes=""), gr.update(elem_classes="selected")), outputs=nav_buttons)

        add_plot_btn.click(add_plot_to_dashboard, [global_state, x_col_dd, y_col_dd, plot_type_dd], [global_state, dashboard_gallery])
        clear_plots_btn.click(clear_dashboard, [global_state], [global_state, dashboard_gallery])

        chat_submit_btn.click(respond_to_chat, [chat_input, chatbot, global_state, api_key_input],
                              [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]) \
                       .then(lambda: "", outputs=[chat_input])
        chat_input.submit(respond_to_chat, [chat_input, chatbot, global_state, api_key_input],
                          [chatbot, copilot_explanation, copilot_code, copilot_plot, copilot_table]) \
                     .then(lambda: "", outputs=[chat_input])

    return demo

if __name__ == "__main__":
    app = create_gradio_interface()
    app.launch(debug=True)