Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -5,52 +5,30 @@ import os
|
|
5 |
import logging
|
6 |
import matplotlib
|
7 |
matplotlib.use('Agg') # Set backend for Matplotlib to avoid GUI conflicts with Gradio
|
8 |
-
import
|
9 |
-
|
10 |
-
|
11 |
-
import
|
12 |
-
from collections import OrderedDict, defaultdict # To maintain section order and for OKR processing
|
13 |
-
import asyncio # For async operations
|
14 |
|
15 |
# --- Module Imports ---
|
16 |
from utils.gradio_utils import get_url_user_token
|
17 |
-
# Functions from newly created/refactored modules
|
18 |
from config import (
|
19 |
LINKEDIN_CLIENT_ID_ENV_VAR, BUBBLE_APP_NAME_ENV_VAR,
|
20 |
-
BUBBLE_API_KEY_PRIVATE_ENV_VAR, BUBBLE_API_ENDPOINT_ENV_VAR
|
21 |
-
PLOT_ID_TO_FORMULA_KEY_MAP)
|
22 |
from services.state_manager import process_and_store_bubble_token
|
23 |
from services.sync_logic import sync_all_linkedin_data_orchestrator
|
24 |
-
from ui.ui_generators import
|
25 |
-
display_main_dashboard,
|
26 |
-
build_analytics_tab_plot_area, # EXPECTED TO RETURN: plot_ui_objects, section_titles_map
|
27 |
-
BOMB_ICON, EXPLORE_ICON, FORMULA_ICON, ACTIVE_ICON
|
28 |
-
)
|
29 |
-
from ui.analytics_plot_generator import update_analytics_plots_figures, create_placeholder_plot
|
30 |
-
from formulas import PLOT_FORMULAS
|
31 |
|
32 |
-
# ---
|
33 |
-
from
|
34 |
-
from
|
35 |
-
# --- END EXISTING CHATBOT MODULE IMPORTS ---
|
36 |
|
37 |
-
# ---
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
format_single_okr_for_display
|
44 |
-
)
|
45 |
-
AGENTIC_MODULES_LOADED = True
|
46 |
-
except ImportError as e:
|
47 |
-
logging.error(f"Could not import agentic pipeline modules: {e}. Tabs 3 and 4 (formerly 5 and 6) will be disabled.")
|
48 |
-
AGENTIC_MODULES_LOADED = False
|
49 |
-
# Define placeholder functions if modules are not loaded to avoid NameErrors
|
50 |
-
async def run_full_analytics_orchestration(*args, **kwargs): return None
|
51 |
-
def format_report_to_markdown(report_string): return "Agentic modules not loaded. Report unavailable."
|
52 |
-
def extract_key_results_for_selection(okrs_dict): return []
|
53 |
-
def format_single_okr_for_display(okr_data, **kwargs): return "Agentic modules not loaded. OKR display unavailable."
|
54 |
|
55 |
# Configure logging
|
56 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
|
@@ -58,532 +36,177 @@ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(
|
|
58 |
# 1. Set Vertex AI usage preference (if applicable)
|
59 |
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "False"
|
60 |
|
61 |
-
# 2. Get your API key
|
62 |
user_provided_api_key = os.environ.get("GEMINI_API_KEY")
|
63 |
-
|
64 |
if user_provided_api_key:
|
65 |
os.environ["GOOGLE_API_KEY"] = user_provided_api_key
|
66 |
logging.info("GOOGLE_API_KEY environment variable has been set from GEMINI_API_KEY.")
|
67 |
else:
|
68 |
-
logging.error(f"CRITICAL ERROR: The API key environment variable 'GEMINI_API_KEY' was not found.
|
69 |
|
70 |
|
71 |
# --- Gradio UI Blocks ---
|
72 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
|
73 |
-
|
|
|
|
|
74 |
token_state = gr.State(value={
|
75 |
"token": None, "client_id": None, "org_urn": None,
|
76 |
"bubble_posts_df": pd.DataFrame(), "bubble_post_stats_df": pd.DataFrame(),
|
77 |
-
"bubble_mentions_df": pd.DataFrame(),
|
78 |
-
"bubble_follower_stats_df": pd.DataFrame(), # Data still in state, but not used by UI
|
79 |
"fetch_count_for_api": 0, "url_user_token_temp_storage": None,
|
80 |
"config_date_col_posts": "published_at", "config_date_col_mentions": "date",
|
81 |
"config_date_col_followers": "date", "config_media_type_col": "media_type",
|
82 |
"config_eb_labels_col": "li_eb_label"
|
83 |
})
|
84 |
|
85 |
-
# States for
|
86 |
chat_histories_st = gr.State({})
|
87 |
current_chat_plot_id_st = gr.State(None)
|
88 |
-
plot_data_for_chatbot_st = gr.State({})
|
|
|
|
|
89 |
|
90 |
-
#
|
91 |
orchestration_raw_results_st = gr.State(None)
|
92 |
-
key_results_for_selection_st = gr.State([])
|
93 |
-
selected_key_result_ids_st = gr.State([])
|
94 |
-
|
95 |
|
|
|
96 |
gr.Markdown("# 🚀 LinkedIn Organization Dashboard")
|
97 |
url_user_token_display = gr.Textbox(label="User Token (Nascosto)", interactive=False, visible=False)
|
98 |
status_box = gr.Textbox(label="Stato Generale Token LinkedIn", interactive=False, value="Inizializzazione...")
|
99 |
org_urn_display = gr.Textbox(label="URN Organizzazione (Nascosto)", interactive=False, visible=False)
|
100 |
|
|
|
101 |
app.load(fn=get_url_user_token, inputs=None, outputs=[url_user_token_display, org_urn_display], api_name="get_url_params", show_progress=False)
|
102 |
|
103 |
-
|
104 |
-
status_msg, new_state, btn_update = process_and_store_bubble_token(url_token, org_urn_val, current_state)
|
105 |
-
dashboard_content = display_main_dashboard(new_state)
|
106 |
-
return status_msg, new_state, btn_update, dashboard_content
|
107 |
-
|
108 |
with gr.Tabs() as tabs:
|
|
|
109 |
with gr.TabItem("1️⃣ Dashboard & Sync", id="tab_dashboard_sync"):
|
110 |
gr.Markdown("Il sistema controlla i dati esistenti da Bubble. 'Sincronizza' si attiva se sono necessari nuovi dati.")
|
111 |
sync_data_btn = gr.Button("🔄 Sincronizza Dati LinkedIn", variant="primary", visible=False, interactive=False)
|
112 |
sync_status_html_output = gr.HTML("<p style='text-align:center;'>Stato sincronizzazione...</p>")
|
113 |
dashboard_display_html = gr.HTML("<p style='text-align:center;'>Caricamento dashboard...</p>")
|
114 |
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
custom_start_date_picker = gr.DateTime(label="Data Inizio", visible=False, include_time=False, type="datetime")
|
127 |
-
custom_end_date_picker = gr.DateTime(label="Data Fine", visible=False, include_time=False, type="datetime")
|
128 |
-
|
129 |
-
apply_filter_btn = gr.Button("🔍 Applica Filtro & Aggiorna Grafici", variant="primary")
|
130 |
-
|
131 |
-
def toggle_custom_date_pickers(selection):
|
132 |
-
is_custom = selection == "Intervallo Personalizzato"
|
133 |
-
return gr.update(visible=is_custom), gr.update(visible=is_custom)
|
134 |
-
|
135 |
-
date_filter_selector.change(
|
136 |
-
fn=toggle_custom_date_pickers,
|
137 |
-
inputs=[date_filter_selector],
|
138 |
-
outputs=[custom_start_date_picker, custom_end_date_picker]
|
139 |
)
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
{"label": "Follower per Anzianità", "id": "followers_by_seniority", "section": "Demografia Follower"},
|
148 |
-
{"label": "Tasso di Engagement nel Tempo", "id": "engagement_rate", "section": "Approfondimenti Performance Post"},
|
149 |
-
{"label": "Copertura nel Tempo", "id": "reach_over_time", "section": "Approfondimenti Performance Post"},
|
150 |
-
{"label": "Visualizzazioni nel Tempo", "id": "impressions_over_time", "section": "Approfondimenti Performance Post"},
|
151 |
-
{"label": "Reazioni (Like) nel Tempo", "id": "likes_over_time", "section": "Approfondimenti Performance Post"},
|
152 |
-
{"label": "Click nel Tempo", "id": "clicks_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
153 |
-
{"label": "Condivisioni nel Tempo", "id": "shares_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
154 |
-
{"label": "Commenti nel Tempo", "id": "comments_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
|
155 |
-
{"label": "Ripartizione Commenti per Sentiment", "id": "comments_sentiment", "section": "Engagement Dettagliato Post nel Tempo"},
|
156 |
-
{"label": "Frequenza Post", "id": "post_frequency_cs", "section": "Analisi Strategia Contenuti"},
|
157 |
-
{"label": "Ripartizione Contenuti per Formato", "id": "content_format_breakdown_cs", "section": "Analisi Strategia Contenuti"},
|
158 |
-
{"label": "Ripartizione Contenuti per Argomenti", "id": "content_topic_breakdown_cs", "section": "Analisi Strategia Contenuti"},
|
159 |
-
{"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"}, # This plot might need data from the removed mentions tab. Consider if this plot should also be removed or if its data source is independent.
|
160 |
-
{"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"} # Same as above.
|
161 |
-
]
|
162 |
-
# IMPORTANT: Review if 'mention_analysis_volume' and 'mention_analysis_sentiment' plots
|
163 |
-
# can still be generated without the dedicated mentions data processing.
|
164 |
-
# If not, they should also be removed from plot_configs.
|
165 |
-
# For now, I am assuming they might draw from a general data pool in token_state.
|
166 |
-
|
167 |
-
assert len(plot_configs) == 19, "Mancata corrispondenza in plot_configs e grafici attesi. (If mentions plots were removed, adjust this number)"
|
168 |
-
|
169 |
-
unique_ordered_sections = list(OrderedDict.fromkeys(pc["section"] for pc in plot_configs))
|
170 |
-
num_unique_sections = len(unique_ordered_sections)
|
171 |
-
|
172 |
-
active_panel_action_state = gr.State(None)
|
173 |
-
explored_plot_id_state = gr.State(None)
|
174 |
-
|
175 |
-
plot_ui_objects = {}
|
176 |
-
section_titles_map = {}
|
177 |
-
|
178 |
-
with gr.Row(equal_height=False):
|
179 |
-
with gr.Column(scale=8) as plots_area_col:
|
180 |
-
ui_elements_tuple = build_analytics_tab_plot_area(plot_configs)
|
181 |
-
if isinstance(ui_elements_tuple, tuple) and len(ui_elements_tuple) == 2:
|
182 |
-
plot_ui_objects, section_titles_map = ui_elements_tuple
|
183 |
-
if not all(sec_name in section_titles_map for sec_name in unique_ordered_sections):
|
184 |
-
logging.error("section_titles_map from build_analytics_tab_plot_area is incomplete.")
|
185 |
-
for sec_name in unique_ordered_sections:
|
186 |
-
if sec_name not in section_titles_map:
|
187 |
-
section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
188 |
-
else:
|
189 |
-
logging.error("build_analytics_tab_plot_area did not return a tuple of (plot_ui_objects, section_titles_map).")
|
190 |
-
plot_ui_objects = ui_elements_tuple if isinstance(ui_elements_tuple, dict) else {}
|
191 |
-
for sec_name in unique_ordered_sections:
|
192 |
-
section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
|
193 |
-
|
194 |
-
|
195 |
-
with gr.Column(scale=4, visible=False) as global_actions_column_ui:
|
196 |
-
gr.Markdown("### 💡 Azioni Contestuali Grafico")
|
197 |
-
insights_chatbot_ui = gr.Chatbot(
|
198 |
-
label="Chat Insights", type="messages", height=450,
|
199 |
-
bubble_full_width=False, visible=False, show_label=False,
|
200 |
-
placeholder="L'analisi AI del grafico apparirà qui. Fai domande di approfondimento!"
|
201 |
-
)
|
202 |
-
insights_chat_input_ui = gr.Textbox(
|
203 |
-
label="La tua domanda:", placeholder="Chiedi all'AI riguardo a questo grafico...",
|
204 |
-
lines=2, visible=False, show_label=False
|
205 |
-
)
|
206 |
-
with gr.Row(visible=False) as insights_suggestions_row_ui:
|
207 |
-
insights_suggestion_1_btn = gr.Button(value="Suggerimento 1", size="sm", min_width=50)
|
208 |
-
insights_suggestion_2_btn = gr.Button(value="Suggerimento 2", size="sm", min_width=50)
|
209 |
-
insights_suggestion_3_btn = gr.Button(value="Suggerimento 3", size="sm", min_width=50)
|
210 |
-
|
211 |
-
formula_display_markdown_ui = gr.Markdown(
|
212 |
-
"I dettagli sulla formula/metodologia appariranno qui.", visible=False
|
213 |
-
)
|
214 |
-
formula_close_hint_md = gr.Markdown(
|
215 |
-
"<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>",
|
216 |
-
visible=False
|
217 |
-
)
|
218 |
-
|
219 |
-
async def handle_panel_action(
|
220 |
-
plot_id_clicked: str, action_type: str, current_active_action_from_state: dict,
|
221 |
-
current_chat_histories: dict, current_chat_plot_id: str,
|
222 |
-
current_plot_data_for_chatbot: dict, current_explored_plot_id: str
|
223 |
-
):
|
224 |
-
logging.info(f"Panel Action: '{action_type}' for plot '{plot_id_clicked}'. Active: {current_active_action_from_state}, Explored: {current_explored_plot_id}")
|
225 |
-
clicked_plot_config = next((p for p in plot_configs if p["id"] == plot_id_clicked), None)
|
226 |
-
if not clicked_plot_config:
|
227 |
-
logging.error(f"Config not found for plot_id {plot_id_clicked}")
|
228 |
-
num_plots = len(plot_configs)
|
229 |
-
error_list_len = 15 + (4 * num_plots) + num_unique_sections
|
230 |
-
error_list = [gr.update()] * error_list_len
|
231 |
-
error_list[11] = current_active_action_from_state; error_list[12] = current_chat_plot_id
|
232 |
-
error_list[13] = current_chat_histories; error_list[14] = current_explored_plot_id
|
233 |
-
return error_list
|
234 |
-
clicked_plot_label = clicked_plot_config["label"]; clicked_plot_section = clicked_plot_config["section"]
|
235 |
-
hypothetical_new_active_state = {"plot_id": plot_id_clicked, "type": action_type}
|
236 |
-
is_toggling_off = current_active_action_from_state == hypothetical_new_active_state
|
237 |
-
action_col_visible_update = gr.update(visible=False)
|
238 |
-
insights_chatbot_visible_update, insights_chat_input_visible_update, insights_suggestions_row_visible_update = gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
239 |
-
formula_display_visible_update = gr.update(visible=False); formula_close_hint_visible_update = gr.update(visible=False)
|
240 |
-
chatbot_content_update, s1_upd, s2_upd, s3_upd, formula_content_update = gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
241 |
-
new_active_action_state_to_set, new_current_chat_plot_id = None, current_chat_plot_id
|
242 |
-
updated_chat_histories, new_explored_plot_id_to_set = current_chat_histories, current_explored_plot_id
|
243 |
-
generated_panel_vis_updates = []; generated_bomb_btn_updates = []; generated_formula_btn_updates = []; generated_explore_btn_updates = []
|
244 |
-
section_title_vis_updates = [gr.update()] * num_unique_sections
|
245 |
-
if is_toggling_off:
|
246 |
-
new_active_action_state_to_set = None; action_col_visible_update = gr.update(visible=False)
|
247 |
-
logging.info(f"Toggling OFF panel {action_type} for {plot_id_clicked}.")
|
248 |
-
for _ in plot_configs: generated_bomb_btn_updates.append(gr.update(value=BOMB_ICON)); generated_formula_btn_updates.append(gr.update(value=FORMULA_ICON))
|
249 |
-
if current_explored_plot_id:
|
250 |
-
explored_cfg = next((p for p in plot_configs if p["id"] == current_explored_plot_id), None)
|
251 |
-
explored_sec = explored_cfg["section"] if explored_cfg else None
|
252 |
-
for i, sec_name in enumerate(unique_ordered_sections): section_title_vis_updates[i] = gr.update(visible=(sec_name == explored_sec))
|
253 |
-
for cfg in plot_configs: is_exp = (cfg["id"] == current_explored_plot_id); generated_panel_vis_updates.append(gr.update(visible=is_exp)); generated_explore_btn_updates.append(gr.update(value=ACTIVE_ICON if is_exp else EXPLORE_ICON))
|
254 |
-
else:
|
255 |
-
for i in range(num_unique_sections): section_title_vis_updates[i] = gr.update(visible=True)
|
256 |
-
for _ in plot_configs: generated_panel_vis_updates.append(gr.update(visible=True)); generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON))
|
257 |
-
if action_type == "insights": new_current_chat_plot_id = None
|
258 |
-
else:
|
259 |
-
new_active_action_state_to_set = hypothetical_new_active_state; action_col_visible_update = gr.update(visible=True)
|
260 |
-
new_explored_plot_id_to_set = None
|
261 |
-
logging.info(f"Toggling ON panel {action_type} for {plot_id_clicked}. Cancelling explore view if any.")
|
262 |
-
for i, sec_name in enumerate(unique_ordered_sections): section_title_vis_updates[i] = gr.update(visible=(sec_name == clicked_plot_section))
|
263 |
-
for cfg in plot_configs: generated_panel_vis_updates.append(gr.update(visible=(cfg["id"] == plot_id_clicked))); generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON))
|
264 |
-
for cfg_btn in plot_configs:
|
265 |
-
is_act_ins = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "insights"}
|
266 |
-
is_act_for = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "formula"}
|
267 |
-
generated_bomb_btn_updates.append(gr.update(value=ACTIVE_ICON if is_act_ins else BOMB_ICON)); generated_formula_btn_updates.append(gr.update(value=ACTIVE_ICON if is_act_for else FORMULA_ICON))
|
268 |
-
if action_type == "insights":
|
269 |
-
insights_chatbot_visible_update, insights_chat_input_visible_update, insights_suggestions_row_visible_update = gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
270 |
-
new_current_chat_plot_id = plot_id_clicked
|
271 |
-
history = current_chat_histories.get(plot_id_clicked, [])
|
272 |
-
summary = current_plot_data_for_chatbot.get(plot_id_clicked, f"No summary for '{clicked_plot_label}'.")
|
273 |
-
if not history:
|
274 |
-
prompt, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)
|
275 |
-
llm_hist = [{"role": "user", "content": prompt}]
|
276 |
-
resp = await generate_llm_response(prompt, plot_id_clicked, clicked_plot_label, llm_hist, summary)
|
277 |
-
history = [{"role": "assistant", "content": resp}]; updated_chat_histories = {**current_chat_histories, plot_id_clicked: history}
|
278 |
-
else: _, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)
|
279 |
-
chatbot_content_update = gr.update(value=history)
|
280 |
-
s1_upd,s2_upd,s3_upd = gr.update(value=sugg[0] if sugg else "N/A"),gr.update(value=sugg[1] if len(sugg)>1 else "N/A"),gr.update(value=sugg[2] if len(sugg)>2 else "N/A")
|
281 |
-
elif action_type == "formula":
|
282 |
-
formula_display_visible_update = gr.update(visible=True); formula_close_hint_visible_update = gr.update(visible=True)
|
283 |
-
f_key = PLOT_ID_TO_FORMULA_KEY_MAP.get(plot_id_clicked)
|
284 |
-
f_text = f"**Formula/Methodology for: {clicked_plot_label}** (ID: `{plot_id_clicked}`)\n\n"
|
285 |
-
if f_key and f_key in PLOT_FORMULAS: f_data = PLOT_FORMULAS[f_key]; f_text += f"### {f_data['title']}\n\n{f_data['description']}\n\n**Calculation:**\n" + "\n".join([f"- {s}" for s in f_data['calculation_steps']])
|
286 |
-
else: f_text += "(No detailed formula information found.)"
|
287 |
-
formula_content_update = gr.update(value=f_text); new_current_chat_plot_id = None
|
288 |
-
final_updates = [action_col_visible_update, insights_chatbot_visible_update, chatbot_content_update, insights_chat_input_visible_update, insights_suggestions_row_visible_update, s1_upd, s2_upd, s3_upd, formula_display_visible_update, formula_content_update, formula_close_hint_visible_update, new_active_action_state_to_set, new_current_chat_plot_id, updated_chat_histories, new_explored_plot_id_to_set]
|
289 |
-
final_updates.extend(generated_panel_vis_updates); final_updates.extend(generated_bomb_btn_updates); final_updates.extend(generated_formula_btn_updates); final_updates.extend(generated_explore_btn_updates); final_updates.extend(section_title_vis_updates)
|
290 |
-
logging.debug(f"handle_panel_action returning {len(final_updates)} updates. Expected {15 + 4*len(plot_configs) + num_unique_sections}.")
|
291 |
-
return final_updates
|
292 |
-
|
293 |
-
async def handle_chat_message_submission(user_message: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict ):
|
294 |
-
if not current_plot_id or not user_message.strip():
|
295 |
-
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
296 |
-
if not isinstance(current_history_for_plot, list): current_history_for_plot = []
|
297 |
-
yield current_history_for_plot, gr.update(value=""), chat_histories; return
|
298 |
-
cfg = next((p for p in plot_configs if p["id"] == current_plot_id), None)
|
299 |
-
lbl = cfg["label"] if cfg else "Selected Plot"
|
300 |
-
summary = current_plot_data_for_chatbot.get(current_plot_id, f"No summary for '{lbl}'.")
|
301 |
-
hist_for_plot = chat_histories.get(current_plot_id, [])
|
302 |
-
if not isinstance(hist_for_plot, list): hist_for_plot = []
|
303 |
-
hist = hist_for_plot.copy() + [{"role": "user", "content": user_message}]
|
304 |
-
yield hist, gr.update(value=""), chat_histories
|
305 |
-
resp = await generate_llm_response(user_message, current_plot_id, lbl, hist, summary)
|
306 |
-
hist.append({"role": "assistant", "content": resp})
|
307 |
-
updated_chat_histories = {**chat_histories, current_plot_id: hist}
|
308 |
-
yield hist, "", updated_chat_histories
|
309 |
-
|
310 |
-
async def handle_suggested_question_click(suggestion_text: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
|
311 |
-
if not current_plot_id or not suggestion_text.strip() or suggestion_text == "N/A":
|
312 |
-
current_history_for_plot = chat_histories.get(current_plot_id, [])
|
313 |
-
if not isinstance(current_history_for_plot, list): current_history_for_plot = []
|
314 |
-
yield current_history_for_plot, gr.update(value=""), chat_histories; return
|
315 |
-
async for update_chunk in handle_chat_message_submission(suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot):
|
316 |
-
yield update_chunk
|
317 |
-
|
318 |
-
def handle_explore_click(plot_id_clicked, current_explored_plot_id_from_state, current_active_panel_action_state):
|
319 |
-
logging.info(f"Explore Click: Plot '{plot_id_clicked}'. Current Explored: {current_explored_plot_id_from_state}. Active Panel: {current_active_panel_action_state}")
|
320 |
-
num_plots = len(plot_configs)
|
321 |
-
if not plot_ui_objects:
|
322 |
-
logging.error("plot_ui_objects not populated for handle_explore_click.")
|
323 |
-
error_list_len = 4 + (4 * num_plots) + num_unique_sections; error_list = [gr.update()] * error_list_len
|
324 |
-
error_list[0] = current_explored_plot_id_from_state; error_list[2] = current_active_panel_action_state
|
325 |
-
return error_list
|
326 |
-
new_explored_id_to_set = None
|
327 |
-
is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)
|
328 |
-
action_col_upd = gr.update(); new_active_panel_state_upd = current_active_panel_action_state; formula_hint_upd = gr.update(visible=False)
|
329 |
-
panel_vis_updates = []; explore_btns_updates = []; bomb_btns_updates = []; formula_btns_updates = []
|
330 |
-
section_title_vis_updates = [gr.update()] * num_unique_sections
|
331 |
-
clicked_cfg = next((p for p in plot_configs if p["id"] == plot_id_clicked), None)
|
332 |
-
sec_of_clicked = clicked_cfg["section"] if clicked_cfg else None
|
333 |
-
if is_toggling_off_explore:
|
334 |
-
new_explored_id_to_set = None
|
335 |
-
logging.info(f"Stopping explore for {plot_id_clicked}. All plots/sections to be visible.")
|
336 |
-
for i in range(num_unique_sections): section_title_vis_updates[i] = gr.update(visible=True)
|
337 |
-
for _ in plot_configs: panel_vis_updates.append(gr.update(visible=True)); explore_btns_updates.append(gr.update(value=EXPLORE_ICON)); bomb_btns_updates.append(gr.update()); formula_btns_updates.append(gr.update())
|
338 |
-
else:
|
339 |
-
new_explored_id_to_set = plot_id_clicked
|
340 |
-
logging.info(f"Exploring {plot_id_clicked}. Hiding other plots/sections.")
|
341 |
-
for i, sec_name in enumerate(unique_ordered_sections): section_title_vis_updates[i] = gr.update(visible=(sec_name == sec_of_clicked))
|
342 |
-
for cfg in plot_configs: is_target = (cfg["id"] == new_explored_id_to_set); panel_vis_updates.append(gr.update(visible=is_target)); explore_btns_updates.append(gr.update(value=ACTIVE_ICON if is_target else EXPLORE_ICON))
|
343 |
-
if current_active_panel_action_state:
|
344 |
-
logging.info("Closing active insight/formula panel due to explore click.")
|
345 |
-
action_col_upd = gr.update(visible=False); new_active_panel_state_upd = None; formula_hint_upd = gr.update(visible=False)
|
346 |
-
bomb_btns_updates = [gr.update(value=BOMB_ICON) for _ in plot_configs]; formula_btns_updates = [gr.update(value=FORMULA_ICON) for _ in plot_configs]
|
347 |
-
else: bomb_btns_updates = [gr.update() for _ in plot_configs]; formula_btns_updates = [gr.update() for _ in plot_configs]
|
348 |
-
final_explore_updates = [new_explored_id_to_set, action_col_upd, new_active_panel_state_upd, formula_hint_upd]
|
349 |
-
final_explore_updates.extend(panel_vis_updates); final_explore_updates.extend(explore_btns_updates); final_explore_updates.extend(bomb_btns_updates); final_explore_updates.extend(formula_btns_updates); final_explore_updates.extend(section_title_vis_updates)
|
350 |
-
logging.debug(f"handle_explore_click returning {len(final_explore_updates)} updates. Expected {4 + 4*len(plot_configs) + num_unique_sections}.")
|
351 |
-
return final_explore_updates
|
352 |
-
|
353 |
-
_base_action_panel_ui_outputs = [global_actions_column_ui, insights_chatbot_ui, insights_chatbot_ui, insights_chat_input_ui, insights_suggestions_row_ui, insights_suggestion_1_btn, insights_suggestion_2_btn, insights_suggestion_3_btn, formula_display_markdown_ui, formula_display_markdown_ui, formula_close_hint_md]
|
354 |
-
_action_panel_state_outputs = [active_panel_action_state, current_chat_plot_id_st, chat_histories_st, explored_plot_id_state]
|
355 |
-
action_panel_outputs_list = _base_action_panel_ui_outputs + _action_panel_state_outputs
|
356 |
-
action_panel_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("panel_component", gr.update()) for pc in plot_configs]); action_panel_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("bomb_button", gr.update()) for pc in plot_configs]); action_panel_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("formula_button", gr.update()) for pc in plot_configs]); action_panel_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("explore_button", gr.update()) for pc in plot_configs]); action_panel_outputs_list.extend([section_titles_map.get(s_name, gr.update()) for s_name in unique_ordered_sections])
|
357 |
-
_explore_base_outputs = [explored_plot_id_state, global_actions_column_ui, active_panel_action_state, formula_close_hint_md]
|
358 |
-
explore_outputs_list = _explore_base_outputs
|
359 |
-
explore_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("panel_component", gr.update()) for pc in plot_configs]); explore_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("explore_button", gr.update()) for pc in plot_configs]); explore_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("bomb_button", gr.update()) for pc in plot_configs]); explore_outputs_list.extend([plot_ui_objects.get(pc["id"], {}).get("formula_button", gr.update()) for pc in plot_configs]); explore_outputs_list.extend([section_titles_map.get(s_name, gr.update()) for s_name in unique_ordered_sections])
|
360 |
-
action_click_inputs = [active_panel_action_state, chat_histories_st, current_chat_plot_id_st, plot_data_for_chatbot_st, explored_plot_id_state]
|
361 |
-
explore_click_inputs = [explored_plot_id_state, active_panel_action_state]
|
362 |
-
def create_panel_action_handler(p_id, action_type_str):
|
363 |
-
async def _handler(curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id): 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)
|
364 |
-
return _handler
|
365 |
-
for config_item in plot_configs:
|
366 |
-
plot_id = config_item["id"]
|
367 |
-
if plot_id in plot_ui_objects:
|
368 |
-
ui_obj = plot_ui_objects[plot_id]
|
369 |
-
if ui_obj.get("bomb_button"): ui_obj["bomb_button"].click(fn=create_panel_action_handler(plot_id, "insights"), inputs=action_click_inputs, outputs=action_panel_outputs_list, api_name=f"action_insights_{plot_id}")
|
370 |
-
if ui_obj.get("formula_button"): ui_obj["formula_button"].click(fn=create_panel_action_handler(plot_id, "formula"), inputs=action_click_inputs, outputs=action_panel_outputs_list, api_name=f"action_formula_{plot_id}")
|
371 |
-
if ui_obj.get("explore_button"): ui_obj["explore_button"].click(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), inputs=explore_click_inputs, outputs=explore_outputs_list, api_name=f"action_explore_{plot_id}")
|
372 |
-
else: logging.warning(f"UI object for plot_id '{plot_id}' not found for click handlers.")
|
373 |
-
chat_submission_outputs = [insights_chatbot_ui, insights_chat_input_ui, chat_histories_st]
|
374 |
-
chat_submission_inputs = [insights_chat_input_ui, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
|
375 |
-
insights_chat_input_ui.submit(fn=handle_chat_message_submission, inputs=chat_submission_inputs, outputs=chat_submission_outputs, api_name="submit_chat_message")
|
376 |
-
suggestion_click_inputs_base = [current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
|
377 |
-
insights_suggestion_1_btn.click(fn=handle_suggested_question_click, inputs=[insights_suggestion_1_btn] + suggestion_click_inputs_base, outputs=chat_submission_outputs, api_name="click_suggestion_1")
|
378 |
-
insights_suggestion_2_btn.click(fn=handle_suggested_question_click, inputs=[insights_suggestion_2_btn] + suggestion_click_inputs_base, outputs=chat_submission_outputs, api_name="click_suggestion_2")
|
379 |
-
insights_suggestion_3_btn.click(fn=handle_suggested_question_click, inputs=[insights_suggestion_3_btn] + suggestion_click_inputs_base, outputs=chat_submission_outputs, api_name="click_suggestion_3")
|
380 |
-
|
381 |
-
# Tab 3 (Menzioni) and Tab 4 (Statistiche Follower) are removed.
|
382 |
-
|
383 |
-
with gr.TabItem("3️⃣ Agentic Analysis Report", id="tab_agentic_report", visible=AGENTIC_MODULES_LOADED): # Renumbered from 5
|
384 |
-
gr.Markdown("## 🤖 Comprehensive Analysis Report (AI Generated)")
|
385 |
-
agentic_pipeline_status_md = gr.Markdown("Stato Pipeline AI (filtro 'Sempre'): In attesa...", visible=True)
|
386 |
-
gr.Markdown("Questo report è generato da un agente AI con filtro 'Sempre' sui dati disponibili. Rivedi criticamente.")
|
387 |
-
agentic_report_display_md = gr.Markdown("La pipeline AI si avvierà automaticamente dopo il caricamento iniziale dei dati o dopo una sincronizzazione.")
|
388 |
-
if not AGENTIC_MODULES_LOADED: gr.Markdown("🔴 **Error:** Agentic pipeline modules could not be loaded. This tab is disabled.")
|
389 |
-
|
390 |
-
with gr.TabItem("4️⃣ Agentic OKRs & Tasks", id="tab_agentic_okrs", visible=AGENTIC_MODULES_LOADED): # Renumbered from 6
|
391 |
-
gr.Markdown("## 🎯 AI Generated OKRs and Actionable Tasks (filtro 'Sempre')")
|
392 |
-
gr.Markdown("Basato sull'analisi AI (filtro 'Sempre'), l'agente ha proposto i seguenti OKR e task. Seleziona i Key Results per dettagli.")
|
393 |
-
if not AGENTIC_MODULES_LOADED: gr.Markdown("🔴 **Error:** Agentic pipeline modules could not be loaded. This tab is disabled.")
|
394 |
-
with gr.Row():
|
395 |
-
with gr.Column(scale=1):
|
396 |
-
gr.Markdown("### Suggested Key Results (da analisi 'Sempre')")
|
397 |
-
key_results_cbg = gr.CheckboxGroup(label="Select Key Results", choices=[], value=[], interactive=True)
|
398 |
-
with gr.Column(scale=3):
|
399 |
-
gr.Markdown("### Detailed OKRs and Tasks for Selected Key Results")
|
400 |
-
okr_detail_display_md = gr.Markdown("I dettagli OKR appariranno qui dopo l'esecuzione della pipeline AI.")
|
401 |
-
def update_okr_display_on_selection(selected_kr_unique_ids: list, raw_orchestration_results: dict, all_krs_for_selection: list):
|
402 |
-
if not raw_orchestration_results or not AGENTIC_MODULES_LOADED: return gr.update(value="Nessun dato dalla pipeline AI o moduli non caricati.")
|
403 |
-
actionable_okrs_dict = raw_orchestration_results.get("actionable_okrs_and_tasks")
|
404 |
-
if not actionable_okrs_dict or not isinstance(actionable_okrs_dict.get("okrs"), list): return gr.update(value="Nessun OKR trovato nei risultati della pipeline.")
|
405 |
-
okrs_list = actionable_okrs_dict["okrs"]
|
406 |
-
kr_id_to_indices = {kr_info['unique_kr_id']: (kr_info['okr_index'], kr_info['kr_index']) for kr_info in all_krs_for_selection}
|
407 |
-
selected_krs_by_okr_idx = defaultdict(list)
|
408 |
-
if selected_kr_unique_ids:
|
409 |
-
for kr_unique_id in selected_kr_unique_ids:
|
410 |
-
if kr_unique_id in kr_id_to_indices: okr_idx, kr_idx = kr_id_to_indices[kr_unique_id]; selected_krs_by_okr_idx[okr_idx].append(kr_idx)
|
411 |
-
output_md_parts = []
|
412 |
-
if not okrs_list: output_md_parts.append("Nessun OKR generato.")
|
413 |
-
else:
|
414 |
-
for okr_idx, okr_data in enumerate(okrs_list):
|
415 |
-
accepted_indices_for_this_okr = selected_krs_by_okr_idx.get(okr_idx)
|
416 |
-
if selected_kr_unique_ids:
|
417 |
-
if accepted_indices_for_this_okr is not None: output_md_parts.append(format_single_okr_for_display(okr_data, accepted_kr_indices=accepted_indices_for_this_okr, okr_main_index=okr_idx))
|
418 |
-
else: output_md_parts.append(format_single_okr_for_display(okr_data, accepted_kr_indices=None, okr_main_index=okr_idx))
|
419 |
-
if not output_md_parts and selected_kr_unique_ids: final_md = "Nessun OKR corrisponde alla selezione corrente o i KR selezionati non hanno task dettagliati."
|
420 |
-
elif not output_md_parts and not selected_kr_unique_ids: final_md = "Nessun OKR generato."
|
421 |
-
else: final_md = "\n\n---\n\n".join(output_md_parts)
|
422 |
-
return gr.update(value=final_md)
|
423 |
-
if AGENTIC_MODULES_LOADED:
|
424 |
-
key_results_cbg.change(fn=update_okr_display_on_selection, inputs=[key_results_cbg, orchestration_raw_results_st, key_results_for_selection_st], outputs=[okr_detail_display_md])
|
425 |
-
|
426 |
-
async def refresh_analytics_graphs_ui(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, current_chat_histories_val):
|
427 |
-
logging.info("Refreshing analytics graph UI elements and resetting actions/chat.")
|
428 |
-
start_time = time.time()
|
429 |
-
plot_gen_results = update_analytics_plots_figures(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, plot_configs)
|
430 |
-
status_msg, gen_figs, new_summaries = plot_gen_results[0], plot_gen_results[1:-1], plot_gen_results[-1]
|
431 |
-
all_updates = [status_msg]
|
432 |
-
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))])
|
433 |
-
all_updates.extend([gr.update(visible=False), gr.update(value=[], visible=False), gr.update(value="", visible=False), gr.update(visible=False), gr.update(value="S1"), gr.update(value="S2"), gr.update(value="S3"), gr.update(value="Formula details here.", visible=False), gr.update(visible=False)])
|
434 |
-
all_updates.extend([None, None, {}, new_summaries])
|
435 |
-
for _ in plot_configs: all_updates.extend([gr.update(value=BOMB_ICON), gr.update(value=FORMULA_ICON), gr.update(value=EXPLORE_ICON), gr.update(visible=True)])
|
436 |
-
all_updates.append(None)
|
437 |
-
all_updates.extend([gr.update(visible=True)] * num_unique_sections)
|
438 |
-
end_time = time.time()
|
439 |
-
logging.info(f"Analytics graph refresh took {end_time - start_time:.2f} seconds.")
|
440 |
-
expected_len = 15 + 5 * len(plot_configs) + num_unique_sections
|
441 |
-
logging.info(f"Prepared {len(all_updates)} updates for graph refresh. Expected {expected_len}.")
|
442 |
-
return tuple(all_updates)
|
443 |
-
|
444 |
-
async def run_agentic_pipeline_autonomously(current_token_state_val): # Removed request: gr.Request for simplicity
|
445 |
-
logging.info(f"Agentic pipeline check triggered for token_state update. Current token: {'Set' if current_token_state_val.get('token') else 'Not Set'}")
|
446 |
-
|
447 |
-
if not current_token_state_val or not current_token_state_val.get("token"):
|
448 |
-
logging.info("Agentic pipeline: Token not available in token_state. Skipping.")
|
449 |
-
yield (
|
450 |
-
gr.update(value="Pipeline AI: In attesa dei dati necessari..."),
|
451 |
-
gr.update(choices=[], value=[], interactive=False),
|
452 |
-
gr.update(value="Pipeline AI: In attesa dei dati necessari..."),
|
453 |
-
None, [], [], "Pipeline AI: In attesa dei dati..."
|
454 |
-
)
|
455 |
-
return
|
456 |
-
|
457 |
-
logging.info("Agentic pipeline starting autonomously with 'Sempre' filter.")
|
458 |
-
yield (
|
459 |
-
gr.update(value="Analisi AI (Sempre) in corso..."),
|
460 |
-
gr.update(choices=[], value=[], interactive=False),
|
461 |
-
gr.update(value="Dettagli OKR (Sempre) in corso di generazione..."),
|
462 |
-
orchestration_raw_results_st.value, # Preserve existing results if any during processing
|
463 |
-
selected_key_result_ids_st.value,
|
464 |
-
key_results_for_selection_st.value,
|
465 |
-
"Esecuzione pipeline AI (Sempre)..."
|
466 |
)
|
467 |
|
468 |
-
if not AGENTIC_MODULES_LOADED:
|
469 |
-
logging.warning("Agentic modules not loaded. Skipping autonomous pipeline.")
|
470 |
-
yield (
|
471 |
-
gr.update(value="Moduli AI non caricati. Report non disponibile."),
|
472 |
-
gr.update(choices=[], value=[], interactive=False),
|
473 |
-
gr.update(value="Moduli AI non caricati. OKR non disponibili."),
|
474 |
-
None, [], [], "Pipeline AI: Moduli non caricati."
|
475 |
-
)
|
476 |
-
return
|
477 |
|
478 |
-
|
479 |
-
date_filter_val_agentic = "Sempre"; custom_start_val_agentic = None; custom_end_val_agentic = None
|
480 |
-
orchestration_output = await run_full_analytics_orchestration(current_token_state_val, date_filter_val_agentic, custom_start_val_agentic, custom_end_val_agentic)
|
481 |
-
agentic_status_text = "Pipeline AI (Sempre) completata."
|
482 |
-
logging.info(f"Autonomous agentic pipeline finished. Output keys: {orchestration_output.keys() if orchestration_output else 'None'}")
|
483 |
-
if orchestration_output:
|
484 |
-
orchestration_results_update = orchestration_output
|
485 |
-
report_str = orchestration_output.get('comprehensive_analysis_report')
|
486 |
-
agentic_report_md_update = gr.update(value=format_report_to_markdown(report_str))
|
487 |
-
actionable_okrs = orchestration_output.get('actionable_okrs_and_tasks')
|
488 |
-
krs_for_ui_selection_list = extract_key_results_for_selection(actionable_okrs)
|
489 |
-
krs_for_selection_update = krs_for_ui_selection_list
|
490 |
-
kr_choices_for_cbg = [(kr['kr_description'], kr['unique_kr_id']) for kr in krs_for_ui_selection_list]
|
491 |
-
key_results_cbg_update = gr.update(choices=kr_choices_for_cbg, value=[], interactive=True)
|
492 |
-
all_okrs_md_parts = []
|
493 |
-
if actionable_okrs and isinstance(actionable_okrs.get("okrs"), list):
|
494 |
-
for okr_idx, okr_item in enumerate(actionable_okrs["okrs"]): all_okrs_md_parts.append(format_single_okr_for_display(okr_item, accepted_kr_indices=None, okr_main_index=okr_idx))
|
495 |
-
if not all_okrs_md_parts: okr_detail_display_md_update = gr.update(value="Nessun OKR generato o trovato (Sempre).")
|
496 |
-
else: okr_detail_display_md_update = gr.update(value="\n\n---\n\n".join(all_okrs_md_parts))
|
497 |
-
selected_krs_update = []
|
498 |
-
else:
|
499 |
-
agentic_report_md_update = gr.update(value="Nessun report generato dalla pipeline AI (Sempre).")
|
500 |
-
key_results_cbg_update = gr.update(choices=[], value=[], interactive=False)
|
501 |
-
okr_detail_display_md_update = gr.update(value="Nessun OKR generato o errore nella pipeline AI (Sempre).")
|
502 |
-
orchestration_results_update = None; selected_krs_update = []; krs_for_selection_update = []
|
503 |
-
yield (agentic_report_md_update, key_results_cbg_update, okr_detail_display_md_update, orchestration_results_update, selected_krs_update, krs_for_selection_update, agentic_status_text)
|
504 |
-
except Exception as e:
|
505 |
-
logging.error(f"Error during autonomous agentic pipeline execution: {e}", exc_info=True)
|
506 |
-
agentic_status_text = f"Errore pipeline AI (Sempre): {str(e)}"
|
507 |
-
yield (gr.update(value=f"Errore generazione report AI (Sempre): {str(e)}"), gr.update(choices=[], value=[], interactive=False), gr.update(value=f"Errore generazione OKR AI (Sempre): {str(e)}"), None, [], [], agentic_status_text)
|
508 |
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
for pc in plot_configs: pid = pc["id"]; graph_refresh_outputs_list.extend([plot_ui_objects.get(pid, {}).get("bomb_button", gr.update()), plot_ui_objects.get(pid, {}).get("formula_button", gr.update()), plot_ui_objects.get(pid, {}).get("explore_button", gr.update()), plot_ui_objects.get(pid, {}).get("panel_component", gr.update())])
|
516 |
-
graph_refresh_outputs_list.append(explored_plot_id_state)
|
517 |
-
graph_refresh_outputs_list.extend([section_titles_map.get(s_name, gr.update()) for s_name in unique_ordered_sections])
|
518 |
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
|
|
|
|
|
|
523 |
|
524 |
-
apply_filter_btn.click(
|
525 |
-
fn=refresh_analytics_graphs_ui,
|
526 |
-
inputs=graph_refresh_inputs,
|
527 |
-
outputs=graph_refresh_outputs_list,
|
528 |
-
show_progress="full"
|
529 |
-
)
|
530 |
|
531 |
initial_load_event = org_urn_display.change(
|
532 |
-
fn=
|
533 |
inputs=[url_user_token_display, org_urn_display, token_state],
|
534 |
outputs=[status_box, token_state, sync_data_btn, dashboard_display_html],
|
535 |
show_progress="full"
|
536 |
)
|
|
|
|
|
537 |
initial_load_event.then(
|
538 |
-
fn=
|
539 |
-
inputs=[token_state,
|
540 |
-
outputs=
|
541 |
show_progress="full"
|
542 |
-
).then(
|
543 |
-
fn=
|
544 |
-
inputs=
|
545 |
-
outputs=
|
546 |
show_progress="minimal"
|
547 |
)
|
548 |
|
|
|
549 |
sync_event_part1 = sync_data_btn.click(
|
550 |
fn=sync_all_linkedin_data_orchestrator,
|
551 |
inputs=[token_state],
|
552 |
-
outputs=[sync_status_html_output, token_state],
|
553 |
show_progress="full"
|
554 |
)
|
|
|
|
|
555 |
sync_event_part2 = sync_event_part1.then(
|
556 |
-
fn=process_and_store_bubble_token,
|
557 |
-
inputs=[url_user_token_display, org_urn_display, token_state],
|
558 |
-
outputs=[status_box, token_state, sync_data_btn],
|
559 |
-
show_progress=False
|
560 |
)
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
|
|
|
|
565 |
show_progress="minimal"
|
566 |
)
|
|
|
|
|
567 |
sync_event_part3 = sync_event_part2.then(
|
568 |
fn=display_main_dashboard,
|
569 |
-
inputs=[token_state],
|
570 |
outputs=[dashboard_display_html],
|
571 |
show_progress=False
|
572 |
)
|
|
|
|
|
573 |
sync_event_graphs_after_sync = sync_event_part3.then(
|
574 |
-
fn=
|
575 |
-
inputs=[token_state,
|
576 |
-
outputs=
|
577 |
show_progress="full"
|
578 |
)
|
579 |
|
580 |
-
|
581 |
if __name__ == "__main__":
|
582 |
if not os.environ.get(LINKEDIN_CLIENT_ID_ENV_VAR): logging.warning(f"ATTENZIONE: '{LINKEDIN_CLIENT_ID_ENV_VAR}' non impostata.")
|
583 |
if not all(os.environ.get(var) for var in [BUBBLE_APP_NAME_ENV_VAR, BUBBLE_API_KEY_PRIVATE_ENV_VAR, BUBBLE_API_ENDPOINT_ENV_VAR]):
|
584 |
logging.warning("ATTENZIONE: Variabili Bubble non impostate.")
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import logging
|
6 |
import matplotlib
|
7 |
matplotlib.use('Agg') # Set backend for Matplotlib to avoid GUI conflicts with Gradio
|
8 |
+
# import time # No longer directly used here for profiling
|
9 |
+
from datetime import datetime, timedelta
|
10 |
+
# import numpy as np # No longer directly used here
|
11 |
+
# from collections import OrderedDict, defaultdict # Moved or not needed directly
|
|
|
|
|
12 |
|
13 |
# --- Module Imports ---
|
14 |
from utils.gradio_utils import get_url_user_token
|
|
|
15 |
from config import (
|
16 |
LINKEDIN_CLIENT_ID_ENV_VAR, BUBBLE_APP_NAME_ENV_VAR,
|
17 |
+
BUBBLE_API_KEY_PRIVATE_ENV_VAR, BUBBLE_API_ENDPOINT_ENV_VAR) # PLOT_ID_TO_FORMULA_KEY_MAP moved
|
|
|
18 |
from services.state_manager import process_and_store_bubble_token
|
19 |
from services.sync_logic import sync_all_linkedin_data_orchestrator
|
20 |
+
from ui.ui_generators import display_main_dashboard # Other UI generators moved or used internally by new modules
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
+
# --- NEW UI MODULE IMPORTS ---
|
23 |
+
from ui import analytics_tab
|
24 |
+
from ui import agentic_module
|
|
|
25 |
|
26 |
+
# --- EXISTING CHATBOT MODULE IMPORTS (used by analytics_tab) ---
|
27 |
+
# from features.chatbot.chatbot_prompts import get_initial_insight_prompt_and_suggestions # Used in analytics_tab
|
28 |
+
# from features.chatbot.chatbot_handler import generate_llm_response # Used in analytics_tab
|
29 |
+
|
30 |
+
# --- AGENTIC PIPELINE IMPORTS (used by agentic_module) ---
|
31 |
+
# AGENTIC_MODULES_LOADED is handled within agentic_module.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
# Configure logging
|
34 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
|
|
|
36 |
# 1. Set Vertex AI usage preference (if applicable)
|
37 |
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "False"
|
38 |
|
39 |
+
# 2. Get your API key
|
40 |
user_provided_api_key = os.environ.get("GEMINI_API_KEY")
|
|
|
41 |
if user_provided_api_key:
|
42 |
os.environ["GOOGLE_API_KEY"] = user_provided_api_key
|
43 |
logging.info("GOOGLE_API_KEY environment variable has been set from GEMINI_API_KEY.")
|
44 |
else:
|
45 |
+
logging.error(f"CRITICAL ERROR: The API key environment variable 'GEMINI_API_KEY' was not found.")
|
46 |
|
47 |
|
48 |
# --- Gradio UI Blocks ---
|
49 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
|
50 |
+
title="LinkedIn Organization Dashboard") as app:
|
51 |
+
|
52 |
+
# --- Core States ---
|
53 |
token_state = gr.State(value={
|
54 |
"token": None, "client_id": None, "org_urn": None,
|
55 |
"bubble_posts_df": pd.DataFrame(), "bubble_post_stats_df": pd.DataFrame(),
|
56 |
+
"bubble_mentions_df": pd.DataFrame(), "bubble_follower_stats_df": pd.DataFrame(),
|
|
|
57 |
"fetch_count_for_api": 0, "url_user_token_temp_storage": None,
|
58 |
"config_date_col_posts": "published_at", "config_date_col_mentions": "date",
|
59 |
"config_date_col_followers": "date", "config_media_type_col": "media_type",
|
60 |
"config_eb_labels_col": "li_eb_label"
|
61 |
})
|
62 |
|
63 |
+
# States for analytics tab chatbot (passed to analytics_tab module)
|
64 |
chat_histories_st = gr.State({})
|
65 |
current_chat_plot_id_st = gr.State(None)
|
66 |
+
plot_data_for_chatbot_st = gr.State({}) # Populated by analytics_tab.handle_refresh_analytics_graphs
|
67 |
+
active_panel_action_state = gr.State(None) # For insights/formula panel
|
68 |
+
explored_plot_id_state = gr.State(None) # For explore plot view
|
69 |
|
70 |
+
# States for Agentic Pipeline (passed to agentic_module)
|
71 |
orchestration_raw_results_st = gr.State(None)
|
72 |
+
key_results_for_selection_st = gr.State([]) # Stores the list of dicts for choices
|
73 |
+
selected_key_result_ids_st = gr.State([]) # Stores the selected unique_kr_ids
|
|
|
74 |
|
75 |
+
# --- Top Level UI ---
|
76 |
gr.Markdown("# 🚀 LinkedIn Organization Dashboard")
|
77 |
url_user_token_display = gr.Textbox(label="User Token (Nascosto)", interactive=False, visible=False)
|
78 |
status_box = gr.Textbox(label="Stato Generale Token LinkedIn", interactive=False, value="Inizializzazione...")
|
79 |
org_urn_display = gr.Textbox(label="URN Organizzazione (Nascosto)", interactive=False, visible=False)
|
80 |
|
81 |
+
# Load URL parameters on app load
|
82 |
app.load(fn=get_url_user_token, inputs=None, outputs=[url_user_token_display, org_urn_display], api_name="get_url_params", show_progress=False)
|
83 |
|
84 |
+
# --- Tabs ---
|
|
|
|
|
|
|
|
|
85 |
with gr.Tabs() as tabs:
|
86 |
+
# --- Tab 1: Dashboard & Sync ---
|
87 |
with gr.TabItem("1️⃣ Dashboard & Sync", id="tab_dashboard_sync"):
|
88 |
gr.Markdown("Il sistema controlla i dati esistenti da Bubble. 'Sincronizza' si attiva se sono necessari nuovi dati.")
|
89 |
sync_data_btn = gr.Button("🔄 Sincronizza Dati LinkedIn", variant="primary", visible=False, interactive=False)
|
90 |
sync_status_html_output = gr.HTML("<p style='text-align:center;'>Stato sincronizzazione...</p>")
|
91 |
dashboard_display_html = gr.HTML("<p style='text-align:center;'>Caricamento dashboard...</p>")
|
92 |
|
93 |
+
# --- Tab 2: Analisi Grafici ---
|
94 |
+
with gr.TabItem("2️⃣ Analisi Grafici", id="tab_analytics"):
|
95 |
+
# Build UI and wire internal events within analytics_tab module
|
96 |
+
(apply_filter_btn_analytics, date_filter_selector_analytics,
|
97 |
+
custom_start_date_picker_analytics, custom_end_date_picker_analytics,
|
98 |
+
analytics_status_md_ref, # Reference to the status markdown in analytics tab
|
99 |
+
analytics_refresh_outputs_components, # list of components for refresh handler output
|
100 |
+
analytics_refresh_outputs_plus_states # list of components + states for refresh handler output
|
101 |
+
) = analytics_tab.build_and_wire_tab(
|
102 |
+
token_state, chat_histories_st, current_chat_plot_id_st,
|
103 |
+
plot_data_for_chatbot_st, active_panel_action_state, explored_plot_id_state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
)
|
105 |
+
|
106 |
+
# --- Tabs 3 & 4: Agentic Pipeline ---
|
107 |
+
# build_and_wire_tabs will create TabItems internally
|
108 |
+
agentic_pipeline_output_components = agentic_module.build_and_wire_tabs(
|
109 |
+
orchestration_raw_results_st,
|
110 |
+
key_results_for_selection_st,
|
111 |
+
selected_key_result_ids_st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
)
|
113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
+
# --- Event Chaining & Orchestration ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
+
# Initial Load Sequence (Simplified: direct calls, complex logic in handlers)
|
118 |
+
def initial_load_sequence_wrapper(url_token, org_urn_val, current_state):
|
119 |
+
# This function is primarily for the first tab's initial state.
|
120 |
+
status_msg, new_state, btn_update = process_and_store_bubble_token(url_token, org_urn_val, current_state)
|
121 |
+
dashboard_content = display_main_dashboard(new_state) # From ui_generators
|
122 |
+
return status_msg, new_state, btn_update, dashboard_content
|
|
|
|
|
|
|
123 |
|
124 |
+
# Outputs for the agentic pipeline handler
|
125 |
+
# Order: report_display, key_results_cbg, okr_detail_display,
|
126 |
+
# orchestration_raw_results_st, selected_key_result_ids_st, key_results_for_selection_st,
|
127 |
+
# agentic_pipeline_status_md
|
128 |
+
agentic_pipeline_full_outputs_list = agentic_pipeline_output_components[:3] + \
|
129 |
+
[orchestration_raw_results_st, selected_key_result_ids_st, key_results_for_selection_st] + \
|
130 |
+
[agentic_pipeline_output_components[3]]
|
131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
initial_load_event = org_urn_display.change(
|
134 |
+
fn=initial_load_sequence_wrapper,
|
135 |
inputs=[url_user_token_display, org_urn_display, token_state],
|
136 |
outputs=[status_box, token_state, sync_data_btn, dashboard_display_html],
|
137 |
show_progress="full"
|
138 |
)
|
139 |
+
|
140 |
+
# After initial load, refresh analytics graphs
|
141 |
initial_load_event.then(
|
142 |
+
fn=analytics_tab.handle_refresh_analytics_graphs,
|
143 |
+
inputs=[token_state, date_filter_selector_analytics, custom_start_date_picker_analytics, custom_end_date_picker_analytics, chat_histories_st],
|
144 |
+
outputs=analytics_refresh_outputs_plus_states, # Use the list from analytics_tab
|
145 |
show_progress="full"
|
146 |
+
).then( # Then run agentic pipeline
|
147 |
+
fn=agentic_module.handle_run_agentic_pipeline,
|
148 |
+
inputs=[token_state, orchestration_raw_results_st, key_results_for_selection_st, selected_key_result_ids_st], # Pass states
|
149 |
+
outputs=agentic_pipeline_full_outputs_list,
|
150 |
show_progress="minimal"
|
151 |
)
|
152 |
|
153 |
+
# Sync Data Event Chain
|
154 |
sync_event_part1 = sync_data_btn.click(
|
155 |
fn=sync_all_linkedin_data_orchestrator,
|
156 |
inputs=[token_state],
|
157 |
+
outputs=[sync_status_html_output, token_state], # token_state is updated here
|
158 |
show_progress="full"
|
159 |
)
|
160 |
+
|
161 |
+
# After sync, re-process token and update dashboard display (Tab 1)
|
162 |
sync_event_part2 = sync_event_part1.then(
|
163 |
+
fn=process_and_store_bubble_token, # This updates token_state again
|
164 |
+
inputs=[url_user_token_display, org_urn_display, token_state], # Pass the updated token_state
|
165 |
+
outputs=[status_box, token_state, sync_data_btn], # token_state updated again
|
166 |
+
show_progress=False
|
167 |
)
|
168 |
+
|
169 |
+
# After token processing, re-run agentic pipeline with potentially new data
|
170 |
+
sync_event_part2.then(
|
171 |
+
fn=agentic_module.handle_run_agentic_pipeline,
|
172 |
+
inputs=[token_state, orchestration_raw_results_st, key_results_for_selection_st, selected_key_result_ids_st], # Pass the latest token_state
|
173 |
+
outputs=agentic_pipeline_full_outputs_list,
|
174 |
show_progress="minimal"
|
175 |
)
|
176 |
+
|
177 |
+
# Then, update the main dashboard display on Tab 1
|
178 |
sync_event_part3 = sync_event_part2.then(
|
179 |
fn=display_main_dashboard,
|
180 |
+
inputs=[token_state], # Use the latest token_state
|
181 |
outputs=[dashboard_display_html],
|
182 |
show_progress=False
|
183 |
)
|
184 |
+
|
185 |
+
# Finally, refresh analytics graphs on Tab 2
|
186 |
sync_event_graphs_after_sync = sync_event_part3.then(
|
187 |
+
fn=analytics_tab.handle_refresh_analytics_graphs,
|
188 |
+
inputs=[token_state, date_filter_selector_analytics, custom_start_date_picker_analytics, custom_end_date_picker_analytics, chat_histories_st],
|
189 |
+
outputs=analytics_refresh_outputs_plus_states, # Use the list from analytics_tab
|
190 |
show_progress="full"
|
191 |
)
|
192 |
|
193 |
+
# --- App Launch ---
|
194 |
if __name__ == "__main__":
|
195 |
if not os.environ.get(LINKEDIN_CLIENT_ID_ENV_VAR): logging.warning(f"ATTENZIONE: '{LINKEDIN_CLIENT_ID_ENV_VAR}' non impostata.")
|
196 |
if not all(os.environ.get(var) for var in [BUBBLE_APP_NAME_ENV_VAR, BUBBLE_API_KEY_PRIVATE_ENV_VAR, BUBBLE_API_ENDPOINT_ENV_VAR]):
|
197 |
logging.warning("ATTENZIONE: Variabili Bubble non impostate.")
|
198 |
+
|
199 |
+
# AGENTIC_MODULES_LOADED is now checked within agentic_module.py, log from there if needed.
|
200 |
+
# We can add a check here based on the import success if desired for app startup.
|
201 |
+
if not agentic_module.AGENTIC_MODULES_LOADED: # Check the flag from the module
|
202 |
+
logging.warning("CRITICAL: Agentic pipeline modules failed to load. Tabs 3 and 4 will be non-functional.")
|
203 |
+
if not os.environ.get("GEMINI_API_KEY") and agentic_module.AGENTIC_MODULES_LOADED:
|
204 |
+
logging.warning("ATTENZIONE: 'GEMINI_API_KEY' non impostata. La pipeline AI per le tab 3 e 4 potrebbe non funzionare.")
|
205 |
+
|
206 |
+
try:
|
207 |
+
logging.info(f"Matplotlib: {matplotlib.__version__}, Backend: {matplotlib.get_backend()}")
|
208 |
+
except ImportError:
|
209 |
+
logging.warning("Matplotlib non trovato.")
|
210 |
+
|
211 |
+
app.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|
212 |
+
|