# -*- coding: utf-8 -*- import gradio as gr import json # requests, os, urllib.parse are used by Bubble_API_Calls.py, not directly here anymore # but good to keep if you add other direct calls later. # Assuming these custom modules exist in your project directory or Python path from Data_Fetching_and_Rendering import fetch_and_render_dashboard from analytics_fetch_and_rendering import fetch_and_render_analytics from mentions_dashboard import generate_mentions_dashboard # Import the function from your utils file from gradio_utils import get_url_user_token # Import the Bubble API call function (ensure filename matches: Bubble_API_Calls.py) from Bubble_API_Calls import fetch_linkedin_token_from_bubble # --- Session State dependent functions --- def check_token_status(current_token_state): """Checks if a valid token exists in the session state.""" if current_token_state and current_token_state.get("token") and current_token_state.get("status"): return "✅ Token available" return "❌ Waiting for token…" def get_active_client_id(current_token_state): """Gets the client_id from the session state if a token is available.""" if current_token_state and current_token_state.get("token") and current_token_state.get("status"): return current_token_state.get("client_id", "Client ID not set") return "" # --- Function to process and store token from Bubble --- def process_and_store_bubble_token(url_user_token_str, current_token_state): """ Fetches token from Bubble, updates session state, and returns UI update values. Args: url_user_token_str: The token string extracted from the URL. current_token_state: The current session state for the token. Returns: Tuple: (bubble_api_status_msg, overall_status, client_id_display, updated_token_state) """ bubble_api_status_msg = "Waiting for URL token..." new_token_state = current_token_state.copy() if current_token_state else {"status": False, "token": None, "client_id": None} if not url_user_token_str or "not found" in url_user_token_str or "Could not access" in url_user_token_str: bubble_api_status_msg = f"ℹ️ No valid user token from URL to query Bubble. ({url_user_token_str})" # Even if no valid URL token, return current status based on existing state return bubble_api_status_msg, check_token_status(new_token_state), get_active_client_id(new_token_state), new_token_state print(f"Attempting to fetch token from Bubble with state: {url_user_token_str}") parsed_token_dict = fetch_linkedin_token_from_bubble(url_user_token_str) if parsed_token_dict and isinstance(parsed_token_dict, dict) and "access_token" in parsed_token_dict: new_token_state["status"] = True new_token_state["token"] = parsed_token_dict new_token_state["client_id"] = f"Bubble (state: {url_user_token_str})" bubble_api_status_msg = f"✅ Token successfully fetched from Bubble for state: {url_user_token_str}" print(bubble_api_status_msg) else: # Fetch failed or no valid token returned, keep previous state or mark as no token # If you want a Bubble failure to explicitly clear any old token: # new_token_state["status"] = False # new_token_state["token"] = None # new_token_state["client_id"] = None # For now, it just means the Bubble fetch didn't provide a new one. bubble_api_status_msg = f"❌ Failed to fetch a valid token from Bubble for state: {url_user_token_str}. Check console logs from Bubble_API_Calls.py." print(bubble_api_status_msg) # If the goal is that ONLY a successful bubble fetch provides a token, then reset status: new_token_state["status"] = False new_token_state["token"] = None # client_id might be kept or cleared based on preference # new_token_state["client_id"] = f"Bubble fetch failed (state: {url_user_token_str})" return bubble_api_status_msg, check_token_status(new_token_state), get_active_client_id(new_token_state), new_token_state # --- Guarded fetch functions (now use token_state) --- def guarded_fetch_dashboard(current_token_state): if not (current_token_state and current_token_state.get("status") and current_token_state.get("token")): return "

❌ Access denied. No token available.

" html = fetch_and_render_dashboard( current_token_state["client_id"], current_token_state["token"] ) return html def guarded_fetch_analytics(current_token_state): if not (current_token_state and current_token_state.get("status") and current_token_state.get("token")): return ( "

❌ Access denied. No token available.

", None, None, None, None, None, None, None ) client_id = current_token_state["client_id"] token_data = current_token_state["token"] count_md, plot, growth_plot, avg_post_eng_rate, interaction_metrics, eb_metrics, mentions_vol_metrics, mentions_sentiment_metrics = fetch_and_render_analytics( client_id, token_data ) return count_md, plot, growth_plot, avg_post_eng_rate, interaction_metrics, eb_metrics, mentions_vol_metrics, mentions_sentiment_metrics def run_mentions_and_load(current_token_state): if not (current_token_state and current_token_state.get("status") and current_token_state.get("token")): return ("

❌ Access denied. No token available.

", None) html, fig = generate_mentions_dashboard( current_token_state["client_id"], current_token_state["token"] ) return html, fig # --- Build the Gradio UI --- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"), title="LinkedIn Post Viewer & Analytics") as app: # Session state to store the token info # Initial value is a dictionary representing an unauthenticated state. token_state = gr.State(value={"status": False, "token": None, "client_id": None}) gr.Markdown("# 🚀 LinkedIn Organization Post Viewer & Analytics") gr.Markdown("Token is supplied via URL parameter for Bubble.io lookup. Then explore dashboard and analytics.") # Hidden textbox to capture token from URL url_user_token_display = gr.Textbox( label="User Token (from URL - Hidden)", interactive=False, placeholder="Attempting to load from URL...", visible=False ) # Display for Bubble API call status bubble_api_status_display = gr.Textbox(label="Bubble API Call Status", interactive=False, placeholder="Waiting for URL token...") # Overall status displays status_box = gr.Textbox(label="Overall Token Status", interactive=False) client_display = gr.Textbox(label="Client ID (Active)", interactive=False) # Note: The textbox for displaying the actual token is removed. # --- Load URL parameter on app start & Link to Bubble Fetch --- app.load( fn=get_url_user_token, inputs=None, # get_url_user_token takes gr.Request implicitly outputs=[url_user_token_display] ) # When the hidden url_user_token_display changes (due to app.load), # trigger the Bubble API call and update session state. url_user_token_display.change( fn=process_and_store_bubble_token, inputs=[url_user_token_display, token_state], # Pass current state outputs=[bubble_api_status_display, status_box, client_display, token_state] # Update UI and state ) # Initial UI state based on initial token_state app.load(fn=check_token_status, inputs=[token_state], outputs=status_box) app.load(fn=get_active_client_id, inputs=[token_state], outputs=client_display) # Timer to periodically update status (e.g., if token could expire or be managed externally) # This might be less critical if token acquisition is only at the start via URL. timer = gr.Timer(5.0) # Poll every 5 seconds, adjust as needed timer.tick(fn=check_token_status, inputs=[token_state], outputs=status_box) timer.tick(fn=get_active_client_id, inputs=[token_state], outputs=client_display) # Tabs for functionality with gr.Tabs(): with gr.TabItem("1️⃣ Dashboard"): gr.Markdown("View your organization's recent posts and their engagement statistics.") fetch_dashboard_btn = gr.Button("📊 Fetch Posts & Stats", variant="primary") dashboard_html = gr.HTML(value="

Waiting for token...

") fetch_dashboard_btn.click( fn=guarded_fetch_dashboard, inputs=[token_state], # Pass session state outputs=[dashboard_html] ) with gr.TabItem("2️⃣ Analytics"): gr.Markdown("View follower count and monthly gains for your organization.") fetch_analytics_btn = gr.Button("📈 Fetch Follower Analytics", variant="primary") follower_count = gr.Markdown("

Waiting for token...

") with gr.Row(): follower_plot = gr.Plot(visible=True) growth_rate_plot = gr.Plot(visible=True) with gr.Row(): post_eng_rate_plot = gr.Plot(visible=True) with gr.Row(): interaction_data = gr.Plot(visible=True) with gr.Row(): eb_data = gr.Plot(visible=True) with gr.Row(): mentions_vol_data = gr.Plot(visible=True) mentions_sentiment_data = gr.Plot(visible=True) fetch_analytics_btn.click( fn=guarded_fetch_analytics, inputs=[token_state], # Pass session state outputs=[follower_count, follower_plot, growth_rate_plot, post_eng_rate_plot, interaction_data, eb_data, mentions_vol_data, mentions_sentiment_data] ) with gr.TabItem("3️⃣ Mentions"): gr.Markdown("Analyze sentiment of recent posts that mention your organization.") fetch_mentions_btn = gr.Button("🧠 Fetch Mentions & Sentiment", variant="primary") mentions_html = gr.HTML(value="

Waiting for token...

") mentions_plot = gr.Plot(visible=True) fetch_mentions_btn.click( fn=run_mentions_and_load, inputs=[token_state], # Pass session state outputs=[mentions_html, mentions_plot] ) # Launch the app if __name__ == "__main__": # Ensure the 'Bubble_API' environment variable is set where this app is run. app.launch(server_name="0.0.0.0", server_port=7860, share=True)