File size: 6,432 Bytes
2e511b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build ``data/<cc>/full_text.jsonl`` from an offline source.

Two sources, both producing the JSONL shape the inference step consumes
(one object per line with a filesystem-safe ``case_id`` slug and ``full_text``):

1. A Goldenset's ``full_text`` column — for jurisdictions whose judgment text
   already lives in the workbook (e.g. Brazil).
2. A directory of PDFs (``--pdf-dir``) — for jurisdictions delivered as PDF
   bundles (e.g. India's ``india_judgments.zip``). Each PDF's stem is the
   ``case_id``; text is extracted with pypdf.

Rows/files whose text is empty or shorter than ``--min-chars`` are reported
and skipped.

Usage:
    uv run legex-build-fulltext --country br
    uv run legex-build-fulltext --xlsx "data/br/Goldenset_Brazil_final (...).xlsx"
    uv run legex-build-fulltext --country in --pdf-dir data/raw/india_real/pdf
"""

from __future__ import annotations

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

from openpyxl import load_workbook
from pypdf import PdfReader

from legex.pdf_export.core import safe_slug
from legex.utils import full_text_jsonl_path, goldenset_path, goldenset_sheet

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

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


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


def build_from_pdf_dir(
    pdf_dir: Path,
    out_path: Path,
    *,
    min_chars: int,
) -> tuple[int, int]:
    """Extract text from every PDF in ``pdf_dir``. Returns (written, skipped)."""
    pdfs = sorted(pdf_dir.glob("*.pdf"))
    if not pdfs:
        raise ValueError(f"no PDFs in {pdf_dir}")
    out_path.parent.mkdir(parents=True, exist_ok=True)
    written = skipped = 0
    with out_path.open("w", encoding="utf-8") as f:
        for pdf in pdfs:
            try:
                reader = PdfReader(str(pdf))
                body = _norm_ws(" ".join((p.extract_text() or "") for p in reader.pages))
            except Exception as exc:  # noqa: BLE001
                log.warning("skip %s: %s", pdf.name, exc)
                skipped += 1
                continue
            if len(body) < min_chars:
                skipped += 1
                log.warning("skip %s: %d chars", pdf.name, len(body))
                continue
            f.write(
                json.dumps({"case_id": pdf.stem, "full_text": body}, ensure_ascii=False) + "\n"
            )
            written += 1
    return written, skipped


def build_from_xlsx(
    xlsx: Path,
    out_path: Path,
    *,
    min_chars: int,
) -> tuple[int, int]:
    """Returns (written, skipped)."""
    wb = load_workbook(xlsx, read_only=True, data_only=True)
    try:
        ws = goldenset_sheet(wb)
        rows = ws.iter_rows(values_only=True)
        header = [str(c).strip() if c is not None else "" for c in next(rows)]
        lower = {h.lower(): i for i, h in enumerate(header)}
        if "full_text" not in lower:
            raise ValueError(f"{xlsx} GOLDENSET sheet has no full_text column ({header})")
        if "case_id" not in lower:
            raise ValueError(f"{xlsx} GOLDENSET sheet has no case_id column")

        ft_idx = lower["full_text"]
        id_idx = lower["case_id"]
        link_idx = lower.get("link")

        out_path.parent.mkdir(parents=True, exist_ok=True)
        written = skipped = 0
        seen: set[str] = set()
        with out_path.open("w", encoding="utf-8") as f:
            for i, row in enumerate(rows):
                if not any(c not in (None, "") for c in row):
                    continue
                case_id = row[id_idx]
                text = row[ft_idx]
                link = row[link_idx] if link_idx is not None and link_idx < len(row) else None
                body = _norm_ws(str(text)) if text is not None else ""
                if len(body) < min_chars:
                    skipped += 1
                    log.warning("skip row %d (case_id=%r): %d chars", i + 2, case_id, len(body))
                    continue
                slug = safe_slug(
                    str(case_id) if case_id is not None else "", str(link or ""), i
                )
                if slug in seen:
                    slug = f"{slug}_{i}"
                seen.add(slug)
                f.write(
                    json.dumps({"case_id": slug, "full_text": body}, ensure_ascii=False) + "\n"
                )
                written += 1
    finally:
        wb.close()
    return written, skipped


def main(argv: list[str] | None = None) -> int:
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    parser = argparse.ArgumentParser(description="Build full_text.jsonl from a Goldenset column.")
    parser.add_argument("--country", help="Country code; resolves the goldenset and output path.")
    parser.add_argument("--xlsx", type=Path, help="Explicit workbook path (overrides --country lookup).")
    parser.add_argument("--pdf-dir", type=Path, help="Extract from a directory of PDFs (stem = case_id).")
    parser.add_argument("--out", type=Path, help="Output JSONL (default data/<cc>/full_text.jsonl).")
    parser.add_argument("--min-chars", type=int, default=100, help="Skip rows shorter than this.")
    parser.add_argument("--force", action="store_true", help="Overwrite an existing full_text.jsonl.")
    args = parser.parse_args(argv)

    if not args.country and not args.xlsx and not args.pdf_dir:
        parser.error("provide --country, --xlsx, and/or --pdf-dir")

    out_path = args.out or (
        full_text_jsonl_path(args.country) if args.country else None
    )
    if out_path is None:
        parser.error("--out is required when --country is not given")
    if out_path.exists() and not args.force:
        log.error("%s exists; pass --force to overwrite", out_path)
        return 1

    if args.pdf_dir:
        if not args.pdf_dir.is_dir():
            log.error("pdf dir not found: %s", args.pdf_dir)
            return 2
        written, skipped = build_from_pdf_dir(args.pdf_dir, out_path, min_chars=args.min_chars)
    else:
        xlsx = args.xlsx or goldenset_path(args.country)
        if not xlsx.exists():
            log.error("workbook not found: %s", xlsx)
            return 2
        written, skipped = build_from_xlsx(xlsx, out_path, min_chars=args.min_chars)

    log.info("wrote %d rows (%d skipped) -> %s", written, skipped, out_path)
    return 0 if written else 1


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