Spaces:
Running
Running
Update services/analytics_tab_module.py
Browse files- services/analytics_tab_module.py +68 -83
services/analytics_tab_module.py
CHANGED
@@ -34,11 +34,7 @@ PLOT_CONFIGS = [
|
|
34 |
{"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"},
|
35 |
{"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"}
|
36 |
]
|
37 |
-
|
38 |
-
# can still be generated without the dedicated mentions data processing.
|
39 |
-
# If not, they should also be removed from plot_configs.
|
40 |
-
# For now, I am assuming they might draw from a general data pool in token_state.
|
41 |
-
assert len(PLOT_CONFIGS) == 19, "Mancata corrispondenza in PLOT_CONFIGS e grafici attesi. (If mentions plots were removed, adjust this number)"
|
42 |
|
43 |
UNIQUE_ORDERED_SECTIONS = list(OrderedDict.fromkeys(pc["section"] for pc in PLOT_CONFIGS))
|
44 |
NUM_UNIQUE_SECTIONS = len(UNIQUE_ORDERED_SECTIONS)
|
@@ -118,9 +114,9 @@ class AnalyticsTab:
|
|
118 |
error_list = [gr.update()] * error_list_len
|
119 |
# Fill specific indices if needed, matching the expected output structure
|
120 |
error_list[11] = current_active_action_from_state # active_panel_action_state
|
121 |
-
error_list[12] = current_chat_plot_id
|
122 |
-
error_list[13] = current_chat_histories
|
123 |
-
error_list[14] = current_explored_plot_id
|
124 |
return error_list
|
125 |
|
126 |
clicked_plot_label = clicked_plot_config["label"]
|
@@ -232,12 +228,12 @@ class AnalyticsTab:
|
|
232 |
|
233 |
# Order of updates must match self.action_panel_outputs_list
|
234 |
final_updates = [
|
235 |
-
action_col_visible_update,
|
236 |
insights_chatbot_visible_update, # insights_chatbot_ui (visibility)
|
237 |
chatbot_content_update, # insights_chatbot_ui (content)
|
238 |
insights_chat_input_visible_update, # insights_chat_input_ui
|
239 |
insights_suggestions_row_visible_update, # insights_suggestions_row_ui
|
240 |
-
s1_upd, s2_upd, s3_upd,
|
241 |
formula_display_visible_update, # formula_display_markdown_ui (visibility)
|
242 |
formula_content_update, # formula_display_markdown_ui (content)
|
243 |
formula_close_hint_visible_update, # formula_close_hint_md
|
@@ -258,8 +254,6 @@ class AnalyticsTab:
|
|
258 |
async def _handle_chat_message_submission(self, user_message: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
259 |
if not current_plot_id or not user_message.strip():
|
260 |
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
261 |
-
# Ensure history is in the format Gradio Chatbot expects (list of lists/tuples or specific dicts)
|
262 |
-
# Assuming it's already [{"role": "user/assistant", "content": "..."}]
|
263 |
yield current_history_for_plot, gr.update(value=""), chat_histories
|
264 |
return
|
265 |
|
@@ -267,20 +261,14 @@ class AnalyticsTab:
|
|
267 |
plot_label = clicked_plot_config["label"] if clicked_plot_config else "Selected Plot"
|
268 |
summary_data = current_plot_data_for_chatbot.get(current_plot_id, f"No summary available for '{plot_label}'.")
|
269 |
|
270 |
-
|
271 |
-
|
272 |
-
if not isinstance(history_for_api, list): history_for_api = [] # Should not happen if initialized correctly
|
273 |
|
274 |
history_for_api.append({"role": "user", "content": user_message})
|
275 |
|
276 |
-
|
277 |
-
# Gradio Chatbot expects list of (user_msg, assistant_msg) tuples or specific dicts.
|
278 |
-
# If current_chat_histories stores [{"role": "user", "content": "..."}], convert for display if needed,
|
279 |
-
# or ensure generate_llm_response and initial prompt also use this dict format.
|
280 |
-
# For simplicity, let's assume chat_histories_st stores a list of such dicts.
|
281 |
-
current_display_history = history_for_api.copy() # This is what will be displayed
|
282 |
|
283 |
-
yield current_display_history, gr.update(value=""), chat_histories
|
284 |
|
285 |
assistant_response = await self.generate_llm_response(user_message, current_plot_id, plot_label, history_for_api, summary_data)
|
286 |
history_for_api.append({"role": "assistant", "content": assistant_response})
|
@@ -288,44 +276,39 @@ class AnalyticsTab:
|
|
288 |
updated_chat_histories = {**chat_histories, current_plot_id: history_for_api}
|
289 |
current_display_history.append({"role": "assistant", "content": assistant_response})
|
290 |
|
291 |
-
|
292 |
yield current_display_history, "", updated_chat_histories
|
293 |
|
294 |
-
|
295 |
async def _handle_suggested_question_click(self, suggestion_text: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
296 |
if not current_plot_id or not suggestion_text.strip() or suggestion_text == "N/A":
|
297 |
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
298 |
yield current_history_for_plot, gr.update(value=""), chat_histories
|
299 |
return
|
300 |
|
301 |
-
# Use async for to stream updates from _handle_chat_message_submission
|
302 |
async for update_chunk in self._handle_chat_message_submission(suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot):
|
303 |
yield update_chunk
|
304 |
|
305 |
-
|
306 |
def _handle_explore_click(self, plot_id_clicked, current_explored_plot_id_from_state, current_active_panel_action_state):
|
307 |
logging.info(f"Explore Click: Plot '{plot_id_clicked}'. Current Explored: {current_explored_plot_id_from_state}. Active Panel: {current_active_panel_action_state}")
|
308 |
num_plots = len(PLOT_CONFIGS)
|
309 |
|
310 |
-
if not self.plot_ui_objects:
|
311 |
logging.error("plot_ui_objects not populated for handle_explore_click.")
|
312 |
-
# Prepare a list of gr.update() of the correct length
|
313 |
error_list_len = 4 + (4 * num_plots) + NUM_UNIQUE_SECTIONS
|
314 |
error_list = [gr.update()] * error_list_len
|
315 |
-
error_list[0] = current_explored_plot_id_from_state
|
316 |
-
error_list[2] = current_active_panel_action_state
|
317 |
return error_list
|
318 |
|
319 |
new_explored_id_to_set = None
|
320 |
is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)
|
321 |
|
322 |
-
action_col_upd = gr.update()
|
323 |
-
new_active_panel_state_upd = current_active_panel_action_state
|
324 |
-
formula_hint_upd = gr.update(visible=False)
|
325 |
|
326 |
panel_vis_updates = []
|
327 |
explore_btns_updates = []
|
328 |
-
bomb_btns_updates = [gr.update()] * num_plots
|
329 |
formula_btns_updates = [gr.update()] * num_plots
|
330 |
section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS
|
331 |
|
@@ -333,16 +316,14 @@ class AnalyticsTab:
|
|
333 |
section_of_clicked_plot = clicked_cfg["section"] if clicked_cfg else None
|
334 |
|
335 |
if is_toggling_off_explore:
|
336 |
-
new_explored_id_to_set = None
|
337 |
logging.info(f"Stopping explore for {plot_id_clicked}. All plots/sections to be visible.")
|
338 |
for i in range(NUM_UNIQUE_SECTIONS):
|
339 |
section_title_vis_updates[i] = gr.update(visible=True)
|
340 |
for _ in PLOT_CONFIGS:
|
341 |
panel_vis_updates.append(gr.update(visible=True))
|
342 |
explore_btns_updates.append(gr.update(value=self.EXPLORE_ICON))
|
343 |
-
|
344 |
-
# Bomb and formula buttons don't change unless an action panel is closed.
|
345 |
-
else: # Exploring a new plot or switching explore
|
346 |
new_explored_id_to_set = plot_id_clicked
|
347 |
logging.info(f"Exploring {plot_id_clicked}. Hiding other plots/sections.")
|
348 |
|
@@ -354,55 +335,75 @@ class AnalyticsTab:
|
|
354 |
panel_vis_updates.append(gr.update(visible=is_target_plot))
|
355 |
explore_btns_updates.append(gr.update(value=self.ACTIVE_ICON if is_target_plot else self.EXPLORE_ICON))
|
356 |
|
357 |
-
if current_active_panel_action_state:
|
358 |
logging.info("Closing active insight/formula panel due to explore click.")
|
359 |
action_col_upd = gr.update(visible=False)
|
360 |
-
new_active_panel_state_upd = None
|
361 |
-
# Reset bomb and formula buttons to their default icons
|
362 |
bomb_btns_updates = [gr.update(value=self.BOMB_ICON) for _ in PLOT_CONFIGS]
|
363 |
formula_btns_updates = [gr.update(value=self.FORMULA_ICON) for _ in PLOT_CONFIGS]
|
364 |
-
formula_hint_upd = gr.update(visible=False)
|
365 |
|
366 |
-
# Order of updates must match self.explore_outputs_list
|
367 |
final_explore_updates = [
|
368 |
-
new_explored_id_to_set,
|
369 |
-
action_col_upd,
|
370 |
-
new_active_panel_state_upd,
|
371 |
-
formula_hint_upd
|
372 |
]
|
373 |
-
final_explore_updates.extend(panel_vis_updates)
|
374 |
-
final_explore_updates.extend(explore_btns_updates)
|
375 |
-
final_explore_updates.extend(bomb_btns_updates)
|
376 |
-
final_explore_updates.extend(formula_btns_updates)
|
377 |
-
final_explore_updates.extend(section_title_vis_updates)
|
378 |
|
379 |
logging.debug(f"handle_explore_click returning {len(final_explore_updates)} updates. Expected {4 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
|
380 |
return final_explore_updates
|
381 |
|
382 |
def _create_panel_action_handler(self, p_id, action_type_str):
|
383 |
-
# This wrapper is needed because Gradio's .click() fn doesn't easily pass extra args fixed at definition time
|
384 |
-
# without using lambdas that might have late binding issues in loops, or functools.partial.
|
385 |
-
# An inner async def is a clean way for this specific pattern with async handlers.
|
386 |
async def _handler(curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id):
|
387 |
return await self._handle_panel_action(p_id, action_type_str, curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id)
|
388 |
return _handler
|
389 |
-
|
|
|
|
|
|
|
390 |
async def _refresh_analytics_graphs_ui(self, current_token_state_val, date_filter_val, custom_start_val, custom_end_val, current_chat_histories_val):
|
391 |
logging.info("Refreshing analytics graph UI elements and resetting actions/chat (within module).")
|
392 |
start_time = time.time()
|
393 |
|
|
|
|
|
|
|
|
|
|
|
|
|
394 |
plot_gen_results = self.update_analytics_plots_figures(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, PLOT_CONFIGS)
|
395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
396 |
|
397 |
all_updates = []
|
398 |
# 1. Status Markdown
|
399 |
all_updates.append(status_msg) # For self.analytics_status_md
|
400 |
|
401 |
# 2. Plot components
|
402 |
-
|
|
|
403 |
all_updates.extend(gen_figs)
|
404 |
else:
|
405 |
-
logging.error(f"Mismatch in generated figures ({len(gen_figs)}) and plot_configs ({len(PLOT_CONFIGS)})")
|
|
|
406 |
all_updates.extend([self.create_placeholder_plot("Error", f"Figura mancante {i}") for i in range(len(PLOT_CONFIGS))])
|
407 |
|
408 |
# 3. UI Resets for Action Panel (9 components)
|
@@ -420,12 +421,10 @@ class AnalyticsTab:
|
|
420 |
all_updates.extend([
|
421 |
None, # active_panel_action_state (reset)
|
422 |
None, # current_chat_plot_id_st (reset)
|
423 |
-
|
424 |
new_summaries_for_chatbot # plot_data_for_chatbot_st (update with new summaries)
|
425 |
])
|
426 |
-
|
427 |
-
# all_updates[-2] = {} # This would reset all chat histories
|
428 |
-
|
429 |
# 5. Plot-specific UI Resets (4 components per plot)
|
430 |
for _ in PLOT_CONFIGS:
|
431 |
all_updates.extend([
|
@@ -505,13 +504,12 @@ class AnalyticsTab:
|
|
505 |
self.explore_outputs_list.extend([self.plot_ui_objects.get(pc["id"], {}).get("formula_button", gr.update()) for pc in PLOT_CONFIGS])# For resetting if panel closes
|
506 |
self.explore_outputs_list.extend([self.section_titles_map.get(s_name, gr.update()) for s_name in UNIQUE_ORDERED_SECTIONS])
|
507 |
|
508 |
-
|
509 |
def _setup_callbacks(self):
|
510 |
# Apply filter button
|
511 |
graph_refresh_inputs = [
|
512 |
self.token_state, self.date_filter_selector,
|
513 |
self.custom_start_date_picker, self.custom_end_date_picker,
|
514 |
-
self.chat_histories_st
|
515 |
]
|
516 |
self.apply_filter_btn.click(
|
517 |
fn=self._refresh_analytics_graphs_ui,
|
@@ -548,7 +546,6 @@ class AnalyticsTab:
|
|
548 |
api_name=f"action_formula_{plot_id}_module"
|
549 |
)
|
550 |
if ui_obj.get("explore_button"):
|
551 |
-
# Lambda is okay here as p_id is captured correctly due to loop variable usage
|
552 |
ui_obj["explore_button"].click(
|
553 |
fn=lambda current_explored_val, current_active_panel_val, p_id=plot_id: self._handle_explore_click(p_id, current_explored_val, current_active_panel_val),
|
554 |
inputs=explore_click_inputs,
|
@@ -577,7 +574,7 @@ class AnalyticsTab:
|
|
577 |
]
|
578 |
self.insights_suggestion_1_btn.click(
|
579 |
fn=self._handle_suggested_question_click,
|
580 |
-
inputs=[self.insights_suggestion_1_btn] + suggestion_click_inputs_base,
|
581 |
outputs=chat_submission_outputs,
|
582 |
api_name="click_suggestion_1_module"
|
583 |
)
|
@@ -595,8 +592,7 @@ class AnalyticsTab:
|
|
595 |
)
|
596 |
|
597 |
def create_tab_ui(self):
|
598 |
-
|
599 |
-
with gr.TabItem("📊 Grafici", id="tab_analytics_module"): # Changed id to avoid conflict if old tab exists temporarily
|
600 |
|
601 |
gr.Markdown("## 📈 Analisi Performance LinkedIn")
|
602 |
gr.Markdown("Seleziona un intervallo di date per i grafici. Clicca i pulsanti (💣 Insights, ƒ Formula, 🧭 Esplora) su un grafico per azioni.")
|
@@ -619,28 +615,22 @@ class AnalyticsTab:
|
|
619 |
outputs=[self.custom_start_date_picker, self.custom_end_date_picker]
|
620 |
)
|
621 |
|
622 |
-
# Plot area and actions column
|
623 |
with gr.Row(equal_height=False):
|
624 |
with gr.Column(scale=8) as self.plots_area_col:
|
625 |
-
|
626 |
-
ui_elements_tuple = self.build_analytics_tab_plot_area(PLOT_CONFIGS) # Call injected function
|
627 |
if isinstance(ui_elements_tuple, tuple) and len(ui_elements_tuple) == 2:
|
628 |
self.plot_ui_objects, self.section_titles_map = ui_elements_tuple
|
629 |
-
# Verify section_titles_map completeness (optional, good for debugging)
|
630 |
if not all(sec_name in self.section_titles_map for sec_name in UNIQUE_ORDERED_SECTIONS):
|
631 |
logging.error("section_titles_map from build_analytics_tab_plot_area is incomplete in module.")
|
632 |
-
# Create placeholders if missing, to prevent errors with output lists
|
633 |
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
634 |
if sec_name not in self.section_titles_map:
|
635 |
logging.warning(f"Creating fallback Markdown for missing section title: {sec_name}")
|
636 |
self.section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
637 |
else:
|
638 |
logging.error("build_analytics_tab_plot_area did not return a tuple of (plot_ui_objects, section_titles_map). Using fallback.")
|
639 |
-
# Fallback: try to use the result if it's a dict, otherwise empty
|
640 |
self.plot_ui_objects = ui_elements_tuple if isinstance(ui_elements_tuple, dict) else {}
|
641 |
-
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
642 |
-
|
643 |
-
|
644 |
|
645 |
with gr.Column(scale=4, visible=False) as self.global_actions_column_ui:
|
646 |
gr.Markdown("### 💡 Azioni Contestuali Grafico")
|
@@ -666,10 +656,5 @@ class AnalyticsTab:
|
|
666 |
visible=False
|
667 |
)
|
668 |
|
669 |
-
# After all UI components are defined, populate the output lists
|
670 |
self._define_callback_outputs()
|
671 |
-
# Then, set up the callbacks that use these components and output lists
|
672 |
self._setup_callbacks()
|
673 |
-
|
674 |
-
# The method doesn't need to return anything as it modifies the Gradio app context directly.
|
675 |
-
# The main app will access necessary components via the instance attributes if needed (e.g., for .then() inputs).
|
|
|
34 |
{"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"},
|
35 |
{"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"}
|
36 |
]
|
37 |
+
assert len(PLOT_CONFIGS) == 19, "Mancata corrispondenza in PLOT_CONFIGS e grafici attesi."
|
|
|
|
|
|
|
|
|
38 |
|
39 |
UNIQUE_ORDERED_SECTIONS = list(OrderedDict.fromkeys(pc["section"] for pc in PLOT_CONFIGS))
|
40 |
NUM_UNIQUE_SECTIONS = len(UNIQUE_ORDERED_SECTIONS)
|
|
|
114 |
error_list = [gr.update()] * error_list_len
|
115 |
# Fill specific indices if needed, matching the expected output structure
|
116 |
error_list[11] = current_active_action_from_state # active_panel_action_state
|
117 |
+
error_list[12] = current_chat_plot_id # current_chat_plot_id_st
|
118 |
+
error_list[13] = current_chat_histories # chat_histories_st
|
119 |
+
error_list[14] = current_explored_plot_id # explored_plot_id_state
|
120 |
return error_list
|
121 |
|
122 |
clicked_plot_label = clicked_plot_config["label"]
|
|
|
228 |
|
229 |
# Order of updates must match self.action_panel_outputs_list
|
230 |
final_updates = [
|
231 |
+
action_col_visible_update, # global_actions_column_ui
|
232 |
insights_chatbot_visible_update, # insights_chatbot_ui (visibility)
|
233 |
chatbot_content_update, # insights_chatbot_ui (content)
|
234 |
insights_chat_input_visible_update, # insights_chat_input_ui
|
235 |
insights_suggestions_row_visible_update, # insights_suggestions_row_ui
|
236 |
+
s1_upd, s2_upd, s3_upd, # suggestion buttons
|
237 |
formula_display_visible_update, # formula_display_markdown_ui (visibility)
|
238 |
formula_content_update, # formula_display_markdown_ui (content)
|
239 |
formula_close_hint_visible_update, # formula_close_hint_md
|
|
|
254 |
async def _handle_chat_message_submission(self, user_message: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
255 |
if not current_plot_id or not user_message.strip():
|
256 |
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
|
|
|
|
257 |
yield current_history_for_plot, gr.update(value=""), chat_histories
|
258 |
return
|
259 |
|
|
|
261 |
plot_label = clicked_plot_config["label"] if clicked_plot_config else "Selected Plot"
|
262 |
summary_data = current_plot_data_for_chatbot.get(current_plot_id, f"No summary available for '{plot_label}'.")
|
263 |
|
264 |
+
history_for_api = chat_histories.get(current_plot_id, []).copy()
|
265 |
+
if not isinstance(history_for_api, list): history_for_api = []
|
|
|
266 |
|
267 |
history_for_api.append({"role": "user", "content": user_message})
|
268 |
|
269 |
+
current_display_history = history_for_api.copy()
|
|
|
|
|
|
|
|
|
|
|
270 |
|
271 |
+
yield current_display_history, gr.update(value=""), chat_histories
|
272 |
|
273 |
assistant_response = await self.generate_llm_response(user_message, current_plot_id, plot_label, history_for_api, summary_data)
|
274 |
history_for_api.append({"role": "assistant", "content": assistant_response})
|
|
|
276 |
updated_chat_histories = {**chat_histories, current_plot_id: history_for_api}
|
277 |
current_display_history.append({"role": "assistant", "content": assistant_response})
|
278 |
|
|
|
279 |
yield current_display_history, "", updated_chat_histories
|
280 |
|
|
|
281 |
async def _handle_suggested_question_click(self, suggestion_text: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
282 |
if not current_plot_id or not suggestion_text.strip() or suggestion_text == "N/A":
|
283 |
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
284 |
yield current_history_for_plot, gr.update(value=""), chat_histories
|
285 |
return
|
286 |
|
|
|
287 |
async for update_chunk in self._handle_chat_message_submission(suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot):
|
288 |
yield update_chunk
|
289 |
|
|
|
290 |
def _handle_explore_click(self, plot_id_clicked, current_explored_plot_id_from_state, current_active_panel_action_state):
|
291 |
logging.info(f"Explore Click: Plot '{plot_id_clicked}'. Current Explored: {current_explored_plot_id_from_state}. Active Panel: {current_active_panel_action_state}")
|
292 |
num_plots = len(PLOT_CONFIGS)
|
293 |
|
294 |
+
if not self.plot_ui_objects:
|
295 |
logging.error("plot_ui_objects not populated for handle_explore_click.")
|
|
|
296 |
error_list_len = 4 + (4 * num_plots) + NUM_UNIQUE_SECTIONS
|
297 |
error_list = [gr.update()] * error_list_len
|
298 |
+
error_list[0] = current_explored_plot_id_from_state
|
299 |
+
error_list[2] = current_active_panel_action_state
|
300 |
return error_list
|
301 |
|
302 |
new_explored_id_to_set = None
|
303 |
is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)
|
304 |
|
305 |
+
action_col_upd = gr.update()
|
306 |
+
new_active_panel_state_upd = current_active_panel_action_state
|
307 |
+
formula_hint_upd = gr.update(visible=False)
|
308 |
|
309 |
panel_vis_updates = []
|
310 |
explore_btns_updates = []
|
311 |
+
bomb_btns_updates = [gr.update()] * num_plots
|
312 |
formula_btns_updates = [gr.update()] * num_plots
|
313 |
section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS
|
314 |
|
|
|
316 |
section_of_clicked_plot = clicked_cfg["section"] if clicked_cfg else None
|
317 |
|
318 |
if is_toggling_off_explore:
|
319 |
+
new_explored_id_to_set = None
|
320 |
logging.info(f"Stopping explore for {plot_id_clicked}. All plots/sections to be visible.")
|
321 |
for i in range(NUM_UNIQUE_SECTIONS):
|
322 |
section_title_vis_updates[i] = gr.update(visible=True)
|
323 |
for _ in PLOT_CONFIGS:
|
324 |
panel_vis_updates.append(gr.update(visible=True))
|
325 |
explore_btns_updates.append(gr.update(value=self.EXPLORE_ICON))
|
326 |
+
else:
|
|
|
|
|
327 |
new_explored_id_to_set = plot_id_clicked
|
328 |
logging.info(f"Exploring {plot_id_clicked}. Hiding other plots/sections.")
|
329 |
|
|
|
335 |
panel_vis_updates.append(gr.update(visible=is_target_plot))
|
336 |
explore_btns_updates.append(gr.update(value=self.ACTIVE_ICON if is_target_plot else self.EXPLORE_ICON))
|
337 |
|
338 |
+
if current_active_panel_action_state:
|
339 |
logging.info("Closing active insight/formula panel due to explore click.")
|
340 |
action_col_upd = gr.update(visible=False)
|
341 |
+
new_active_panel_state_upd = None
|
|
|
342 |
bomb_btns_updates = [gr.update(value=self.BOMB_ICON) for _ in PLOT_CONFIGS]
|
343 |
formula_btns_updates = [gr.update(value=self.FORMULA_ICON) for _ in PLOT_CONFIGS]
|
344 |
+
formula_hint_upd = gr.update(visible=False)
|
345 |
|
|
|
346 |
final_explore_updates = [
|
347 |
+
new_explored_id_to_set,
|
348 |
+
action_col_upd,
|
349 |
+
new_active_panel_state_upd,
|
350 |
+
formula_hint_upd
|
351 |
]
|
352 |
+
final_explore_updates.extend(panel_vis_updates)
|
353 |
+
final_explore_updates.extend(explore_btns_updates)
|
354 |
+
final_explore_updates.extend(bomb_btns_updates)
|
355 |
+
final_explore_updates.extend(formula_btns_updates)
|
356 |
+
final_explore_updates.extend(section_title_vis_updates)
|
357 |
|
358 |
logging.debug(f"handle_explore_click returning {len(final_explore_updates)} updates. Expected {4 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
|
359 |
return final_explore_updates
|
360 |
|
361 |
def _create_panel_action_handler(self, p_id, action_type_str):
|
|
|
|
|
|
|
362 |
async def _handler(curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id):
|
363 |
return await self._handle_panel_action(p_id, action_type_str, curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id)
|
364 |
return _handler
|
365 |
+
|
366 |
+
# =========================================================================
|
367 |
+
# == MODIFIED FUNCTION: _refresh_analytics_graphs_ui
|
368 |
+
# =========================================================================
|
369 |
async def _refresh_analytics_graphs_ui(self, current_token_state_val, date_filter_val, custom_start_val, custom_end_val, current_chat_histories_val):
|
370 |
logging.info("Refreshing analytics graph UI elements and resetting actions/chat (within module).")
|
371 |
start_time = time.time()
|
372 |
|
373 |
+
# --- FIX STARTS HERE ---
|
374 |
+
# The original code used complex slicing (plot_gen_results[1:-1]) which is brittle.
|
375 |
+
# It assumes the figures are returned as a flat list. If update_analytics_plots_figures
|
376 |
+
# returns a more standard (status, [list_of_figs], summary) tuple, the slicing fails.
|
377 |
+
# This new unpacking is more robust and assumes update_analytics_plots_figures returns
|
378 |
+
# a 3-element tuple/list where the second element is the list of figures.
|
379 |
plot_gen_results = self.update_analytics_plots_figures(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, PLOT_CONFIGS)
|
380 |
+
|
381 |
+
# This direct unpacking is safer than slicing.
|
382 |
+
# It assumes `update_analytics_plots_figures` returns a 3-element structure like:
|
383 |
+
# (status_string, list_of_figure_objects, summaries_dict)
|
384 |
+
try:
|
385 |
+
status_msg, gen_figs, new_summaries_for_chatbot = plot_gen_results
|
386 |
+
except (ValueError, TypeError) as e:
|
387 |
+
logging.error(f"Could not unpack results from update_analytics_plots_figures. Error: {e}")
|
388 |
+
logging.error(f"Expected 3 elements (status, figs_list, summaries), but received {len(plot_gen_results)} elements.")
|
389 |
+
# Fallback to error state
|
390 |
+
status_msg = f"Errore: L'aggiornamento dei grafici non è riuscito a causa di un formato di dati imprevisto."
|
391 |
+
gen_figs = [self.create_placeholder_plot("Error", f"Dati non validi {i}") for i in range(len(PLOT_CONFIGS))]
|
392 |
+
new_summaries_for_chatbot = {}
|
393 |
+
|
394 |
+
# --- FIX ENDS HERE ---
|
395 |
|
396 |
all_updates = []
|
397 |
# 1. Status Markdown
|
398 |
all_updates.append(status_msg) # For self.analytics_status_md
|
399 |
|
400 |
# 2. Plot components
|
401 |
+
# This check is now more likely to succeed with the corrected unpacking.
|
402 |
+
if isinstance(gen_figs, list) and len(gen_figs) == len(PLOT_CONFIGS):
|
403 |
all_updates.extend(gen_figs)
|
404 |
else:
|
405 |
+
logging.error(f"Mismatch in generated figures ({len(gen_figs) if isinstance(gen_figs, list) else 'N/A'}) and plot_configs ({len(PLOT_CONFIGS)})")
|
406 |
+
# If there's still a mismatch, create placeholders to avoid crashing Gradio
|
407 |
all_updates.extend([self.create_placeholder_plot("Error", f"Figura mancante {i}") for i in range(len(PLOT_CONFIGS))])
|
408 |
|
409 |
# 3. UI Resets for Action Panel (9 components)
|
|
|
421 |
all_updates.extend([
|
422 |
None, # active_panel_action_state (reset)
|
423 |
None, # current_chat_plot_id_st (reset)
|
424 |
+
{}, # chat_histories_st (reset all chats on refresh)
|
425 |
new_summaries_for_chatbot # plot_data_for_chatbot_st (update with new summaries)
|
426 |
])
|
427 |
+
|
|
|
|
|
428 |
# 5. Plot-specific UI Resets (4 components per plot)
|
429 |
for _ in PLOT_CONFIGS:
|
430 |
all_updates.extend([
|
|
|
504 |
self.explore_outputs_list.extend([self.plot_ui_objects.get(pc["id"], {}).get("formula_button", gr.update()) for pc in PLOT_CONFIGS])# For resetting if panel closes
|
505 |
self.explore_outputs_list.extend([self.section_titles_map.get(s_name, gr.update()) for s_name in UNIQUE_ORDERED_SECTIONS])
|
506 |
|
|
|
507 |
def _setup_callbacks(self):
|
508 |
# Apply filter button
|
509 |
graph_refresh_inputs = [
|
510 |
self.token_state, self.date_filter_selector,
|
511 |
self.custom_start_date_picker, self.custom_end_date_picker,
|
512 |
+
self.chat_histories_st
|
513 |
]
|
514 |
self.apply_filter_btn.click(
|
515 |
fn=self._refresh_analytics_graphs_ui,
|
|
|
546 |
api_name=f"action_formula_{plot_id}_module"
|
547 |
)
|
548 |
if ui_obj.get("explore_button"):
|
|
|
549 |
ui_obj["explore_button"].click(
|
550 |
fn=lambda current_explored_val, current_active_panel_val, p_id=plot_id: self._handle_explore_click(p_id, current_explored_val, current_active_panel_val),
|
551 |
inputs=explore_click_inputs,
|
|
|
574 |
]
|
575 |
self.insights_suggestion_1_btn.click(
|
576 |
fn=self._handle_suggested_question_click,
|
577 |
+
inputs=[self.insights_suggestion_1_btn] + suggestion_click_inputs_base,
|
578 |
outputs=chat_submission_outputs,
|
579 |
api_name="click_suggestion_1_module"
|
580 |
)
|
|
|
592 |
)
|
593 |
|
594 |
def create_tab_ui(self):
|
595 |
+
with gr.TabItem("📊 Grafici", id="tab_analytics_module"):
|
|
|
596 |
|
597 |
gr.Markdown("## 📈 Analisi Performance LinkedIn")
|
598 |
gr.Markdown("Seleziona un intervallo di date per i grafici. Clicca i pulsanti (💣 Insights, ƒ Formula, 🧭 Esplora) su un grafico per azioni.")
|
|
|
615 |
outputs=[self.custom_start_date_picker, self.custom_end_date_picker]
|
616 |
)
|
617 |
|
|
|
618 |
with gr.Row(equal_height=False):
|
619 |
with gr.Column(scale=8) as self.plots_area_col:
|
620 |
+
ui_elements_tuple = self.build_analytics_tab_plot_area(PLOT_CONFIGS)
|
|
|
621 |
if isinstance(ui_elements_tuple, tuple) and len(ui_elements_tuple) == 2:
|
622 |
self.plot_ui_objects, self.section_titles_map = ui_elements_tuple
|
|
|
623 |
if not all(sec_name in self.section_titles_map for sec_name in UNIQUE_ORDERED_SECTIONS):
|
624 |
logging.error("section_titles_map from build_analytics_tab_plot_area is incomplete in module.")
|
|
|
625 |
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
626 |
if sec_name not in self.section_titles_map:
|
627 |
logging.warning(f"Creating fallback Markdown for missing section title: {sec_name}")
|
628 |
self.section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
629 |
else:
|
630 |
logging.error("build_analytics_tab_plot_area did not return a tuple of (plot_ui_objects, section_titles_map). Using fallback.")
|
|
|
631 |
self.plot_ui_objects = ui_elements_tuple if isinstance(ui_elements_tuple, dict) else {}
|
632 |
+
for sec_name in UNIQUE_ORDERED_SECTIONS:
|
633 |
+
self.section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
|
|
634 |
|
635 |
with gr.Column(scale=4, visible=False) as self.global_actions_column_ui:
|
636 |
gr.Markdown("### 💡 Azioni Contestuali Grafico")
|
|
|
656 |
visible=False
|
657 |
)
|
658 |
|
|
|
659 |
self._define_callback_outputs()
|
|
|
660 |
self._setup_callbacks()
|
|
|
|
|
|