# ui_generators.py """ Generates HTML content and Matplotlib plots for the Gradio UI tabs, and UI components for the Analytics tab. """ import pandas as pd import logging import matplotlib.pyplot as plt import matplotlib # To ensure backend is switched before any plt import from other modules if app structure changes import gradio as gr # Added for UI components # Switch backend for Matplotlib to Agg for Gradio compatibility matplotlib.use('Agg') # Assuming config.py contains all necessary constants from config import ( BUBBLE_POST_DATE_COLUMN_NAME, BUBBLE_MENTIONS_DATE_COLUMN_NAME, BUBBLE_MENTIONS_ID_COLUMN_NAME, FOLLOWER_STATS_TYPE_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN, FOLLOWER_STATS_ORGANIC_COLUMN, FOLLOWER_STATS_PAID_COLUMN, FOLLOWER_STATS_CATEGORY_COLUMN_DT, UI_DATE_FORMAT, UI_MONTH_FORMAT ) # Configure logging for this module if not already configured at app level # logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(module)s - %(module)s - %(message)s') # --- Constants for Button Icons/Text --- # These are also defined/imported in app.py, ensure consistency BOMB_ICON = "đŸ’Ŗ" EXPLORE_ICON = "🧭" FORMULA_ICON = "ƒ" ACTIVE_ICON = "❌ Close" # Ensure this matches app.py def build_home_tab_ui(): """ Constructs the entire UI for the Home tab, including the header, overview, feature cards, and navigation buttons. Returns: tuple: A tuple containing the Gradio Button components for Graphs, Reports, and OKR Table, allowing app.py to attach click handlers for tab navigation. """ # Custom CSS for enhanced styling css_styles = """ """ with gr.Column(scale=1, elem_classes="home-page-container"): # Inject custom CSS gr.HTML(css_styles) # Main hero section gr.HTML("""

🚀 LinkedIn Employer Brand Analytics

Transform your LinkedIn presence with data-driven insights and actionable strategies

Measure, analyze, and enhance your employer brand to attract top talent and build a stronger digital presence

""") # Overview section with improved spacing gr.HTML("""

📊 What This Dashboard Offers

Our comprehensive analytics platform helps you understand and optimize your LinkedIn employer brand performance with real-time insights, automated reporting, and AI-powered recommendations.

📈 Real-time data visualization and trend analysis
📋 Automated quarterly and weekly performance reports
đŸŽ¯ AI-powered OKRs and actionable recommendations
🚀 Strategic insights to improve employer branding
""") # Navigation cards with improved layout gr.HTML(""" """) # Create buttons with better spacing with gr.Row(equal_height=True): with gr.Column(): btn_graphs = gr.Button("🚀 Explore Graphs", variant="primary", size="lg", elem_classes="nav-button", scale=1) with gr.Column(): btn_reports = gr.Button("📊 View Reports", variant="primary", size="lg", elem_classes="nav-button", scale=1) with gr.Row(equal_height=True): with gr.Column(): btn_okr = gr.Button("đŸŽ¯ Access OKRs", variant="primary", size="lg", elem_classes="nav-button", scale=1) with gr.Column(): btn_help = gr.Button("📚 Documentation", variant="secondary", size="lg", elem_classes="nav-button", scale=1) # How it works section with enhanced styling gr.HTML("""

â„šī¸ How It Works

1
Data Collection
Automatically syncs with your LinkedIn organization data and processes engagement metrics in real-time
2
AI Analysis
Advanced algorithms analyze trends, sentiment, and performance patterns to generate actionable insights
3
Actionable Results
Receive specific recommendations, measurable goals, and strategic action plans to improve your employer brand
""") return btn_graphs, btn_reports, btn_okr, btn_help def create_analytics_plot_panel(plot_label_str, plot_id_str): """ Creates an individual plot panel with its plot component and action buttons. Plot title and action buttons are on the same row. Returns the panel (Column), plot component, and button components. """ # Icons are defined globally or imported. For this function, ensure they are accessible. # If not using from config directly here, you might need to pass them or use fixed strings. # Using fixed strings as a fallback if import fails, though they should be available via app.py's import. local_bomb_icon, local_explore_icon, local_formula_icon = BOMB_ICON, EXPLORE_ICON, FORMULA_ICON with gr.Column(visible=True) as panel_component: # Main container for this plot with gr.Row(variant="compact"): gr.Markdown(f"#### {plot_label_str}") # Plot title (scale might help balance) with gr.Row(elem_classes="plot-actions", scale=1): # Action buttons container, give it some min_width bomb_button = gr.Button(value=local_bomb_icon, variant="secondary", size="sm", min_width=30, elem_id=f"bomb_btn_{plot_id_str}") formula_button = gr.Button(value=local_formula_icon, variant="secondary", size="sm", min_width=30, elem_id=f"formula_btn_{plot_id_str}") explore_button = gr.Button(value=local_explore_icon, variant="secondary", size="sm", min_width=30, elem_id=f"explore_btn_{plot_id_str}") # MODIFIED: Added height to gr.Plot for consistent sizing plot_component = gr.Plot(label=plot_label_str, show_label=False) # Adjust height as needed logging.debug(f"Created analytics panel for: {plot_label_str} (ID: {plot_id_str}) with fixed plot height.") return panel_component, plot_component, bomb_button, explore_button, formula_button def build_analytics_tab_plot_area(plot_configs): """ Builds the main plot area for the Analytics tab, arranging plot panels into rows of two, with section titles appearing before their respective plots. Returns a tuple: - plot_ui_objects (dict): Dictionary of plot UI objects. - section_titles_map (dict): Dictionary mapping section names to their gr.Markdown title components. """ logging.info(f"Building plot area for {len(plot_configs)} analytics plots with interleaved section titles.") plot_ui_objects = {} section_titles_map = {} last_rendered_section = None idx = 0 while idx < len(plot_configs): current_plot_config = plot_configs[idx] current_section_name = current_plot_config["section"] # Render section title if it's new for this block of plots if current_section_name != last_rendered_section: if current_section_name not in section_titles_map: # Create the Markdown component for the section title section_md_component = gr.Markdown(f"## {current_section_name}", visible=True) section_titles_map[current_section_name] = section_md_component logging.debug(f"Rendered and stored Markdown for section: {current_section_name}") # No 'else' needed here for visibility, as it's handled by click handlers if sections are hidden/shown. # The component is created once and its visibility is controlled elsewhere. last_rendered_section = current_section_name with gr.Row(equal_height=True): # Row for one or two plots. equal_height=False allows plots to define their height. # --- Process the first plot in the row (config1) --- config1 = plot_configs[idx] # Safety check for section consistency (should always pass if configs are ordered by section) if config1["section"] != current_section_name: logging.warning(f"Plot {config1['id']} section mismatch. Expected {current_section_name}, got {config1['section']}. This might affect layout if a new section title was expected.") # If a new section starts unexpectedly, ensure its title is created if missing if config1["section"] not in section_titles_map: sec_md = gr.Markdown(f"### {config1['section']}", visible=True) # Create and make visible section_titles_map[config1['section']] = sec_md last_rendered_section = config1["section"] # Update the current section context panel_col1, plot_comp1, bomb_btn1, explore_btn1, formula_btn1 = \ create_analytics_plot_panel(config1["label"], config1["id"]) plot_ui_objects[config1["id"]] = { "plot_component": plot_comp1, "bomb_button": bomb_btn1, "explore_button": explore_btn1, "formula_button": formula_btn1, "label": config1["label"], "panel_component": panel_col1, # This is the gr.Column containing the plot and its actions "section": config1["section"] } logging.debug(f"Created UI panel for plot_id: {config1['id']} in section {config1['section']}") idx += 1 # --- Process the second plot in the row (config2), if applicable --- if idx < len(plot_configs): config2 = plot_configs[idx] # Only add to the same row if it's part of the same section if config2["section"] == current_section_name: panel_col2, plot_comp2, bomb_btn2, explore_btn2, formula_btn2 = \ create_analytics_plot_panel(config2["label"], config2["id"]) plot_ui_objects[config2["id"]] = { "plot_component": plot_comp2, "bomb_button": bomb_btn2, "explore_button": explore_btn2, "formula_button": formula_btn2, "label": config2["label"], "panel_component": panel_col2, "section": config2["section"] } logging.debug(f"Created UI panel for plot_id: {config2['id']} in same row, section {config2['section']}") idx += 1 # If the next plot is in a new section, it will be handled in the next iteration of the while loop, # starting with a new section title and a new gr.Row. logging.info(f"Finished building plot area. Total plot objects: {len(plot_ui_objects)}. Section titles created: {len(section_titles_map)}") if len(plot_ui_objects) != len(plot_configs): logging.error(f"MISMATCH: Expected {len(plot_configs)} plot objects, but created {len(plot_ui_objects)}.") return plot_ui_objects, section_titles_map def create_enhanced_report_tab(agentic_modules_loaded_status: bool): """ Creates an enhanced report tab with Medium-style design for optimal readability. This function returns the Gradio components that will be updated. """ # Custom CSS for Medium-style design report_css = """ """ # Inject custom CSS gr.HTML(report_css) # Main container with gr.Column(elem_classes=["report-container"]): # Header section with gr.Column(elem_classes=["report-header"]): # This HTML component will display the dynamic title and subtitle report_header_html_display = gr.HTML("""
📊 Comprehensive Analysis Report
AI-Generated Insights from Your LinkedIn Data
Generated from Bubble.io
""") # Report selection section with gr.Column(elem_classes=["report-selection"]): gr.HTML("""
Report Library
Select a pre-generated report from your analysis library to view detailed insights, trends, and recommendations based on your LinkedIn organization data.
""") # Status indicator (now hidden by default via CSS) agentic_pipeline_status_md = gr.Markdown( "🔄 **Status:** Loading report data...", elem_classes=["loading-indicator"] # This class now hides the element ) # Report selector dropdown with gr.Row(): report_selector_dd = gr.Dropdown( label="📋 Select Report", choices=[], interactive=True, info="Choose from your available analysis reports", elem_classes=["report-dropdown"] ) # Report content display area with gr.Column(elem_classes=["report-content"]): # This Markdown component will display the actual report text, formatted as Markdown report_body_markdown_display = gr.Markdown( """
📄
No Report Selected
Please select a report from the library above to view its detailed analysis and insights.
""", # Apply styles to the content within the Markdown component using a wrapper div elem_classes=["report-body-content"] ) # Error handling for when modules are not loaded if not agentic_modules_loaded_status: gr.HTML("""
âš ī¸ Module Loading Error
Agentic analysis modules could not be loaded. Please check your configuration.
""") # Return both header HTML and body Markdown components for app.py to update return agentic_pipeline_status_md, report_selector_dd, report_header_html_display, report_body_markdown_display