""" Curium Lead Intelligence Platform - Main Entry Point Multipage Streamlit app with shared sidebar and role-based access control. """ import streamlit as st import time import os from pathlib import Path from dotenv import load_dotenv # Load environment variables env_path = Path(__file__).parent / '.env' load_dotenv(dotenv_path=env_path, override=True) # Import modules from network_loader import init_network_tables, get_network_stats, load_master_csv from collator import init_company_db, get_company_stats, get_all_source_health from ui_components import inject_global_css, render_source_health_dots from settings_store import ( init_settings_table, get_scheduled_hunt_enabled, set_scheduled_hunt_enabled, set_last_hunt_at, set_last_council_scan_at, hunt_cooldown_status, format_relative, ) import auth from audit_log import log_event def check_api_key(): return bool(os.environ.get("ANTHROPIC_API_KEY")) def run_autonomous_hunt(status_container=None): """Run the fully autonomous hunter with progress updates.""" from hunter import run_hunt def progress_callback(msg): if status_container: status_container.write(msg) return run_hunt(min_score=50, progress_callback=progress_callback) # ============================================================================= # PAGE CONFIG # ============================================================================= st.set_page_config( page_title="Curium Lead Intelligence", page_icon="\U0001f3af", layout="wide" ) # State sync β€” pull leads.db from HF Dataset BEFORE we initialise the DB # tables. The Dockerfile CMD runs `streamlit` directly (bypassing # entrypoint.sh), so the pull MUST happen here to work on HF Spaces. No-op # if HF_TOKEN / HF_STATE_REPO Space secrets aren't set. try: import state_sync state_sync.pull_state(verbose=True) except Exception as _ssync_err: print(f"[app] state_sync pull failed (non-fatal): {_ssync_err}", flush=True) init_company_db() init_network_tables() init_settings_table() # Start the periodic state-sync after init so the first periodic push has # real data to push (and won't no-op on the safety guard). try: state_sync.start_periodic_sync() except Exception as _ssync_err: print(f"[app] state_sync init failed (non-fatal): {_ssync_err}", flush=True) # Inject global CSS inject_global_css() # ============================================================================= # PUBLIC FEEDBACK FORM β€” bypasses auth when ?form=feedback in the URL. # Linked from the bottom of every weekly digest email so recipients can # submit feedback without logging in. Renders just the form, nothing else. # ============================================================================= if st.query_params.get("form") == "feedback": from feedback_form import render_feedback_form render_feedback_form() st.stop() # ============================================================================= # ONE-CLICK EMAIL CTA HANDLER # Handles ?action=converted|not_relevant|actioned&token=lead-xxx&from=Name # Linked from CTA buttons inside the weekly digest email. Runs before auth # so the recipient doesn't need to be logged in β€” the token + from param # is sufficient to record the action. # ============================================================================= _cta_action = st.query_params.get("action", "") _cta_token = st.query_params.get("token", "") _cta_from = st.query_params.get("from", "") if _cta_action in ("converted", "not_relevant", "actioned") and _cta_token: try: from collator import add_lead_action # Extract a human-readable company name from the token # Token format: lead--YYYYwWW β†’ slug is the company identifier import re as _re _slug_match = _re.match(r"lead-(.+)-\d{4}w\d{2}$", _cta_token) _company = _slug_match.group(1).replace("-", " ").title() if _slug_match else _cta_token add_lead_action( company=_company, colleague=_cta_from or "email_cta", action=_cta_action, notes=f"One-click CTA from digest email (token: {_cta_token})", ) _ACTION_LABELS = { "converted": ("πŸ†", "Brilliant!", "That's logged as a conversion."), "not_relevant": ("πŸ‘", "Got it.", "We'll drop that one from your list."), "actioned": ("βœ…", "Nice work.", "That's logged β€” we'll follow up next week."), } _icon, _heading, _body = _ACTION_LABELS[_cta_action] st.markdown( f"""
{_icon}

{_heading}

{_body}

{_company} {(' β€” logged for ' + _cta_from) if _cta_from else ''}

Open dashboard β†’
""", unsafe_allow_html=True, ) except Exception as _e: st.error(f"Couldn't record that action: {_e}") st.stop() # ============================================================================= # AUTH GATE - login screen blocks rendering until signed in # ============================================================================= auth.render_login_screen() has_api_key = check_api_key() is_admin = auth.is_admin() # ============================================================================= # SIDEBAR - Shared across all pages # ============================================================================= with st.sidebar: st.markdown( '
' 'CURIUM
' 'Lead Intelligence Platform' '
', unsafe_allow_html=True, ) auth.render_user_chip() st.divider() # ------------------------------------------------------------------------- # HUNT NOW (admin only, with cooldown) # ------------------------------------------------------------------------- hunt_cd = hunt_cooldown_status() hunt_blocked_by_cooldown = hunt_cd["locked"] hunt_disabled = (not has_api_key) or (not is_admin) or hunt_blocked_by_cooldown if not is_admin: hunt_help = auth.ADMIN_BLOCKED_TOOLTIP elif hunt_blocked_by_cooldown: unlock_str = hunt_cd["unlock_at"].astimezone().strftime("%H:%M") hunt_help = ( f"Cooldown active \u2014 next hunt available at {unlock_str} " f"({hunt_cd['minutes_remaining']} min). Cooldown: {hunt_cd['cooldown_minutes']} min." ) else: hunt_help = ( "**Full intelligence sweep** \u2014 broad market discovery + targeted UK council scan.\n\n" "Scans 9 sources: Jobs \u00b7 News \u00b7 Tenders \u00b7 Annual Reports \u00b7 " "Employee Sentiment \u00b7 M&A/PE Deals \u00b7 LinkedIn Groups \u00b7 LinkedIn Intel " "\u00b7 Councils (~70 UK councils with per-council network mapping).\n\n" "Signal-driven \u2014 a news headline or job posting can surface a brand new company " "to track. Best for weekly intelligence refresh and Market Research briefings. " "Takes 10\u201320 minutes." ) if st.button("\U0001f680 HUNT NOW", type="primary", use_container_width=True, disabled=hunt_disabled, help=hunt_help): if is_admin and not hunt_blocked_by_cooldown: log_event(auth.current_user(), auth.current_role(), "hunt_now_started", {}) # Stamp the cooldown timestamp BEFORE running the hunt. On HF Spaces # the websocket can drop a long-running script before completion; # we still want "Last hunt" to reflect that an attempt was made # (and to enforce the cooldown so the user can't hammer the button). set_last_hunt_at() status_box = st.empty() progress_container = st.container() with progress_container: st.write("**Live Progress:**") status_area = st.empty() try: results = run_autonomous_hunt(status_area) st.session_state['last_hunt_results'] = results log_event(auth.current_user(), auth.current_role(), "hunt_now_completed", {"new_companies": (results or {}).get("new_companies", 0)}) # Critical-path persistence: hunt just finished, push state # to HF Dataset immediately so a container restart can't # erase the work. try: import state_sync as _ssync _ssync.push_state(verbose=True) except Exception: pass time.sleep(1) st.rerun() except Exception as e: log_event(auth.current_user(), auth.current_role(), "hunt_now_failed", {"error": str(e)}) st.error(f"Hunt failed: {e}") # Last-hunt freshness indicator (visible to ALL users) # Use not markdown ** because the surrounding div uses # unsafe_allow_html which doesn't parse markdown. last_hunt_caption = f"Last hunt: {format_relative(hunt_cd['last_at'])}" if hunt_blocked_by_cooldown and is_admin: last_hunt_caption += f" \u00b7 next available in {hunt_cd['minutes_remaining']} min" st.markdown( f'
' f'{last_hunt_caption}
', unsafe_allow_html=True, ) if not is_admin: st.caption("View-only account") elif not has_api_key: st.warning("\u26a0\ufe0f ANTHROPIC_API_KEY not set in environment") # Source health indicator dots (visible to all) try: source_health = get_all_source_health() render_source_health_dots(source_health) except Exception: pass # ------------------------------------------------------------------------- # State persistence (HF Dataset sync) β€” admin can force a push, all see status # ------------------------------------------------------------------------- try: import state_sync sync_st = state_sync.status() if sync_st["configured"]: last_pushed = sync_st.get("last_pushed_at") last_pulled = sync_st.get("last_pulled_at") caption_parts = [f"πŸ’Ύ {sync_st['repo']}"] if last_pulled: caption_parts.append(f"pulled {last_pulled[11:16]}") if last_pushed: caption_parts.append(f"pushed {last_pushed[11:16]}") elif last_pulled: caption_parts.append("no push yet (auto every 5 min)") else: caption_parts.append("waiting for first sync") err = sync_st.get("last_error") caption = " Β· ".join(caption_parts) if err: caption += f" ⚠️ {err[:60]}" st.markdown( f'
{caption}
', unsafe_allow_html=True, ) # Surface any pending push result from a previous rerun so users # see explicit success/failure instead of silently swallowed errors. push_result = st.session_state.pop("state_push_result", None) if push_result: if push_result.get("success"): st.success(f"βœ… Pushed state ({push_result.get('size_mb','?')} MB)") else: st.error(f"❌ Push failed: {push_result.get('error','unknown')}") if is_admin: col_sync, col_diag = st.columns(2) with col_sync: if st.button("πŸ’Ύ Sync now", key="btn_state_sync_now", use_container_width=True, help="Push the current leads.db to the HF Dataset repo immediately."): with st.spinner("Pushing state…"): try: ok = state_sync.push_state(force=True, verbose=True) if ok: st.session_state["state_push_result"] = { "success": True, "size_mb": f"{Path('leads.db').stat().st_size/1024/1024:.1f}" if Path('leads.db').exists() else "?", } else: st.session_state["state_push_result"] = { "success": False, "error": state_sync.status().get("last_error") or "push returned False (unchanged?)", } except Exception as e: st.session_state["state_push_result"] = { "success": False, "error": f"{type(e).__name__}: {e}", } st.rerun() with col_diag: if st.button("πŸ” Diagnose", key="btn_state_diag", use_container_width=True, help="Run a full diagnostic of the state sync setup."): st.session_state["show_state_diag"] = True st.rerun() if is_admin and st.session_state.get("show_state_diag"): with st.expander("πŸ” State sync diagnostic", expanded=True): diag = state_sync.diagnose() for line in diag: st.markdown(line) if st.button("Hide diagnostic", key="btn_hide_state_diag"): st.session_state["show_state_diag"] = False st.rerun() else: if is_admin: with st.expander("⚠️ State persistence not configured"): st.markdown( "Without persistent storage, **all data wipes on every " "container restart** (every code push). To enable free " "persistence via a private HF Dataset repo, add these " "Space secrets:\n\n" "1. `HF_TOKEN` β€” an HF token with **write** access " "(create at huggingface.co/settings/tokens)\n" "2. `HF_STATE_REPO` β€” e.g. `mipwr-admin/curium-intel-state` " "(the repo will be auto-created on first push)\n\n" "Then redeploy. The DB is pulled at startup and pushed " "every 5 minutes if changed." ) except Exception as _ssync_err: pass st.divider() # Note: the Service Line filter (TD / CC / CODE 3i radio) was removed # from the sidebar β€” Dashboard.py defaults to 'All' when the session # value is missing, so removing the control simply locks the view to # 'All' which is the universal default. # Note: COUNCIL SCAN was a separate sidebar button. It's now folded into # HUNT NOW as the 9th source (handled in hunter.py), so we no longer # render a second button. The set_last_council_scan_at timestamp is # still updated by the council step inside hunter._hunt_councils for # backward compatibility. # ------------------------------------------------------------------------- # Quick stats (visible to all). Three sales-critical KPIs only \u2014 # per-source record counts duplicate the Source Health page, and were # removed from the sidebar to reduce noise. # ------------------------------------------------------------------------- try: sidebar_stats = get_company_stats() c1, c2, c3 = st.columns(3) c1.metric( "\U0001f3e2 Companies", sidebar_stats['total_companies'], help="Total companies tracked across all signals", ) c2.metric( "\U0001f525 Hot", sidebar_stats['hot_companies'], help="Companies scoring 50+ \u2014 your top-priority leads", ) c3.metric( "\U0001f517 Network", sidebar_stats['with_network'], help="Companies where the team has a LinkedIn connection (warm route in)", ) except Exception: st.caption("No data yet \u2014 run a hunt to get started") st.divider() # ------------------------------------------------------------------------- # Network (visible to all; upload is admin-only) # ------------------------------------------------------------------------- st.subheader("\U0001f517 Network") # Render any pending upload result from a previous rerun (so the toast # survives the st.rerun() that follows a successful import). pending = st.session_state.pop("network_upload_result", None) if pending: if pending.get("success") and pending.get("imported", 0) > 0: n = pending["imported"] colleagues = pending.get("colleagues", []) or [] st.success( f"\u2705 Loaded {n:,} connections from {len(colleagues)} team member" f"{'s' if len(colleagues) != 1 else ''}" ) st.info( "**Next:** click \U0001f3af **HUNT NOW** above to scan signals and " "match them against your team's network for warm intros." ) elif pending.get("success"): detected = pending.get("detected_columns") or {} headers = pending.get("headers") or [] st.warning( "File parsed but **0 connections imported**. " f"Rows scanned: {pending.get('total_rows', 0)}, " f"skipped (no name): {pending.get('skipped', 0)}, " f"errors: {pending.get('errors', 0)}." ) with st.expander("Debug: detected columns"): st.json({"detected": detected, "headers_seen": headers}) else: st.error(f"Import failed: {pending.get('error', 'Unknown error')}") if pending.get("trace"): with st.expander("Debug: traceback"): st.code(pending["trace"]) try: net_stats = get_network_stats() total = net_stats.get('total_connections', 0) or 0 team = net_stats.get('team_members') or [] if total > 0: st.caption( f"{total:,} connections loaded across {len(team)} team member" f"{'s' if len(team) != 1 else ''}" ) else: st.caption("0 connections loaded") except Exception: st.caption("No network data") if is_admin: uploaded_file = st.file_uploader( "Upload Connections", type=['csv', 'xlsx'], help="Upload your team's LinkedIn connections export (CSV or Excel). " "Required columns: Owner, Full Name, Company, Position. " "If a large XLSX silently fails, run " "`venv/bin/python scripts/prep_connections.py ` " "locally to produce a small CSV first.", ) with st.expander("ℹ️ Large XLSX won't upload?", expanded=False): st.markdown( "HF Spaces' edge proxy can silently drop file uploads above " "~10 MB (the in-browser upload looks fine but the bytes never " "reach Python). If your master workbook is large, convert it " "to a slim CSV locally first:\n\n" "```bash\n" "venv/bin/python scripts/prep_connections.py " "\"/path/to/LinkedIn Connection Data.xlsx\"\n" "```\n\n" "The script auto-picks the right sheet (prefers *New Data* " "with movement tracking) and writes a CSV next to the source β€” " "typically 3-5 MB. Upload that CSV here." ) # Diagnostic: log every render so we can tell from HF runtime logs # whether the file_uploader is delivering bytes to Python. If we see # repeated "uploaded_file=None" right after the user clicks upload, # the websocket/HTTP layer is dropping the file before the script runs. print( f"[network-upload] file_uploader -> " f"{'None' if uploaded_file is None else f'{uploaded_file.name} ({uploaded_file.size:,}B)'}", flush=True, ) if uploaded_file is not None: # Each upload is identified by name+size; only import once per upload. upload_key = f"{uploaded_file.name}:{uploaded_file.size}" if st.session_state.get("network_upload_processed") != upload_key: # Wrap the entire handler so any exception still produces a # toast on the post-rerun render, instead of silently killing # the rerun and leaving the user staring at "0 connections". try: os.makedirs("data", exist_ok=True) ext = uploaded_file.name.rsplit('.', 1)[-1].lower() if '.' in uploaded_file.name else 'csv' file_path = f"data/my_team_connections.{ext}" with open(file_path, "wb") as f: f.write(uploaded_file.getbuffer()) with st.spinner("Importing connections\u2026"): result = load_master_csv(file_path, clear_existing=True) except Exception as e: import traceback result = { "success": False, "error": f"{type(e).__name__}: {e}", "trace": traceback.format_exc(), "imported": 0, } st.session_state["network_upload_processed"] = upload_key st.session_state["network_upload_result"] = result log_event( auth.current_user(), auth.current_role(), "network_upload", { "imported": result.get("imported", 0), "success": result.get("success", False), "error": result.get("error"), }, ) # Critical-path persistence: 30k+ rows just imported β€” push to # HF Dataset immediately so it survives the next container restart. if result.get("success") and result.get("imported", 0) > 0: try: import state_sync as _ssync _ssync.push_state(verbose=True) except Exception: pass st.rerun() else: st.caption("\U0001f512 Connection upload is admin-only") st.divider() # ------------------------------------------------------------------------- # LinkedIn Deep Intelligence (admin only) # ------------------------------------------------------------------------- if is_admin: with st.expander("\U0001f50d LinkedIn Deep", expanded=False): st.caption("Enrich companies with LinkedIn profile data, mutual connections, and activity signals") try: from linkedin_intel import get_linkedin_session_status li_status = get_linkedin_session_status() if li_status == "connected": st.success("LinkedIn: Connected") elif li_status == "expired": st.warning("LinkedIn: Session expired") else: st.caption("LinkedIn: Not configured") if st.button("\U0001f510 Setup LinkedIn Login", use_container_width=True): st.session_state['linkedin_setup'] = True st.rerun() if st.session_state.get('linkedin_setup'): st.info( "A browser window will open. Please log in to LinkedIn " "(including 2FA if needed). Do NOT close the browser \u2014 " "it will close automatically once login is detected. " "(Note: this only works when running locally, not on Azure.)" ) try: from playwright.sync_api import sync_playwright from linkedin_intel import setup_linkedin_login with sync_playwright() as p: success = setup_linkedin_login(p) if success: log_event(auth.current_user(), auth.current_role(), "linkedin_login_setup", {"result": "success"}) st.success("LinkedIn login saved successfully!") else: st.error("Login timed out. Please try again.") except ImportError: st.error("Playwright not installed. Run: pip install playwright && playwright install chromium") except Exception as e: st.error(f"Login setup failed: {e}") finally: st.session_state['linkedin_setup'] = False try: from linkedin_intel import check_daily_limits limits = check_daily_limits() st.caption( f"Today: {limits['used_profiles']}/80 profiles, " f"{limits['used_searches']}/15 searches" ) except Exception: pass except ImportError: st.caption("LinkedIn module not available") st.divider() # --------------------------------------------------------------------- # Scheduled Hunt toggle (admin only) # Persisted to leads.db so the Container Apps Job sees the same state. # --------------------------------------------------------------------- with st.expander("\u23f0 Scheduled Hunt", expanded=False): st.caption( "Daily automated hunt at 07:00 UTC, Mon\u2013Fri. " "Not active yet \u2014 will be enabled when scheduled " "automation is configured (GitHub Actions or similar)." ) current_state = get_scheduled_hunt_enabled() new_state = st.toggle( "Enable scheduled daily hunt", value=current_state, key="scheduled_hunt_toggle", help="Pre-configured for future automation. When ON, the scheduled runner will execute hunts automatically. When OFF, it exits without spending API credits." ) if new_state != current_state: set_scheduled_hunt_enabled(new_state) log_event(auth.current_user(), auth.current_role(), "scheduled_hunt_toggle", {"enabled": new_state}) st.success(f"Scheduled hunt {'enabled' if new_state else 'disabled'}.") st.divider() # --------------------------------------------------------------------- # Database Backup & Restore (admin only) # On Hugging Face free tier, the disk is ephemeral. Use these to # download a snapshot before code pushes, and restore after rebuild. # --------------------------------------------------------------------- with st.expander("\U0001f4be Database Backup / Restore", expanded=False): st.caption( "Download a snapshot of leads.db before pushing code changes. " "After a Space rebuild, upload the file to restore." ) # Download db_path = Path("leads.db") if db_path.exists() and db_path.stat().st_size > 0: with open(db_path, "rb") as f: st.download_button( "\U0001f4e5 Download Database Backup", data=f, file_name="leads_backup.db", mime="application/x-sqlite3", use_container_width=True, ) st.caption(f"Size: {db_path.stat().st_size / 1024:.0f} KB") else: st.caption("No database to download yet \u2014 run a hunt first.") st.divider() # Restore restore_file = st.file_uploader( "Restore Database from Backup", type=["db"], key="restore_db_upload", help="Upload a leads_backup.db file to replace the current database", ) if restore_file is not None: import shutil # Safety: back up current DB before overwriting if db_path.exists(): shutil.copy2(db_path, db_path.with_suffix(".db.bak")) with open(db_path, "wb") as f: f.write(restore_file.getbuffer()) log_event(auth.current_user(), auth.current_role(), "database_restored", {"size_kb": len(restore_file.getbuffer()) // 1024}) st.success("\u2705 Database restored. Refreshing...") st.rerun() st.divider() # --------------------------------------------------------------------- # Clear All Data (admin only) - destructive # --------------------------------------------------------------------- if st.button("\U0001f5d1\ufe0f Clear All Data", type="secondary"): from collator import clear_all_data as clear_collator_data clear_collator_data() log_event(auth.current_user(), auth.current_role(), "clear_all_data", {}) st.rerun() # ============================================================================= # NAVIGATION # ============================================================================= pages = st.navigation([ st.Page("pages/1_Dashboard.py", title="Dashboard", icon="\U0001f3af", default=True), st.Page("pages/2_Approach_Brief.py", title="Approach Brief", icon="\U0001f4cb"), st.Page("pages/3_Tenders.py", title="Government Tenders", icon="\U0001f3db\ufe0f"), st.Page("pages/4_Councils.py", title="Council Opportunities", icon="\U0001f3db\ufe0f"), st.Page("pages/5_LinkedIn_Hub.py", title="LinkedIn Hub", icon="\U0001f517"), st.Page("pages/6_Intelligence.py", title="Intelligence Query", icon="\U0001f916"), st.Page("pages/8_Market_Research.py", title="Market Research", icon="\U0001f4f0"), st.Page("pages/7_Source_Health.py", title="Source Health", icon="\U0001f6e0\ufe0f"), ]) pages.run()