ComparerToolV2 / app.py
GopiBNA's picture
Upload app.py
bb70e89 verified
Raw History Blame Contribute Delete
44 kB
"""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 = """
<style>
#MainMenu, footer, header[data-testid="stHeader"] {visibility: hidden;}
[data-testid="stToolbar"] {display: none;}
.block-container {padding-top: 0 !important; max-width: 1200px; background: #FFFFFF;}
body, .stApp {background: #FFFFFF !important;}
.bna-header {
background: linear-gradient(90deg, #2541B2 0%, #6B3FA0 60%, #8338EC 100%);
color: #FFFFFF; padding: 28px 36px; border-radius: 0 0 8px 8px;
margin: 0 -24px 24px -24px;
display: flex; align-items: center; gap: 18px;
}
.bna-header .icon {
width: 44px; height: 44px;
background: rgba(255,255,255,0.18); border-radius: 10px;
display: flex; align-items: center; justify-content: center;
font-size: 22px;
}
.bna-header h1 {margin: 0; font-size: 30px; font-weight: 700; line-height: 1.1;}
.bna-header p {margin: 4px 0 0 0; font-size: 14px; opacity: 0.92;}
.stTabs [data-baseweb="tab-list"] {
gap: 8px; border-bottom: 2px solid #E5E7EB; background: #FFFFFF; padding: 0 12px;
}
.stTabs [data-baseweb="tab"] {
height: 56px !important; padding: 0 32px !important;
background: transparent; border-radius: 8px 8px 0 0;
color: #4B5563 !important; font-weight: 600 !important; font-size: 17px !important;
}
.stTabs [data-baseweb="tab"] p {font-size: 17px !important; font-weight: 600 !important;}
.stTabs [aria-selected="true"] {
color: #2541B2 !important; border-bottom: 4px solid #2541B2 !important; background: #F8FAFC !important;
}
[data-testid="stVerticalBlock"] > [data-testid="stVerticalBlockBorderWrapper"] {
background: #FFFFFF; border: 1px solid #E5E7EB; border-radius: 10px;
padding: 26px 32px !important; box-shadow: 0 1px 3px rgba(0,0,0,0.04);
}
.stTextInput input, .stSelectbox > div > div, .stFileUploader section {
background: #FFFFFF !important; color: #111827 !important;
border: 1px solid #D1D5DB !important; border-radius: 6px !important;
}
.stTextInput input::placeholder {color: #9CA3AF !important;}
.stTextInput label, .stSelectbox label, .stFileUploader label, .field-label {
color: #111827 !important; font-weight: 500 !important;
}
.field-label {font-size: 14px; padding-top: 10px;}
h2.section-title {
font-size: 20px; margin: 0 0 18px 0; color: #1F2937;
display: flex; align-items: center; gap: 8px;
}
h2.section-title .gear {color: #2541B2;}
div.stButton > button[kind="primary"], div.stDownloadButton > button {
background: linear-gradient(180deg, #F97316 0%, #EA580C 100%) !important;
color: white !important; border: none !important; font-weight: 600 !important;
padding: 10px 22px !important; border-radius: 8px !important;
}
div.stButton > button[kind="primary"]:hover, div.stDownloadButton > button:hover {
background: linear-gradient(180deg, #EA580C 0%, #C2410C 100%) !important;
}
div.stButton > button[kind="primary"]:disabled, div.stDownloadButton > button:disabled {
background: #F3F4F6 !important; color: #9CA3AF !important;
}
/* "Clear" — ghost / outline style so it visually de-emphasises vs.
the primary actions (Run, Download). */
div.stButton > button:not([kind="primary"]) {
background: #FFFFFF !important; color: #4B5563 !important;
border: 1.5px solid #D1D5DB !important;
font-weight: 500 !important; padding: 10px 22px !important; border-radius: 8px !important;
}
div.stButton > button:not([kind="primary"]):hover {
background: #F9FAFB !important; color: #111827 !important;
border-color: #9CA3AF !important;
}
/* Status banners under the action row */
.status-banner {
margin-top: 18px; padding: 14px 18px; border-radius: 10px;
display: flex; align-items: center; gap: 12px; font-size: 14px;
}
.status-banner .icon {font-size: 18px;}
.status-banner.running {
background: linear-gradient(90deg, #EFF6FF 0%, #F5F3FF 100%);
border: 1px solid #C7D2FE; color: #3730A3;
}
.status-banner.success {
background: linear-gradient(90deg, #ECFDF5 0%, #F0FDF4 100%);
border: 1px solid #A7F3D0; color: #065F46;
}
.status-banner.error {
background: #FEF2F2; border: 1px solid #FECACA; color: #991B1B;
}
.status-banner b {font-weight: 600;}
.pulse-dot {
width: 10px; height: 10px; border-radius: 50%; background: #4F46E5;
animation: pulse 1.4s infinite;
}
@keyframes pulse {
0%, 100% {opacity: 1; transform: scale(1);}
50% {opacity: 0.4; transform: scale(1.3);}
}
.kpi-tile {
background: #FFFFFF; border: 1px solid #E5E7EB; border-left: 4px solid #2541B2;
border-radius: 8px; padding: 16px 18px; margin-bottom: 12px;
}
.kpi-tile .label {color: #6B7280; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em;}
.kpi-tile .value {color: #111827; font-size: 28px; font-weight: 600; margin-top: 4px;}
.kpi-tile.match {border-left-color: #16A34A;}
.kpi-tile.differ {border-left-color: #F59E0B;}
.kpi-tile.stale {border-left-color: #8B5CF6;}
.kpi-tile.missing {border-left-color: #6B7280;}
.stProgress > div > div > div {background: linear-gradient(90deg, #2541B2, #8338EC) !important;}
/* Streamlit shows a "Press Enter to apply" hint next to text inputs
whenever the value changes. It looks like an error tooltip and
confuses non-technical users. Hide it. */
[data-testid="InputInstructions"] {display: none !important;}
[data-testid="stTextInput"] [data-baseweb="input"] + div {display: none !important;}
/* --- Connection gate (3-tier) -------------------------------------- */
.gate-title {color: #1E3A8A; font-size: 22px; font-weight: 600;
margin: 4px 0 4px 0; display: flex; align-items: center; gap: 10px;}
.gate-sub {color: #6B7280; font-size: 13px; margin: 0 0 20px 0;}
.tier-card {
background: #FFFFFF; border: 1px solid #E5E7EB;
border-radius: 10px; padding: 16px 18px; margin-bottom: 14px;
display: flex; align-items: flex-start; gap: 14px;
}
.tier-card.primary {background: linear-gradient(90deg, #EFF6FF 0%, #F5F3FF 100%);
border-color: #C7D2FE;}
.tier-icon {font-size: 22px; flex-shrink: 0; line-height: 1.2;
width: 36px; height: 36px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
background: rgba(255,255,255,0.6);}
.tier-card.primary .tier-icon {color: #3730A3;}
.tier-card .tier-body {flex: 1;}
.tier-card h4 {margin: 0 0 4px 0; font-size: 15px; font-weight: 600;
color: #111827;}
.tier-card.primary h4 {color: #3730A3;}
.tier-card p {margin: 0 0 10px 0; font-size: 13px; color: #4B5563;
line-height: 1.5;}
.tier-card.primary p {color: #3730A3;}
.connected-pill {
display: inline-flex; align-items: center; gap: 8px;
background: #ECFDF5; color: #065F46; border: 1px solid #A7F3D0;
padding: 6px 12px; border-radius: 20px; font-size: 13px;
font-weight: 500;
}
.connected-pill .dot {width: 8px; height: 8px; border-radius: 50%;
background: #10B981;}
</style>
"""
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(
'<div class="bna-header"><div class="icon">🔒</div>'
'<div><h1>BNA Comparator</h1>'
'<p>Team-internal -- please sign in to continue.</p>'
'</div></div>',
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(
'<div class="bna-header"><div class="icon">📦</div>'
'<div><h1>Compare many projects in one shot</h1>'
'<p>Upload one ZIP of AI Excels, pick a language, hit Run</p>'
'</div></div>',
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'<div class="field-label">{text}</div>', unsafe_allow_html=True)
def _kpi(label, value, kind=""):
return (
f'<div class="kpi-tile {kind}">'
f'<div class="label">{label}</div>'
f'<div class="value">{value}</div>'
f'</div>'
)
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(
'<div class="gate-title">🔗 Connect to BNAmericas</div>'
'<p class="gate-sub">Sign in to BNAmericas to start a batch.</p>',
unsafe_allow_html=True,
)
# ---------- Primary: live BNA browser --------------------------
st.markdown(
'<div class="tier-card primary">'
'<div class="tier-icon">⚡</div>'
'<div class="tier-body">'
'<h4>Sign in to BNAmericas — live</h4>'
'<p>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.</p>'
'</div></div>',
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(
'<div class="connected-pill">'
'<span class="dot"></span>Connected via live BNA session'
'</div>',
unsafe_allow_html=True,
)
else:
st.markdown(
f'<div class="connected-pill">'
f'<span class="dot"></span>Connected as {ss.bna_email}'
f'</div>',
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(
'<h2 class="section-title"><span class="gear">⚙</span> Inputs</h2>',
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('<div style="height: 18px;"></div>', 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(
'<div class="status-banner running">'
'<div class="pulse-dot"></div>'
'<div><b>Working on your batch…</b> &nbsp;'
'This usually takes a minute or two per project. '
'Switch to the <b>Log</b> tab to follow along live.</div>'
'</div>',
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'<div class="status-banner success">'
f'<div class="icon">✅</div>'
f'<div><b>Batch complete!</b> &nbsp;'
f'Processed <b>{s["ok"]}/{s["total"]}</b> projects '
f'({s.get("failed", 0)} failed). &nbsp;'
f'Head to the <b>Dashboard</b> tab to explore results, '
f'or grab the ZIP above.</div>'
f'</div>',
unsafe_allow_html=True,
)
elif ss.run_status == "error":
st.markdown(
f'<div class="status-banner error">'
f'<div class="icon">⚠️</div>'
f'<div><b>Something went wrong.</b> &nbsp;'
f'Check the <b>Log</b> tab for details, then try again.</div>'
f'</div>',
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'<div class="dash-tile" style="border-left-color: {color};">'
f' <div class="dash-tile-icon" style="color: {color};">{icon}</div>'
f' <div class="dash-tile-body">'
f' <div class="dash-tile-value">{value}</div>'
f' <div class="dash-tile-label">{label}</div>'
f' </div>'
f'</div>'
)
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("""
<style>
.dash-header h3 {color: #1E3A8A; font-size: 22px; margin: 0;}
.dash-header p {color: #6B7280; font-size: 13px; margin: 2px 0 18px 0;}
.dash-grid {
display: grid; grid-template-columns: repeat(4, 1fr);
gap: 14px; margin-bottom: 18px;
}
.dash-tile {
background: #FFFFFF; border: 1px solid #E5E7EB; border-left: 4px solid #2541B2;
border-radius: 8px; padding: 16px 18px;
display: flex; align-items: center; gap: 14px;
min-height: 70px;
}
.dash-tile-icon {font-size: 22px; flex-shrink: 0;}
.dash-tile-value {font-size: 30px; font-weight: 700; color: #111827; line-height: 1;}
.dash-tile-label {font-size: 12px; color: #6B7280; margin-top: 4px; text-transform: capitalize;}
.dash-legend {
background: #FFFFFF; border: 1px solid #E5E7EB; border-radius: 8px;
padding: 16px 20px; margin-top: 8px;
}
.dash-legend h4 {color: #1E3A8A; font-size: 15px; margin: 0 0 10px 0;
display: flex; align-items: center; gap: 8px;}
.dash-legend ul {margin: 0; padding-left: 18px; color: #374151; font-size: 13px;}
.dash-legend li {margin: 4px 0;}
.dash-legend b {color: #1F2937;}
.pp-header {color: #1E3A8A; font-size: 18px; margin: 22px 0 12px 0;
display: flex; align-items: center; gap: 8px;}
.pp-row {
display: grid;
grid-template-columns: 22px 2fr 70px 70px 70px 80px;
gap: 14px; align-items: center;
padding: 10px 14px; border-bottom: 1px solid #F3F4F6;
font-size: 14px;
}
.pp-row:hover {background: #F9FAFB;}
.pp-colhead {
display: grid;
grid-template-columns: 22px 2fr 70px 70px 70px 80px;
gap: 14px; align-items: center;
padding: 10px 14px; border-bottom: 2px solid #E5E7EB;
background: #F8FAFC; border-radius: 6px 6px 0 0;
font-size: 12px; font-weight: 600;
color: #4B5563; text-transform: uppercase; letter-spacing: 0.05em;
}
.pp-dot {width: 10px; height: 10px; border-radius: 50%;}
.pp-dot.ok {background: #16A34A;}
.pp-dot.fail {background: #DC2626;}
.pp-name {color: #111827; font-weight: 500;}
.pp-m {color: #16A34A;}
.pp-d {color: #DC2626;}
.pp-s {color: #8B5CF6;}
.pp-rate {color: #2541B2; font-weight: 600;}
</style>
""", unsafe_allow_html=True)
# Batch results header
st.markdown(
'<div class="dash-header">'
'<h3>🌿 &nbsp;Batch results</h3>'
'<p>Across every project in this batch</p>'
'</div>',
unsafe_allow_html=True,
)
# KPI grid (3 rows × 4 cols, like the desktop app)
tiles_html = '<div class="dash-grid">'
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 += '</div>'
st.markdown(tiles_html, unsafe_allow_html=True)
# Legend
st.markdown(
'<div class="dash-legend">'
'<h4>ℹ️ What do these mean?</h4>'
'<ul>'
'<li><b>Matches</b> — AI value agrees with BNA value.</li>'
'<li><b>Differs</b> — AI value differs from BNA. Researcher review needed.</li>'
'<li><b>Missing on Both</b> — Field is blank on both sides.</li>'
'<li><b>Missing on AI</b> — BNA has a value; AI doesn\'t.</li>'
'<li><b>Stale AI</b> — AI value is older than BNA\'s last review.</li>'
'<li><b>Recommendations</b> — Differ + Stale AI rows for the researcher to action.</li>'
'</ul>'
'</div>',
unsafe_allow_html=True,
)
# Per-project breakdown
st.markdown(
'<div class="pp-header">📋 &nbsp;Per-project breakdown</div>',
unsafe_allow_html=True,
)
# Column headers
st.markdown(
'<div class="pp-colhead">'
'<div>Status</div>'
'<div>Project name</div>'
'<div>Matches</div>'
'<div>Differs</div>'
'<div>Stale AI</div>'
'<div>Match rate</div>'
'</div>',
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'<div class="pp-row">'
f'<div class="pp-dot {dot_cls}"></div>'
f'<div class="pp-name">{name}</div>'
f'<div class="pp-m">✓ {m}</div>'
f'<div class="pp-d">≠ {d}</div>'
f'<div class="pp-s">⏰ {s_ai}</div>'
f'<div class="pp-rate">📊 {mr_str}</div>'
f'</div>',
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'<div class="status-banner running">'
f'<div class="pulse-dot"></div>'
f'<div><b>You\'re in the queue.</b> &nbsp;'
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.</div>'
f'</div>',
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()