Spaces:
Running
Running
Create analytics_tab.py
Browse files- ui/analytics_tab.py +683 -0
ui/analytics_tab.py
ADDED
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ui/analytics_tab.py
|
2 |
+
import gradio as gr
|
3 |
+
import pandas as pd
|
4 |
+
import logging
|
5 |
+
from collections import OrderedDict
|
6 |
+
import asyncio
|
7 |
+
from datetime import datetime, timedelta
|
8 |
+
|
9 |
+
# --- Module Imports ---
|
10 |
+
from config import PLOT_ID_TO_FORMULA_KEY_MAP
|
11 |
+
from ui.ui_generators import (
|
12 |
+
build_analytics_tab_plot_area,
|
13 |
+
BOMB_ICON, EXPLORE_ICON, FORMULA_ICON, ACTIVE_ICON
|
14 |
+
)
|
15 |
+
from ui.analytics_plot_generator import update_analytics_plots_figures, create_placeholder_plot
|
16 |
+
from formulas import PLOT_FORMULAS
|
17 |
+
from features.chatbot.chatbot_prompts import get_initial_insight_prompt_and_suggestions
|
18 |
+
from features.chatbot.chatbot_handler import generate_llm_response
|
19 |
+
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
PLOT_CONFIGS = [
|
23 |
+
{"label": "Numero di Follower nel Tempo", "id": "followers_count", "section": "Dinamiche dei Follower"},
|
24 |
+
{"label": "Tasso di Crescita Follower", "id": "followers_growth_rate", "section": "Dinamiche dei Follower"},
|
25 |
+
{"label": "Follower per Località", "id": "followers_by_location", "section": "Demografia Follower"},
|
26 |
+
{"label": "Follower per Ruolo (Funzione)", "id": "followers_by_role", "section": "Demografia Follower"},
|
27 |
+
{"label": "Follower per Settore", "id": "followers_by_industry", "section": "Demografia Follower"},
|
28 |
+
{"label": "Follower per Anzianità", "id": "followers_by_seniority", "section": "Demografia Follower"},
|
29 |
+
{"label": "Tasso di Engagement nel Tempo", "id": "engagement_rate", "section": "Approfondimenti Performance Post"},
|
30 |
+
{"label": "Copertura nel Tempo", "id": "reach_over_time", "section": "Approfondimenti Performance Post"},
|
31 |
+
{"label": "Visualizzazioni nel Tempo", "id": "impressions_over_time", "section": "Approfondimenti Performance Post"},
|
32 |
+
{"label": "Reazioni (Like) nel Tempo", "id": "likes_over_time", "section": "Approfondimenti Performance Post"},
|
33 |
+
{"label": "Click nel Tempo", "id": "clicks_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
34 |
+
{"label": "Condivisioni nel Tempo", "id": "shares_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
35 |
+
{"label": "Commenti nel Tempo", "id": "comments_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
36 |
+
{"label": "Ripartizione Commenti per Sentiment", "id": "comments_sentiment", "section": "Engagement Dettagliato Post nel Tempo"},
|
37 |
+
{"label": "Frequenza Post", "id": "post_frequency_cs", "section": "Analisi Strategia Contenuti"},
|
38 |
+
{"label": "Ripartizione Contenuti per Formato", "id": "content_format_breakdown_cs", "section": "Analisi Strategia Contenuti"},
|
39 |
+
{"label": "Ripartizione Contenuti per Argomenti", "id": "content_topic_breakdown_cs", "section": "Analisi Strategia Contenuti"},
|
40 |
+
{"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"},
|
41 |
+
{"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"}
|
42 |
+
]
|
43 |
+
# IMPORTANT: Review if 'mention_analysis_volume' and 'mention_analysis_sentiment' plots
|
44 |
+
# can still be generated without the dedicated mentions data processing.
|
45 |
+
# If not, they should also be removed from PLOT_CONFIGS.
|
46 |
+
# For now, I am assuming they might draw from a general data pool in token_state.
|
47 |
+
assert len(PLOT_CONFIGS) == 19, "Mancata corrispondenza in PLOT_CONFIGS e grafici attesi."
|
48 |
+
|
49 |
+
UNIQUE_ORDERED_SECTIONS = list(OrderedDict.fromkeys(pc["section"] for pc in PLOT_CONFIGS))
|
50 |
+
NUM_UNIQUE_SECTIONS = len(UNIQUE_ORDERED_SECTIONS)
|
51 |
+
|
52 |
+
# Store references to UI components that handlers need to update
|
53 |
+
_plot_ui_objects = {}
|
54 |
+
_section_titles_map = {}
|
55 |
+
_global_actions_column_ui = None
|
56 |
+
_insights_chatbot_ui = None
|
57 |
+
_insights_chat_input_ui = None
|
58 |
+
_insights_suggestions_row_ui = None
|
59 |
+
_insights_suggestion_1_btn = None
|
60 |
+
_insights_suggestion_2_btn = None
|
61 |
+
_insights_suggestion_3_btn = None
|
62 |
+
_formula_display_markdown_ui = None
|
63 |
+
_formula_close_hint_md = None
|
64 |
+
_analytics_status_md = None
|
65 |
+
_date_filter_selector = None
|
66 |
+
_custom_start_date_picker = None
|
67 |
+
_custom_end_date_picker = None
|
68 |
+
|
69 |
+
|
70 |
+
def handle_toggle_custom_date_pickers(selection):
|
71 |
+
is_custom = selection == "Intervallo Personalizzato"
|
72 |
+
return gr.update(visible=is_custom), gr.update(visible=is_custom)
|
73 |
+
|
74 |
+
async def handle_panel_action(
|
75 |
+
plot_id_clicked: str, action_type: str, current_active_action_from_state: dict,
|
76 |
+
current_chat_histories: dict, current_chat_plot_id: str,
|
77 |
+
current_plot_data_for_chatbot: dict, current_explored_plot_id: str
|
78 |
+
):
|
79 |
+
logger.info(f"Panel Action: '{action_type}' for plot '{plot_id_clicked}'. Active: {current_active_action_from_state}, Explored: {current_explored_plot_id}")
|
80 |
+
clicked_plot_config = next((p for p in PLOT_CONFIGS if p["id"] == plot_id_clicked), None)
|
81 |
+
if not clicked_plot_config:
|
82 |
+
logger.error(f"Config not found for plot_id {plot_id_clicked}")
|
83 |
+
num_plots = len(PLOT_CONFIGS)
|
84 |
+
error_list_len = 15 + (4 * num_plots) + NUM_UNIQUE_SECTIONS # Matches expected length in original code
|
85 |
+
error_list = [gr.update()] * error_list_len
|
86 |
+
error_list[11] = current_active_action_from_state # active_panel_action_state
|
87 |
+
error_list[12] = current_chat_plot_id # current_chat_plot_id_st
|
88 |
+
error_list[13] = current_chat_histories # chat_histories_st
|
89 |
+
error_list[14] = current_explored_plot_id # explored_plot_id_state
|
90 |
+
return error_list
|
91 |
+
|
92 |
+
clicked_plot_label = clicked_plot_config["label"]
|
93 |
+
clicked_plot_section = clicked_plot_config["section"]
|
94 |
+
hypothetical_new_active_state = {"plot_id": plot_id_clicked, "type": action_type}
|
95 |
+
is_toggling_off = current_active_action_from_state == hypothetical_new_active_state
|
96 |
+
|
97 |
+
action_col_visible_update = gr.update(visible=False)
|
98 |
+
insights_chatbot_visible_update = gr.update(visible=False)
|
99 |
+
insights_chat_input_visible_update = gr.update(visible=False)
|
100 |
+
insights_suggestions_row_visible_update = gr.update(visible=False)
|
101 |
+
formula_display_visible_update = gr.update(visible=False)
|
102 |
+
formula_close_hint_visible_update = gr.update(visible=False)
|
103 |
+
|
104 |
+
chatbot_content_update = gr.update()
|
105 |
+
s1_upd, s2_upd, s3_upd = gr.update(), gr.update(), gr.update()
|
106 |
+
formula_content_update = gr.update()
|
107 |
+
|
108 |
+
new_active_action_state_to_set = None
|
109 |
+
new_current_chat_plot_id = current_chat_plot_id
|
110 |
+
updated_chat_histories = current_chat_histories
|
111 |
+
new_explored_plot_id_to_set = current_explored_plot_id
|
112 |
+
|
113 |
+
generated_panel_vis_updates = []
|
114 |
+
generated_bomb_btn_updates = []
|
115 |
+
generated_formula_btn_updates = []
|
116 |
+
generated_explore_btn_updates = []
|
117 |
+
section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS
|
118 |
+
|
119 |
+
if is_toggling_off:
|
120 |
+
new_active_action_state_to_set = None
|
121 |
+
action_col_visible_update = gr.update(visible=False)
|
122 |
+
logger.info(f"Toggling OFF panel {action_type} for {plot_id_clicked}.")
|
123 |
+
for _ in PLOT_CONFIGS:
|
124 |
+
generated_bomb_btn_updates.append(gr.update(value=BOMB_ICON))
|
125 |
+
generated_formula_btn_updates.append(gr.update(value=FORMULA_ICON))
|
126 |
+
|
127 |
+
if current_explored_plot_id:
|
128 |
+
explored_cfg = next((p for p in PLOT_CONFIGS if p["id"] == current_explored_plot_id), None)
|
129 |
+
explored_sec = explored_cfg["section"] if explored_cfg else None
|
130 |
+
for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
|
131 |
+
section_title_vis_updates[i] = gr.update(visible=(sec_name == explored_sec))
|
132 |
+
for cfg in PLOT_CONFIGS:
|
133 |
+
is_exp = (cfg["id"] == current_explored_plot_id)
|
134 |
+
generated_panel_vis_updates.append(gr.update(visible=is_exp))
|
135 |
+
generated_explore_btn_updates.append(gr.update(value=ACTIVE_ICON if is_exp else EXPLORE_ICON))
|
136 |
+
else:
|
137 |
+
for i in range(NUM_UNIQUE_SECTIONS):
|
138 |
+
section_title_vis_updates[i] = gr.update(visible=True)
|
139 |
+
for _ in PLOT_CONFIGS:
|
140 |
+
generated_panel_vis_updates.append(gr.update(visible=True))
|
141 |
+
generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON))
|
142 |
+
if action_type == "insights":
|
143 |
+
new_current_chat_plot_id = None # Reset chat plot ID
|
144 |
+
else: # Toggling ON or switching
|
145 |
+
new_active_action_state_to_set = hypothetical_new_active_state
|
146 |
+
action_col_visible_update = gr.update(visible=True)
|
147 |
+
new_explored_plot_id_to_set = None # Cancel explore view
|
148 |
+
logger.info(f"Toggling ON panel {action_type} for {plot_id_clicked}. Cancelling explore view if any.")
|
149 |
+
|
150 |
+
for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
|
151 |
+
section_title_vis_updates[i] = gr.update(visible=(sec_name == clicked_plot_section))
|
152 |
+
for cfg in PLOT_CONFIGS:
|
153 |
+
generated_panel_vis_updates.append(gr.update(visible=(cfg["id"] == plot_id_clicked)))
|
154 |
+
generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON)) # Reset all explore buttons
|
155 |
+
|
156 |
+
for cfg_btn in PLOT_CONFIGS:
|
157 |
+
is_active_insights = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "insights"}
|
158 |
+
is_active_formula = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "formula"}
|
159 |
+
generated_bomb_btn_updates.append(gr.update(value=ACTIVE_ICON if is_active_insights else BOMB_ICON))
|
160 |
+
generated_formula_btn_updates.append(gr.update(value=ACTIVE_ICON if is_active_formula else FORMULA_ICON))
|
161 |
+
|
162 |
+
if action_type == "insights":
|
163 |
+
insights_chatbot_visible_update = gr.update(visible=True)
|
164 |
+
insights_chat_input_visible_update = gr.update(visible=True)
|
165 |
+
insights_suggestions_row_visible_update = gr.update(visible=True)
|
166 |
+
new_current_chat_plot_id = plot_id_clicked
|
167 |
+
history = current_chat_histories.get(plot_id_clicked, [])
|
168 |
+
summary = current_plot_data_for_chatbot.get(plot_id_clicked, f"No summary for '{clicked_plot_label}'.")
|
169 |
+
|
170 |
+
if not history: # First time opening chat for this plot
|
171 |
+
prompt, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)
|
172 |
+
llm_history_for_api = [{"role": "user", "content": prompt}] # History for LLM call
|
173 |
+
# Yield initial state if you want to show "Thinking..."
|
174 |
+
# For simplicity, directly call and update.
|
175 |
+
response_text = await generate_llm_response(prompt, plot_id_clicked, clicked_plot_label, llm_history_for_api, summary)
|
176 |
+
history = [{"role": "assistant", "content": response_text}] # Gradio chat history
|
177 |
+
updated_chat_histories = {**current_chat_histories, plot_id_clicked: history}
|
178 |
+
else: # Re-opening chat, just get suggestions
|
179 |
+
_, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)
|
180 |
+
|
181 |
+
chatbot_content_update = gr.update(value=history)
|
182 |
+
s1_upd = gr.update(value=sugg[0] if sugg and len(sugg) > 0 else "N/A")
|
183 |
+
s2_upd = gr.update(value=sugg[1] if sugg and len(sugg) > 1 else "N/A")
|
184 |
+
s3_upd = gr.update(value=sugg[2] if sugg and len(sugg) > 2 else "N/A")
|
185 |
+
|
186 |
+
elif action_type == "formula":
|
187 |
+
formula_display_visible_update = gr.update(visible=True)
|
188 |
+
formula_close_hint_visible_update = gr.update(visible=True)
|
189 |
+
formula_key = PLOT_ID_TO_FORMULA_KEY_MAP.get(plot_id_clicked)
|
190 |
+
formula_text = f"**Formula/Methodology for: {clicked_plot_label}** (ID: `{plot_id_clicked}`)\n\n"
|
191 |
+
if formula_key and formula_key in PLOT_FORMULAS:
|
192 |
+
formula_data = PLOT_FORMULAS[formula_key]
|
193 |
+
formula_text += f"### {formula_data['title']}\n\n{formula_data['description']}\n\n**Calculation:**\n"
|
194 |
+
formula_text += "\n".join([f"- {step}" for step in formula_data['calculation_steps']])
|
195 |
+
else:
|
196 |
+
formula_text += "(No detailed formula information found.)"
|
197 |
+
formula_content_update = gr.update(value=formula_text)
|
198 |
+
new_current_chat_plot_id = None # Ensure chat context is cleared if formula is opened
|
199 |
+
|
200 |
+
# Order of outputs must match the list provided to .click() in build_and_wire_tab
|
201 |
+
final_updates = [
|
202 |
+
action_col_visible_update, # global_actions_column_ui
|
203 |
+
insights_chatbot_visible_update, # insights_chatbot_ui (visibility)
|
204 |
+
chatbot_content_update, # insights_chatbot_ui (content)
|
205 |
+
insights_chat_input_visible_update, # insights_chat_input_ui
|
206 |
+
insights_suggestions_row_visible_update, # insights_suggestions_row_ui
|
207 |
+
s1_upd, # insights_suggestion_1_btn
|
208 |
+
s2_upd, # insights_suggestion_2_btn
|
209 |
+
s3_upd, # insights_suggestion_3_btn
|
210 |
+
formula_display_visible_update, # formula_display_markdown_ui (visibility)
|
211 |
+
formula_content_update, # formula_display_markdown_ui (content)
|
212 |
+
formula_close_hint_visible_update, # formula_close_hint_md
|
213 |
+
new_active_action_state_to_set, # active_panel_action_state (state)
|
214 |
+
new_current_chat_plot_id, # current_chat_plot_id_st (state)
|
215 |
+
updated_chat_histories, # chat_histories_st (state)
|
216 |
+
new_explored_plot_id_to_set # explored_plot_id_state (state)
|
217 |
+
]
|
218 |
+
final_updates.extend(generated_panel_vis_updates) # plot_ui_objects[pc["id"]]["panel_component"]
|
219 |
+
final_updates.extend(generated_bomb_btn_updates) # plot_ui_objects[pc["id"]]["bomb_button"]
|
220 |
+
final_updates.extend(generated_formula_btn_updates)# plot_ui_objects[pc["id"]]["formula_button"]
|
221 |
+
final_updates.extend(generated_explore_btn_updates) # plot_ui_objects[pc["id"]]["explore_button"]
|
222 |
+
final_updates.extend(section_title_vis_updates) # section_titles_map[s_name]
|
223 |
+
|
224 |
+
logger.debug(f"handle_panel_action returning {len(final_updates)} updates. Expected {15 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
|
225 |
+
return final_updates
|
226 |
+
|
227 |
+
async def handle_chat_message_submission(user_message: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict ):
|
228 |
+
if not current_plot_id or not user_message.strip():
|
229 |
+
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
230 |
+
if not isinstance(current_history_for_plot, list): current_history_for_plot = []
|
231 |
+
yield current_history_for_plot, gr.update(value=""), chat_histories # chatbot, chat_input, chat_histories_st
|
232 |
+
return
|
233 |
+
|
234 |
+
cfg = next((p for p in PLOT_CONFIGS if p["id"] == current_plot_id), None)
|
235 |
+
lbl = cfg["label"] if cfg else "Selected Plot"
|
236 |
+
summary = current_plot_data_for_chatbot.get(current_plot_id, f"No summary for '{lbl}'.")
|
237 |
+
|
238 |
+
hist_for_plot = chat_histories.get(current_plot_id, [])
|
239 |
+
if not isinstance(hist_for_plot, list): hist_for_plot = [] # Ensure it's a list
|
240 |
+
|
241 |
+
# Append user message to local history for display
|
242 |
+
current_display_history = hist_for_plot.copy() + [{"role": "user", "content": user_message}]
|
243 |
+
yield current_display_history, gr.update(value=""), chat_histories # Update UI immediately with user message
|
244 |
+
|
245 |
+
# Prepare history for LLM (this might be different from display history if system prompts are used internally)
|
246 |
+
llm_call_history = current_display_history # Or a modified version
|
247 |
+
|
248 |
+
response_text = await generate_llm_response(user_message, current_plot_id, lbl, llm_call_history, summary)
|
249 |
+
|
250 |
+
# Append AI response to display history
|
251 |
+
current_display_history.append({"role": "assistant", "content": response_text})
|
252 |
+
|
253 |
+
# Update the master chat_histories state
|
254 |
+
updated_chat_histories = {**chat_histories, current_plot_id: current_display_history}
|
255 |
+
|
256 |
+
yield current_display_history, "", updated_chat_histories
|
257 |
+
|
258 |
+
|
259 |
+
async def handle_suggested_question_click(suggestion_text: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
260 |
+
if not current_plot_id or not suggestion_text.strip() or suggestion_text == "N/A":
|
261 |
+
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
262 |
+
if not isinstance(current_history_for_plot, list): current_history_for_plot = []
|
263 |
+
yield current_history_for_plot, gr.update(value=""), chat_histories
|
264 |
+
return
|
265 |
+
|
266 |
+
# Use an async generator to stream updates from handle_chat_message_submission
|
267 |
+
async for update_chunk in handle_chat_message_submission(suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot):
|
268 |
+
yield update_chunk
|
269 |
+
|
270 |
+
|
271 |
+
def handle_explore_click(plot_id_clicked, current_explored_plot_id_from_state, current_active_panel_action_state):
|
272 |
+
logger.info(f"Explore Click: Plot '{plot_id_clicked}'. Current Explored: {current_explored_plot_id_from_state}. Active Panel: {current_active_panel_action_state}")
|
273 |
+
num_plots = len(PLOT_CONFIGS)
|
274 |
+
|
275 |
+
if not _plot_ui_objects: # Ensure _plot_ui_objects is populated
|
276 |
+
logger.error("_plot_ui_objects not populated for handle_explore_click.")
|
277 |
+
# Construct an error return list of the correct length
|
278 |
+
error_list_len = 4 + (4 * num_plots) + NUM_UNIQUE_SECTIONS
|
279 |
+
error_list = [gr.update()] * error_list_len
|
280 |
+
error_list[0] = current_explored_plot_id_from_state # explored_plot_id_state
|
281 |
+
error_list[2] = current_active_panel_action_state # active_panel_action_state
|
282 |
+
# Other elements remain gr.update()
|
283 |
+
return error_list
|
284 |
+
|
285 |
+
new_explored_id_to_set = None
|
286 |
+
is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)
|
287 |
+
|
288 |
+
action_col_upd = gr.update() # Default: no change
|
289 |
+
new_active_panel_state_upd = current_active_panel_action_state # Default: no change
|
290 |
+
formula_hint_upd = gr.update(visible=False) # Default: hide formula hint
|
291 |
+
|
292 |
+
panel_vis_updates = []
|
293 |
+
explore_btns_updates = []
|
294 |
+
bomb_btns_updates = [gr.update() for _ in PLOT_CONFIGS] # Default: no change
|
295 |
+
formula_btns_updates = [gr.update() for _ in PLOT_CONFIGS] # Default: no change
|
296 |
+
section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS
|
297 |
+
|
298 |
+
clicked_cfg = next((p for p in PLOT_CONFIGS if p["id"] == plot_id_clicked), None)
|
299 |
+
sec_of_clicked = clicked_cfg["section"] if clicked_cfg else None
|
300 |
+
|
301 |
+
if is_toggling_off_explore:
|
302 |
+
new_explored_id_to_set = None
|
303 |
+
logger.info(f"Stopping explore for {plot_id_clicked}. All plots/sections to be visible.")
|
304 |
+
for i in range(NUM_UNIQUE_SECTIONS):
|
305 |
+
section_title_vis_updates[i] = gr.update(visible=True)
|
306 |
+
for _ in PLOT_CONFIGS:
|
307 |
+
panel_vis_updates.append(gr.update(visible=True))
|
308 |
+
explore_btns_updates.append(gr.update(value=EXPLORE_ICON))
|
309 |
+
# Bomb and Formula buttons remain as they were unless an action panel was closed
|
310 |
+
else: # Activating explore for plot_id_clicked or switching explore target
|
311 |
+
new_explored_id_to_set = plot_id_clicked
|
312 |
+
logger.info(f"Exploring {plot_id_clicked}. Hiding other plots/sections.")
|
313 |
+
for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
|
314 |
+
section_title_vis_updates[i] = gr.update(visible=(sec_name == sec_of_clicked))
|
315 |
+
for cfg in PLOT_CONFIGS:
|
316 |
+
is_target = (cfg["id"] == new_explored_id_to_set)
|
317 |
+
panel_vis_updates.append(gr.update(visible=is_target))
|
318 |
+
explore_btns_updates.append(gr.update(value=ACTIVE_ICON if is_target else EXPLORE_ICON))
|
319 |
+
|
320 |
+
if current_active_panel_action_state: # If an action panel (insights/formula) is open
|
321 |
+
logger.info("Closing active insight/formula panel due to explore click.")
|
322 |
+
action_col_upd = gr.update(visible=False)
|
323 |
+
new_active_panel_state_upd = None # Clear active panel state
|
324 |
+
formula_hint_upd = gr.update(visible=False) # Hide formula hint specifically
|
325 |
+
# Reset bomb and formula buttons to their default icons
|
326 |
+
bomb_btns_updates = [gr.update(value=BOMB_ICON) for _ in PLOT_CONFIGS]
|
327 |
+
formula_btns_updates = [gr.update(value=FORMULA_ICON) for _ in PLOT_CONFIGS]
|
328 |
+
|
329 |
+
# Order of outputs must match the list provided to .click() in build_and_wire_tab
|
330 |
+
final_explore_updates = [
|
331 |
+
new_explored_id_to_set, # explored_plot_id_state
|
332 |
+
action_col_upd, # global_actions_column_ui
|
333 |
+
new_active_panel_state_upd, # active_panel_action_state
|
334 |
+
formula_hint_upd # formula_close_hint_md (specifically for closing formula panel)
|
335 |
+
]
|
336 |
+
final_explore_updates.extend(panel_vis_updates) # plot_ui_objects[pc["id"]]["panel_component"]
|
337 |
+
final_explore_updates.extend(explore_btns_updates) # plot_ui_objects[pc["id"]]["explore_button"]
|
338 |
+
final_explore_updates.extend(bomb_btns_updates) # plot_ui_objects[pc["id"]]["bomb_button"]
|
339 |
+
final_explore_updates.extend(formula_btns_updates) # plot_ui_objects[pc["id"]]["formula_button"]
|
340 |
+
final_explore_updates.extend(section_title_vis_updates) # section_titles_map[s_name]
|
341 |
+
|
342 |
+
logger.debug(f"handle_explore_click returning {len(final_explore_updates)} updates. Expected {4 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
|
343 |
+
return final_explore_updates
|
344 |
+
|
345 |
+
async def handle_refresh_analytics_graphs(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, current_chat_histories_val):
|
346 |
+
logger.info("Refreshing analytics graph UI elements and resetting actions/chat.")
|
347 |
+
# Call the existing plot generation logic
|
348 |
+
plot_gen_results = update_analytics_plots_figures(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, PLOT_CONFIGS)
|
349 |
+
status_msg, gen_figs, new_summaries_for_chatbot = plot_gen_results[0], plot_gen_results[1:-1], plot_gen_results[-1]
|
350 |
+
|
351 |
+
all_updates = [status_msg] # For analytics_status_md
|
352 |
+
all_updates.extend(gen_figs if len(gen_figs) == len(PLOT_CONFIGS) else [create_placeholder_plot("Error", f"Fig missing {i}") for i in range(len(PLOT_CONFIGS))]) # For each plot component
|
353 |
+
|
354 |
+
# Updates for resetting the global action panel UI
|
355 |
+
all_updates.extend([
|
356 |
+
gr.update(visible=False), # global_actions_column_ui
|
357 |
+
gr.update(value=[], visible=False), # insights_chatbot_ui (content and visibility)
|
358 |
+
gr.update(value="", visible=False), # insights_chat_input_ui
|
359 |
+
gr.update(visible=False), # insights_suggestions_row_ui
|
360 |
+
gr.update(value="Suggerimento 1"), # insights_suggestion_1_btn
|
361 |
+
gr.update(value="Suggerimento 2"), # insights_suggestion_2_btn
|
362 |
+
gr.update(value="Suggerimento 3"), # insights_suggestion_3_btn
|
363 |
+
gr.update(value="Formula details here.", visible=False), # formula_display_markdown_ui
|
364 |
+
gr.update(visible=False) # formula_close_hint_md
|
365 |
+
])
|
366 |
+
|
367 |
+
# Updates for resetting relevant states
|
368 |
+
all_updates.extend([
|
369 |
+
None, # active_panel_action_state
|
370 |
+
None, # current_chat_plot_id_st
|
371 |
+
{}, # chat_histories_st (resetting all chat histories on graph refresh)
|
372 |
+
new_summaries_for_chatbot # plot_data_for_chatbot_st
|
373 |
+
])
|
374 |
+
|
375 |
+
# Updates for resetting plot-specific action buttons and panel visibility
|
376 |
+
for _ in PLOT_CONFIGS:
|
377 |
+
all_updates.extend([
|
378 |
+
gr.update(value=BOMB_ICON), # bomb_button
|
379 |
+
gr.update(value=FORMULA_ICON), # formula_button
|
380 |
+
gr.update(value=EXPLORE_ICON), # explore_button
|
381 |
+
gr.update(visible=True) # panel_component (make all plot panels visible)
|
382 |
+
])
|
383 |
+
|
384 |
+
all_updates.append(None) # explored_plot_id_state (reset explore state)
|
385 |
+
|
386 |
+
# Updates for making all section titles visible
|
387 |
+
all_updates.extend([gr.update(visible=True)] * NUM_UNIQUE_SECTIONS)
|
388 |
+
|
389 |
+
expected_len = 1 + len(PLOT_CONFIGS) + 9 + 4 + (4 * len(PLOT_CONFIGS)) + 1 + NUM_UNIQUE_SECTIONS # Match original structure
|
390 |
+
logger.info(f"Prepared {len(all_updates)} updates for graph refresh. Expected {expected_len}.")
|
391 |
+
if len(all_updates) != expected_len:
|
392 |
+
logger.error(f"MISMATCH in refresh_analytics_graphs_ui output length. Got {len(all_updates)}, expected {expected_len}")
|
393 |
+
# Fallback to a safe number of gr.update() if length mismatch to avoid Gradio error
|
394 |
+
# This part needs careful review if mismatches occur.
|
395 |
+
# For now, assume the calculation is correct based on original structure.
|
396 |
+
return tuple(all_updates)
|
397 |
+
|
398 |
+
|
399 |
+
def build_and_wire_tab(token_state, chat_histories_st, current_chat_plot_id_st, plot_data_for_chatbot_st, active_panel_action_state, explored_plot_id_state):
|
400 |
+
"""Builds the UI for the Analytics Tab and wires up its internal event handlers."""
|
401 |
+
global _plot_ui_objects, _section_titles_map, _global_actions_column_ui, \
|
402 |
+
_insights_chatbot_ui, _insights_chat_input_ui, _insights_suggestions_row_ui, \
|
403 |
+
_insights_suggestion_1_btn, _insights_suggestion_2_btn, _insights_suggestion_3_btn, \
|
404 |
+
_formula_display_markdown_ui, _formula_close_hint_md, _analytics_status_md, \
|
405 |
+
_date_filter_selector, _custom_start_date_picker, _custom_end_date_picker
|
406 |
+
|
407 |
+
# These will be returned to app.py for .then() chains if needed, or for constructing output lists
|
408 |
+
# that app.py will manage for calls to handlers in this module.
|
409 |
+
components_for_refresh_outputs = []
|
410 |
+
|
411 |
+
with gr.Column(): # Main column for the tab
|
412 |
+
_analytics_status_md = gr.Markdown("Stato analisi grafici...")
|
413 |
+
components_for_refresh_outputs.append(_analytics_status_md)
|
414 |
+
|
415 |
+
gr.Markdown("## 📈 Analisi Performance LinkedIn")
|
416 |
+
gr.Markdown("Seleziona un intervallo di date per i grafici. Clicca i pulsanti (💣 Insights, ƒ Formula, 🧭 Esplora) su un grafico per azioni.")
|
417 |
+
|
418 |
+
with gr.Row():
|
419 |
+
_date_filter_selector = gr.Radio(
|
420 |
+
["Sempre", "Ultimi 7 Giorni", "Ultimi 30 Giorni", "Intervallo Personalizzato"],
|
421 |
+
label="Seleziona Intervallo Date per Grafici", value="Sempre", scale=3
|
422 |
+
)
|
423 |
+
with gr.Column(scale=2):
|
424 |
+
_custom_start_date_picker = gr.DateTime(label="Data Inizio", visible=False, include_time=False, type="datetime")
|
425 |
+
_custom_end_date_picker = gr.DateTime(label="Data Fine", visible=False, include_time=False, type="datetime")
|
426 |
+
|
427 |
+
apply_filter_btn = gr.Button("🔍 Applica Filtro & Aggiorna Grafici", variant="primary")
|
428 |
+
|
429 |
+
_date_filter_selector.change(
|
430 |
+
fn=handle_toggle_custom_date_pickers,
|
431 |
+
inputs=[_date_filter_selector],
|
432 |
+
outputs=[_custom_start_date_picker, _custom_end_date_picker]
|
433 |
+
)
|
434 |
+
|
435 |
+
with gr.Row(equal_height=False):
|
436 |
+
with gr.Column(scale=8) as plots_area_col:
|
437 |
+
# Call the existing UI generator for plots
|
438 |
+
# This function needs to populate _plot_ui_objects and _section_titles_map
|
439 |
+
# For simplicity, assume build_analytics_tab_plot_area is adapted or its results are processed here
|
440 |
+
ui_elements_tuple = build_analytics_tab_plot_area(PLOT_CONFIGS)
|
441 |
+
if isinstance(ui_elements_tuple, tuple) and len(ui_elements_tuple) == 2:
|
442 |
+
_plot_ui_objects, _section_titles_map = ui_elements_tuple
|
443 |
+
if not all(sec_name in _section_titles_map for sec_name in UNIQUE_ORDERED_SECTIONS):
|
444 |
+
logger.error("section_titles_map from build_analytics_tab_plot_area is incomplete.")
|
445 |
+
# Ensure _section_titles_map has all keys for safety in handlers
|
446 |
+
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
447 |
+
if sec_name not in _section_titles_map:
|
448 |
+
_section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
449 |
+
else: # Fallback if the function signature changes or an error occurs
|
450 |
+
logger.error("build_analytics_tab_plot_area did not return a tuple of (plot_ui_objects, section_titles_map).")
|
451 |
+
_plot_ui_objects = ui_elements_tuple if isinstance(ui_elements_tuple, dict) else {}
|
452 |
+
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
453 |
+
_section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
454 |
+
# Ensure all plot IDs have a placeholder in _plot_ui_objects for safety
|
455 |
+
for pc_cfg in PLOT_CONFIGS:
|
456 |
+
if pc_cfg['id'] not in _plot_ui_objects:
|
457 |
+
_plot_ui_objects[pc_cfg['id']] = {
|
458 |
+
"plot_component": gr.Plot(label=pc_cfg['label']), # Placeholder
|
459 |
+
"panel_component": gr.Group(visible=True), # Placeholder
|
460 |
+
"bomb_button": gr.Button(value=BOMB_ICON, size="sm", min_width=10),
|
461 |
+
"formula_button": gr.Button(value=FORMULA_ICON, size="sm", min_width=10),
|
462 |
+
"explore_button": gr.Button(value=EXPLORE_ICON, size="sm", min_width=10)
|
463 |
+
}
|
464 |
+
|
465 |
+
|
466 |
+
_global_actions_column_ui = gr.Column(scale=4, visible=False) # Assign to module-level var
|
467 |
+
with _global_actions_column_ui:
|
468 |
+
gr.Markdown("### 💡 Azioni Contestuali Grafico")
|
469 |
+
_insights_chatbot_ui = gr.Chatbot(
|
470 |
+
label="Chat Insights", type="messages", height=450,
|
471 |
+
bubble_full_width=False, visible=False, show_label=False,
|
472 |
+
placeholder="L'analisi AI del grafico apparirà qui. Fai domande di approfondimento!"
|
473 |
+
)
|
474 |
+
_insights_chat_input_ui = gr.Textbox(
|
475 |
+
label="La tua domanda:", placeholder="Chiedi all'AI riguardo a questo grafico...",
|
476 |
+
lines=2, visible=False, show_label=False
|
477 |
+
)
|
478 |
+
_insights_suggestions_row_ui = gr.Row(visible=False)
|
479 |
+
with _insights_suggestions_row_ui:
|
480 |
+
_insights_suggestion_1_btn = gr.Button(value="Suggerimento 1", size="sm", min_width=50)
|
481 |
+
_insights_suggestion_2_btn = gr.Button(value="Suggerimento 2", size="sm", min_width=50)
|
482 |
+
_insights_suggestion_3_btn = gr.Button(value="Suggerimento 3", size="sm", min_width=50)
|
483 |
+
|
484 |
+
_formula_display_markdown_ui = gr.Markdown(
|
485 |
+
"I dettagli sulla formula/metodologia appariranno qui.", visible=False
|
486 |
+
)
|
487 |
+
_formula_close_hint_md = gr.Markdown(
|
488 |
+
"<p style='font-size:0.9em; text-align:center; margin-top:10px;'><em>Click the active ƒ button on the plot again to close this panel.</em></p>",
|
489 |
+
visible=False
|
490 |
+
)
|
491 |
+
|
492 |
+
# --- Outputs for handle_refresh_analytics_graphs ---
|
493 |
+
# Order: analytics_status_md
|
494 |
+
# plot_components (from _plot_ui_objects)
|
495 |
+
# global_actions_column_ui, insights_chatbot_ui (vis), insights_chatbot_ui (val), insights_chat_input_ui, insights_suggestions_row_ui, s1,s2,s3, formula_display_md (vis), formula_display_md (val), formula_close_hint
|
496 |
+
# active_panel_action_state, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st
|
497 |
+
# bomb_buttons, formula_buttons, explore_buttons, panel_components (from _plot_ui_objects)
|
498 |
+
# explored_plot_id_state
|
499 |
+
# section_title_markdowns (from _section_titles_map)
|
500 |
+
|
501 |
+
for pc_cfg in PLOT_CONFIGS: # plot_components
|
502 |
+
components_for_refresh_outputs.append(_plot_ui_objects.get(pc_cfg["id"], {}).get("plot_component", gr.Plot()))
|
503 |
+
|
504 |
+
components_for_refresh_outputs.extend([ # UI resets for global action panel
|
505 |
+
_global_actions_column_ui, _insights_chatbot_ui, _insights_chat_input_ui,
|
506 |
+
_insights_suggestions_row_ui, _insights_suggestion_1_btn, _insights_suggestion_2_btn,
|
507 |
+
_insights_suggestion_3_btn, _formula_display_markdown_ui, _formula_close_hint_md
|
508 |
+
])
|
509 |
+
# Note: For components like _insights_chatbot_ui that need separate visibility and value updates,
|
510 |
+
# handle_refresh_analytics_graphs provides two gr.update() calls. The outputs list here should map to that.
|
511 |
+
# The current handle_refresh_analytics_graphs structure implies the value for _insights_chatbot_ui is part of its visibility update.
|
512 |
+
# This needs to be consistent. The original code had `insights_chatbot_ui` twice in `_base_action_panel_ui_outputs`.
|
513 |
+
# Let's assume for now that `gr.update(value=[], visible=False)` handles both for `_insights_chatbot_ui`.
|
514 |
+
|
515 |
+
# States are not components, they are updated directly by handlers.
|
516 |
+
# The list `components_for_refresh_outputs` is for Gradio `outputs=[...]` argument.
|
517 |
+
|
518 |
+
for pc_cfg in PLOT_CONFIGS: # plot action buttons and panels
|
519 |
+
plot_obj = _plot_ui_objects.get(pc_cfg["id"], {})
|
520 |
+
components_for_refresh_outputs.extend([
|
521 |
+
plot_obj.get("bomb_button", gr.Button()),
|
522 |
+
plot_obj.get("formula_button", gr.Button()),
|
523 |
+
plot_obj.get("explore_button", gr.Button()),
|
524 |
+
plot_obj.get("panel_component", gr.Group())
|
525 |
+
])
|
526 |
+
|
527 |
+
for sec_name in UNIQUE_ORDERED_SECTIONS: # section titles
|
528 |
+
components_for_refresh_outputs.append(_section_titles_map.get(sec_name, gr.Markdown()))
|
529 |
+
|
530 |
+
|
531 |
+
# --- Outputs for handle_panel_action & handle_explore_click ---
|
532 |
+
# These lists are constructed inside the handlers themselves using the module-level component variables.
|
533 |
+
# What app.py needs is the list of components that these handlers will update.
|
534 |
+
|
535 |
+
action_panel_event_outputs = [
|
536 |
+
_global_actions_column_ui, _insights_chatbot_ui, _insights_chatbot_ui, # vis, val
|
537 |
+
_insights_chat_input_ui, _insights_suggestions_row_ui,
|
538 |
+
_insights_suggestion_1_btn, _insights_suggestion_2_btn, _insights_suggestion_3_btn,
|
539 |
+
_formula_display_markdown_ui, _formula_display_markdown_ui, # vis, val
|
540 |
+
_formula_close_hint_md,
|
541 |
+
# States: active_panel_action_state, current_chat_plot_id_st, chat_histories_st, explored_plot_id_state
|
542 |
+
]
|
543 |
+
# Add plot-specific components (panels, buttons)
|
544 |
+
for pc in PLOT_CONFIGS:
|
545 |
+
ui_obj = _plot_ui_objects.get(pc["id"], {})
|
546 |
+
action_panel_event_outputs.extend([
|
547 |
+
ui_obj.get("panel_component", gr.Group()), ui_obj.get("bomb_button", gr.Button()),
|
548 |
+
ui_obj.get("formula_button", gr.Button()), ui_obj.get("explore_button", gr.Button())
|
549 |
+
])
|
550 |
+
# Add section titles
|
551 |
+
for s_name in UNIQUE_ORDERED_SECTIONS:
|
552 |
+
action_panel_event_outputs.append(_section_titles_map.get(s_name, gr.Markdown()))
|
553 |
+
|
554 |
+
|
555 |
+
explore_event_outputs = [
|
556 |
+
# States: explored_plot_id_state, active_panel_action_state
|
557 |
+
_global_actions_column_ui, _formula_close_hint_md
|
558 |
+
]
|
559 |
+
# Add plot-specific components (panels, buttons)
|
560 |
+
for pc in PLOT_CONFIGS:
|
561 |
+
ui_obj = _plot_ui_objects.get(pc["id"], {})
|
562 |
+
explore_event_outputs.extend([
|
563 |
+
ui_obj.get("panel_component", gr.Group()), ui_obj.get("explore_button", gr.Button()),
|
564 |
+
ui_obj.get("bomb_button", gr.Button()), ui_obj.get("formula_button", gr.Button())
|
565 |
+
])
|
566 |
+
# Add section titles
|
567 |
+
for s_name in UNIQUE_ORDERED_SECTIONS:
|
568 |
+
explore_event_outputs.append(_section_titles_map.get(s_name, gr.Markdown()))
|
569 |
+
|
570 |
+
# --- Event Wiring ---
|
571 |
+
action_click_inputs = [active_panel_action_state, chat_histories_st, current_chat_plot_id_st, plot_data_for_chatbot_st, explored_plot_id_state]
|
572 |
+
explore_click_inputs = [explored_plot_id_state, active_panel_action_state]
|
573 |
+
|
574 |
+
def create_panel_action_handler_closure(p_id, action_type_str): # Renamed from original to avoid conflict
|
575 |
+
async def _handler(curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id):
|
576 |
+
return await handle_panel_action(p_id, action_type_str, curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id)
|
577 |
+
return _handler
|
578 |
+
|
579 |
+
for config_item in PLOT_CONFIGS:
|
580 |
+
plot_id = config_item["id"]
|
581 |
+
if plot_id in _plot_ui_objects:
|
582 |
+
ui_obj = _plot_ui_objects[plot_id]
|
583 |
+
# The outputs list for these handlers needs to include the state variables as well.
|
584 |
+
# The handlers themselves return updates for states.
|
585 |
+
# Gradio's .click() outputs should be components + states.
|
586 |
+
|
587 |
+
# Corrected output lists for action/explore handlers to include states
|
588 |
+
# These are the components that receive updates, PLUS the state objects themselves.
|
589 |
+
# The `handle_panel_action` and `handle_explore_click` functions are designed to return a list
|
590 |
+
# where the state updates are correctly positioned.
|
591 |
+
|
592 |
+
# Outputs for panel actions (insights/formula)
|
593 |
+
panel_action_outputs_plus_states = action_panel_event_outputs[:11] + \
|
594 |
+
[active_panel_action_state, current_chat_plot_id_st, chat_histories_st, explored_plot_id_state] + \
|
595 |
+
action_panel_event_outputs[11:]
|
596 |
+
|
597 |
+
# Outputs for explore actions
|
598 |
+
explore_action_outputs_plus_states = [explored_plot_id_state] + \
|
599 |
+
explore_event_outputs[:1] + \
|
600 |
+
[active_panel_action_state] + \
|
601 |
+
explore_event_outputs[1:]
|
602 |
+
|
603 |
+
|
604 |
+
if ui_obj.get("bomb_button"):
|
605 |
+
ui_obj["bomb_button"].click(
|
606 |
+
fn=create_panel_action_handler_closure(plot_id, "insights"),
|
607 |
+
inputs=action_click_inputs,
|
608 |
+
outputs=panel_action_outputs_plus_states, # Pass the combined list
|
609 |
+
api_name=f"action_insights_{plot_id}"
|
610 |
+
)
|
611 |
+
if ui_obj.get("formula_button"):
|
612 |
+
ui_obj["formula_button"].click(
|
613 |
+
fn=create_panel_action_handler_closure(plot_id, "formula"),
|
614 |
+
inputs=action_click_inputs,
|
615 |
+
outputs=panel_action_outputs_plus_states, # Pass the combined list
|
616 |
+
api_name=f"action_formula_{plot_id}"
|
617 |
+
)
|
618 |
+
if ui_obj.get("explore_button"):
|
619 |
+
ui_obj["explore_button"].click(
|
620 |
+
fn=lambda current_explored_val, current_active_panel_val, p_id=plot_id: handle_explore_click(p_id, current_explored_val, current_active_panel_val),
|
621 |
+
inputs=explore_click_inputs,
|
622 |
+
outputs=explore_action_outputs_plus_states, # Pass the combined list
|
623 |
+
api_name=f"action_explore_{plot_id}"
|
624 |
+
)
|
625 |
+
else:
|
626 |
+
logger.warning(f"UI object for plot_id '{plot_id}' not found for click handlers.")
|
627 |
+
|
628 |
+
chat_submission_outputs = [_insights_chatbot_ui, _insights_chat_input_ui, chat_histories_st]
|
629 |
+
chat_submission_inputs = [_insights_chat_input_ui, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
|
630 |
+
|
631 |
+
_insights_chat_input_ui.submit(
|
632 |
+
fn=handle_chat_message_submission,
|
633 |
+
inputs=chat_submission_inputs,
|
634 |
+
outputs=chat_submission_outputs,
|
635 |
+
api_name="submit_chat_message"
|
636 |
+
)
|
637 |
+
|
638 |
+
suggestion_click_inputs_base = [current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
|
639 |
+
_insights_suggestion_1_btn.click(
|
640 |
+
fn=handle_suggested_question_click,
|
641 |
+
inputs=[_insights_suggestion_1_btn] + suggestion_click_inputs_base,
|
642 |
+
outputs=chat_submission_outputs, api_name="click_suggestion_1"
|
643 |
+
)
|
644 |
+
_insights_suggestion_2_btn.click(
|
645 |
+
fn=handle_suggested_question_click,
|
646 |
+
inputs=[_insights_suggestion_2_btn] + suggestion_click_inputs_base,
|
647 |
+
outputs=chat_submission_outputs, api_name="click_suggestion_2"
|
648 |
+
)
|
649 |
+
_insights_suggestion_3_btn.click(
|
650 |
+
fn=handle_suggested_question_click,
|
651 |
+
inputs=[_insights_suggestion_3_btn] + suggestion_click_inputs_base,
|
652 |
+
outputs=chat_submission_outputs, api_name="click_suggestion_3"
|
653 |
+
)
|
654 |
+
|
655 |
+
# This button's event is handled by app.py's .then chain calling handle_refresh_analytics_graphs
|
656 |
+
# So, build_and_wire_tab needs to return this button and the list of components its handler updates.
|
657 |
+
# The handle_refresh_analytics_graphs is now part of this module.
|
658 |
+
# So, apply_filter_btn.click can be wired here directly.
|
659 |
+
|
660 |
+
# The output list for handle_refresh_analytics_graphs needs to include states as well.
|
661 |
+
refresh_outputs_plus_states = components_for_refresh_outputs[:1+len(PLOT_CONFIGS)+9] + \
|
662 |
+
[active_panel_action_state, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st] + \
|
663 |
+
components_for_refresh_outputs[1+len(PLOT_CONFIGS)+9 : 1+len(PLOT_CONFIGS)+9 + 4*len(PLOT_CONFIGS)] + \
|
664 |
+
[explored_plot_id_state] + \
|
665 |
+
components_for_refresh_outputs[1+len(PLOT_CONFIGS)+9 + 4*len(PLOT_CONFIGS):]
|
666 |
+
|
667 |
+
|
668 |
+
apply_filter_btn.click(
|
669 |
+
fn=handle_refresh_analytics_graphs,
|
670 |
+
inputs=[token_state, _date_filter_selector, _custom_start_date_picker, _custom_end_date_picker, chat_histories_st],
|
671 |
+
outputs=refresh_outputs_plus_states, # Use the constructed list
|
672 |
+
show_progress="full"
|
673 |
+
)
|
674 |
+
|
675 |
+
# Return components that app.py might need for .then() chains or direct interaction.
|
676 |
+
# For now, app.py mainly needs the list of components that handle_refresh_analytics_graphs updates,
|
677 |
+
# if that handler is called from app.py. Since it's now wired internally, this might be simpler.
|
678 |
+
return (apply_filter_btn, _date_filter_selector, _custom_start_date_picker, _custom_end_date_picker,
|
679 |
+
_analytics_status_md, # For initial load
|
680 |
+
components_for_refresh_outputs, # The full list of components for refresh
|
681 |
+
refresh_outputs_plus_states # The list including states for refresh
|
682 |
+
)
|
683 |
+
|