code / legex /fulltext /build_full_text.py
anonymous
[code] Reproduction bundle.
2e511b5
Raw
History Blame Contribute Delete
6.43 kB
"""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())