| |
| """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: |
| 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()) |
|
|