File size: 6,609 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
214
215
"""Ingest Harvey-AI extractions from a single xlsx into per-country CSVs.

`data/raw/harvey.xlsx` (Sheet1) holds Harvey's outputs for 23 jurisdictions
with 4 columns per question (Value / Reasoning / Citations / Comments). We
keep only the Value columns, clean them, match each row to a Goldenset
case_id via the PDF filename, and write a CSV that looks exactly like the
output of `legex.inference` — so `legex-evaluate`, `legex-analysis`, and
`legex-plots` treat Harvey as just another model.
"""

import argparse
import csv
import logging
import re
import sys
from collections import defaultdict
from pathlib import Path

from openpyxl import load_workbook

from legex.config import settings
from legex.inference import _output_columns
from legex.utils import (
    classified_csv_path,
    goldenset_path,
    goldenset_sheet,
    norm_case_id,
)

log = logging.getLogger(__name__)


HARVEY_FOLDER_TO_CC: dict[str, str] = {
    "Armenia": "am",
    "Australia": "au",
    "Belgium": "be",
    "Brazil": "br",
    "China": "cn",
    "Dominican_Republic": "do",
    "France": "fr",
    "Georgia": "ge",
    "Germany": "de",
    "Hong_Kong": "hk",
    "India": "in",
    "Nepal": "np",
    "New_Zealand": "nz",
    "Philippines": "ph",
    "Russia": "ru",
    "Schweiz_final": "ch",
    "Singapore": "sg",
    "South_Korea fixed": "kr",
    "Spain": "es",
    "Taiwan": "tw",
    "Ukraine": "ua",
    "United_Kingdom": "uk",
    "United_States": "us",
}


# Harvey Sheet1 value-column index → Goldenset header name.
HARVEY_COL_TO_GOLD: dict[int, str] = {
    7: "legal_subject_judgement",
    11: "trial_start_date",
    15: "trial_end_date",
    19: "dispute_value_nominal",
    23: "plaintiff_loosing_share",
    27: "court_cost_awarded_nominal",
    31: "party_compensation_awarded_nominal",
    35: "plaintiffs_all_count",
    39: "defendants_all_count",
    43: "plaintiff_no1_ISIC1_industry_category",
    47: "defendant_no1_ISIC1_industry_category",
}

_CITATION_RE = re.compile(r"\s*(?:\[\d+\])+\s*$")
_EMPTY_LITERALS = {"", "—"}


def _clean(value: object) -> str:
    if value is None:
        return ""
    s = str(value).strip()
    if s in _EMPTY_LITERALS:
        return ""
    s = _CITATION_RE.sub("", s).strip()
    if s.lower() == "nonpecuniary":
        return "nonpecuniary"
    return s


def _gold_case_id_index(cc: str) -> dict[str, str] | None:
    """{ norm_case_id(gold) → gold case_id } for one country, or None if no Goldenset."""
    gs = goldenset_path(cc)
    if not gs.exists():
        return None
    wb = load_workbook(gs, read_only=True, data_only=True)
    ws = goldenset_sheet(wb)
    rows = ws.iter_rows(values_only=True)
    header = [str(c) if c is not None else "" for c in next(rows)]
    try:
        cid_idx = header.index("case_id")
    except ValueError as e:
        raise ValueError(f"{gs}: GOLDENSET sheet has no case_id column") from e
    index: dict[str, str] = {}
    for row in rows:
        if not any(row):
            continue
        raw = row[cid_idx]
        if raw is None:
            continue
        gold = str(raw).strip()
        if not gold:
            continue
        index.setdefault(norm_case_id(gold), gold)
    return index


def ingest(
    xlsx: Path,
    prompt_version: str = "v3",
    source: str = "full_text",
    model: str = "harvey",
) -> None:
    columns = _output_columns()
    wb = load_workbook(xlsx, read_only=True, data_only=True)
    if "Sheet1" not in wb.sheetnames:
        raise ValueError(f"{xlsx} missing Sheet1 (found {wb.sheetnames})")
    ws = wb["Sheet1"]
    rows_iter = ws.iter_rows(values_only=True)
    next(rows_iter)  # skip header

    by_folder: dict[str, list[tuple]] = defaultdict(list)
    for row in rows_iter:
        if not row or row[0] is None:
            continue
        folder = row[1]
        if folder is None:
            continue
        by_folder[str(folder)].append(row)

    for folder, rows in by_folder.items():
        cc = HARVEY_FOLDER_TO_CC.get(folder)
        if cc is None:
            log.warning(f"unknown folder {folder!r}, skipping {len(rows)} row(s)")
            continue
        index = _gold_case_id_index(cc)
        if index is None:
            log.info(f"[{cc}] no Goldenset on disk, skipping {len(rows)} Harvey row(s)")
            continue

        out = classified_csv_path(cc, prompt_version, source, model)
        out.parent.mkdir(parents=True, exist_ok=True)

        matched = 0
        unmatched = 0
        with open(out, "w", encoding="utf-8", newline="") as f:
            writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
            writer.writeheader()
            for row in rows:
                stem = Path(str(row[0])).stem
                gold = index.get(norm_case_id(stem))
                if gold is None:
                    unmatched += 1
                    log.info(f"[{cc}] no Goldenset match for {row[0]!r}")
                    continue
                out_row = {col: "" for col in columns}
                out_row["case_id"] = gold
                out_row["model"] = model
                for harvey_idx, gold_col in HARVEY_COL_TO_GOLD.items():
                    if harvey_idx < len(row):
                        out_row[gold_col] = _clean(row[harvey_idx])
                writer.writerow(out_row)
                matched += 1
        log.info(
            f"[{cc}] wrote {matched} Harvey row(s) → {out} "
            f"({unmatched} unmatched, {len(rows)} total)"
        )


def main() -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler(sys.stderr)],
    )
    parser = argparse.ArgumentParser(
        prog="legex-harvey-ingest",
        description="Convert data/raw/harvey.xlsx into per-country Goldenset_*_harvey.csv files.",
    )
    parser.add_argument(
        "--xlsx",
        type=Path,
        default=settings.raw_dir / "harvey.xlsx",
        help="Path to harvey.xlsx (default: data/raw/harvey.xlsx).",
    )
    parser.add_argument("--prompt_version", default="v3")
    parser.add_argument(
        "--source",
        choices=("full_text", "pdf"),
        default="full_text",
        help="Source bucket label used in the CSV filename (default: full_text).",
    )
    parser.add_argument("--model", default="harvey", help="Model slug for the CSV filename.")
    args = parser.parse_args()
    ingest(
        xlsx=args.xlsx,
        prompt_version=args.prompt_version,
        source=args.source,
        model=args.model,
    )


if __name__ == "__main__":
    main()