# Copyright (C) 2026 Hengzhe Zhao. All rights reserved. # Licensed under dual license: AGPL-3.0 (open-source) or commercial. See LICENSE. """Shared utilities for the Prefero multi-page Streamlit app.""" from __future__ import annotations import sys from pathlib import Path import streamlit as st ROOT = Path(__file__).resolve().parents[1] SRC = ROOT / "src" if str(SRC) not in sys.path: sys.path.insert(0, str(SRC)) from auth import auth_gate, username_gate # noqa: E402 from session_queue import queue_gate, heartbeat as queue_heartbeat, is_session_active # noqa: E402 # ── session-state keys and their defaults ────────────────────────── _SESSION_DEFAULTS: dict[str, object] = { "df": None, "data_label": "", "true_params": {}, "model_results": None, "model_history": [], "bootstrap_results": None, "lc_result": None, "lc_bic_comparison": None, "lc_best_q": None, "saved_models": [], "authenticated": False, "auth_email": "", "username": "", "user_id": 0, } def require_auth() -> None: """Run the auth gate. Currently a no-op (open access).""" if not auth_gate(): st.stop() def require_queue_slot() -> None: """Block the page if the server is at capacity. When queue is disabled (default for local dev), this is a no-op. Otherwise shows a branded waiting room with cultural queuing facts. """ if not queue_gate(): st.stop() def _check_session_timeout() -> None: """If the session was evicted due to inactivity, clear state and redirect. Skips the check when estimation is actively running (the user is waiting for Slowbro to finish, not actually idle). """ import os if os.environ.get("PREFERO_QUEUE_ENABLED", "").lower() != "true": return # queue disabled → no timeout # Don't kick users while estimation is running if st.session_state.get("_estimation_running"): return if not st.session_state.get("username"): return # no username set → nothing to expire # Only check if user was previously admitted to the queue. # Without this, fresh users who haven't entered the queue yet # would be incorrectly treated as evicted. if not st.session_state.get("_queue_admitted"): return if not is_session_active(): # Session was evicted — clear state so user re-enters for key in ("username", "user_id"): st.session_state[key] = _SESSION_DEFAULTS.get(key, "") st.session_state.pop("_queue_session_id", None) st.session_state.pop("_queue_admitted", None) st.warning("Your session expired due to inactivity. Please choose a username to continue.") st.stop() def _inject_activity_heartbeat() -> None: """Inject JavaScript that detects user activity and auto-refreshes to keep the session alive. Monitors scroll, mouse movement, keyboard, and touch events on the parent document. If activity is detected within the last 90 seconds, triggers a lightweight page reload every 90 seconds. Streamlit session state persists across reloads, so the heartbeat() call in init_session_state() naturally refreshes the server-side timestamp. """ import os if os.environ.get("PREFERO_QUEUE_ENABLED", "").lower() != "true": return # no queue → no need for activity tracking import streamlit.components.v1 as _components _components.html( """ """, height=0, ) def init_session_state() -> None: """Ensure every shared session-state key exists with its default value.""" for key, default in _SESSION_DEFAULTS.items(): if key not in st.session_state: st.session_state[key] = default _check_session_timeout() require_auth() # username_gate removed — visitors see the home page directly # if not username_gate(): # st.stop() require_queue_slot() queue_heartbeat() if not st.session_state.get("_saved_models_loaded"): username = st.session_state.get("username", "") if username: try: from model_store import load_models st.session_state.saved_models = load_models(username) except Exception: st.session_state.saved_models = [] st.session_state._saved_models_loaded = True st.session_state["_queue_admitted"] = True _inject_activity_heartbeat() import inspect _caller = inspect.stack()[1].filename _page = Path(_caller).stem _visit_key = f"_visited_{_page}" if not st.session_state.get(_visit_key): st.session_state[_visit_key] = True try: from community_db import init_db, log_activity init_db() log_activity(st.session_state.get("username", "anonymous"), "page_visit", _page) except Exception: pass def data_is_loaded() -> bool: """Return True when a DataFrame has been loaded into session state.""" return st.session_state.get("df") is not None def _is_admin_user() -> bool: """Check if the current user has admin privileges.""" import os admin_csv = os.environ.get("PREFERO_ADMIN_USERS", "") if not admin_csv.strip(): return False admin_users = {u.strip().lower() for u in admin_csv.split(",") if u.strip()} current = st.session_state.get("username", "").strip().lower() return current in admin_users def slowbro_status() -> None: """Inject global Slowbro status widget into Streamlit's fixed header.""" _slowbro_img = ( "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites" "/pokemon/other/official-artwork/80.png" ) # Hide Admin from sidebar unless developer mode is active _hide_admin_css = "" if not st.session_state.get("_dev_mode_active"): _hide_admin_css = """ [data-testid="stSidebarNav"] a[href*="Admin"] { display: none !important; } """ st.markdown( f""" """, unsafe_allow_html=True, ) def sidebar_branding() -> None: """Render common sidebar branding and data-status indicator.""" slowbro_status() st.sidebar.markdown("## Prefero") st.sidebar.caption("Discrete Choice Experiment Analysis") username = st.session_state.get("username", "") if username: st.sidebar.caption(f"Signed in as **{username}**") st.sidebar.divider() if data_is_loaded(): st.sidebar.success(f"Data loaded: {st.session_state.data_label}") else: st.sidebar.info("No data loaded yet.") # ── Saved models in sidebar ── _saved = st.session_state.get("saved_models", []) if _saved: with st.sidebar.expander(f"Saved Models ({len(_saved)}/10)", expanded=False): _sb_delete_idx: int | None = None for i, sm in enumerate(_saved): est = sm.get("estimation") try: _ll = f"{est.log_likelihood:.1f}" except Exception: _ll = "?" st.caption(f"**{sm.get('label', 'model')}** ({sm.get('model_type', '?')}) LL:{_ll}") if st.button("✕ Delete", key=f"_sb_del_saved_{i}"): _sb_delete_idx = i if _sb_delete_idx is not None: _uname = st.session_state.get("username", "") if _uname: try: from model_store import delete_saved_model, load_models if delete_saved_model(_uname, _sb_delete_idx): st.session_state.saved_models = load_models(_uname) except Exception: pass st.rerun() # Developer mode prompt (admin users only) if _is_admin_user() and not st.session_state.get("_dev_mode_active"): import os _dev_key = os.environ.get("PREFERO_ADMIN_PASSWORD", "") if _dev_key: st.sidebar.divider() with st.sidebar.expander("Developer Mode"): key_input = st.text_input("Developer key", type="password", key="_sidebar_dev_key") if st.button("Unlock", key="_sidebar_dev_unlock", use_container_width=True): if key_input == _dev_key: st.session_state["_dev_mode_active"] = True st.rerun() else: st.error("Incorrect key.") # ── License notice (always at sidebar bottom) ── st.sidebar.divider() st.sidebar.markdown( "
"
"© 2026 Hengzhe Zhao
"
"Dual-licensed: AGPL-3.0 & Commercial
" f"Slowbro guides you to the next step
", unsafe_allow_html=True, ) if st.button( f"{next_icon} Go to {next_name}", key=f"_nav_next_{next_name}", use_container_width=True, ): st.switch_page(next_path)