"""CLI wrapper around batch_runner.run_batch. Streamlit's main process holds Playwright's sync API in a poisoned state after the first use (event loop closes; second call fails). The cleanest workaround is to run each batch in a brand-new Python subprocess, which gets a fresh Playwright instance every time. Invocation (called by app.py, not by humans): python run_batch_cli.py Config is read from stdin as a single JSON object. Keeping it off the command line prevents the BNA password from appearing in `ps aux`. `output_json` is where the summary dict is written when the run finishes. `log_jsonl` is appended to as the run progresses, one JSON line per log message; the Streamlit side tails this file to update the live log view. The wrapper is wrapped from end-to-end in a BaseException-catching block so that ANY failure path (import error, SystemExit, OOM trace, etc.) still produces a result.json the Streamlit side can surface. Without that, the user gets the unhelpful "Subprocess exited without writing a result file." message. """ from __future__ import annotations import json import sys import traceback from pathlib import Path def _redact(text: str, secret: str) -> str: if not secret or not text: return text return text.replace(secret, "***REDACTED***") def _emergency_write(out_path: Path, err: str, tb: str = "") -> None: """Write a minimal error result.json without raising.""" try: out_path.write_text( json.dumps({"ok": False, "error": err, "traceback": tb}), encoding="utf-8", ) except Exception: pass def main() -> int: # ---- argv check (before anything else) ----------------------------- if len(sys.argv) != 3: print("Usage: run_batch_cli.py ", file=sys.stderr) # No out_path known yet — best we can do is exit 2. return 2 out_path = Path(sys.argv[1]) log_path = Path(sys.argv[2]) # ---- everything below MUST write a result.json on failure ---------- bna_password = "" try: # Engine import is deferred until inside the try so an ImportError # gets surfaced via result.json rather than killing the subprocess # silently. HERE = Path(__file__).resolve().parent if str(HERE) not in sys.path: sys.path.insert(0, str(HERE)) import batch_runner # noqa # Read config from stdin try: raw = sys.stdin.read() except Exception as e: _emergency_write(out_path, f"Could not read config from stdin: {e}", traceback.format_exc()) return 1 if not raw.strip(): _emergency_write(out_path, "Empty config received from Streamlit on stdin.") return 1 try: cfg = json.loads(raw) except Exception as e: _emergency_write(out_path, f"Could not parse config JSON: {e}", traceback.format_exc()) return 1 bna_password = cfg.get("password", "") or "" def _log(level: str, message: str) -> None: try: with log_path.open("a", encoding="utf-8") as fh: fh.write(json.dumps({ "type": "log", "level": level, "message": _redact(message, bna_password), }) + "\n") except Exception: pass def _progress(info) -> None: try: with log_path.open("a", encoding="utf-8") as fh: fh.write(json.dumps({ "type": "progress", "info": info, }, default=str) + "\n") except Exception: pass # ---- the actual batch run ------------------------------------- summary = batch_runner.run_batch( ai_zip_path=cfg["ai_zip_path"], lang=cfg.get("lang", "es"), email=cfg.get("email", ""), password=cfg.get("password", ""), output_folder=cfg["output_folder"], tie_path=cfg["tie_path"], log=_log, progress=_progress, headless=cfg.get("headless", True), manual_login=cfg.get("manual_login", False), bna_cookies=cfg.get("bna_cookies", ""), ) out_path.write_text( json.dumps({"ok": True, "summary": summary}, default=str), encoding="utf-8", ) return 0 except SystemExit as se: # batch_runner or something it imports called sys.exit(). _emergency_write( out_path, f"SystemExit during batch run (code {se.code!r}). " "Check the Log tab for the last successful step.", _redact(traceback.format_exc(), bna_password), ) return 1 except KeyboardInterrupt: _emergency_write(out_path, "Batch interrupted by user.") return 1 except MemoryError: _emergency_write( out_path, "Out of memory. Try reducing the number of AI Excels per " "batch or upgrading the HF Space tier.", ) return 1 except BaseException as e: # noqa: B902 # Catch absolutely anything else (including ImportError) and # surface a useful message instead of "Subprocess exited without # writing a result file." tb = _redact(traceback.format_exc(), bna_password) err = _redact(f"{type(e).__name__}: {e}", bna_password) _emergency_write(out_path, err, tb) return 1 if __name__ == "__main__": try: rc = main() except BaseException: # main() itself raised — try to capture it (but only if main() # didn't already write a useful result.json). if len(sys.argv) >= 2: out_path = Path(sys.argv[1]) # Only overwrite the result file if it doesn't exist yet — # main()'s own except clauses produce better messages. if not out_path.exists() or out_path.stat().st_size == 0: _emergency_write( out_path, f"Fatal: {traceback.format_exc()}", ) rc = 1 # Plain sys.exit on the return code — must NOT be wrapped in try/except # because that would catch the SystemExit and overwrite the result file # main() already wrote with this useless "Fatal: SystemExit: 1". sys.exit(rc)