File size: 16,811 Bytes
247642a
 
 
c7ac04c
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecacd2c
5ed1762
 
 
 
 
 
 
 
d5622b5
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5622b5
5ed1762
 
 
 
 
 
 
 
 
 
 
 
d5622b5
 
5ed1762
54dbea6
d5622b5
 
54dbea6
 
 
5ed1762
d5622b5
 
5ed1762
 
54dbea6
d5622b5
5ed1762
 
 
f5dc9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ed1762
 
 
 
 
 
 
427172c
 
 
5ed1762
 
ecacd2c
 
 
a576dc9
 
 
 
 
ecacd2c
54dbea6
f5dc9c2
c62aef1
 
 
 
 
 
 
 
 
 
 
 
5ed1762
 
 
 
 
 
 
f5dc9c2
 
 
 
 
 
 
 
 
 
 
5ed1762
c62aef1
5ed1762
 
 
 
f5dc9c2
13ace81
 
 
 
 
 
 
5fd6e58
 
 
 
 
 
 
 
 
0cef694
c62aef1
 
 
 
 
5ed1762
c62aef1
5ed1762
 
 
c62aef1
5ed1762
c62aef1
5ed1762
 
 
 
c62aef1
5ed1762
 
 
 
 
 
 
 
 
 
c7ac04c
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
ecacd2c
 
 
 
 
 
 
a576dc9
 
 
 
 
 
 
ecacd2c
 
 
a576dc9
 
 
 
 
 
ecacd2c
 
13ace81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd2d73e
 
 
 
 
 
 
 
 
 
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecacd2c
 
 
 
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecacd2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
ecacd2c
 
 
 
 
 
 
 
 
 
 
 
 
 
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c62aef1
 
5ed1762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# 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(
        """
        <script>
        (function() {
            var INTERVAL = 90000;  // 90 seconds
            var lastActivity = Date.now();
            var events = ['scroll', 'mousemove', 'keydown', 'touchstart', 'click', 'wheel'];
            var doc;
            try { doc = window.parent.document; } catch(e) { return; }

            events.forEach(function(e) {
                doc.addEventListener(e, function() { lastActivity = Date.now(); }, {passive: true});
            });

            setInterval(function() {
                if (Date.now() - lastActivity < INTERVAL) {
                    // User was active โ€” trigger Streamlit rerun to refresh heartbeat
                    try { window.parent.location.reload(); } catch(e) {}
                }
            }, INTERVAL);
        })();
        </script>
        """,
        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"""
        <style>
        /* Hide default Streamlit status widget entirely */
        [data-testid="stStatusWidget"] {{
            display: none !important;
        }}
{_hide_admin_css}
        /* Slowbro pill โ€” injected into Streamlit's fixed header via ::after */
        [data-testid="stHeader"]::after {{
            content: "Slowbro is resting...";
            position: absolute;
            top: 50%;
            right: 46px;
            transform: translateY(-50%);
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 3px 12px 3px 30px;
            border-radius: 20px;
            background: rgba(50,50,50,0.9) url("{_slowbro_img}") no-repeat 6px center / 20px 20px;
            font-size: 0.76rem;
            color: #bbb;
            pointer-events: none;
            white-space: nowrap;
            z-index: 999;
        }}
        </style>
        """,
        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(
        "<p style='font-size:0.7rem; color:#888; text-align:center;'>"
        "&copy; 2026 Hengzhe Zhao<br>"
        "Dual-licensed: <a href='https://github.com/WilZ2200/prefero/blob/main/LICENSE' "
        "target='_blank' style='color:#888;'>AGPL-3.0</a> &amp; Commercial</p>",
        unsafe_allow_html=True,
    )


def require_data() -> None:
    """Show a blocking message and stop if no data is loaded."""
    if not data_is_loaded():
        st.warning("Please load a dataset first on the **Data** page.")
        st.stop()


# โ”€โ”€ Multilingual scrolling banner โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

_TRANSLATIONS = [
    ("Prefero", "en"),
    ("ใƒ—ใƒฌใƒ•ใ‚งใƒญ", "ja"),
    ("ํ”„๋ ˆํŽ˜๋กœ", "ko"),
    ("ะŸั€ะตั„ะตั€ะพ", "ru"),
    ("ุจุฑูŠููŠุฑูˆ", "ar"),
    ("เคชเฅเคฐเฅ‡เคซเคผเฅ‡เคฐเฅ‹", "hi"),
    ("เน€เธžเธฃเน€เธŸเน‚เธฃ", "th"),
    ("ฮ ฯฮตฯ†ฮญฯฮฟ", "el"),
    ("แƒžแƒ แƒ”แƒคแƒ”แƒ แƒ", "ka"),
    ("ืคืจืคืจื•", "he"),
    ("เฆชเงเฆฐเง‡เฆซเง‡เฆฐเง‹", "bn"),
    ("เฐชเฑเฐฐเฑ†เฐซเฑ†เฐฐเฑ‹", "te"),
    ("Prรฉfรฉro", "fr"),
    ("Prefero", "la"),
]


def language_banner() -> None:
    """Render the scrolling multilingual Prefero banner."""
    st.markdown(
        """
        <style>
        @keyframes scroll-left {
            0%   { transform: translateX(0%); }
            100% { transform: translateX(-50%); }
        }
        .scroll-banner-wrap {
            position: relative;
            margin-bottom: 8px;
        }
        .scroll-banner {
            overflow: hidden;
            white-space: nowrap;
            padding: 12px 0;
            border-top: 1px solid rgba(128,128,128,0.2);
            border-bottom: 1px solid rgba(128,128,128,0.2);
        }
        .scroll-inner {
            display: inline-block;
            animation: scroll-left 30s linear infinite;
        }
        .scroll-inner span {
            font-size: 1.05rem;
            letter-spacing: 0.03em;
            opacity: 0.75;
            padding: 0 16px;
        }
        .scroll-inner .zh { font-weight: 700; opacity: 1.0; font-size: 1.2rem; }
        .banner-help {
            position: absolute;
            right: 6px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
        }
        .banner-help-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: rgba(128,128,128,0.18);
            color: rgba(128,128,128,0.7);
            font-size: 0.75rem;
            font-weight: 600;
            cursor: default;
            user-select: none;
            line-height: 1;
        }
        .banner-help-icon:hover {
            background: rgba(128,128,128,0.30);
            color: rgba(128,128,128,0.95);
        }
        .banner-help-tooltip {
            display: none;
            position: absolute;
            right: 0;
            top: 28px;
            width: 260px;
            padding: 12px 14px;
            background: var(--background-color, #fff);
            border: 1px solid rgba(128,128,128,0.2);
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.10);
            white-space: normal;
            font-size: 0.82rem;
            line-height: 1.5;
            color: var(--text-color, #444);
            z-index: 100;
        }
        .banner-help:hover .banner-help-tooltip {
            display: block;
        }
        </style>
        """,
        unsafe_allow_html=True,
    )

    span_html = ""
    for name, lang in _TRANSLATIONS:
        cls = "zh" if lang == "zh" else ""
        span_html += f'<span class="{cls}">{name}</span>\u00b7'
    doubled = span_html * 2

    st.markdown(
        f"""
        <div class="scroll-banner-wrap">
            <div class="scroll-banner">
                <div class="scroll-inner">{doubled}</div>
            </div>
            <div class="banner-help">
                <div class="banner-help-icon">?</div>
                <div class="banner-help-tooltip">
                    The name <b>Prefero</b> is shown in many languages
                    to celebrate the wonderful diversity of our users.
                    Translations may not be perfectly accurate &mdash;
                    if you spot an error, we would love to hear from you
                    on the <b>Community</b> page!
                </div>
            </div>
        </div>
        """,
        unsafe_allow_html=True,
    )


# โ”€โ”€ Page-to-page navigation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

_SLOWBRO_NAV_IMG = (
    "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites"
    "/pokemon/other/official-artwork/80.png"
)

_PAGE_ORDER = [
    ("pages/1_๐Ÿ“Š_Data.py", "Data", "๐Ÿ“Š"),
    ("pages/2_โš™๏ธ_Model.py", "Model", "โš™๏ธ"),
    ("pages/3_๐Ÿ“ˆ_Results.py", "Results", "๐Ÿ“ˆ"),
    ("pages/4_๐Ÿ”„_Compare.py", "Compare", "๐Ÿ”„"),
    ("pages/5_๐ŸŽฏ_Bootstrap.py", "Bootstrap", "๐ŸŽฏ"),
    ("pages/6_๐Ÿ“_Report.py", "Report", "๐Ÿ“"),
    ("pages/7_๐Ÿ’ฌ_Community.py", "Community", "๐Ÿ’ฌ"),
]


def slowbro_next_step(current_page: str) -> None:
    """Render a 'Slowbro guides you to the next step' button at page bottom.

    Parameters
    ----------
    current_page : str
        The page file path relative to app/, e.g. "pages/1_๐Ÿ“Š_Data.py".
    """
    current_idx = None
    for i, (path, _, _) in enumerate(_PAGE_ORDER):
        if path == current_page:
            current_idx = i
            break

    if current_idx is None or current_idx >= len(_PAGE_ORDER) - 1:
        return  # last page or unknown โ€” no next step

    next_path, next_name, next_icon = _PAGE_ORDER[current_idx + 1]

    st.divider()
    col_img, col_btn = st.columns([1, 4])
    with col_img:
        st.image(_SLOWBRO_NAV_IMG, width=64)
    with col_btn:
        st.markdown(
            f"<p style='margin:0; color:gray; font-size:0.85em;'>"
            f"Slowbro guides you to the next step</p>",
            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)