| """Extract full text from goldenset PDFs in data/raw/drive-download-*/<Country>/. |
| |
| Writes data/<cc>/full_text.jsonl with fields: case_id, full_text. |
| Text is whitespace-normalized (no newlines, runs of whitespace collapsed to one space). |
| |
| Usage: |
| uv run python -m legex.extract_raw_text |
| uv run python -m legex.extract_raw_text --country kr |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import logging |
| import re |
| import sys |
| from pathlib import Path |
|
|
| from pypdf import PdfReader |
|
|
| log = logging.getLogger("legex.extract_raw_text") |
|
|
| REPO_ROOT = Path(__file__).resolve().parent.parent |
| RAW_DIR = REPO_ROOT / "data" / "raw" |
| DATA_DIR = REPO_ROOT / "data" |
|
|
| FOLDER_TO_CC: dict[str, str] = { |
| "Armenia": "am", |
| "Belgium": "be", |
| "China": "cn", |
| "Dominican_Republic": "do", |
| "Georgia": "ge", |
| "Hong_Kong": "hk", |
| "India": "in", |
| "Nepal": "np", |
| "New_Zealand": "nz", |
| "Philippines": "ph", |
| "Russia": "ru", |
| "Singapore": "sg", |
| "South_Korea fixed": "kr", |
| "South_Korea": "kr", |
| "Spain": "es", |
| "Taiwan": "tw", |
| "Ukraine": "ua", |
| "United_States": "us", |
| } |
|
|
|
|
| _WS_RE = re.compile(r"\s+") |
|
|
|
|
| def normalize_ws(text: str) -> str: |
| return _WS_RE.sub(" ", text).strip() |
|
|
|
|
| def extract_pdf_text(pdf: Path) -> str: |
| try: |
| reader = PdfReader(str(pdf)) |
| text = " ".join((page.extract_text() or "") for page in reader.pages) |
| except Exception as e: |
| log.warning(f"failed to read {pdf}: {type(e).__name__}: {e}") |
| return "" |
| return normalize_ws(text) |
|
|
|
|
| def find_country_folders() -> dict[str, list[Path]]: |
| """Map country code -> list of PDFs found across all drive-download-* folders.""" |
| by_cc: dict[str, list[Path]] = {} |
| unknown: list[str] = [] |
| for drive_dir in sorted(RAW_DIR.glob("drive-download-*")): |
| if not drive_dir.is_dir(): |
| continue |
| for sub in sorted(drive_dir.iterdir()): |
| if not sub.is_dir(): |
| continue |
| cc = FOLDER_TO_CC.get(sub.name) |
| if cc is None: |
| unknown.append(str(sub)) |
| continue |
| pdfs = sorted(sub.glob("*.pdf")) |
| by_cc.setdefault(cc, []).extend(pdfs) |
| if unknown: |
| log.warning("unmapped folders (skipped): %s", ", ".join(unknown)) |
| return by_cc |
|
|
|
|
| def write_jsonl(cc: str, pdfs: list[Path]) -> Path: |
| out_dir = DATA_DIR / cc |
| out_dir.mkdir(parents=True, exist_ok=True) |
| out_path = out_dir / "full_text.jsonl" |
| with out_path.open("w", encoding="utf-8") as f: |
| for pdf in pdfs: |
| text = extract_pdf_text(pdf) |
| f.write(json.dumps({"case_id": pdf.stem, "full_text": text}, ensure_ascii=False)) |
| f.write("\n") |
| return out_path |
|
|
|
|
| def main() -> int: |
| logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") |
| ap = argparse.ArgumentParser(description=__doc__) |
| ap.add_argument( |
| "--country", |
| "-c", |
| action="append", |
| help="Only process the given country code (repeatable). Default: all.", |
| ) |
| args = ap.parse_args() |
|
|
| if not RAW_DIR.exists(): |
| log.error("raw dir not found: %s", RAW_DIR) |
| return 1 |
|
|
| by_cc = find_country_folders() |
| if args.country: |
| wanted = {c.lower() for c in args.country} |
| by_cc = {cc: pdfs for cc, pdfs in by_cc.items() if cc in wanted} |
| missing = wanted - set(by_cc) |
| if missing: |
| log.error("no PDFs found for: %s", ", ".join(sorted(missing))) |
| return 1 |
|
|
| if not by_cc: |
| log.error("no country folders matched") |
| return 1 |
|
|
| for cc in sorted(by_cc): |
| pdfs = by_cc[cc] |
| log.info("[%s] extracting %d PDFs", cc, len(pdfs)) |
| out = write_jsonl(cc, pdfs) |
| log.info("[%s] wrote %s", cc, out) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|