File size: 9,614 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import json
import random
import re
import shutil
from pathlib import Path

from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet

from legex.config import settings
from legex.models.base import Case
from legex.scrapers import SCRAPERS


def raw_path(cc: str) -> Path:
    return settings.raw_dir / f"{cc}.jsonl"


def filtered_path(cc: str) -> Path:
    return settings.processed_dir / f"{cc}_filtered.jsonl"


def sampled_path(cc: str) -> Path:
    return settings.processed_dir / f"{cc}_sampled.jsonl"


# Names like:
#   Goldenset_Australia.xlsx
#   Goldenset_Hong_Kong_final.xlsx
#   Goldenset_Brazil_final (datalocation_...).xlsx
#   Georgia_Goldenset_final.xlsx
_GOLDENSET_NAME_PATTERNS = (
    re.compile(r"^Goldenset_(.+?)(?:_final.*)?\.xlsx$"),
    re.compile(r"^(.+?)_Goldenset(?:_final.*)?\.xlsx$"),
)


def _country_from_goldenset_filename(name: str) -> str | None:
    for pat in _GOLDENSET_NAME_PATTERNS:
        m = pat.match(name)
        if m:
            return m.group(1).strip()
    return None


def _existing_goldenset_files(cc: str) -> list[Path]:
    d = settings.data_dir / cc
    if not d.is_dir():
        return []
    return sorted(d.glob("*Goldenset*.xlsx"))


def _preferred_goldenset_file(cc: str) -> Path | None:
    files = _existing_goldenset_files(cc)
    finals = [f for f in files if "final" in f.stem.lower()]
    return (finals or files or [None])[0]


def _country_for(cc: str) -> str:
    """Country name used in Goldenset filenames.

    Prefers the name extracted from the same Goldenset xlsx that
    `goldenset_path` would pick, then the scraper's `country` attr, then cc.
    """
    f = _preferred_goldenset_file(cc)
    if f is not None:
        name = _country_from_goldenset_filename(f.name)
        if name:
            return name
    scraper = SCRAPERS.get(cc)
    if scraper is not None:
        return getattr(scraper, "country", cc)
    return cc


def countries_with_goldenset() -> list[str]:
    """Country codes that have a Goldenset xlsx under data/<cc>/."""
    if not settings.data_dir.is_dir():
        return []
    return sorted(
        d.name for d in settings.data_dir.iterdir() if d.is_dir() and _existing_goldenset_files(d.name)
    )


# Round-2 submission layout: JSONL gold + inference_<system>.csv per jurisdiction.
EXCLUDED_FOR_EVAL: frozenset[str] = frozenset(
    {"tw", "br", "hk", "in", "rs", "np", "be"}
)


def goldenset_jsonl_path(cc: str) -> Path:
    """Submission-style gold path: data/<cc>/goldenset_<cc>.jsonl."""
    return settings.data_dir / cc / f"goldenset_{cc}.jsonl"


def inference_csv_path(cc: str, system: str) -> Path:
    """Submission-style prediction path: data/<cc>/inference_<system>.csv.

    `system` is one of `harvey`, `gemini`, `gpt`.
    """
    return settings.data_dir / cc / f"inference_{system}.csv"


def countries_with_goldenset_jsonl() -> list[str]:
    """Country codes that have a submission-style goldenset_<cc>.jsonl on disk."""
    if not settings.data_dir.is_dir():
        return []
    return sorted(
        d.name for d in settings.data_dir.iterdir()
        if d.is_dir() and goldenset_jsonl_path(d.name).exists()
    )


def evaluable_countries() -> list[str]:
    """countries_with_goldenset_jsonl() minus the round-2 exclusion set."""
    return [cc for cc in countries_with_goldenset_jsonl() if cc not in EXCLUDED_FOR_EVAL]


def goldenset_path(cc: str) -> Path:
    f = _preferred_goldenset_file(cc)
    if f is not None:
        return f
    return settings.data_dir / cc / f"Goldenset_{_country_for(cc)}.xlsx"


def goldenset_sheet(wb) -> Worksheet:
    """Return the GOLDENSET worksheet, tolerating names like 'GOLDENSET (2)'."""
    if "GOLDENSET" in wb.sheetnames:
        return wb["GOLDENSET"]
    for name in wb.sheetnames:
        if name.upper().startswith("GOLDENSET"):
            return wb[name]
    raise ValueError(f"workbook has no GOLDENSET sheet, found {wb.sheetnames}")


def full_text_jsonl_path(cc: str) -> Path:
    """Optional per-case full_text source at data/<cc>/full_text.jsonl.

    Used as a fallback when the GOLDENSET xlsx full_text column is missing
    or empty (e.g. for jurisdictions where the text is too large for Excel
    or only available via scraping).
    """
    return settings.data_dir / cc / "full_text.jsonl"


_CASE_ID_SEP_RE = re.compile(r"[\s/\\\-._;]+")


def norm_case_id(s: str) -> str:
    """Loose case_id key for matching across sources.

    Different sources use different separators (spaces, slashes, dots, dashes,
    underscores) for the same id — e.g. xlsx `G.R. No. 266431` vs jsonl PDF
    stem `G.R._No._266431`. Collapse all of those to a single underscore and
    lowercase so the two compare equal.
    """
    return _CASE_ID_SEP_RE.sub("_", s.strip()).strip("_").lower()


def read_full_text_jsonl(cc: str) -> dict[str, str]:
    """case_id -> full_text from data/<cc>/full_text.jsonl, or {} if absent.

    Both the original case_id and its [[norm_case_id]] form are inserted as
    keys so callers can look up by either. Normalized keys never overwrite
    raw keys.
    """
    path = full_text_jsonl_path(cc)
    if not path.exists():
        return {}
    out: dict[str, str] = {}
    norm_extras: dict[str, str] = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            d = json.loads(line)
            cid = d.get("case_id")
            text = d.get("full_text")
            if cid is None or not text:
                continue
            cid_s = str(cid)
            out[cid_s] = str(text)
            norm_extras.setdefault(norm_case_id(cid_s), str(text))
    for k, v in norm_extras.items():
        out.setdefault(k, v)
    return out


def model_filename_slug(model: str) -> str:
    """litellm model id → safe filename segment (e.g. gemini/gemini-3.1-flash-lite)."""
    return model.replace("/", "_").replace("\\", "_").replace(":", "_")


def classified_csv_path(cc: str, prompt_version: str, source: str, model: str) -> Path:
    """Per-country LLM output path. `source` ∈ {"full_text", "pdf"}."""
    country = _country_for(cc)
    slug = model_filename_slug(model)
    return settings.data_dir / cc / f"Goldenset_{country}_{prompt_version}_{source}_{slug}.csv"


def pdf_paths(cc: str) -> list[Path]:
    """PDFs the README places at data/<cc>/*.pdf."""
    return sorted((settings.data_dir / cc).glob("*.pdf"))


def write_jsonl(cases: list[Case], path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        for c in cases:
            f.write(c.model_dump_json() + "\n")


def read_jsonl(path: Path) -> list[Case]:
    with open(path, encoding="utf-8") as f:
        return [Case.model_validate_json(line) for line in f if line.strip()]


def random_sample(cases: list[Case], n: int, seed: int = 0) -> list[Case]:
    if n >= len(cases):
        return list(cases)
    return random.Random(seed).sample(cases, n)


def write_goldenset_xlsx(cases: list[Case], template: Path, output: Path) -> None:
    output.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(template, output)
    wb = load_workbook(output)
    if "GOLDENSET" not in wb.sheetnames:
        raise ValueError(f"Template has no GOLDENSET sheet, found {wb.sheetnames}")
    ws = wb["GOLDENSET"]
    for i, case in enumerate(cases[:130]):
        ws.cell(row=i + 2, column=1, value=case.case_id)
        ws.cell(row=i + 2, column=2, value=case.link)
        # Column C is called full_text. Excel cell limit 32767 chars, thus we have to cut of for the labeling.
        if case.full_text:
            ws.cell(row=i + 2, column=3, value=case.full_text[:32000])
    wb.save(output)


def load_coding_rules(template: Path) -> list[tuple[str, str]]:
    wb = load_workbook(template, read_only=True, data_only=True)
    if "Variables_Coding_Rules" not in wb.sheetnames:
        raise ValueError(
            f"{template} has no Variables_Coding_Rules sheet, found {wb.sheetnames}"
        )
    ws = wb["Variables_Coding_Rules"]
    rules: list[tuple[str, str]] = []
    for row in ws.iter_rows(min_row=2, max_col=2, values_only=True):
        variable, explanation = row
        if not variable:
            continue
        rules.append((str(variable), str(explanation or "")))
    return rules


def load_goldenset_columns(template: Path) -> list[str]:
    """Header row of the GOLDENSET sheet — defines the column order."""
    wb = load_workbook(template, read_only=True, data_only=True)
    if "GOLDENSET" not in wb.sheetnames:
        raise ValueError(f"{template} has no GOLDENSET sheet, found {wb.sheetnames}")
    ws = wb["GOLDENSET"]
    header = next(ws.iter_rows(min_row=1, max_row=1, values_only=True))
    return [str(c) for c in header if c]


def load_isic_categories(template: Path) -> list[tuple[str, str, str]]:
    wb = load_workbook(template, read_only=True, data_only=True)
    if "ISIC_Level1_Categories" not in wb.sheetnames:
        raise ValueError(
            f"{template} has no ISIC_Level1_Categories sheet, found {wb.sheetnames}"
        )
    ws = wb["ISIC_Level1_Categories"]
    rows = list(ws.iter_rows(min_row=1, max_col=4, values_only=True))
    categories: list[tuple[str, str, str]] = []
    for row in rows:
        _isic_code, coded_value, category, description = row
        if not coded_value or coded_value == "Coded Value":
            continue
        categories.append((str(coded_value), str(category or ""), str(description or "")))
    return categories