"""Render judgment pages with a real browser and write ``full_text.jsonl``. Some courts (Taiwan's ``judgment.judicial.gov.tw``, Hong Kong's ``legalref.judiciary.hk``) reject plain HTTP clients or hide the judgment behind script/anti-bot checks, so the requests-based ``scrape_full_text`` only captured error placeholders. This module drives headless Chromium via Playwright, waits for the judgment container to appear, and extracts its text. Output matches ``legex.scrape_full_text`` / ``data//full_text.jsonl`` so the inference step consumes it unchanged: one JSON object per line with a filesystem-safe ``case_id`` slug and a ``full_text`` body prefixed with the original ``case_id``/``link``. Per-site content selectors live in ``CONTENT_SELECTORS``; unknown sites fall back to the page ``body``. Rows whose extracted text is shorter than ``--min-chars`` are recorded with a ``RENDER_EMPTY`` marker and retried on the next ``--resume`` run. Usage: uv run legex-render-fulltext --country tw uv run legex-render-fulltext --country tw --limit 5 --headed uv run legex-render-fulltext --country hk --resume """ from __future__ import annotations import argparse import json import logging import sys import time from collections.abc import Callable from pathlib import Path from openpyxl import load_workbook from legex.pdf_export.core import safe_slug from legex.pdf_export.workbook import cell, header_map from legex.fulltext.scrape_full_text import build_full_text, normalize_ws from legex.utils import full_text_jsonl_path, goldenset_path, goldenset_sheet log = logging.getLogger("legex.render_full_text") # CSS selector for the element holding the judgment body, per country code. CONTENT_SELECTORS: dict[str, str] = { "tw": "#jud", # FJUD data.aspx judgment container "hk": "body", # ju_body.jsp renders the whole judgment in } _DEFAULT_SELECTOR = "body" def _rewrite_hk(url: str) -> str: """Hong Kong links point at the frameset ``ju_frame.jsp``; the judgment itself lives in the inner ``ju_body.jsp`` frame, which loads on its own.""" if "ju_frame.jsp" in url: return url.replace("ju_frame.jsp", "ju_body.jsp") + "&AH=&QS=&FN=&currpage=T" return url # Per-country link rewrites applied before navigation. URL_REWRITES: dict[str, Callable[[str], str]] = { "hk": _rewrite_hk, } # Marker stored for rows that rendered but yielded no usable text, so a # --resume run re-attempts them instead of treating them as done. _EMPTY_MARKER = "RENDER_EMPTY" _UA = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15" ) def _load_done(out_path: Path) -> set[str]: """case_id slugs already present with real (non-empty) text.""" done: set[str] = set() if not out_path.exists(): return done with out_path.open(encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: rec = json.loads(line) except json.JSONDecodeError: continue cid = rec.get("case_id") body = rec.get("full_text", "") if cid and _EMPTY_MARKER not in body: done.add(cid) return done def _extract_text(page, selector: str, min_chars: int) -> str: """Best non-empty text among the comma-separated selector candidates.""" best = "" for sel in [s.strip() for s in selector.split(",") if s.strip()]: try: loc = page.locator(sel).first if loc.count() == 0: continue txt = loc.inner_text(timeout=5_000) except Exception: # noqa: BLE001 - selector may be absent on a page continue txt = normalize_ws(txt or "") if len(txt) > len(best): best = txt if len(best) >= min_chars: break return best def render_country( cc: str, out_path: Path, *, selector: str, pause_s: float, nav_timeout_ms: int, min_chars: int, limit: int | None, resume: bool, headed: bool, ) -> tuple[int, int]: """Render every link in the country's goldenset. Returns (written, empty).""" from playwright.sync_api import sync_playwright rewrite = URL_REWRITES.get(cc, lambda u: u) gs = goldenset_path(cc) wb = load_workbook(gs, read_only=True, data_only=True) ws = goldenset_sheet(wb) rows = ws.iter_rows(values_only=True) header = next(rows, None) if not header: wb.close() log.error("[%s] empty goldenset %s", cc, gs) return 0, 0 h = header_map(header) idx_case = h.get("case_id") idx_link = h.get("link") idx_text = h.get("full_text") if idx_link is None: wb.close() log.error("[%s] no 'link' column in %s", cc, gs) return 0, 0 done = _load_done(out_path) if resume else set() mode = "a" if (resume and out_path.exists()) else "w" out_path.parent.mkdir(parents=True, exist_ok=True) written = empty = 0 with sync_playwright() as p: browser = p.chromium.launch(headless=not headed) context = browser.new_context(user_agent=_UA, locale="zh-TW") page = context.new_page() page.set_default_navigation_timeout(nav_timeout_ms) with out_path.open(mode, encoding="utf-8") as out: row_idx = 1 for row in rows: row_idx += 1 if not row: continue link = (cell(row, idx_link) or "").strip() case_id_raw = str(cell(row, idx_case) or "").strip() sheet_full = cell(row, idx_text) if idx_text is not None else None if not link and not case_id_raw: continue slug = safe_slug(case_id_raw, link or None, row_idx) if slug in done: continue if limit is not None and (written + empty) >= limit: break body, source = "", "render" if link.startswith("http"): nav_url = rewrite(link) try: page.goto(nav_url, wait_until="domcontentloaded") try: page.wait_for_selector( selector.split(",")[0].strip(), timeout=nav_timeout_ms ) except Exception: # noqa: BLE001 - fall back to whatever loaded pass body = _extract_text(page, selector, min_chars) except Exception as e: # noqa: BLE001 log.warning("[%s] render failed row %d: %s", cc, row_idx, e) body = "" if len(body) < min_chars: empty += 1 sheet = normalize_ws(str(sheet_full)) if sheet_full else "" if len(sheet) >= min_chars: body, source = sheet, "full_text (Fallback)" else: body = f"{_EMPTY_MARKER} (rendered {len(body)} chars)" source = "render (leer)" else: written += 1 full = build_full_text(case_id_raw, link, source, body) out.write(json.dumps({"case_id": slug, "full_text": full}, ensure_ascii=False)) out.write("\n") out.flush() done.add(slug) if (written + empty) % 10 == 0: log.info("[%s] %d ok / %d empty", cc, written, empty) time.sleep(pause_s) context.close() browser.close() wb.close() log.info("[%s] done: %d rendered, %d empty -> %s", cc, written, empty, out_path) return written, empty def main(argv: list[str] | None = None) -> int: logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") ap = argparse.ArgumentParser(description="Render judgment pages with Playwright.") ap.add_argument("--country", required=True, help="Country code (resolves goldenset + output).") ap.add_argument("--out", type=Path, default=None, help="Output jsonl (default data//full_text.jsonl).") ap.add_argument("--selector", default=None, help="Override the content CSS selector.") ap.add_argument("--pause", type=float, default=1.0, help="Seconds between page loads.") ap.add_argument("--nav-timeout", type=int, default=30_000, help="Navigation timeout (ms).") ap.add_argument("--min-chars", type=int, default=300, help="Below this a render counts as empty.") ap.add_argument("--limit", type=int, default=None, help="Max rows to render.") ap.add_argument("--resume", action="store_true", help="Skip rows already captured with text.") ap.add_argument("--headed", action="store_true", help="Show the browser window (debugging).") args = ap.parse_args(argv) cc = args.country gs = goldenset_path(cc) if not gs.exists(): log.error("no goldenset for %s at %s", cc, gs) return 2 out_path = args.out or full_text_jsonl_path(cc) selector = args.selector or CONTENT_SELECTORS.get(cc, _DEFAULT_SELECTOR) log.info("[%s] rendering with selector %r -> %s", cc, selector, out_path) written, empty = render_country( cc, out_path, selector=selector, pause_s=args.pause, nav_timeout_ms=args.nav_timeout, min_chars=args.min_chars, limit=args.limit, resume=args.resume, headed=args.headed, ) return 0 if written else 1 if __name__ == "__main__": sys.exit(main())