"""BNA Comparator -- Web Edition.""" from __future__ import annotations import io import json import os import subprocess import sys import tempfile import threading import time import uuid import zipfile from datetime import datetime from pathlib import Path import streamlit as st # ------------------------------------------------------------------- # Run queue — single process-wide queue so concurrent researcher # clicks serialize cleanly. Streamlit runs all sessions in one Python # process, so a module-level threading.Lock + list is sufficient. # ------------------------------------------------------------------- _QUEUE_LOCK = threading.Lock() _QUEUE: list[dict] = [] # [{"id": str, "started": bool}] def queue_enqueue(sid: str) -> None: with _QUEUE_LOCK: if not any(q["id"] == sid for q in _QUEUE): _QUEUE.append({"id": sid, "started": False}) def queue_position(sid: str) -> int: """0 = my turn now. N>0 = N batches ahead. -1 = not in queue.""" with _QUEUE_LOCK: for i, q in enumerate(_QUEUE): if q["id"] == sid: return i return -1 def queue_mark_started(sid: str) -> None: with _QUEUE_LOCK: for q in _QUEUE: if q["id"] == sid: q["started"] = True return def queue_dequeue(sid: str) -> None: with _QUEUE_LOCK: _QUEUE[:] = [q for q in _QUEUE if q["id"] != sid] HERE = Path(__file__).resolve().parent st.set_page_config( page_title="BNA vs AI -- Batch", page_icon="🧭", layout="wide", initial_sidebar_state="collapsed", ) CSS = """ """ st.markdown(CSS, unsafe_allow_html=True) _team_pw = os.environ.get("BNA_WEB_PASSWORD", "").strip() if _team_pw: if "auth_ok" not in st.session_state: st.session_state.auth_ok = False if not st.session_state.auth_ok: st.markdown( '
🔒
' '

BNA Comparator

' '

Team-internal -- please sign in to continue.

' '
', unsafe_allow_html=True, ) pw = st.text_input("Team password", type="password", key="_pw") if st.button("Sign in", type="primary"): if pw == _team_pw: st.session_state.auth_ok = True st.rerun() else: st.error("Wrong password.") st.stop() st.markdown( '
📦
' '

Compare many projects in one shot

' '

Upload one ZIP of AI Excels, pick a language, hit Run

' '
', unsafe_allow_html=True, ) ss = st.session_state ss.setdefault("last_run", None) ss.setdefault("last_zip_bytes", None) ss.setdefault("last_zip_name", "") ss.setdefault("log_lines", []) ss.setdefault("progress_rows", []) ss.setdefault("trigger_run", False) ss.setdefault("uploader_nonce", 0) ss.setdefault("run_status", "idle") # idle | running | success | error ss.setdefault("run_error_msg", "") ss.setdefault("queue_id", None) # Live-browser connection state ss.setdefault("bna_connected", False) ss.setdefault("bna_method", "") # "cookie" | "password" ss.setdefault("bna_cookies", "") ss.setdefault("bna_email", "") ss.setdefault("bna_password", "") ss.setdefault("gate_choice", "") # "" | "live" | "pwd" ss.setdefault("live_browser_proc", None) ss.setdefault("live_state_path", "") def _stage_uploads(uploads, into_dir: Path) -> Path: into_dir.mkdir(parents=True, exist_ok=True) for up in uploads: target = into_dir / up.name target.write_bytes(up.getvalue()) if up.name.lower().endswith(".zip"): try: with zipfile.ZipFile(target, "r") as zf: zf.extractall(into_dir) except zipfile.BadZipFile: st.error(f"'{up.name}' is not a valid ZIP.") st.stop() target.unlink(missing_ok=True) return into_dir def _zip_directory(src: Path) -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: for root, _, files in os.walk(src): for f in files: full = Path(root) / f arc = full.relative_to(src) zf.write(full, arc) return buf.getvalue() def _label(col, text): col.markdown(f'
{text}
', unsafe_allow_html=True) def _kpi(label, value, kind=""): return ( f'
' f'
{label}
' f'
{value}
' f'
' ) def _run_batch_in_subprocess(ai_dir, out_dir, tie_path, email, password, lang, log_box, progress_callback, bna_cookies=""): """Spawn a fresh Python subprocess to run the batch. Each subprocess gets a clean Playwright instance — sidesteps the "Event loop is closed" issue we'd hit if we called sync_playwright twice in this same Streamlit process.""" with tempfile.TemporaryDirectory(prefix="bna_ipc_") as ipc: ipc_path = Path(ipc) out_json = ipc_path / "result.json" log_jsonl = ipc_path / "log.jsonl" cfg = { "ai_zip_path": str(ai_dir), "output_folder": str(out_dir), "tie_path": str(tie_path), "email": email, "password": password, "bna_cookies": bna_cookies, "lang": lang, "headless": True, "manual_login": False, } log_jsonl.touch() # Pass config via stdin (not as a CLI argument or a config file # path). Keeps the BNA password out of the process list and out # of any file that might survive a crash. cli = HERE / "engine" / "run_batch_cli.py" proc = subprocess.Popen( [sys.executable, str(cli), str(out_json), str(log_jsonl)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) try: proc.stdin.write(json.dumps(cfg)) proc.stdin.close() finally: cfg = None # drop the local reference ASAP # Tail the log file while the subprocess runs last_pos = 0 while proc.poll() is None: try: with log_jsonl.open("r", encoding="utf-8") as fh: fh.seek(last_pos) new = fh.read() last_pos = fh.tell() for line in new.splitlines(): if not line.strip(): continue try: rec = json.loads(line) except Exception: continue if rec.get("type") == "log": ss.log_lines.append(f"[{rec['level']}] {rec['message']}") if len(ss.log_lines) > 500: ss.log_lines[:] = ss.log_lines[-500:] elif rec.get("type") == "progress": progress_callback(rec["info"]) try: log_box.code("\n".join(ss.log_lines[-60:]), language="text") except Exception: pass except Exception: pass time.sleep(0.6) # Drain whatever's left in the log file after the subprocess exits try: with log_jsonl.open("r", encoding="utf-8") as fh: fh.seek(last_pos) rest = fh.read() for line in rest.splitlines(): if not line.strip(): continue try: rec = json.loads(line) except Exception: continue if rec.get("type") == "log": ss.log_lines.append(f"[{rec['level']}] {rec['message']}") elif rec.get("type") == "progress": progress_callback(rec["info"]) except Exception: pass if not out_json.exists(): return None, "Subprocess exited without writing a result file." result = json.loads(out_json.read_text(encoding="utf-8")) if not result.get("ok"): return None, result.get("error") + "\n" + result.get("traceback", "") return result["summary"], None # ==================================================================== # Connection gate — runs before the tabs. The primary path is the # live BNA browser streamed via noVNC. Email + password is a hidden # fallback for cases where the live view doesn't work. # ==================================================================== def _render_gate() -> None: with st.container(border=True): st.markdown( '
🔗 Connect to BNAmericas
' '

Sign in to BNAmericas to start a batch.

', unsafe_allow_html=True, ) # ---------- Primary: live BNA browser -------------------------- st.markdown( '
' '
⚡
' '
' '

Sign in to BNAmericas — live

' '

Click below to open a BNA window right here. Sign in ' 'as you normally would. When the dashboard loads we ' 'auto-connect and the batch tools open up.

' '
', unsafe_allow_html=True, ) if ss.gate_choice != "live": cA, _ = st.columns([1.4, 4]) if cA.button("Open BNA window", type="primary", key="t1_open"): ss.gate_choice = "live" state_path = Path(tempfile.gettempdir()) / f"live_{uuid.uuid4().hex[:8]}.json" ss.live_state_path = str(state_path) cli = HERE / "engine" / "live_browser.py" env = {**os.environ, "DISPLAY": os.environ.get("DISPLAY", ":99")} proc = subprocess.Popen( [sys.executable, str(cli), str(state_path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env, ) ss.live_browser_proc = proc.pid st.rerun() else: with st.container(border=True): st.markdown( "**Sign in below — we'll detect it automatically.** " "The window is a live view of a browser running on " "our server. Use your normal BNAmericas credentials." ) novnc_src = ( "/novnc/vnc.html" "?autoconnect=true" "&resize=scale" "&path=websockify" "&reconnect=true" ) st.components.v1.iframe(novnc_src, height=620, scrolling=False) state = {} try: if ss.live_state_path and Path(ss.live_state_path).exists(): state = json.loads(Path(ss.live_state_path).read_text(encoding="utf-8")) except Exception: state = {} status = state.get("status", "starting") if status == "starting": st.info("Opening BNAmericas in the window above…") elif status == "waiting_for_login": st.info("Waiting for you to sign in. The window closes itself once you're in.") elif status == "connected": ss.bna_cookies = state.get("cookies", "") ss.bna_method = "cookie" ss.bna_connected = True try: Path(ss.live_state_path).unlink(missing_ok=True) except Exception: pass st.rerun() elif status == "timed_out": st.warning("Sign-in timed out after 10 minutes. Click Cancel and try again.") elif status == "error": st.error(f"Live browser error: {state.get('message','(unknown)')}") cancel, _ = st.columns([1, 4]) if cancel.button("Cancel", key="live_cancel"): try: if ss.live_browser_proc: os.kill(int(ss.live_browser_proc), 15) except Exception: pass ss.gate_choice = "" ss.live_browser_proc = None st.rerun() if status in ("starting", "waiting_for_login"): time.sleep(2) st.rerun() # ---------- Fallback: email + password (collapsed) ------------ with st.expander("Use email and password instead"): st.caption( "We'll sign in using your BNA credentials. Used only " "for this batch, never stored." ) email_in = st.text_input( "BNA email", autocomplete="username", key="g_email" ) pw_in = st.text_input( "BNA password", type="password", autocomplete="current-password", key="g_pw" ) cgo, _ = st.columns([1.4, 4]) if cgo.button("Connect with password", type="primary", key="g_go"): if not (email_in and pw_in): st.error("Enter both email and password.") else: ss.bna_email = email_in ss.bna_password = pw_in ss.bna_method = "password" ss.bna_connected = True st.rerun() if not ss.bna_connected: _render_gate() st.stop() # Small "connected" strip above the tabs, with a Disconnect link. _strip_col1, _strip_col2 = st.columns([6, 1]) with _strip_col1: if ss.bna_method == "cookie": st.markdown( '
' 'Connected via live BNA session' '
', unsafe_allow_html=True, ) else: st.markdown( f'
' f'Connected as {ss.bna_email}' f'
', unsafe_allow_html=True, ) with _strip_col2: if st.button("Disconnect", key="disconnect"): for k in ("bna_connected", "bna_method", "bna_cookies", "bna_email", "bna_password", "gate_choice"): ss[k] = "" if isinstance(ss.get(k), str) else False st.rerun() tab_inputs, tab_dashboard, tab_log = st.tabs( ["📋 Inputs", "📊 Dashboard", "📜 Log"] ) # ---- Inputs tab ------------------------------------------------------ with tab_inputs: with st.container(border=True): st.markdown( '

⚙ Inputs

', unsafe_allow_html=True, ) c1, c2 = st.columns([1, 4]) _label(c1, "AI Excels (ZIP or folder)") ai_files = c2.file_uploader( "AI Excels", type=None, accept_multiple_files=True, label_visibility="collapsed", key=f"uploader_{ss.uploader_nonce}", ) c1, c2 = st.columns([1, 4]) _label(c1, "Output language") lang_label = c2.selectbox( "Output language", options=["English", "Español", "Português"], index=1, label_visibility="collapsed", ) lang = {"English": "en", "Español": "es", "Português": "pt"}[lang_label] # Credentials were captured on the gate. Inputs tab is now # just AI Excels + Output language + action buttons. st.markdown('
', unsafe_allow_html=True) _, c_btns = st.columns([1, 4]) b1, b2, b3, _ = c_btns.columns([1.4, 1.8, 1.2, 4]) run_disabled = not ai_files if b1.button("▶ Run batch", type="primary", disabled=run_disabled): ss.trigger_run = True ss.run_status = "running" ss.last_run = None ss.run_error_msg = "" if ss.last_zip_bytes: b2.download_button( "⬇ Download results ZIP", data=ss.last_zip_bytes, file_name=ss.last_zip_name or "bna_comparator_results.zip", mime="application/zip", ) else: b2.button("⬇ Download results ZIP", disabled=True) if b3.button("🧹 Clear"): ss.uploader_nonce += 1 ss.last_run = None ss.last_zip_bytes = None ss.last_zip_name = "" ss.log_lines = [] ss.progress_rows = [] ss.run_status = "idle" ss.run_error_msg = "" st.rerun() # Status banner under the inputs card — shows run progress / outcome if ss.run_status == "running": st.markdown( '
' '
' '
Working on your batch…  ' 'This usually takes a minute or two per project. ' 'Switch to the Log tab to follow along live.
' '
', unsafe_allow_html=True, ) if ss.last_run is not None: s = ss.last_run total = s.get("total", 0) or 1 done = s.get("ok", 0) + s.get("failed", 0) st.progress( min(1.0, done / total), text=f"{done} of {total} projects processed", ) else: st.progress(0.05, text="Starting up the browser session…") elif ss.run_status == "success" and ss.last_run is not None: s = ss.last_run st.markdown( f'
' f'
✅
' f'
Batch complete!  ' f'Processed {s["ok"]}/{s["total"]} projects ' f'({s.get("failed", 0)} failed).  ' f'Head to the Dashboard tab to explore results, ' f'or grab the ZIP above.
' f'
', unsafe_allow_html=True, ) elif ss.run_status == "error": st.markdown( f'
' f'
⚠️
' f'
Something went wrong.  ' f'Check the Log tab for details, then try again.
' f'
', unsafe_allow_html=True, ) with st.expander("Error details"): st.code(ss.run_error_msg or "(no message)", language="text") # ---- Dashboard tab --------------------------------------------------- def _kpi_tile(icon: str, value, label: str, color: str) -> str: return ( f'
' f'
{icon}
' f'
' f'
{value}
' f'
{label}
' f'
' f'
' ) with tab_dashboard: if ss.last_run is None: st.info("Run a batch first -- the dashboard fills in once it finishes.") else: s = ss.last_run rows = s.get("rows") or [] agg = {"matches": 0, "differs": 0, "stale_ai": 0, "missing_on_ai": 0, "pending_disclosure": 0, "total_fields": 0} rates = [] recommendations = 0 for r in rows: for k in agg: v = r.get(k, 0) if isinstance(v, (int, float)): agg[k] += v mr = r.get("match_rate", 0) if isinstance(mr, (int, float)): rates.append(mr) recommendations += (r.get("differs", 0) or 0) + (r.get("stale_ai", 0) or 0) avg_match_rate = round(sum(rates) / max(1, len(rates)), 1) if rates else 0.0 # Dashboard-specific styling st.markdown(""" """, unsafe_allow_html=True) # Batch results header st.markdown( '
' '

🌿  Batch results

' '

Across every project in this batch

' '
', unsafe_allow_html=True, ) # KPI grid (3 rows × 4 cols, like the desktop app) tiles_html = '
' tiles_html += _kpi_tile("📁", s.get("total", 0), "Projects", "#2541B2") tiles_html += _kpi_tile("✅", s.get("ok", 0), "Succeeded", "#16A34A") tiles_html += _kpi_tile("⚠️", s.get("failed", 0), "Failed", "#DC2626") tiles_html += _kpi_tile("📊", f"{avg_match_rate}%", "Match Rate", "#8B5CF6") tiles_html += _kpi_tile("📋", agg["total_fields"], "Total Fields", "#2541B2") tiles_html += _kpi_tile("✓", agg["matches"], "Matches", "#16A34A") tiles_html += _kpi_tile("≠", agg["differs"], "Differs", "#DC2626") tiles_html += _kpi_tile("⌛", agg["pending_disclosure"], "Missing on Both", "#6B7280") tiles_html += _kpi_tile("Ⓑ", agg["missing_on_ai"], "Missing on AI", "#8B5CF6") tiles_html += _kpi_tile("⏰", agg["stale_ai"], "Stale AI", "#8B5CF6") tiles_html += _kpi_tile("⭐", recommendations, "Recommendations", "#F97316") tiles_html += '
' st.markdown(tiles_html, unsafe_allow_html=True) # Legend st.markdown( '
' '

ℹ️ What do these mean?

' '' '
', unsafe_allow_html=True, ) # Per-project breakdown st.markdown( '
📋  Per-project breakdown
', unsafe_allow_html=True, ) # Column headers st.markdown( '
' '
Status
' '
Project name
' '
Matches
' '
Differs
' '
Stale AI
' '
Match rate
' '
', unsafe_allow_html=True, ) for r in rows: name = r.get("name", "(unnamed)") status_ok = (r.get("status", "") or "").lower() in ("ok", "success", "") dot_cls = "ok" if status_ok else "fail" m = r.get("matches", 0) or 0 d = r.get("differs", 0) or 0 s_ai = r.get("stale_ai", 0) or 0 mr = r.get("match_rate", 0) or 0 mr_str = f"{mr}%" if isinstance(mr, (int, float)) else str(mr) st.markdown( f'
' f'
' f'
{name}
' f'
✓ {m}
' f'
≠ {d}
' f'
⏰ {s_ai}
' f'
📊 {mr_str}
' f'
', unsafe_allow_html=True, ) # ---- Log tab --------------------------------------------------------- with tab_log: if not ss.log_lines: st.info("Live log will appear here as the run progresses.") else: st.code("\n".join(ss.log_lines), language="text") # ---- The actual run -------------------------------------------------- if ss.trigger_run: ss.trigger_run = False ss.log_lines = [] ss.progress_rows = [] # Give this run a stable session id and join the queue. if not ss.get("queue_id"): ss.queue_id = f"q_{uuid.uuid4().hex[:12]}" sid = ss.queue_id queue_enqueue(sid) # If someone else is running right now, hold here and show a # waiting banner. The Streamlit thread blocks until our turn — that # is fine: this researcher can't click anything else mid-run anyway. with tab_inputs: wait_box = st.empty() try: pos = queue_position(sid) while pos > 0: ahead = pos wait_box.markdown( f'
' f'
' f'
You\'re in the queue.  ' f'{ahead} batch{"es" if ahead != 1 else ""} ahead of you. ' f'Your run will start automatically — feel free to ' f'leave this tab open.
' f'
', unsafe_allow_html=True, ) time.sleep(2) pos = queue_position(sid) wait_box.empty() queue_mark_started(sid) except Exception: queue_dequeue(sid) ss.queue_id = None raise try: with tab_log: log_box = st.empty() log_box.code("[INFO] Run starting in subprocess...", language="text") with tempfile.TemporaryDirectory(prefix="bna_web_") as tmp: tmp_path = Path(tmp) ai_dir = _stage_uploads(ai_files, tmp_path / "ai_input") out_dir = tmp_path / "output" out_dir.mkdir() tie_path = HERE / "resources" / "TIE_Requirements.xlsx" def _progress_cb(info): ss.progress_rows.append(info) summary, error = _run_batch_in_subprocess( ai_dir=ai_dir, out_dir=out_dir, tie_path=tie_path, email=ss.bna_email, password=ss.bna_password, lang=lang, log_box=log_box, progress_callback=_progress_cb, bna_cookies=ss.bna_cookies, ) if error: ss.log_lines.append(f"[ERROR] {error}") ss.run_status = "error" ss.run_error_msg = error else: zip_bytes = _zip_directory(out_dir) ss.last_zip_bytes = zip_bytes ts = datetime.now().strftime("%Y%m%d_%H%M%S") ss.last_zip_name = f"bna_comparator_results_{ts}.zip" ss.last_run = summary ss.run_status = "success" ss.log_lines.append( f"[INFO] Done -- {summary['ok']}/{summary['total']} OK, " f"{summary['failed']} failed." ) finally: queue_dequeue(sid) ss.queue_id = None st.rerun()