Report with ID '{_id}' was not found in the database.
"""
if not selected_report_id:
return gr.update(value=empty_header_html), gr.update(value=empty_body_markdown_no_selection)
agentic_df = current_token_state.get("bubble_agentic_analysis_data")
if agentic_df is None or agentic_df.empty:
return gr.update(value=empty_header_html), gr.update(value=empty_body_markdown_no_data)
selected_report_series_df = agentic_df[agentic_df['_id'] == selected_report_id]
if selected_report_series_df.empty:
return gr.update(value=empty_header_html), gr.update(value=empty_body_markdown_not_found(selected_report_id))
selected_report_series = selected_report_series_df.iloc[0]
# Call the format_report_for_display, which now returns a dict
formatted_content_parts = format_report_for_display_func(selected_report_series)
# Update the two separate Gradio components
return (
gr.update(value=formatted_content_parts['header_html']),
gr.update(value=formatted_content_parts['body_markdown'])
)
def build_main_app_ui(
PLOT_ID_TO_FORMULA_KEY_MAP: Dict[str, Any],
PLOT_FORMULAS: Dict[str, Any],
BOMB_ICON: str,
EXPLORE_ICON: str,
FORMULA_ICON: str,
ACTIVE_ICON: str,
build_analytics_tab_plot_area_func: Callable,
update_analytics_plots_figures_func: Callable,
create_placeholder_plot_func: Callable,
get_initial_insight_prompt_and_suggestions_func: Callable,
generate_llm_response_func: Callable,
build_home_tab_ui_func: Callable,
create_enhanced_report_tab_func: Callable,
create_enhanced_okr_tab_func: Callable,
format_report_for_display_func: Callable, # New argument to pass the formatting function
AGENTIC_MODULES_LOADED: bool, # ADD THIS PARAMETER
get_initial_okr_display_func: Callable = None, # ADD THIS PARAMETER TOO
# NEW: Added parameters for initial event binding functions
initial_data_load_sequence_func: Callable = None,
get_url_user_token_func: Callable = None,
load_and_display_agentic_results_func: Callable = None,
format_okrs_for_enhanced_display_func: Callable = None,
update_report_display_enhanced_func: Callable = None
) -> tuple:
"""
Builds the main Gradio application UI with enhanced styling and structure.
Args:
(All necessary functions and constants are passed as arguments to ensure self-containment
within the UI module without direct imports of non-UI related logic)
AGENTIC_MODULES_LOADED (bool): Whether agentic modules are loaded
get_initial_okr_display_func (callable): Function to get initial OKR display
initial_data_load_sequence_func (callable): Function to handle initial data load.
get_url_user_token_func (callable): Function to get URL user token.
load_and_display_agentic_results_func (callable): Function to load and display agentic results.
format_okrs_for_enhanced_display_func (callable): Function to format OKRs for enhanced display.
update_report_display_enhanced_func (callable): Function to update enhanced report display.
Returns:
tuple: A tuple containing:
- app (gr.Blocks): The main Gradio application object.
- url_user_token_display (gr.Textbox): Hidden component for user token.
- org_urn_display (gr.Textbox): Hidden component for organization URN.
- status_box (gr.Textbox): Component for system status.
- token_state (gr.State): Gradio state for token and data.
- reconstruction_cache_st (gr.State): State for reconstructed OKR data cache.
- enhanced_okr_display_html (gr.HTML): HTML component for enhanced OKR display.
- tabs (gr.Tabs): The main tabs component.
- report_selector_dd (gr.Dropdown): Dropdown for selecting reports.
- agentic_display_outputs (list): List of Gradio components for agentic results.
- analytics_tab_instance (AnalyticsTab): The analytics tab instance itself.
- chat_histories_st (gr.State): State for chat histories.
- current_chat_plot_id_st (gr.State): State for current chat plot ID.
- plot_data_for_chatbot_st (gr.State): State for plot data for chatbot.
- format_report_for_display_func (callable): The report display formatting function.
"""
app = gr.Blocks(
theme=custom_theme,
css=CUSTOM_CSS,
title="LinkedIn Organization Dashboard",
head="""
"""
)
with app:
# --- STATE MANAGEMENT ---
token_state = gr.State(value={
"token": None, "client_id": None, "org_urn": None,
"bubble_posts_df": pd.DataFrame(), "bubble_post_stats_df": pd.DataFrame(),
"bubble_mentions_df": pd.DataFrame(), "bubble_follower_stats_df": pd.DataFrame(),
"bubble_agentic_analysis_data": pd.DataFrame(), # To store agentic results from Bubble
"url_user_token_temp_storage": None,
"config_date_col_posts": "published_at", "config_date_col_mentions": "date",
"config_date_col_followers": "date", "config_media_type_col": "media_type",
"config_eb_labels_col": "li_eb_label"
})
# States for analytics tab chatbot
chat_histories_st = gr.State({})
current_chat_plot_id_st = gr.State(None)
plot_data_for_chatbot_st = gr.State({})
# States for agentic results display
orchestration_raw_results_st = gr.State(None)
# KEPT for compatibility with load_and_display_agentic_results signature
key_results_for_selection_st = gr.State([])
selected_key_result_ids_st = gr.State([])
# --- NEW: Session-specific cache for reconstructed OKR data ---
reconstruction_cache_st = gr.State({})
# NEW: State to hold the actionable_okrs dictionary explicitly
actionable_okrs_data_st = gr.State({})
# --- UI LAYOUT ---
# Main Header
with gr.Row():
with gr.Column():
gr.HTML("""
🚀 LinkedIn Organization Dashboard
Advanced Analytics & AI-Powered Insights for LinkedIn Organizations
""")
# Hidden components for token management
url_user_token_display = gr.Textbox(label="User Token (Hidden)", interactive=False, visible=False)
org_urn_display = gr.Textbox(label="Org URN (Hidden)", interactive=False, visible=False)
# Status section with better styling
with gr.Row():
with gr.Column():
gr.HTML('
')
# Instantiate AnalyticsTab here, after all its required gr.State components are defined
from services.analytics_tab_module import AnalyticsTab # Local import to ensure it's loaded within context
analytics_icons = {'bomb': BOMB_ICON, 'explore': EXPLORE_ICON, 'formula': FORMULA_ICON, 'active': ACTIVE_ICON}
analytics_tab_instance = AnalyticsTab(
token_state=token_state,
chat_histories_st=chat_histories_st,
current_chat_plot_id_st=current_chat_plot_id_st,
plot_data_for_chatbot_st=plot_data_for_chatbot_st,
plot_id_to_formula_map=PLOT_ID_TO_FORMULA_KEY_MAP,
plot_formulas_data=PLOT_FORMULAS,
icons=analytics_icons,
fn_build_plot_area=build_analytics_tab_plot_area_func,
fn_update_plot_figures=update_analytics_plots_figures_func,
fn_create_placeholder_plot=create_placeholder_plot_func,
fn_get_initial_insight=get_initial_insight_prompt_and_suggestions_func,
fn_generate_llm_response=generate_llm_response_func
)
with gr.Tabs(elem_classes=["tab-nav"]) as tabs:
# --- HOME TAB ---
with gr.TabItem("🏠 Home", id="tab_home", elem_classes=["tabitem"]):
# Call the new function from ui_generators to build the Home tab content
btn_graphs, btn_reports, btn_okr, btn_help = build_home_tab_ui_func()
# Link buttons to tab selection
btn_graphs.click(fn=lambda: gr.update(selected="tab_analytics_module"), outputs=tabs)
btn_reports.click(fn=lambda: gr.update(selected="tab_agentic_report"), outputs=tabs)
btn_okr.click(fn=lambda: gr.update(selected="tab_agentic_okrs"), outputs=tabs)
# btn_help.click(fn=lambda: gr.update(selected="tab_help"), outputs=tabs) # Uncomment if you add a help tab
# Analytics Tab
analytics_tab_instance.create_tab_ui() # This is the "Graphs" tab, assuming its ID is "tab_analytics_module"
# --- AGENTIC ANALYSIS REPORT TAB ---
with gr.TabItem("📊 Analysis Reports", id="tab_agentic_report", visible=True, elem_classes=["tabitem"]): # Set visible to True to allow `create_enhanced_report_tab_func` to return components
# The create_enhanced_report_tab function handles the CSS and HTML structure
agentic_pipeline_status_md, report_selector_dd, report_header_html_display, report_body_markdown_display = \
create_enhanced_report_tab_func(True) # Pass True to create elements
# --- AGENTIC OKRS TAB ---
with gr.TabItem("🎯 OKRs & Tasks", id="tab_agentic_okrs", visible=True, elem_classes=["tabitem"]): # Set visible to True to allow components to be created
gr.HTML("""
🎯 AI Generated OKRs and Actionable Tasks
Based on AI analysis, the agent has proposed the following OKRs and actionable tasks from Bubble.io data.
""")
# The `AGENTIC_MODULES_LOADED` check should control visibility from app.py, not prevent creation here
# to avoid NoneType errors during UI building.
if not AGENTIC_MODULES_LOADED: # This check is for conditional display, not creation
gr.HTML("""
🔴
Module Loading Error
Agentic modules could not be loaded. This tab is currently unavailable.
🚀 Built with Gradio • 🔗 LinkedIn API • 🤖 AI Analytics • ☁️ Bubble.io Integration
""")
# Ensure agentic_display_outputs correctly maps to the newly created components
# This list must match the outputs of load_and_display_agentic_results
# These variables are now defined within the `with app:` block
agentic_display_outputs = [
agentic_pipeline_status_md, # 0: Status Markdown (hidden)
report_selector_dd, # 1: Dropdown for selecting reports
key_results_cbg if AGENTIC_MODULES_LOADED else gr.State([]), # Ensure it's a component or dummy state
okr_detail_display_md if AGENTIC_MODULES_LOADED else gr.State(None), # Ensure it's a component or dummy state
orchestration_raw_results_st, # 4: Raw results state
selected_key_result_ids_st, # 5: Selected KR IDs state (kept hidden)
key_results_for_selection_st, # 6: All KRs for selection state (kept hidden)
report_header_html_display, # 7: New HTML output for header
report_body_markdown_display, # 8: New Markdown output for body
reconstruction_cache_st, # 9: Reconstruction cache state
enhanced_okr_display_html, # 10: The enhanced HTML display for OKRs
actionable_okrs_data_st # 11: NEW: The actionable_okrs dictionary state
]
# Event handlers (moved here to be within the gr.Blocks context)
if get_url_user_token_func: # Check if the function is provided
app.load(fn=get_url_user_token_func, inputs=None, outputs=[url_user_token_display, org_urn_display], api_name="get_url_params", show_progress=False)
if AGENTIC_MODULES_LOADED and update_report_display_enhanced_func: # Check if function is provided
report_selector_dd.change(
fn=lambda sr_id, c_state: update_report_display_enhanced_func(sr_id, c_state, format_report_for_display_func),
inputs=[report_selector_dd, token_state],
outputs=[agentic_display_outputs[7], agentic_display_outputs[8]], # report_header_html_display, report_body_markdown_display
show_progress="minimal"
)
if initial_data_load_sequence_func: # Check if function is provided
initial_load_event = org_urn_display.change(
fn=initial_data_load_sequence_func,
inputs=[url_user_token_display, org_urn_display, token_state],
outputs=[status_box, token_state],
show_progress="full"
)
# Chain the loading events
if analytics_tab_instance:
initial_load_event.then(
fn=analytics_tab_instance._refresh_analytics_graphs_ui,
inputs=[token_state, analytics_tab_instance.date_filter_selector, analytics_tab_instance.custom_start_date_picker,
analytics_tab_instance.custom_end_date_picker, chat_histories_st], # Changed from chat_histories_st_returned
outputs=analytics_tab_instance.graph_refresh_outputs_list,
show_progress="full"
)
if AGENTIC_MODULES_LOADED and load_and_display_agentic_results_func:
initial_load_event.then(
fn=load_and_display_agentic_results_func,
inputs=[token_state, reconstruction_cache_st],
outputs=agentic_display_outputs,
show_progress="minimal"
)
if AGENTIC_MODULES_LOADED and format_okrs_for_enhanced_display_func:
initial_load_event.then(
fn=format_okrs_for_enhanced_display_func,
inputs=[reconstruction_cache_st],
outputs=[enhanced_okr_display_html],
show_progress="minimal"
)
return (app, url_user_token_display, org_urn_display, status_box,
token_state, reconstruction_cache_st, enhanced_okr_display_html,
tabs, report_selector_dd, agentic_display_outputs,
analytics_tab_instance, chat_histories_st, # Returned directly as defined in this function
current_chat_plot_id_st, plot_data_for_chatbot_st, # Returned directly as defined in this function
format_report_for_display_func) # Return format_report_for_display_func as well