File size: 6,733 Bytes
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
c775112
27c9320
 
c775112
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c775112
 
 
 
 
 
 
 
 
 
 
27c9320
c775112
27c9320
 
 
c775112
27c9320
 
 
 
 
c775112
 
27c9320
c775112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c775112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
c775112
27c9320
 
 
 
c775112
fa9a6c3
c775112
fa9a6c3
 
c775112
fa9a6c3
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""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 <output_json> <log_jsonl>

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 <output_json> <log_jsonl>",
              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)