Spaces:
Runtime error
Runtime error
Download engine/batch_runner.py from BNAmericas/ComparerTool: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/batch_runner.py
- Command line
-
hf download hf://spaces/BNAmericas/ComparerTool/engine/batch_runner.py
-
curl -L -o batch_runner.py https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/batch_runner.py
31.5 kB
| """ | |
| Batch runner for the BNA Comparator. | |
| Reuses every comparison module (rules / transformer / scraper / comparator / | |
| insights / translator / tie_loader) from this folder. Adds nothing new on | |
| top of the comparison logic itself — only orchestration: | |
| 1. Unzip the uploaded AI Excels into a working temp folder. | |
| 2. For each AI Excel: | |
| - Read its 'ProjectData' tab. | |
| - Pick the permalink from the row whose Field is | |
| 'Project Permalink' (or any of the multilingual aliases). | |
| - Pick the project name from the 'Project Name' row. | |
| - Build URL: https://app.bnamericas.com/project/section/all/content/<permalink> | |
| 3. Log in to BNAmericas ONCE. | |
| 4. For each project, load the page, scrape, compare, write outputs, | |
| zip the per-project output folder. | |
| 5. Write a batch_summary.xlsx at the end. | |
| A single failure does NOT abort the batch — it is logged and the loop | |
| moves on. The summary spreadsheet captures every row's outcome. | |
| Performance: | |
| * One browser context for the whole batch (login once, reuse). | |
| * Per-project bna_fields dict is fresh (no state leak). | |
| * TIE workbook is loaded once and reused across every project. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import re | |
| import shutil | |
| import sys | |
| import tempfile | |
| import time | |
| import zipfile | |
| from datetime import datetime | |
| from typing import Callable, Dict, List, Optional | |
| import openpyxl | |
| from openpyxl.styles import Font, PatternFill, Alignment, Border, Side | |
| # Reuse comparator modules — they live alongside this file | |
| from tie_loader import TIE | |
| from scraper import BNAScraper | |
| from comparator import read_ai_file, build_comparison_rows, write_outputs | |
| import insights | |
| import team_session | |
| BASE_URL_PREFIX = "https://app.bnamericas.com/project/section/all/content/" | |
| # Field-name aliases (case-insensitive, EN/ES/PT) used to find the | |
| # Permalink and Project Name rows inside each AI Excel's ProjectData. | |
| PERMALINK_ALIASES = { | |
| "project permalink", "permalink", "project permalink (slug)", "slug", | |
| "permalink del proyecto", "permalink do projeto", | |
| } | |
| PROJECT_NAME_ALIASES = { | |
| "project name", "name", | |
| "nombre del proyecto", "nombre", | |
| "nome do projeto", "nome", | |
| } | |
| # ---------------------------------------------------------------------- | |
| # Helpers | |
| # ---------------------------------------------------------------------- | |
| def _slug(s: str) -> str: | |
| """Filesystem-safe slug derived from a project name. | |
| Kept short (<=40 chars) because Windows MAX_PATH=260 and the | |
| full path here is: <output>/_tmp_BNA_<slug>_<ts>/Technical output | |
| files/<long debug filename>.xlsx. Long Latin-American project names | |
| blow past 260 instantly. 40 chars is plenty to recognise the project | |
| when browsing the output folder.""" | |
| s = re.sub(r"[^\w\- ]+", "", str(s or "").strip()) | |
| s = re.sub(r"\s+", "_", s).strip("_-") | |
| return s[:40] or "project" | |
| def _norm_field(s) -> str: | |
| return re.sub(r"\s+", " ", str(s or "")).strip().lower() | |
| def _extract_meta_from_ai(ai_rows: List[dict]) -> Dict[str, str]: | |
| """Return {'permalink': ..., 'name': ...} from an AI 'ProjectData' table. | |
| Permalink: row whose Field is 'Project Permalink' (or alias). | |
| Project Name: row whose Field is 'Project Name' (or alias).""" | |
| out = {"permalink": "", "name": ""} | |
| for r in ai_rows: | |
| field_key = _norm_field(r.get("Field")) | |
| val = r.get("Value") | |
| if val is None: | |
| continue | |
| sval = str(val).strip() | |
| if not sval: | |
| continue | |
| if not out["permalink"] and field_key in PERMALINK_ALIASES: | |
| # If a full URL was pasted, strip the base. | |
| if BASE_URL_PREFIX in sval: | |
| sval = sval.split(BASE_URL_PREFIX, 1)[1] | |
| out["permalink"] = sval.lstrip("/").strip() | |
| elif not out["name"] and field_key in PROJECT_NAME_ALIASES: | |
| out["name"] = sval | |
| if out["permalink"] and out["name"]: | |
| break | |
| return out | |
| def _lp(p: str) -> str: | |
| """Prefix a Windows path with \\\\?\\ so it can exceed MAX_PATH (260). | |
| No-op on non-Windows or when already prefixed.""" | |
| if os.name != "nt": return p | |
| p = os.path.abspath(p) | |
| if p.startswith("\\\\?\\"): return p | |
| if p.startswith("\\\\"): | |
| return "\\\\?\\UNC\\" + p.lstrip("\\") | |
| return "\\\\?\\" + p | |
| def _downloads_folder() -> str: | |
| """Return the OS-native Downloads folder. Tries the Windows Shell | |
| 'Known Folder' API first, then ~/Downloads, then the user home.""" | |
| home = os.path.expanduser("~") | |
| if os.name == "nt": | |
| try: | |
| import ctypes | |
| from ctypes import wintypes | |
| FOLDERID_Downloads = "{374DE290-123F-4565-9164-39C4925E467B}" | |
| SHGetKnownFolderPath = ctypes.windll.shell32.SHGetKnownFolderPath | |
| SHGetKnownFolderPath.argtypes = [ctypes.c_char_p, wintypes.DWORD, | |
| wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)] | |
| guid = (ctypes.c_byte * 16)() | |
| ctypes.windll.ole32.IIDFromString(FOLDERID_Downloads, ctypes.byref(guid)) | |
| path_ptr = ctypes.c_wchar_p() | |
| res = SHGetKnownFolderPath(ctypes.cast(guid, ctypes.c_char_p), 0, 0, ctypes.byref(path_ptr)) | |
| if res == 0 and path_ptr.value: | |
| return path_ptr.value | |
| except Exception: | |
| pass | |
| candidate = os.path.join(home, "Downloads") | |
| if os.path.isdir(candidate): | |
| return candidate | |
| return home | |
| def _can_write_to(folder: str) -> bool: | |
| """Probe whether `folder` is actually writable. Returns True if a | |
| small file can be created and deleted there, False otherwise.""" | |
| try: | |
| os.makedirs(_lp(folder), exist_ok=True) | |
| probe = os.path.join(folder, f".bna_probe_{os.getpid()}.tmp") | |
| with open(_lp(probe), "w", encoding="utf-8") as f: | |
| f.write("probe") | |
| os.remove(_lp(probe)) | |
| return True | |
| except Exception: | |
| return False | |
| def _zip_folder(src_folder: str, dst_zip: str) -> str: | |
| """Zip every file in src_folder into dst_zip. Returns dst_zip path.""" | |
| with zipfile.ZipFile(_lp(dst_zip), "w", zipfile.ZIP_DEFLATED) as zf: | |
| for root, _, files in os.walk(_lp(src_folder)): | |
| for f in files: | |
| full = os.path.join(root, f) | |
| arc = os.path.relpath(full, _lp(src_folder)) | |
| zf.write(full, arc) | |
| return dst_zip | |
| def _write_summary(summary_path: str, rows: List[Dict], lang: str = "en"): | |
| """Write batch_summary.xlsx with one row per project.""" | |
| labels = { | |
| "en": { | |
| "title": "Batch Summary", | |
| "headers": ["#", "Project Name", "Permalink", "URL", "AI File", | |
| "Status", "Output ZIP", "Matches", "Differs", | |
| "Stale AI", "Missing on AI", "Missing on Both", | |
| "Match Rate (%)", "Error"], | |
| }, | |
| "es": { | |
| "title": "Resumen del Lote", | |
| "headers": ["#", "Nombre del Proyecto", "Permalink", "URL", "Archivo IA", | |
| "Estado", "ZIP de Salida", "Coincidencias", "Diferencias", | |
| "IA Antigua", "Falta en IA", "Falta en Ambos", | |
| "Tasa de Coincidencia (%)", "Error"], | |
| }, | |
| "pt": { | |
| "title": "Resumo do Lote", | |
| "headers": ["#", "Nome do Projeto", "Permalink", "URL", "Arquivo IA", | |
| "Status", "ZIP de Saída", "Coincidências", "Diferenças", | |
| "IA Antiga", "Falta em IA", "Falta em Ambos", | |
| "Taxa de Coincidência (%)", "Erro"], | |
| }, | |
| } | |
| L = labels.get(lang, labels["en"]) | |
| wb = openpyxl.Workbook() | |
| ws = wb.active | |
| ws.title = L["title"][:31] | |
| HEADER_FILL = PatternFill("solid", fgColor="1F4E78") | |
| HEADER_FONT = Font(color="FFFFFF", bold=True) | |
| OK_FILL = PatternFill("solid", fgColor="C6EFCE") | |
| FAIL_FILL = PatternFill("solid", fgColor="FFC7CE") | |
| THIN = Side(style="thin", color="BFBFBF") | |
| BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN) | |
| for i, h in enumerate(L["headers"], 1): | |
| c = ws.cell(row=1, column=i, value=h) | |
| c.fill = HEADER_FILL | |
| c.font = HEADER_FONT | |
| c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) | |
| c.border = BORDER | |
| ws.row_dimensions[1].height = 28 | |
| for i, r in enumerate(rows, 2): | |
| values = [ | |
| i - 1, | |
| r.get("name", ""), | |
| r.get("permalink", ""), | |
| r.get("url", ""), | |
| r.get("ai_file", ""), | |
| r.get("status", ""), | |
| r.get("output_zip", ""), | |
| r.get("matches", ""), | |
| r.get("differs", ""), | |
| r.get("stale_ai", ""), | |
| r.get("missing_on_ai", ""), | |
| r.get("missing_on_both", ""), | |
| r.get("match_rate", ""), | |
| r.get("error", ""), | |
| ] | |
| for col, v in enumerate(values, 1): | |
| c = ws.cell(row=i, column=col, value=v) | |
| c.alignment = Alignment(wrap_text=True, vertical="top") | |
| c.border = BORDER | |
| fill = OK_FILL if r.get("status") == "OK" else FAIL_FILL | |
| for col in range(1, len(values) + 1): | |
| ws.cell(row=i, column=col).fill = fill | |
| widths = [5, 32, 36, 60, 28, 10, 60, 10, 10, 10, 12, 14, 14, 40] | |
| for i, w in enumerate(widths, 1): | |
| ws.column_dimensions[ws.cell(row=1, column=i).column_letter].width = w | |
| wb.save(_lp(summary_path)) | |
| # ---------------------------------------------------------------------- | |
| # Public entry point | |
| # ---------------------------------------------------------------------- | |
| def run_batch( | |
| ai_zip_path: str, | |
| lang: str, | |
| email: str, | |
| password: str, | |
| output_folder: str, | |
| tie_path: str, | |
| log: Callable[[str, str], None] = lambda lvl, m: None, | |
| progress: Callable[[Dict], None] = lambda info: None, | |
| headless: bool = True, | |
| manual_login: bool = False, | |
| bna_cookies: str = "", | |
| ) -> Dict: | |
| """Run the batch. Returns a summary dict with overall stats. | |
| `ai_zip_path` may be EITHER: | |
| - a path to a .zip file containing AI Excels (sub-folders inside the | |
| ZIP are walked recursively), OR | |
| - a path to a regular folder containing AI Excels (walked recursively). | |
| The permalink + project name for each project are read from the | |
| AI Excel itself ('Project Permalink' and 'Project Name' rows on the | |
| ProjectData tab). | |
| `log(level, message)` is the structured logger used by the GUI. | |
| `progress(info)` is called once per project with a dict | |
| {'index', 'total', 'name', 'status', 'output_zip', 'error', | |
| 'metrics': <insights metrics dict>} | |
| so the GUI can render a live progress list + dashboard. | |
| """ | |
| ts_run = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| os.makedirs(_lp(output_folder), exist_ok=True) | |
| summary_rows: List[Dict] = [] | |
| # 1) Resolve the AI source — accept either a ZIP file or a regular folder. | |
| # For a ZIP: extract into a temp dir we clean up at the end. | |
| # For a folder: walk it directly, no extraction, no temp dir. | |
| temp_dir: Optional[str] = None | |
| if not ai_zip_path or not os.path.exists(ai_zip_path): | |
| raise RuntimeError( | |
| f"AI source not found: {ai_zip_path!r}. " | |
| f"Pass either a .zip file or a folder containing AI Excels.") | |
| if os.path.isdir(ai_zip_path): | |
| scan_dir = ai_zip_path | |
| log("INFO", f"Reading AI Excels from folder: {scan_dir}") | |
| else: | |
| temp_dir = tempfile.mkdtemp(prefix="bna_batch_ai_") | |
| log("INFO", f"Extracting AI Excels from ZIP to {temp_dir}") | |
| try: | |
| with zipfile.ZipFile(ai_zip_path, "r") as zf: | |
| zf.extractall(temp_dir) | |
| except zipfile.BadZipFile: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| raise RuntimeError( | |
| f"'{ai_zip_path}' is neither a folder nor a valid .zip file.") | |
| except Exception as e: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| raise RuntimeError(f"Could not extract AI ZIP: {e}") | |
| scan_dir = temp_dir | |
| # 1b) Reorganise output_folder into two sibling sub-folders: | |
| # <output_folder>/AI Output folder/ (verbatim copy of the AI source) | |
| # <output_folder>/Comparer Tool Output folder/ (every artefact the engine writes) | |
| # All downstream writes (per-project ZIPs, batch_summary.xlsx, etc.) | |
| # go into the Comparer Tool Output folder. Web app callers re-zip the | |
| # whole parent so the researcher's download archive has the | |
| # two-folder layout out of the box; the desktop GUI writes to the | |
| # same layout under whichever folder the researcher picked. | |
| ai_copy_dir = os.path.join(output_folder, "AI Output folder") | |
| comparer_out_dir = os.path.join(output_folder, "Comparer Tool Output folder") | |
| try: | |
| os.makedirs(_lp(ai_copy_dir), exist_ok=True) | |
| os.makedirs(_lp(comparer_out_dir), exist_ok=True) | |
| except Exception as e: | |
| raise RuntimeError( | |
| f"Could not create output sub-folders inside " | |
| f"'{output_folder}': {e}") | |
| # Copy the AI source into 'AI Output folder' so the researcher's | |
| # download archive includes their original files alongside the | |
| # Comparator's output. | |
| try: | |
| if not os.listdir(_lp(ai_copy_dir)): # only fill it the first time | |
| for entry in os.listdir(_lp(scan_dir)): | |
| src = os.path.join(scan_dir, entry) | |
| dst = os.path.join(ai_copy_dir, entry) | |
| if os.path.isdir(src): | |
| shutil.copytree(_lp(src), _lp(dst)) | |
| else: | |
| shutil.copy2(_lp(src), _lp(dst)) | |
| log("INFO", f"AI source copied into '{ai_copy_dir}'") | |
| except Exception as e: | |
| # Non-fatal: continue even if the copy step fails so the | |
| # comparison itself isn't blocked by an OS quirk. | |
| log("WARNING", | |
| f"Could not copy AI source into 'AI Output folder': {e}. " | |
| f"Comparator output will still be written.") | |
| # Redirect all subsequent writes to the Comparer Tool Output folder | |
| output_folder = comparer_out_dir | |
| # 2) Collect every AI Excel under scan_dir | |
| ai_files: List[str] = [] | |
| for root, _, files in os.walk(scan_dir): | |
| for f in files: | |
| if f.lower().endswith((".xlsx", ".xls", ".xlsm")) and not f.startswith("~$"): | |
| ai_files.append(os.path.join(root, f)) | |
| ai_files.sort() | |
| total = len(ai_files) | |
| src_label = "folder" if temp_dir is None else "ZIP" | |
| log("INFO", f"{total} AI Excel files found in {src_label}.") | |
| if total == 0: | |
| if temp_dir is not None: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| raise RuntimeError( | |
| f"No AI Excel files (.xlsx/.xls/.xlsm) found in {src_label} " | |
| f"'{ai_zip_path}'. Check the path and try again.") | |
| # 3) Load TIE once | |
| log("INFO", f"Loading TIE workbook: {tie_path}") | |
| tie = TIE(tie_path) | |
| chip_list = None | |
| try: | |
| chip_list = list(dict.fromkeys(tie.company_chip_mapping.values())) | |
| except Exception: | |
| pass | |
| # 4) Single scraper context — login once, reuse across every project. | |
| # If the auto-login fails (Cloudflare bot detection / MFA / etc.) | |
| # and the researcher hasn't already picked manual login, we fall | |
| # back to manual login automatically: re-launch the browser | |
| # visible and wait for them to sign in by hand once. Beats erroring | |
| # out and making them restart from the GUI. | |
| log("INFO", f"Launching browser (headless={headless})") | |
| try: | |
| with BNAScraper( | |
| log=lambda m: log("INFO", m), | |
| headless=headless, | |
| manual_login=manual_login, | |
| debug_dir=None, | |
| company_chips=chip_list, | |
| bna_lang=lang, | |
| ) as sc: | |
| # Three-stage login resolution, in order of preference: | |
| # 1. Team-lead daily session cookie (set via Admin tab). | |
| # Bypasses Cloudflare's bot challenge because it arrives at | |
| # BNA as an already-authenticated session, not a fresh login. | |
| # 2. Researcher-supplied cookies argument (legacy / advanced). | |
| # 3. Researcher's email + password with retry-with-jitter. | |
| login_ok = False | |
| team_cookie = team_session.get_cookie_if_fresh() | |
| if team_cookie: | |
| log("INFO", "Trying team session cookie (set by team lead)...") | |
| login_ok = sc.inject_cookies(team_cookie) | |
| if login_ok: | |
| log("INFO", "Connected via team session cookie.") | |
| else: | |
| log("WARNING", | |
| "Team session cookie was rejected (likely expired). " | |
| "Falling back to researcher credentials.") | |
| if not login_ok and bna_cookies: | |
| log("INFO", "Trying researcher-supplied BNA session cookie...") | |
| login_ok = sc.inject_cookies(bna_cookies) | |
| if login_ok: | |
| log("INFO", "Connected via researcher session cookie.") | |
| else: | |
| log("WARNING", | |
| "Researcher cookie not accepted -- falling back to " | |
| "email + password.") | |
| if not login_ok: | |
| # Retry-with-jitter. BNA sits behind Cloudflare which sometimes | |
| # throws a transient bot-challenge on first attempt and lets | |
| # the second one through. We try up to 3 times with a small | |
| # random pause between tries so retries don't look automated | |
| # either. Cookies are wiped between tries to avoid carrying | |
| # over a failed challenge token. | |
| import random | |
| backoffs = [0, 6, 18] # seconds before attempts 1, 2, 3 | |
| for attempt_idx, base_wait in enumerate(backoffs, start=1): | |
| if base_wait > 0: | |
| delay = base_wait + random.uniform(0.5, 4.5) | |
| log("INFO", | |
| f"Login retry {attempt_idx}/3 in " | |
| f"{delay:.1f}s (Cloudflare cooldown)...") | |
| time.sleep(delay) | |
| try: sc._context.clear_cookies() | |
| except Exception: pass | |
| log("INFO", f"Logging in to BNAmericas (attempt {attempt_idx}/3)...") | |
| if sc.login(email, password): | |
| login_ok = True | |
| break | |
| if not login_ok and not manual_login: | |
| # The headed manual-login fallback only makes sense on a | |
| # desktop with a display. The web app runs on Hugging Face | |
| # Spaces, which is a headless Linux container with no X | |
| # server -- launching a visible Chromium there crashes with | |
| # "Missing X server or $DISPLAY". Detect that case and raise | |
| # a clean login error instead of a Playwright traceback. | |
| has_display = bool(os.environ.get("DISPLAY")) or sys.platform.startswith(("win", "darwin")) | |
| if not has_display: | |
| raise RuntimeError( | |
| "BNA login failed. Double-check your BNAmericas email " | |
| "and password, then try again. If the password is " | |
| "definitely correct, BNAmericas may have temporarily " | |
| "flagged the sign-in -- wait ~10 minutes and retry." | |
| ) | |
| log("WARNING", | |
| "Auto-login was blocked by BNAmericas (Cloudflare / MFA / " | |
| "captcha). Re-launching browser in MANUAL login mode — " | |
| "please sign in by hand in the window that opens; the " | |
| "batch will continue automatically.") | |
| # Close the current (headless) scraper and switch to a | |
| # visible browser with manual login. The whole 'with' is | |
| # nested so cleanup still happens. | |
| try: sc.__exit__(None, None, None) | |
| except Exception: pass | |
| sc2 = BNAScraper( | |
| log=lambda m: log("INFO", m), | |
| headless=False, | |
| manual_login=True, | |
| debug_dir=None, | |
| company_chips=chip_list, | |
| bna_lang=lang, | |
| ).__enter__() | |
| try: | |
| if not sc2.login(email, password): | |
| raise RuntimeError("BNA login failed in both auto and manual modes.") | |
| sc = sc2 # swap so the rest of the loop uses the new scraper | |
| login_ok = True | |
| except Exception: | |
| try: sc2.__exit__(None, None, None) | |
| except Exception: pass | |
| raise | |
| if not login_ok: | |
| raise RuntimeError("BNA login failed.") | |
| # Align BNA's UI language with the researcher's Output Language | |
| # selection BEFORE any project page is loaded. This makes BNA | |
| # render fields directly in the target language (es / pt), so | |
| # extracted values like project name, descriptions, current | |
| # stage etc. come out in the right language instead of whatever | |
| # the account's last-used language happened to be. | |
| if lang in ("en", "es", "pt"): | |
| try: | |
| log("INFO", f"Aligning BNA UI language to '{lang}'...") | |
| sc.set_bna_language(lang) | |
| except Exception as e: | |
| log("WARNING", | |
| f"Could not switch BNA UI language to '{lang}': {e}. " | |
| f"Falling back to extract-then-translate via TIE tables.") | |
| for i, ai_path in enumerate(ai_files, 1): | |
| ai_basename = os.path.basename(ai_path) | |
| row_summary = { | |
| "name": "", "permalink": "", "url": "", | |
| "ai_file": ai_basename, "status": "FAILED", | |
| "output_zip": "", "error": "", | |
| "matches": "", "differs": "", "stale_ai": "", | |
| "missing_on_ai": "", "missing_on_both": "", "match_rate": "", | |
| } | |
| # Per-project log buffer — gets baked into the per-project | |
| # Log.xlsx so each ZIP carries its own run log alongside | |
| # the technical output files. | |
| proj_log: List[str] = [] | |
| def _log_proj(level, message): | |
| ts_msg = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") | |
| proj_log.append(f"{ts_msg}|{level}|{message}") | |
| log(level, message) | |
| log("INFO", f"[{i}/{total}] {ai_basename}") | |
| _log_proj("INFO", f"Processing {ai_basename}") | |
| try: | |
| ai_rows = read_ai_file(ai_path) | |
| if not ai_rows: | |
| raise RuntimeError("AI file has no data rows.") | |
| meta = _extract_meta_from_ai(ai_rows) | |
| permalink = meta["permalink"] | |
| name = meta["name"] or os.path.splitext(ai_basename)[0] | |
| if not permalink: | |
| raise RuntimeError( | |
| "AI file is missing a 'Project Permalink' row. " | |
| "Add a row with Field='Project Permalink' and " | |
| "Value=<slug>." | |
| ) | |
| url = BASE_URL_PREFIX + permalink.lstrip("/") | |
| row_summary.update({"name": name, "permalink": permalink, "url": url}) | |
| _log_proj("INFO", f" Permalink: {permalink}") | |
| _log_proj("INFO", f" URL: {url}") | |
| _log_proj("INFO", f" {len(ai_rows)} AI fields loaded.") | |
| # Create the per-project temp output folder up front so | |
| # we have a place to drop Technical output files (the | |
| # scraper's debug dumps + the rule trace). These are | |
| # exactly the same artifacts the single-project app | |
| # writes under 'Technical output files'. | |
| proj_ts = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| base_name = f"BNA_{_slug(name)}" | |
| # Stage all per-project work in TEMP so OneDrive (or | |
| # any synced output folder) only ever sees the FINAL | |
| # ZIP, not the hundreds of intermediate scrape / | |
| # debug writes. This single change cuts OneDrive | |
| # background sync activity by ~10x during batches. | |
| project_out_dir = os.path.join( | |
| tempfile.gettempdir(), | |
| f"bna_proj_{_slug(name)}_{proj_ts}") | |
| tech_folder = os.path.join(project_out_dir, | |
| "Technical output files") | |
| os.makedirs(_lp(tech_folder), exist_ok=True) | |
| # Point the (already-running) scraper's debug_dir at | |
| # this project's tech folder. Reusing the same browser | |
| # session means we just mutate the attribute — no need | |
| # to tear down the scraper per project. | |
| sc.debug_dir = tech_folder | |
| if not sc.load_project(url): | |
| raise RuntimeError("Could not load project page.") | |
| bna_fields = sc.extract_fields() | |
| # Use the project name from the AI as authoritative for | |
| # the 'Project Name' comparison row. | |
| if name: | |
| bna_fields["Project Name"] = name | |
| rows = build_comparison_rows(ai_rows, bna_fields, tie, | |
| lang=lang, debug_dir=tech_folder) | |
| metrics = insights.compute(rows) | |
| # Try writing to the user-selected output folder first. | |
| # If anything fails (path too long, OneDrive lock, | |
| # permission denied, disk full, ...), fall back to | |
| # the user's local Downloads folder and emit a clear | |
| # warning so they know where to find the files. | |
| final_output_folder = output_folder | |
| write_err = None | |
| try: | |
| write_outputs( | |
| project_out_dir, rows, proj_log, | |
| metrics, tie, base_name=base_name, | |
| languages=(lang,), | |
| project_url=url, | |
| ) | |
| zip_path = os.path.join(output_folder, | |
| f"{base_name}_{proj_ts}.zip") | |
| _zip_folder(project_out_dir, zip_path) | |
| except Exception as we: | |
| write_err = we | |
| if write_err is not None: | |
| dl = _downloads_folder() | |
| _log_proj("WARNING", | |
| f" Could not write to '{output_folder}' " | |
| f"({write_err.__class__.__name__}: {write_err}). " | |
| f"Falling back to Downloads: {dl}") | |
| final_output_folder = dl | |
| # Rebuild output paths under Downloads | |
| fb_project_dir = os.path.join(dl, | |
| f"_t_{_slug(name)}_{proj_ts}") | |
| fb_tech = os.path.join(fb_project_dir, | |
| "Technical output files") | |
| os.makedirs(_lp(fb_tech), exist_ok=True) | |
| # Replay technical files into the fallback tech folder | |
| try: | |
| for fname in os.listdir(_lp(tech_folder)): | |
| shutil.copy2(_lp(os.path.join(tech_folder, fname)), | |
| _lp(os.path.join(fb_tech, fname))) | |
| except Exception as ce: | |
| _log_proj("WARNING", f" Tech copy partial: {ce}") | |
| write_outputs( | |
| fb_project_dir, rows, proj_log, | |
| metrics, tie, base_name=base_name, | |
| languages=(lang,), | |
| project_url=url, | |
| ) | |
| zip_path = os.path.join(dl, | |
| f"{base_name}_{proj_ts}.zip") | |
| _zip_folder(fb_project_dir, zip_path) | |
| shutil.rmtree(fb_project_dir, ignore_errors=True) | |
| _log_proj("WARNING", | |
| f" Saved to Downloads instead: {zip_path}") | |
| shutil.rmtree(project_out_dir, ignore_errors=True) | |
| row_summary.update({ | |
| "status": "OK", | |
| "output_zip": zip_path, | |
| "matches": metrics.get("matches", 0), | |
| "differs": metrics.get("differs", 0), | |
| "stale_ai": metrics.get("stale_ai", 0), | |
| "missing_on_ai": metrics.get("missing_on_ai", 0), | |
| "missing_on_both": metrics.get("pending_disclosure", 0), | |
| "match_rate": metrics.get("match_rate", 0), | |
| }) | |
| _log_proj("INFO", f" OK -> {zip_path}") | |
| progress({"index": i, "total": total, "name": name, | |
| "status": "OK", "output_zip": zip_path, "error": "", | |
| "metrics": metrics}) | |
| except Exception as e: | |
| err = str(e) | |
| _log_proj("ERROR", f" {err}") | |
| row_summary["error"] = err | |
| if not row_summary["name"]: | |
| row_summary["name"] = os.path.splitext(ai_basename)[0] | |
| progress({"index": i, "total": total, | |
| "name": row_summary["name"], | |
| "status": "FAILED", "output_zip": "", "error": err}) | |
| summary_rows.append(row_summary) | |
| finally: | |
| # Only clean up the temp dir if we created one (ZIP path). When the | |
| # researcher pointed at a regular folder, leave it untouched. | |
| if temp_dir is not None: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| # 5) Write batch summary — with Downloads fallback if the user's | |
| # chosen folder rejects the write (locked, full, path too long). | |
| summary_path = os.path.join(output_folder, f"batch_summary_{ts_run}.xlsx") | |
| try: | |
| _write_summary(summary_path, summary_rows, lang=lang) | |
| log("INFO", f"Batch summary written: {summary_path}") | |
| except Exception as se: | |
| dl = _downloads_folder() | |
| log("WARNING", | |
| f"Could not write batch summary to '{output_folder}' " | |
| f"({se.__class__.__name__}: {se}). Falling back to {dl}.") | |
| summary_path = os.path.join(dl, f"batch_summary_{ts_run}.xlsx") | |
| _write_summary(summary_path, summary_rows, lang=lang) | |
| log("WARNING", f"Batch summary saved to Downloads: {summary_path}") | |
| ok = sum(1 for r in summary_rows if r["status"] == "OK") | |
| failed = total - ok | |
| return { | |
| "total": total, "ok": ok, "failed": failed, | |
| "summary_path": summary_path, | |
| "rows": summary_rows, | |
| } | |