File size: 7,140 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python3
"""Convert handcrafted Goldenset XLSX files to anonymised JSONL.

For each ``Goldenset_*_final*.xlsx`` workbook under ``<data-dir>/<cc>/`` the
GOLDENSET sheet is read, rows that the expert annotator did not fully
classify are dropped (criterion: ``legal_subject_judgement`` must be
populated, which the annotators used as the marker that a row has been
substantively reviewed), and the remaining rows are written to
``<out-dir>/<cc>/goldenset_<cc>.jsonl`` as one JSON object per line.

Each output record contains the case identifiers (``case_id``, ``link``,
``full_text``) followed by the 14 schema fields defined in
``legex/models/classification.py``. ``full_text`` falls back to
``<data-dir>/<cc>/full_text.jsonl`` when the XLSX cell is empty, mirroring the
behaviour of ``legex.inference._read_goldenset_cases``.

Usage
-----
    python convert_goldenset_to_jsonl.py \
        --data-dir ../data \
        --out-dir ./data

Without arguments the script assumes ``./data`` for both inputs and outputs and
processes the 19 jurisdictions of the paper.
"""

from __future__ import annotations

import argparse
import json
import sys
from datetime import date, datetime
from pathlib import Path
from typing import Any, Iterable

from openpyxl import load_workbook

JURISDICTIONS = (
    "am", "au", "be", "br", "ch", "de", "es", "fr", "ge", "hk",
    "in", "np", "nz", "ph", "rs", "sg", "tw", "uk", "us",
)

SCHEMA_FIELDS = (
    "legal_subject_judgement",
    "trial_start_date",
    "trial_end_date",
    "dispute_value_nominal",
    "Currency_dispute_value_nominal",
    "plaintiff_loosing_share",
    "court_cost_awarded_nominal",
    "Currency_court_cost_awarded_nominal",
    "party_compensation_awarded_nominal",
    "Currency_party_compensation_awarded_nominal",
    "plaintiffs_all_count",
    "defendants_all_count",
    "plaintiff_no1_ISIC1_industry_category",
    "defendant_no1_ISIC1_industry_category",
)

EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})


def normalise(value: Any) -> Any:
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.date().isoformat()
    if isinstance(value, date):
        return value.isoformat()
    if isinstance(value, float):
        if value != value:  # NaN
            return None
        if value.is_integer():
            return int(value)
        return value
    if isinstance(value, int):
        return value
    s = str(value).strip()
    if s.lower() in EMPTY_LITERALS:
        return None
    return s


def find_goldenset_xlsx(data_dir: Path, cc: str) -> Path | None:
    """Return the *_final*.xlsx workbook for a jurisdiction, if any."""
    jurisdiction_dir = data_dir / cc
    if not jurisdiction_dir.exists():
        return None
    matches = sorted(jurisdiction_dir.glob("*_final*.xlsx"))
    if not matches:
        matches = sorted(jurisdiction_dir.glob("*Goldenset*.xlsx"))
    return matches[0] if matches else None


def find_goldenset_sheet(workbook):
    for name in workbook.sheetnames:
        if name.upper().startswith("GOLDENSET"):
            return workbook[name]
    raise ValueError(f"No GOLDENSET sheet in {workbook.sheetnames}")


def load_full_text_fallback(data_dir: Path, cc: str) -> dict[str, str]:
    path = data_dir / cc / "full_text.jsonl"
    if not path.exists():
        return {}
    fallback: dict[str, str] = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        if not line.strip():
            continue
        record = json.loads(line)
        case_id = record.get("case_id") or record.get("id")
        text = record.get("full_text") or record.get("text")
        if case_id and text:
            fallback[str(case_id)] = str(text)
    return fallback


def convert_workbook(xlsx_path: Path, fallback: dict[str, str]) -> list[dict[str, Any]]:
    wb = load_workbook(xlsx_path, read_only=True, data_only=True)
    ws = find_goldenset_sheet(wb)

    row_iter: Iterable[tuple] = ws.iter_rows(values_only=True)
    header = [str(c) if c is not None else "" for c in next(row_iter)]
    if "case_id" not in header:
        raise ValueError(f"{xlsx_path} GOLDENSET sheet missing case_id column")

    records: list[dict[str, Any]] = []
    for row in row_iter:
        if not any(row):
            continue
        cells = dict(zip(header, row))
        case_id = normalise(cells.get("case_id"))
        if not case_id:
            continue
        labels = {field: normalise(cells.get(field)) for field in SCHEMA_FIELDS}
        if labels["legal_subject_judgement"] is None:
            continue
        full_text = normalise(cells.get("full_text"))
        if not full_text:
            full_text = fallback.get(str(case_id))
        record: dict[str, Any] = {
            "case_id": str(case_id),
            "link": normalise(cells.get("link")),
            "full_text": full_text,
        }
        record.update(labels)
        records.append(record)
    return records


def write_jsonl(records: list[dict[str, Any]], out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", encoding="utf-8") as f:
        for record in records:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument(
        "--data-dir",
        type=Path,
        default=Path("data"),
        help="Directory containing <cc>/Goldenset_*_final*.xlsx workbooks.",
    )
    parser.add_argument(
        "--out-dir",
        type=Path,
        default=Path("data"),
        help="Directory to write goldenset_<cc>.jsonl files into (per jurisdiction).",
    )
    parser.add_argument(
        "--jurisdictions",
        nargs="+",
        default=list(JURISDICTIONS),
        help="ISO codes to process (default: the 19 jurisdictions of the paper).",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Report counts without writing JSONL files.",
    )
    args = parser.parse_args(argv)

    data_dir: Path = args.data_dir.resolve()
    out_dir: Path = args.out_dir.resolve()

    total = 0
    missing: list[str] = []
    for cc in args.jurisdictions:
        xlsx = find_goldenset_xlsx(data_dir, cc)
        if xlsx is None:
            missing.append(cc)
            print(f"[{cc}] no Goldenset XLSX found in {data_dir / cc}", file=sys.stderr)
            continue
        fallback = load_full_text_fallback(data_dir, cc)
        records = convert_workbook(xlsx, fallback)
        out_path = out_dir / cc / f"goldenset_{cc}.jsonl"
        if not args.dry_run:
            write_jsonl(records, out_path)
        print(f"[{cc}] {xlsx.name} -> {out_path.relative_to(out_dir.parent)}: {len(records)} rows")
        total += len(records)

    print(f"\nTotal: {total} rows across {len(args.jurisdictions) - len(missing)} jurisdictions.")
    if missing:
        print(f"Missing XLSX for: {', '.join(missing)}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())