Spaces:
Runtime error
Runtime error
Download app.py from BNAmericas/ComparerTool: direct link, hf CLI and curl.
- Browser
- Download file 72.1 kB
-
https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/app.py
- Command line
-
hf download hf://spaces/BNAmericas/ComparerTool/app.py
-
curl -L -o app.py https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/app.py
72.1 kB
"""BNA Comparator -- Web Edition."""
from __future__ import annotations
import io
import json
import os
import re
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
# Add engine folder to sys.path so we can import team_session for the
# Admin tab. batch_runner already runs from inside engine/ as a
# subprocess, so this is only needed for the in-process UI handler.
_ENGINE_DIR = Path(__file__).resolve().parent / "engine"
if str(_ENGINE_DIR) not in sys.path:
sys.path.insert(0, str(_ENGINE_DIR))
import team_session # noqa: E402
import feedback_store # noqa: E402
# -------------------------------------------------------------------
# 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;}
/* ββ Run batch (primary) ββ orange βββββββββββββββββββββββββββββββ */
div.stButton > button[kind="primary"] {
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:not(:disabled) {
background: linear-gradient(180deg, #EA580C 0%, #C2410C 100%) !important;
}
div.stButton > button[kind="primary"]:disabled {
background: #F3F4F6 !important; color: #9CA3AF !important;
}
/* ββ Download results ZIP ββ BNAmericas blue βββββββββββββββββββββ */
div.stDownloadButton > button {
background: linear-gradient(180deg, #2541B2 0%, #1E3A8A 100%) !important;
color: #FFFFFF !important; border: none !important; font-weight: 600 !important;
padding: 10px 22px !important; border-radius: 8px !important;
}
div.stDownloadButton > button:hover:not(:disabled) {
background: linear-gradient(180deg, #1E3A8A 0%, #172554 100%) !important;
}
div.stDownloadButton > button:disabled,
div.stButton > button:disabled[data-testid='btn_download_disabled'] {
background: #E5E7EB !important; color: #9CA3AF !important;
}
/* ββ Clear ββ light-grey fill ββββββββββββββββββββββββββββββββββββ */
div.stButton > button:not([kind="primary"]) {
background: #E5E7EB !important; color: #374151 !important;
border: 1px solid #D1D5DB !important;
font-weight: 500 !important; padding: 10px 22px !important; border-radius: 8px !important;
}
div.stButton > button:not([kind="primary"]):hover:not(:disabled) {
background: #D1D5DB !important; color: #111827 !important;
border-color: #9CA3AF !important;
}
div.stButton > button:not([kind="primary"]):disabled {
background: #F3F4F6 !important; color: #9CA3AF !important;
border: 1px solid #E5E7EB !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)
ss.setdefault("zip_layout", {})
REQUIRED_ZIP_FOLDERS = ("Input", "Output", "Summary")
def _validation_error(title: str, body: str) -> None:
"""Surface a validation failure in BOTH tabs and halt the run.
The Inputs tab needs to see the error too β without this it stays
stuck on the pulsing "Working on your batchβ¦" banner because the
validation runs inside `with tab_log:` and st.stop() doesn't
re-render the Inputs side.
Flow:
1. Push the failure into ss.run_status / ss.run_error_msg so the
Inputs status block displays the same error banner on rerun.
2. Append a [ERROR] line to ss.log_lines so the Log tab keeps it
in the live trace.
3. Trigger a rerun β after that, both tabs render the error.
"""
# Strip HTML for the plain-text log and error_msg, keep markup for UI.
plain = re.sub(r"<[^>]+>", "", body).strip()
ss.run_status = "error"
ss.run_error_msg = f"{title}\n\n{plain}"
ss.log_lines.append(f"[ERROR] Validation failed: {title} β {plain}")
# Render in the current context (Log tab when called from trigger_run)
# so the researcher sees something immediately, even before the rerun.
st.markdown(
f'<div class="status-banner error">'
f'<div class="icon">β οΈ</div>'
f'<div><b>{title}</b><br>{body}</div>'
f'</div>',
unsafe_allow_html=True,
)
# Also clear the run queue and Streamlit-stop the current run.
try:
if ss.get("queue_id"):
queue_dequeue(ss.queue_id)
ss.queue_id = None
except Exception:
pass
st.rerun()
def _stage_zip(upload, into_dir: Path) -> Path:
"""Strict validation pipeline for the single-ZIP upload.
The Comparator now accepts exactly one ZIP, with this internal
structure:
Comparator_<batch-name>.zip
βββ Input/ β AI Excel files (.xlsx)
βββ Output/ β (created/managed by Comparator; can be empty)
βββ Summary/ β (created/managed by Comparator; can be empty)
Any deviation raises a clear, actionable validation message and
halts the run before the engine starts. The engine then reads AI
Excels from `Input/`, writes per-project results to `Output/`, and
drops the batch summary into `Summary/`.
"""
into_dir.mkdir(parents=True, exist_ok=True)
# --- 1) File presence ----------------------------------------------
if upload is None:
_validation_error(
"No file uploaded",
"Drop a ZIP into the uploader. The Comparator accepts exactly "
"one ZIP per run β see the panel for the required folder layout.",
)
raw_name = (upload.name or "").strip()
if not raw_name:
_validation_error(
"Upload has no filename",
"Your browser sent a file with an empty name. Try uploading again, "
"or rename the ZIP before uploading.",
)
# --- 2) Extension --------------------------------------------------
if not raw_name.lower().endswith(".zip"):
_validation_error(
f'"{raw_name}" is not a ZIP file',
"The Comparator only accepts a single <code>.zip</code> archive. "
"Right-click the folder containing your Input/Output/Summary "
"folders β <b>Send to β Compressed (zipped) folder</b>, then "
"upload the resulting <code>.zip</code>.",
)
# --- 3) Save to disk -----------------------------------------------
basename = raw_name.replace("\\", "/").split("/")[-1] or raw_name
zip_path = into_dir / basename
try:
zip_path.write_bytes(upload.getvalue() or b"")
except Exception as e:
_validation_error(
"Could not save your upload",
f"Something went wrong saving <code>{basename}</code> to the "
f"server: <code>{e}</code>. Try uploading again.",
)
# --- 4) Valid ZIP --------------------------------------------------
try:
zf = zipfile.ZipFile(zip_path, "r")
except zipfile.BadZipFile:
_validation_error(
f'"{basename}" is not a valid ZIP',
"The file uploaded with a <code>.zip</code> extension but its "
"contents are corrupted or in a different format. Re-create the "
"ZIP and upload again.",
)
# --- 5) Structure: Input / Output / Summary at the top level -------
# Walk the ZIP namelist to find which top-level folders exist. We
# tolerate either Comparator_xxx/Input/ (single root wrapper, e.g.
# Windows ZIP creates this) OR Input/ directly at the root.
with zf:
names = zf.namelist()
# Build a map of top-level entries β list of children. A folder
# entry shows up as either an explicit empty dir entry ending in /
# (`Input/`) or via its children (`Input/data.xlsx`). A loose file
# at the root has no children.
is_dir: dict[str, bool] = {}
nested_under: dict[str, set[str]] = {}
loose_files: set[str] = set()
for n in names:
normalized = n.replace("\\", "/")
parts = [p for p in normalized.split("/") if p]
if not parts:
continue
top = parts[0]
if len(parts) == 1 and not normalized.endswith("/"):
# Loose file at root (e.g. Summary.xlsx)
loose_files.add(top)
is_dir.setdefault(top, False)
else:
is_dir[top] = True
if len(parts) >= 2:
nested_under.setdefault(top, set()).add(parts[1])
# Treat Summary leniently: a 'Summary.xlsx' (or .xls/.xlsm) file at
# the root counts the same as a 'Summary/' folder β researchers
# often keep the previous summary workbook beside Input/ and
# Output/ folders. We'll auto-create Summary/ during extract and
# move the file inside.
summary_loose_file = ""
for f in loose_files:
if f.lower().startswith("summary.") and f.lower().endswith(
(".xlsx", ".xls", ".xlsm")
):
summary_loose_file = f
break
# The folders we count toward "structure satisfied"
top_level_folders = {k for k, v in is_dir.items() if v}
wrapper = ""
has_all_folders = all(f in top_level_folders for f in REQUIRED_ZIP_FOLDERS)
has_input_output_plus_summary_file = (
"Input" in top_level_folders
and "Output" in top_level_folders
and summary_loose_file
)
if has_all_folders:
wrapper = ""
elif has_input_output_plus_summary_file:
# Layout will be normalised after extraction (move file into Summary/)
wrapper = ""
elif len(top_level_folders) == 1 and not loose_files:
only = next(iter(top_level_folders))
children = nested_under.get(only, set())
if all(folder in children for folder in REQUIRED_ZIP_FOLDERS):
wrapper = only
else:
_validation_error(
"ZIP is missing the required folders",
f"Your ZIP contains a single top folder <code>{only}/</code>, "
f"but inside it we expected <code>Input/</code>, "
f"<code>Output/</code>, and <code>Summary/</code>. "
f"Found instead: <code>{', '.join(sorted(children)) or '(empty)'}</code>.",
)
else:
# Build a friendly "found" description for the error
found_bits = []
for f in sorted(top_level_folders):
found_bits.append(f"<code>{f}/</code>")
for f in sorted(loose_files):
found_bits.append(f"<code>{f}</code>")
found_desc = ", ".join(found_bits) or "<code>(empty ZIP)</code>"
missing = [f for f in REQUIRED_ZIP_FOLDERS if f not in top_level_folders]
# Special-case: Summary was uploaded as a file with a non-Excel
# extension or wrong name.
extra_hint = ""
if "Summary" in missing and any(
f.lower().startswith("summary") for f in loose_files
):
extra_hint = (
"<br><br>It looks like you have a <code>Summary</code> "
"item at the root but it's a file, not a folder. "
"Either put it inside a <code>Summary/</code> folder, "
"rename it to <code>Summary.xlsx</code>, or just delete "
"it (the Comparator creates the summary itself)."
)
_validation_error(
"ZIP is missing the required folders",
f"The ZIP must contain three folders at its root: "
f"<code>Input/</code>, <code>Output/</code>, "
f"<code>Summary/</code>.<br>"
f"Missing: <code>{', '.join(missing) or '(none β but layout is off)'}</code>."
f"<br><br>Found at root: {found_desc}.{extra_hint}",
)
# --- 6) Extract -----------------------------------------------
try:
zf_ref = zipfile.ZipFile(zip_path, "r")
with zf_ref:
zf_ref.extractall(into_dir)
except Exception as e:
_validation_error(
"Could not unpack the ZIP",
f"Extraction failed with: <code>{e}</code>. Re-create the ZIP "
f"with standard tooling (Windows: right-click β Send to β "
f"Compressed; Mac: right-click β Compress) and try again.",
)
# Resolve the actual Input/ folder on disk after extraction
root = into_dir / wrapper if wrapper else into_dir
input_dir = root / "Input"
output_dir = root / "Output"
summary_dir = root / "Summary"
# Belt-and-braces: make sure the dirs actually exist on disk too
for d in (input_dir, output_dir, summary_dir):
d.mkdir(parents=True, exist_ok=True)
# If the researcher uploaded a loose Summary.xlsx at the root
# (instead of a Summary/ folder), move it into Summary/ so the
# engine has a clean layout to write into.
if not wrapper: # only need this dance for root-layout ZIPs
for candidate in root.iterdir():
if (
candidate.is_file()
and candidate.name.lower().startswith("summary.")
and candidate.name.lower().endswith((".xlsx", ".xls", ".xlsm"))
):
try:
candidate.replace(summary_dir / candidate.name)
except Exception:
pass
# --- 7) Output/ must have at least one Excel file ------------------
# The AI pipeline's output Excels live under Output/ (possibly nested
# under per-project subfolders). The Comparator walks Output/ recursively
# for any .xlsx / .xls / .xlsm.
excels = []
for ext in (".xlsx", ".xls", ".xlsm"):
excels.extend(output_dir.rglob(f"*{ext}"))
excels = [p for p in excels if not p.name.startswith("~$")]
if not excels:
_validation_error(
"The Output/ folder has no AI Excels",
"Your ZIP has the right structure, but <code>Output/</code> "
"(or any of its sub-folders) contains no Excel files. Put your "
"AI output Excels (<code>.xlsx</code>) anywhere inside "
"<code>Output/</code> β they can be in per-project sub-folders "
"if you prefer β then re-zip and upload again.",
)
# Stash the resolved layout on the upload object via attribute trick β
# the run handler reads it back from session_state instead, set there.
ss.zip_layout = {
"root": str(root),
"input": str(input_dir),
"output": str(output_dir),
"summary": str(summary_dir),
"zip_basename": basename,
}
return root
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 _live_error_banner(lines: list[str]) -> str:
"""Build the live error/warning banner HTML for the Inputs tab.
Only the last few ERROR/WARNING lines are shown so the banner
stays compact during a long-running batch."""
error_lines = [l for l in lines if "[ERROR]" in l or "[WARNING]" in l]
if not error_lines:
return ""
recent = error_lines[-5:]
body = "\n".join(recent).replace("<", "<").replace(">", ">")
return (
'<div class="status-banner error" style="margin-top: 14px;">'
'<div class="icon">β οΈ</div>'
'<div style="flex:1;"><b>Something is going wrong in the run.</b>'
'<br>The Log tab has the full trace. Latest lines:'
f'<pre style="white-space: pre-wrap; margin: 8px 0 0; '
f'font-size: 12px; background: rgba(255,255,255,0.5); '
f'padding: 8px; border-radius: 4px; max-height: 160px; '
f'overflow: auto;">{body}</pre>'
'</div></div>'
)
def _run_batch_in_subprocess(ai_dir, out_dir, tie_path, email, password,
lang, log_box, progress_callback,
bna_cookies="", inputs_error_box=None):
"""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
saw_error = False
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":
level = str(rec.get("level", "INFO")).upper()
ss.log_lines.append(f"[{level}] {rec['message']}")
if len(ss.log_lines) > 500:
ss.log_lines[:] = ss.log_lines[-500:]
if level in ("ERROR", "WARNING"):
saw_error = True
elif rec.get("type") == "progress":
progress_callback(rec["info"])
try:
log_box.code("\n".join(ss.log_lines[-60:]), language="text")
except Exception:
pass
# Push a live error excerpt into the Inputs tab so the
# researcher sees problems without having to switch tabs.
if saw_error and inputs_error_box is not None:
try:
inputs_error_box.markdown(
_live_error_banner(ss.log_lines),
unsafe_allow_html=True,
)
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
# Admin tab is hidden by default. It only appears when the team lead
# visits the app with ``?admin=1`` in the URL. Even when it appears,
# every action inside it requires the secret stored in the HF Space
# environment variable ``ADMIN_PASSWORD`` so a researcher who stumbles
# onto the URL can't see or change anything.
def _admin_mode() -> bool:
try:
qp = st.query_params
return str(qp.get("admin", "")).lower() in ("1", "true", "yes")
except Exception:
return False
if _admin_mode():
tab_inputs, tab_dashboard, tab_log, tab_guide, tab_feedback, tab_admin = st.tabs(
["π Inputs", "π Dashboard", "π Log", "π User Guide",
"π¬ Send feedback", "π Admin"]
)
else:
tab_inputs, tab_dashboard, tab_log, tab_guide, tab_feedback = st.tabs(
["π Inputs", "π Dashboard", "π Log", "π User Guide",
"π¬ Send feedback"]
)
tab_admin = None
# ---- 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, "Agentic AI Output Zip")
with c2:
ai_zip = st.file_uploader(
"Agentic AI Output Zip",
type=["zip"],
accept_multiple_files=False,
label_visibility="collapsed",
key=f"uploader_{ss.uploader_nonce}",
help="Upload a single .zip with Input/, Output/, and Summary/ folders inside.",
)
st.caption(
"Required ZIP layout: "
"**`Input/`** Β· "
"**`Output/`** (your AI output Excels β sub-folders OK) Β· "
"**`Summary/`** (or `Summary.xlsx`). "
"One ZIP per run."
)
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",
key=f"lang_{ss.uploader_nonce}",
)
lang = {"English": "en", "EspaΓ±ol": "es", "PortuguΓͺs": "pt"}[lang_label]
c1, c2 = st.columns([1, 4])
_label(c1, "BNA email")
bna_email = c2.text_input(
"BNA email", autocomplete="username", label_visibility="collapsed",
key=f"email_{ss.uploader_nonce}",
)
c1, c2 = st.columns([1, 4])
_label(c1, "BNA password")
bna_password = c2.text_input(
"BNA password", type="password",
autocomplete="current-password", label_visibility="collapsed",
key=f"password_{ss.uploader_nonce}",
)
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])
# Single source of truth for the run-in-progress condition
is_running = ss.run_status == "running"
has_results = bool(ss.last_zip_bytes)
all_inputs_filled = bool(ai_zip and bna_email and bna_password)
# --- Run batch (primary action) ---------------------------------
# Enabled only when:
# * Nothing is running
# * ZIP + email + password are all filled
# Disabled the moment Run is clicked and until the run finishes
# (success or error).
run_disabled = is_running or (not all_inputs_filled)
if b1.button("βΆ Run batch", type="primary",
disabled=run_disabled, key="btn_run"):
ss.trigger_run = True
ss.run_status = "running"
ss.last_run = None
ss.last_zip_bytes = None # Drop previous result so the
ss.last_zip_name = "" # Download button disables for the
# new run (re-enables on success).
ss.run_error_msg = ""
# Force an immediate rerun so the button renders as
# *disabled* (and the Clear/Download buttons too) BEFORE
# the long-running subprocess block kicks off. Without
# this rerun, the script keeps executing the rest of the
# page (where the buttons were already painted as enabled)
# straight into the subprocess block β the researcher
# would see an enabled Run button for the whole batch.
st.rerun()
# --- Download results ZIP ---------------------------------------
# Enabled only when nothing is running AND a results ZIP exists
# from the most recent batch. Skinned BNAmericas blue (#2541B2)
# via the global CSS at the top of this file.
if has_results and not is_running:
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",
key="btn_download",
)
else:
b2.button("β¬ Download results ZIP", disabled=True,
key="btn_download_disabled")
# --- Clear (light-grey safety net) ------------------------------
# Always enabled when nothing is running. Researchers can clear
# mistakes even before they've filled every field. Light-grey
# fill (#E5E7EB) skinned via the global CSS at the top.
if b3.button("π§Ή Clear", disabled=is_running, key="btn_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> '
'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β¦")
# Surface any ERROR / WARNING lines already in the log without
# waiting for the subprocess to finish.
error_banner = _live_error_banner(ss.log_lines)
if error_banner:
st.markdown(error_banner, unsafe_allow_html=True)
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> '
f'Processed <b>{s["ok"]}/{s["total"]}</b> projects '
f'({s.get("failed", 0)} failed). '
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":
# Headline banner β always visible, points at the Log tab.
st.markdown(
f'<div class="status-banner error">'
f'<div class="icon">β οΈ</div>'
f'<div><b>Something went wrong.</b> '
f'See the message below for what to do, and switch to the '
f'<b>Log</b> tab for the full trace.</div>'
f'</div>',
unsafe_allow_html=True,
)
# Always-visible error message (no need to expand).
if ss.run_error_msg:
st.markdown(
'<div class="status-banner error" style="margin-top: 12px;">'
'<div class="icon">π</div>'
'<div style="flex:1;"><b>Details</b>'
'<pre style="white-space: pre-wrap; margin: 8px 0 0; '
'font-size: 12px; background: rgba(255,255,255,0.5); '
'padding: 8px; border-radius: 4px; max-height: 280px; '
'overflow: auto;">'
+ (ss.run_error_msg or "(no message)").replace("<", "<").replace(">", ">") +
'</pre></div></div>',
unsafe_allow_html=True,
)
# ---- 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: 70px 2fr 90px 90px 90px 110px;
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: 70px 2fr 90px 90px 90px 110px;
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>πΏ 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">π 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")
# ---- User Guide tab --------------------------------------------------
# Single source of truth: GUIDE_FOR_RESEARCHERS.md (edit-then-rebuild
# the PDF via tools/build_guide_pdf.py). The tab renders the markdown
# inline for instant reading, and offers the styled PDF as a download
# for offline / printing use.
with tab_guide:
_guide_md = HERE / "GUIDE_FOR_RESEARCHERS.md"
_guide_pdf = HERE / "GUIDE_FOR_RESEARCHERS.pdf"
# Custom CSS to give the rendered markdown a calm, branded look β
# blue h2 headings, soft borders on tables and code, comfortable
# spacing. Only applies inside this tab via a scoped container.
st.markdown(
"<style>"
".guide-wrap h2 {color: #1E3A8A; border-bottom: 2px solid #E5E7EB; "
" padding-bottom: 6px; margin-top: 26px;}"
".guide-wrap h3 {color: #1E3A8A; margin-top: 18px;}"
".guide-wrap table {border-collapse: collapse; width: 100%; "
" margin: 12px 0; font-size: 14px;}"
".guide-wrap th {background: #F8FAFC; color: #1E3A8A; "
" text-align: left; padding: 8px 12px; border-bottom: 2px solid #E5E7EB;}"
".guide-wrap td {padding: 8px 12px; border-bottom: 1px solid #F1F5F9; "
" vertical-align: top;}"
".guide-wrap code {background: #F3F4F6; color: #1E3A8A; "
" padding: 1px 6px; border-radius: 4px; font-size: 0.9em;}"
".guide-wrap ul {line-height: 1.7;}"
".guide-cover {background: #2541B2; color: #FFFFFF; padding: 22px 26px; "
" border-radius: 10px; margin-bottom: 18px;}"
".guide-cover h2 {color: #FFFFFF !important; border: 0 !important; "
" margin: 0 !important; padding: 0 !important; font-size: 22px;}"
".guide-cover p {margin: 6px 0 0 0; color: #DBE3F8; font-size: 14px;}"
"</style>",
unsafe_allow_html=True,
)
# Cover banner + download button row
col_title, col_dl = st.columns([4, 1])
with col_title:
st.markdown(
'<div class="guide-cover">'
'<h2>π Comparer Tool β Quick Guide</h2>'
'<p>Everything you need for your first batch (and the next hundred).</p>'
'</div>',
unsafe_allow_html=True,
)
with col_dl:
if _guide_pdf.exists():
st.markdown('<div style="height: 14px;"></div>', unsafe_allow_html=True)
st.download_button(
"β¬ Download PDF",
data=_guide_pdf.read_bytes(),
file_name="Comparer_Tool_User_Guide.pdf",
mime="application/pdf",
key="btn_guide_pdf",
)
# Render the markdown body (skip the first H1 + lead paragraph,
# they're already shown in the cover banner above).
if _guide_md.exists():
raw_md = _guide_md.read_text(encoding="utf-8")
body_md = raw_md
# Drop the first H1 line + its immediate lead paragraph.
lines = body_md.split("\n")
out = []
seen_h1 = False
skipped_lead = False
for line in lines:
if not seen_h1 and line.startswith("# "):
seen_h1 = True
continue
if seen_h1 and not skipped_lead and line.strip() == "":
continue
if seen_h1 and not skipped_lead and not line.startswith("#"):
skipped_lead = True
continue
out.append(line)
body_md = "\n".join(out)
st.markdown(
f'<div class="guide-wrap">\n\n{body_md}\n\n</div>',
unsafe_allow_html=True,
)
else:
st.error(
"Guide content file is missing. Please upload "
"`GUIDE_FOR_RESEARCHERS.md` to the Space root."
)
# ---- Feedback tab ---------------------------------------------------
# Researcher-facing form. Submits feedback (free text + uploaded
# screenshots + technical files from a batch) to disk, and forwards a
# summary email if SMTP is configured on the HF Space.
with tab_feedback:
st.markdown(
'<h2 class="section-title"><span class="gear">π¬</span> Send feedback</h2>',
unsafe_allow_html=True,
)
st.markdown(
"<p style='color:#4B5563; font-size:14px;'>"
"Spot something off β a wrong match, a confusing column, a feature "
"you wish existed? Tell the team here. Attach screenshots and the "
"project's technical files so we can reproduce it quickly."
"</p>",
unsafe_allow_html=True,
)
if "fb_nonce" not in ss:
ss.fb_nonce = 0
with st.form(f"feedback_form_{ss.fb_nonce}", clear_on_submit=False):
c1, c2 = st.columns(2)
with c1:
fb_name = st.text_input(
"Your name",
value="",
placeholder="e.g. Jane Doe",
)
with c2:
fb_email = st.text_input(
"Your email",
value="",
placeholder="jane.doe@bnamericas.com",
)
c3, c4 = st.columns(2)
with c3:
fb_type = st.selectbox(
"What kind of feedback?",
["Bug β something is wrong",
"Suggestion β improvement idea",
"Question β how does this work?",
"Praise β this works well"],
index=0,
)
with c4:
fb_severity = st.selectbox(
"Severity (bugs only)",
["Low β minor / cosmetic",
"Medium β wrong value but workable",
"High β blocks my batch"],
index=0,
)
c5, c6 = st.columns(2)
with c5:
fb_project = st.text_input(
"Project name (optional)",
value="",
placeholder="e.g. Cerro Bayo Expansion",
)
with c6:
fb_permalink = st.text_input(
"Project permalink (optional)",
value="",
placeholder="e.g. cerro-bayo-expansion",
help="The BNAmericas permalink for the project β copy "
"from the URL or from the AI Excel's ProjectData tab.",
)
fb_subject = st.text_input(
"Short subject",
value="",
placeholder="One line β what's this feedback about?",
)
fb_comment = st.text_area(
"Your feedback",
value="",
height=180,
placeholder=(
"Describe what happened, what you expected, and what you "
"actually saw. The more detail the better."
),
)
fb_screenshots = st.file_uploader(
"Screenshots (optional β drag in one or more images)",
type=["png", "jpg", "jpeg", "gif", "bmp", "webp"],
accept_multiple_files=True,
key=f"fb_shots_{ss.fb_nonce}",
)
fb_tech_files = st.file_uploader(
"Technical files from the batch (optional β Excel, Log.txt, "
"or the whole results ZIP)",
type=["xlsx", "xls", "csv", "txt", "log", "json", "zip"],
accept_multiple_files=True,
key=f"fb_tech_{ss.fb_nonce}",
)
fb_submit = st.form_submit_button("π¨ Submit feedback", type="primary")
if fb_submit:
if not (fb_comment or "").strip():
st.error("Please write at least a short comment before submitting.")
else:
attachments = []
for up in (fb_screenshots or []):
try:
attachments.append((up.name, up.getvalue()))
except Exception:
pass
for up in (fb_tech_files or []):
try:
attachments.append((up.name, up.getvalue()))
except Exception:
pass
manifest = feedback_store.save_submission(
fields={
"researcher_name": (fb_name or "").strip(),
"researcher_email": (fb_email or "").strip(),
"feedback_type": fb_type.split(" β ", 1)[0],
"severity": fb_severity.split(" β ", 1)[0],
"project_ref": (fb_project or "").strip(),
"permalink": (fb_permalink or "").strip(),
"subject": (fb_subject or "").strip(),
"comment": fb_comment.strip(),
},
attachments=attachments,
)
sid = manifest["submission_id"]
success_html = (
f'<div style="background:#DCFCE7; color:#166534; '
f'padding:14px 18px; border-radius:8px; margin:14px 0;">'
f'β
<b>Thanks β feedback received.</b><br>'
f'Reference id: <code>{sid}</code><br>'
f'<span style="font-size:13px;">The AI Content team '
f'will review and follow up shortly.</span>'
f'</div>'
)
st.markdown(success_html, unsafe_allow_html=True)
# Reset the form for the next submission.
ss.fb_nonce += 1
# ---- Admin tab (hidden β team-lead daily session refresh) -----------
# Only renders when ?admin=1 is in the URL AND the team lead enters the
# password configured in the HF Space's ADMIN_PASSWORD secret. Everything
# in this tab is silent for normal researchers.
if tab_admin is not None:
with tab_admin:
st.markdown(
'<h2 class="section-title"><span class="gear">π</span> '
'Admin β Team session</h2>',
unsafe_allow_html=True,
)
_admin_pwd_expected = os.environ.get("ADMIN_PASSWORD", "")
if not _admin_pwd_expected:
st.warning(
"Admin password is not configured. Set the "
"`ADMIN_PASSWORD` secret on the Hugging Face Space, "
"then reload."
)
else:
if not ss.get("admin_authed"):
_pwd = st.text_input(
"Admin password",
type="password",
key="admin_pwd_input",
)
if st.button("Unlock", key="admin_unlock_btn"):
if _pwd == _admin_pwd_expected:
ss.admin_authed = True
st.rerun()
else:
st.error("Wrong password.")
else:
# ---- Session status panel ----
_age = team_session.age_hours()
if _age is None:
_status_html = (
'<div style="background:#FEE2E2; color:#991B1B; '
'padding:10px 14px; border-radius:8px; margin:8px 0;">'
'β οΈ <b>No team session on file.</b> Researchers '
'are falling back to email + password.'
'</div>'
)
elif _age < 12:
_status_html = (
f'<div style="background:#DCFCE7; color:#166534; '
f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
f'β
<b>Session active.</b> Refreshed '
f'{_age:.1f} hours ago.'
f'</div>'
)
elif _age < 22:
_status_html = (
f'<div style="background:#FEF3C7; color:#92400E; '
f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
f'π‘ <b>Session aging.</b> Refreshed '
f'{_age:.1f} hours ago β please refresh soon.'
f'</div>'
)
else:
_status_html = (
f'<div style="background:#FEE2E2; color:#991B1B; '
f'padding:10px 14px; border-radius:8px; margin:8px 0;">'
f'β οΈ <b>Session stale.</b> Refreshed '
f'{_age:.1f} hours ago β researchers will fall '
f'back to passwords.'
f'</div>'
)
st.markdown(_status_html, unsafe_allow_html=True)
# ---- How-to (collapsed) ----
with st.expander("How to copy your BNA cookie (30 seconds)"):
st.markdown(
"1. Sign in to **app.bnamericas.com** in Chrome, "
"Edge, Brave, or Arc.\n"
"2. Press `F12` (Mac: `Cmd + Option + I`).\n"
"3. Click the **Console** tab.\n"
"4. Type: `copy(document.cookie)` then press "
"Enter.\n"
"5. The cookie is on your clipboard. Paste it "
"below and click **Save**."
)
# ---- Paste box + buttons ----
new_cookie = st.text_area(
"Paste fresh BNA session cookie",
value="",
height=110,
placeholder="_bna_session=...; cf_clearance=...; "
"XSRF-TOKEN=...",
key="admin_cookie_input",
)
_b1, _b2, _b3 = st.columns([1, 1, 4])
with _b1:
if st.button(
"πΎ Save", key="admin_save_btn", type="primary"
):
cookie_clean = (new_cookie or "").strip()
if len(cookie_clean) < 50 or "=" not in cookie_clean:
st.error(
"That doesn't look like a cookie string. "
"It should be at least 50 characters and "
"contain `name=value` pairs."
)
else:
team_session.save_session(
cookie_clean,
refreshed_by=os.environ.get(
"USER", "team-lead"
),
)
st.success(
"Session saved. Researchers' next batch "
"will use it automatically."
)
st.rerun()
with _b2:
if st.button("π Clear", key="admin_clear_btn"):
team_session.clear_session()
st.info("Session cleared.")
st.rerun()
# ---- Feedback inbox ----
st.markdown(
"<div style='margin-top:28px; padding-top:18px; "
"border-top:1px solid #E5E7EB;'></div>",
unsafe_allow_html=True,
)
_fb_records = feedback_store.list_submissions()
_fb_count = len(_fb_records)
st.markdown(
f"<h3 style='color:#1E3A8A; margin-bottom:6px;'>"
f"π¬ Researcher feedback</h3>"
f"<p style='font-size:14px; color:#374151; margin-top:0;'>"
f"{_fb_count} submission{'s' if _fb_count != 1 else ''} on file. "
f"Edit Status and Notes inline, click Save changes, then "
f"download the Excel for your next meeting."
f"</p>",
unsafe_allow_html=True,
)
if _fb_count == 0:
st.caption(
"No researcher feedback has been submitted yet."
)
else:
# Top action row: download buttons.
_dl1, _dl2, _ = st.columns([2, 2, 4])
with _dl1:
st.download_button(
"π Download as Excel",
data=feedback_store.export_all_as_excel(),
file_name="bna_comparer_feedback.xlsx",
mime="application/vnd.openxmlformats-officedocument."
"spreadsheetml.sheet",
key="admin_feedback_xlsx",
type="primary",
)
with _dl2:
st.download_button(
"β¬ Download attachments (.zip)",
data=feedback_store.collect_all_as_zip(),
file_name="bna_comparer_feedback.zip",
mime="application/zip",
key="admin_feedback_zip",
help="Per-submission folders with feedback.json + "
"screenshots + technical files.",
)
# Build the editable table.
import pandas as pd
_rows = []
for rec in _fb_records:
f = rec.get("fields", {})
_rows.append({
"Submission ID": rec.get("submission_id", ""),
"Received (UTC)": (rec.get("received_at") or "")[:19],
"Researcher": f.get("researcher_name") or "Anonymous",
"Type": f.get("feedback_type") or "-",
"Severity": f.get("severity") or "-",
"Permalink": f.get("permalink") or "",
"Subject": f.get("subject") or "(no subject)",
"Comment": f.get("comment") or "",
"Attachments": len(rec.get("attachments", [])),
"Status": rec.get("status",
feedback_store.DEFAULT_STATUS),
"Admin notes": rec.get("admin_notes", ""),
})
_df = pd.DataFrame(_rows)
edited = st.data_editor(
_df,
key="admin_fb_editor",
use_container_width=True,
hide_index=True,
column_config={
"Submission ID": st.column_config.TextColumn(
disabled=True, width="small"),
"Received (UTC)": st.column_config.TextColumn(
disabled=True, width="small"),
"Researcher": st.column_config.TextColumn(
disabled=True, width="medium"),
"Type": st.column_config.TextColumn(
disabled=True, width="small"),
"Severity": st.column_config.TextColumn(
disabled=True, width="small"),
"Permalink": st.column_config.TextColumn(
disabled=True, width="medium"),
"Subject": st.column_config.TextColumn(
disabled=True, width="medium"),
"Comment": st.column_config.TextColumn(
disabled=True, width="large"),
"Attachments": st.column_config.NumberColumn(
disabled=True, width="small"),
"Status": st.column_config.SelectboxColumn(
options=list(feedback_store.STATUS_OPTIONS),
required=True, width="small"),
"Admin notes": st.column_config.TextColumn(
width="large",
help="Your notes β visible only to you and "
"anyone with admin access."),
},
)
if st.button(
"πΎ Save changes",
key="admin_fb_save",
type="primary",
):
updates = {}
for _, row in edited.iterrows():
sid = row["Submission ID"]
updates[sid] = {
"status": row["Status"],
"admin_notes": row.get("Admin notes", "") or "",
}
n = feedback_store.update_many(updates)
st.success(f"Saved status and notes for {n} submission"
f"{'s' if n != 1 else ''}.")
st.rerun()
# ---- 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> '
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
# Placeholder in the Inputs tab so the polling loop can push live
# error excerpts there without the researcher having to switch tabs.
inputs_error_box = tab_inputs.empty()
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)
# Strict single-ZIP validation + extract Input/Output/Summary
staged_root = _stage_zip(ai_zip, tmp_path / "staged")
layout = ss.zip_layout
# AI source Excels are inside Output/ (the AI pipeline's
# outputs become the Comparator's inputs).
ai_dir = Path(layout["output"])
# The engine now organises its output into:
# <engine_out>/AI Output folder/ (copy of AI source)
# <engine_out>/Comparer Tool Output folder/ (engine results)
# We zip engine_out directly for download β researcher
# gets a clean 2-sub-folder archive.
engine_out = tmp_path / "results"
engine_out.mkdir(parents=True, exist_ok=True)
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=engine_out, tie_path=tie_path,
email=bna_email, password=bna_password,
lang=lang, log_box=log_box, progress_callback=_progress_cb,
inputs_error_box=inputs_error_box,
)
if error:
ss.log_lines.append(f"[ERROR] {error}")
ss.run_status = "error"
ss.run_error_msg = error
else:
# Engine has already arranged engine_out as the
# AI Output folder + Comparer Tool Output folder layout.
zip_bytes = _zip_directory(engine_out)
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()
"""BNA Comparator -- Web Edition."""
from __future__ import annotations
import io
import json
import os
import re
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
# Add engine folder to sys.path so we can import team_session for the
# Admin tab. batch_runner already runs from inside engine/ as a
# subprocess, so this is only needed for the in-process UI handler.
_ENGINE_DIR = Path(__file__).resolve().parent / "engine"
if str(_ENGINE_DIR) not in sys.path:
sys.path.insert(0, str(_ENGINE_DIR))
import team_session # noqa: E402
import feedback_store # noqa: E402
# -------------------------------------------------------------------
# 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;