File size: 3,876 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
"""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())