File size: 5,623 Bytes
6f5156a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Scrape full text from a goldenset xlsx's GOLDENSET sheet into a JSONL file.

For each row of the GOLDENSET sheet, fetches the URL in the ``link`` column
(HTML or PDF), extracts text, and writes one JSON line in the same shape as
``data/am/full_text.jsonl``:

    {"case_id": "<slug>", "full_text": "case_id: <orig> link: <url> Quelle Text: <source> <body>"}

``case_id`` (key) is the filesystem-safe slug of the workbook's case_id;
the body keeps the original case_id and link verbatim. Whitespace in the
body is collapsed to single spaces so each record stays on one line.

Usage:
    uv run python -m legex.scrape_full_text data/am/Goldenset_Armenia_final.xlsx
    uv run python -m legex.scrape_full_text data/gh/Goldenset_Ghana.xlsx --resume
"""

from __future__ import annotations

import argparse
import json
import logging
import re
import sys
from pathlib import Path

import openpyxl

from legex.pdf_export.core import safe_slug
from legex.pdf_export.urls import pick_body
from legex.pdf_export.workbook import cell, header_map

log = logging.getLogger("legex.scrape_full_text")

_WS_RE = re.compile(r"\s+")


def normalize_ws(text: str) -> str:
    return _WS_RE.sub(" ", text).strip()


def build_full_text(case_id: str, link: str, source: str, body: str) -> str:
    return normalize_ws(
        f"case_id: {case_id} link: {link} Quelle Text: {source} {body}"
    )


def _load_existing_case_ids(out_path: Path) -> set[str]:
    seen: set[str] = set()
    with out_path.open("r", 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")
            if cid:
                seen.add(cid)
    return seen


def scrape_xlsx(
    xlsx: Path,
    out_path: Path,
    *,
    pause_s: float,
    req_timeout: float,
    limit: int | None,
    resume: bool,
) -> int:
    wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True)
    if "GOLDENSET" not in wb.sheetnames:
        wb.close()
        log.error("no GOLDENSET sheet in %s", xlsx)
        return 0
    ws = wb["GOLDENSET"]
    rows = ws.iter_rows(values_only=True)
    header_row = next(rows, None)
    if not header_row:
        wb.close()
        return 0
    h = header_map(header_row)
    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("no 'link' column in %s", xlsx)
        return 0

    existing: set[str] = set()
    mode = "w"
    if resume and out_path.exists():
        existing = _load_existing_case_ids(out_path)
        mode = "a"
        log.info("resume: %d existing case_ids in %s", len(existing), out_path)

    out_path.parent.mkdir(parents=True, exist_ok=True)
    written = 0
    row_idx = 1
    label = xlsx.parent.name
    with out_path.open(mode, encoding="utf-8") as out:
        for row in rows:
            row_idx += 1
            if not row:
                continue
            link_val = (cell(row, idx_link) or "").strip()
            case_id_raw = cell(row, idx_case)
            sheet_full = cell(row, idx_text) if idx_text is not None else None
            if (
                not str(case_id_raw or "").strip()
                and not link_val
                and not (sheet_full or "").strip()
            ):
                continue
            slug = safe_slug(case_id_raw, link_val or None, row_idx)
            if slug in existing:
                continue
            body, source = pick_body(link_val, sheet_full, pause_s, req_timeout)
            full = build_full_text(
                str(case_id_raw or "").strip(), link_val, source, body
            )
            out.write(
                json.dumps({"case_id": slug, "full_text": full}, ensure_ascii=False)
            )
            out.write("\n")
            out.flush()
            existing.add(slug)
            written += 1
            if written % 10 == 0:
                log.info("[%s] %d written", label, written)
            if limit is not None and written >= limit:
                break
    wb.close()
    log.info("[%s] done: %d written -> %s", label, written, out_path)
    return written


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("xlsx", type=Path, help="Path to Goldenset_*.xlsx")
    ap.add_argument(
        "--out",
        type=Path,
        default=None,
        help="Output jsonl path (default: <xlsx.parent>/full_text.jsonl)",
    )
    ap.add_argument(
        "--pause", type=float, default=0.5, help="Seconds between requests (default: 0.5)"
    )
    ap.add_argument(
        "--timeout", type=float, default=28.0, help="Request timeout in seconds (default: 28)"
    )
    ap.add_argument("--limit", type=int, default=None, help="Max rows to scrape")
    ap.add_argument(
        "--resume",
        action="store_true",
        help="Append to existing jsonl, skipping case_ids already present",
    )
    args = ap.parse_args()

    if not args.xlsx.is_file():
        log.error("xlsx not found: %s", args.xlsx)
        return 1

    out_path = args.out or (args.xlsx.parent / "full_text.jsonl")
    scrape_xlsx(
        args.xlsx,
        out_path,
        pause_s=args.pause,
        req_timeout=args.timeout,
        limit=args.limit,
        resume=args.resume,
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())