| 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" |
|
|
|
|
| |
| |
| |
| |
| |
| _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) |
| ) |
|
|
|
|
| |
| 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) |
| |
| 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 |
|
|