| """LLM inference over Goldenset full_text or per-country PDFs. |
| |
| For each registered country, reads case inputs from either: |
| - the `full_text` column of `data/<cc>/Goldenset_*.xlsx`, or |
| - the PDFs at `data/<cc>/*.pdf` |
| |
| runs an LLM with the Vorlage coding rules, and appends a CSV of predictions |
| to `data/<cc>/Goldenset_{country}_{prompt_version}_{full_text|pdf}_{model}.csv`. |
| Successful rows (by case_id) are skipped; rows with a non-empty `error` |
| column are retried on the next run. |
| """ |
|
|
| import argparse |
| import asyncio |
| import csv |
| import json |
| import logging |
| import os |
| import sys |
| import threading |
| import time |
| from collections.abc import Callable |
| from datetime import date |
| from pathlib import Path |
|
|
| from dotenv import load_dotenv |
| from openpyxl import load_workbook |
|
|
| from legex.config import settings |
| from legex.models.base import Case |
| from legex.models.classification import Classification |
| from legex.prompts import PromptPlan, load_plan |
| from legex.scrapers import SCRAPERS |
| from legex.utils import ( |
| classified_csv_path, |
| countries_with_goldenset, |
| goldenset_path, |
| goldenset_sheet, |
| load_coding_rules, |
| load_goldenset_columns, |
| load_isic_categories, |
| norm_case_id, |
| pdf_paths, |
| read_full_text_jsonl, |
| ) |
|
|
| log = logging.getLogger(__name__) |
|
|
| _DATE_FIELD_KEYS: frozenset[str] = frozenset( |
| name |
| for name, info in Classification.model_fields.items() |
| if date in getattr(info.annotation, "__args__", (info.annotation,)) |
| ) |
|
|
|
|
| def _coerce_json_dates(data: dict) -> None: |
| """JSON has no date type; convert strings before pydantic validation.""" |
| for key in _DATE_FIELD_KEYS: |
| if key not in data: |
| continue |
| val = data[key] |
| if isinstance(val, str) and val: |
| data[key] = date.fromisoformat(val) |
|
|
|
|
| def _parse_classification(content: str) -> Classification: |
| """Parse LLM JSON; accept a one-element array when the model returns a list.""" |
| data = json.loads(content) |
| if isinstance(data, list): |
| if len(data) != 1 or not isinstance(data[0], dict): |
| raise ValueError("expected a JSON object or a one-element array of objects") |
| data = data[0] |
| _coerce_json_dates(data) |
| return Classification.model_validate(data) |
|
|
|
|
| class _RequestRateLimiter: |
| """Minimum spacing between LLM calls (60 / rpm seconds). None rpm = no limit.""" |
|
|
| def __init__(self, rpm: int | None) -> None: |
| self._min_interval = 60.0 / rpm if rpm else 0.0 |
| self._last_at = 0.0 |
| self._sync_lock = threading.Lock() |
| self._async_lock: asyncio.Lock | None = None |
|
|
| def acquire(self) -> None: |
| if self._min_interval <= 0: |
| return |
| with self._sync_lock: |
| now = time.monotonic() |
| wait = self._min_interval - (now - self._last_at) |
| if wait > 0: |
| time.sleep(wait) |
| self._last_at = time.monotonic() |
|
|
| async def acquire_async(self) -> None: |
| if self._min_interval <= 0: |
| return |
| if self._async_lock is None: |
| self._async_lock = asyncio.Lock() |
| async with self._async_lock: |
| now = time.monotonic() |
| wait = self._min_interval - (now - self._last_at) |
| if wait > 0: |
| await asyncio.sleep(wait) |
| self._last_at = time.monotonic() |
|
|
|
|
| def inference_output_path(cc: str, prompt_version: str, source: str, model: str) -> Path: |
| return classified_csv_path(cc, prompt_version, source, model) |
|
|
|
|
| |
| |
| |
| _FIELD_TO_COL: dict[str, str] = { |
| name: (info.alias or name) for name, info in Classification.model_fields.items() |
| } |
| _COL_TO_FIELD: dict[str, str] = {col: field for field, col in _FIELD_TO_COL.items()} |
|
|
|
|
| def _output_columns() -> list[str]: |
| headers = load_goldenset_columns(settings.template) |
| return [h for h in headers if h != "full_text"] + ["model", "error"] |
|
|
|
|
| def _read_goldenset_cases(cc: str) -> list[Case]: |
| """Pull case_id / link / full_text rows from the GOLDENSET sheet. |
| |
| Falls back to data/<cc>/full_text.jsonl (keyed by case_id) when the xlsx |
| full_text column is empty or absent, so jurisdictions whose text doesn't |
| fit in Excel can still be classified. |
| """ |
| path = goldenset_path(cc) |
| wb = load_workbook(path, 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)] |
| idx = {h.strip().lower(): i for i, h in enumerate(header) if h} |
| for required in ("case_id", "link"): |
| if required not in idx: |
| raise ValueError(f"{path} GOLDENSET sheet missing column {required!r}") |
| full_text_idx = idx.get("full_text") |
| fallback = read_full_text_jsonl(cc) |
| if full_text_idx is None and not fallback: |
| raise ValueError( |
| f"{path} GOLDENSET sheet has no full_text column and no " |
| f"data/{cc}/full_text.jsonl fallback" |
| ) |
|
|
| cases: list[Case] = [] |
| n_from_jsonl = 0 |
| for row in rows: |
| if not any(row): |
| continue |
| case_id = row[idx["case_id"]] |
| link = row[idx["link"]] |
| full_text = row[full_text_idx] if full_text_idx is not None else None |
| if not full_text and case_id is not None: |
| cid_s = str(case_id) |
| fb = fallback.get(cid_s) or fallback.get(norm_case_id(cid_s)) |
| if fb: |
| full_text = fb |
| n_from_jsonl += 1 |
| cases.append( |
| Case( |
| case_id=str(case_id) if case_id is not None else None, |
| link=str(link) if link is not None else None, |
| jurisdiction=cc, |
| full_text=str(full_text) if full_text is not None else None, |
| ) |
| ) |
| if n_from_jsonl: |
| log.info(f"[{cc}] using full_text from full_text.jsonl for {n_from_jsonl} case(s)") |
| return cases |
|
|
|
|
| def _read_pdf_cases(cc: str) -> list[Case]: |
| """One Case per PDF at data/<cc>/*.pdf; case_id = file stem.""" |
| from pypdf import PdfReader |
|
|
| cases: list[Case] = [] |
| for pdf in pdf_paths(cc): |
| try: |
| reader = PdfReader(str(pdf)) |
| text = "\n".join((page.extract_text() or "") for page in reader.pages) |
| except Exception as e: |
| log.warning(f"[{cc}] failed to read {pdf.name}: {type(e).__name__}: {e}") |
| text = "" |
| cases.append( |
| Case( |
| case_id=pdf.stem, |
| link=str(pdf), |
| jurisdiction=cc, |
| full_text=text or None, |
| ) |
| ) |
| return cases |
|
|
|
|
| def _read_cases(cc: str, source: str) -> list[Case]: |
| if source == "full_text": |
| return _read_goldenset_cases(cc) |
| return _read_pdf_cases(cc) |
|
|
|
|
| def _empty_row(case: Case, model: str, columns: list[str]) -> dict[str, str]: |
| row: dict[str, str] = {col: "" for col in columns} |
| row["case_id"] = case.case_id or "" |
| row["link"] = case.link or "" |
| row["model"] = model |
| return row |
|
|
|
|
| async def _classify_case_single( |
| case: Case, |
| system_prompt: str, |
| model: str, |
| columns: list[str], |
| limiter: _RequestRateLimiter, |
| ) -> dict[str, str]: |
| import litellm |
|
|
| row = _empty_row(case, model, columns) |
| if not case.full_text: |
| row["error"] = "no full_text" |
| return row |
|
|
| try: |
| await limiter.acquire_async() |
| resp = await litellm.acompletion( |
| model=model, |
| messages=[ |
| {"role": "system", "content": system_prompt}, |
| {"role": "user", "content": case.full_text}, |
| ], |
| response_format=Classification, |
| ) |
| content = resp["choices"][0]["message"]["content"] |
| parsed = _parse_classification(content) |
| except Exception as e: |
| row["error"] = f"{type(e).__name__}: {e}" |
| return row |
|
|
| extras = [col for col in _FIELD_TO_COL.values() if col not in row] |
| if extras: |
| row["error"] = f"Classification fields not in GOLDENSET header: {extras}" |
| return row |
| for field, col in _FIELD_TO_COL.items(): |
| value = getattr(parsed, field) |
| row[col] = "" if value is None else str(value) |
| return row |
|
|
|
|
| async def _classify_one_column( |
| column: str, |
| system_prompt: str, |
| full_text: str, |
| model: str, |
| limiter: _RequestRateLimiter, |
| ) -> tuple[str, object | None, str | None]: |
| """Return (CSV column, value, error). `column` is the CSV header name |
| (alias-aware); we read the corresponding Python attribute off the |
| parsed Classification.""" |
| import litellm |
|
|
| try: |
| await limiter.acquire_async() |
| resp = await litellm.acompletion( |
| model=model, |
| messages=[ |
| {"role": "system", "content": system_prompt}, |
| {"role": "user", "content": full_text}, |
| ], |
| response_format={"type": "json_object"}, |
| ) |
| content = resp["choices"][0]["message"]["content"] |
| parsed = _parse_classification(content) |
| field = _COL_TO_FIELD.get(column, column) |
| return column, getattr(parsed, field), None |
| except Exception as e: |
| return column, None, f"{column}: {type(e).__name__}: {e}" |
|
|
|
|
| async def _classify_case_per_column( |
| case: Case, |
| column_systems: dict[str, str], |
| model: str, |
| columns: list[str], |
| limiter: _RequestRateLimiter, |
| ) -> dict[str, str]: |
| row = _empty_row(case, model, columns) |
| if not case.full_text: |
| row["error"] = "no full_text" |
| return row |
|
|
| extras = [c for c in column_systems if c not in row] |
| if extras: |
| row["error"] = f"Per-column prompts target fields not in GOLDENSET header: {extras}" |
| return row |
|
|
| results = await asyncio.gather( |
| *( |
| _classify_one_column(col, sys_prompt, case.full_text, model, limiter) |
| for col, sys_prompt in column_systems.items() |
| ) |
| ) |
| errors: list[str] = [] |
| for col, value, err in results: |
| if err is not None: |
| errors.append(err) |
| elif value is not None: |
| row[col] = str(value) |
| if errors: |
| row["error"] = "; ".join(errors) |
| return row |
|
|
|
|
| class _CsvRowWriter: |
| """Append rows to a CSV, flushing after each write.""" |
|
|
| def __init__(self, path: Path, columns: list[str]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| write_header = not path.exists() |
| self._file = open(path, "a", encoding="utf-8", newline="") |
| self._writer = csv.DictWriter(self._file, fieldnames=columns) |
| if write_header: |
| self._writer.writeheader() |
|
|
| def write_row(self, row: dict[str, str]) -> None: |
| self._writer.writerow(row) |
| self._file.flush() |
|
|
| def close(self) -> None: |
| self._file.close() |
|
|
| def __enter__(self) -> "_CsvRowWriter": |
| return self |
|
|
| def __exit__(self, *args: object) -> None: |
| self.close() |
|
|
|
|
| def _classify_cases( |
| cases: list[Case], |
| plan: PromptPlan, |
| model: str, |
| columns: list[str], |
| limiter: _RequestRateLimiter, |
| write_row: Callable[[dict[str, str]], None], |
| concurrency: int = 1, |
| ) -> int: |
| """Classify cases and stream each result via write_row. Returns success count. |
| |
| With concurrency > 1, up to N cases are processed in parallel; the rate |
| limiter still gates total request throughput. Rows are written as each |
| case finishes, so output order is non-deterministic when concurrency > 1. |
| """ |
|
|
| async def run_all() -> int: |
| sem = asyncio.Semaphore(max(1, concurrency)) |
|
|
| async def process(case: Case) -> dict[str, str]: |
| async with sem: |
| if plan.mode == "single": |
| return await _classify_case_single( |
| case, plan.system or "", model, columns, limiter |
| ) |
| return await _classify_case_per_column( |
| case, plan.column_systems or {}, model, columns, limiter |
| ) |
|
|
| ok = 0 |
| for coro in asyncio.as_completed([process(c) for c in cases]): |
| row = await coro |
| write_row(row) |
| if not row["error"]: |
| ok += 1 |
| return ok |
|
|
| return asyncio.run(run_all()) |
|
|
|
|
| def _successful_case_ids(path: Path) -> set[str]: |
| if not path.exists(): |
| return set() |
| ids: set[str] = set() |
| with open(path, encoding="utf-8", newline="") as f: |
| for r in csv.DictReader(f): |
| if (r.get("error") or "").strip(): |
| continue |
| cid = (r.get("case_id") or "").strip() |
| if cid: |
| ids.add(cid) |
| return ids |
|
|
|
|
| def _drop_case_ids(path: Path, columns: list[str], case_ids: set[str]) -> int: |
| """Remove rows for the given case_ids. Returns number of rows removed.""" |
| if not path.exists() or not case_ids: |
| return 0 |
| with open(path, encoding="utf-8", newline="") as f: |
| rows = list(csv.DictReader(f)) |
| kept = [r for r in rows if (r.get("case_id") or "").strip() not in case_ids] |
| removed = len(rows) - len(kept) |
| if removed == 0: |
| return 0 |
| with open(path, "w", encoding="utf-8", newline="") as f: |
| writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore") |
| writer.writeheader() |
| writer.writerows(kept) |
| return removed |
|
|
|
|
| def classify( |
| countries: list[str] | None, |
| model: str, |
| source: str, |
| prompt_version: str, |
| limit: int | None, |
| rpm: int | None = None, |
| concurrency: int = 1, |
| ) -> None: |
| rules = load_coding_rules(settings.template) |
| isic = load_isic_categories(settings.template) |
| columns = _output_columns() |
| plan = load_plan(prompt_version, rules, isic) |
| limiter = _RequestRateLimiter(rpm) |
| if rpm: |
| log.info(f"Rate limit: {rpm} requests/min ({limiter._min_interval:.2f}s between calls)") |
| if concurrency > 1: |
| log.info(f"Concurrency: up to {concurrency} cases in parallel") |
|
|
| targets = countries or countries_with_goldenset() or list(SCRAPERS) |
| for cc in targets: |
| if source == "full_text": |
| gs = goldenset_path(cc) |
| if not gs.exists(): |
| log.warning(f"[{cc}] missing {gs}, skipping") |
| continue |
| else: |
| if not pdf_paths(cc): |
| log.warning(f"[{cc}] no PDFs at {settings.data_dir / cc}/*.pdf, skipping") |
| continue |
|
|
| cases = _read_cases(cc, source) |
| if not cases: |
| log.info(f"[{cc}] no cases found, skipping") |
| continue |
|
|
| out = inference_output_path(cc, prompt_version, source, model) |
| done = _successful_case_ids(out) |
| todo = [c for c in cases if (c.case_id or "") not in done] |
| if limit is not None: |
| todo = todo[:limit] |
| if not todo: |
| log.info(f"[{cc}] all {len(cases)} cases already classified in {out}, skipping") |
| continue |
|
|
| retry_ids = {c.case_id for c in todo if c.case_id} |
| n_removed = _drop_case_ids(out, columns, retry_ids) |
| n_new = len(todo) - n_removed |
| if n_removed: |
| log.info(f"[{cc}] retrying {n_removed} failed case(s), {n_new} new") |
|
|
| log.info( |
| f"[{cc}] classifying {len(todo)} cases ({len(done)} already done) " |
| f"in {plan.mode} mode → {out}" |
| ) |
| with _CsvRowWriter(out, columns) as writer: |
| n_ok = _classify_cases( |
| todo, plan, model, columns, limiter, writer.write_row, concurrency |
| ) |
| log.info(f"[{cc}] classified {n_ok}/{len(todo)} → {out}") |
|
|
|
|
| def main() -> None: |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(message)s", |
| handlers=[logging.StreamHandler(sys.stderr)], |
| ) |
| load_dotenv(override=True) |
| print(f"gemini key {os.environ.get('GEMINI_API_KEY')}") |
|
|
| parser = argparse.ArgumentParser( |
| prog="legex-classify", |
| description="Run LLM inference over Goldenset full_text or per-country PDFs.", |
| ) |
| parser.add_argument( |
| "--country", |
| action="extend", |
| nargs="+", |
| dest="countries", |
| help="Country code (repeatable). Defaults to all registered scrapers.", |
| ) |
| parser.add_argument( |
| "--model", |
| default="gpt-4o-mini", |
| help="litellm model id (e.g. gpt-4o-mini, anthropic/claude-opus-4-7).", |
| ) |
| parser.add_argument( |
| "--prompt_version", |
| default="v1", |
| help="Prompt version under legex/prompts/ (default: v1).", |
| ) |
| parser.add_argument( |
| "--limit", |
| type=int, |
| default=None, |
| help="Cap NEW cases per country (useful for cheap dry runs).", |
| ) |
| parser.add_argument( |
| "--rpm", |
| type=int, |
| default=None, |
| metavar="N", |
| help="Max LLM requests per minute (applies to every completion call).", |
| ) |
| parser.add_argument( |
| "--concurrency", |
| type=int, |
| default=1, |
| metavar="N", |
| help="Process up to N cases in parallel (default: 1).", |
| ) |
| source = parser.add_mutually_exclusive_group(required=True) |
| source.add_argument( |
| "--full_text", |
| dest="source", |
| action="store_const", |
| const="full_text", |
| help="Read input from the full_text column of data/<cc>/Goldenset_*.xlsx.", |
| ) |
| source.add_argument( |
| "--pdf", |
| dest="source", |
| action="store_const", |
| const="pdf", |
| help="Read input from data/<cc>/*.pdf.", |
| ) |
| args = parser.parse_args() |
| if args.rpm is not None and args.rpm <= 0: |
| parser.error("--rpm must be a positive integer") |
| if args.concurrency <= 0: |
| parser.error("--concurrency must be a positive integer") |
|
|
| classify( |
| countries=args.countries, |
| model=args.model, |
| source=args.source, |
| prompt_version=args.prompt_version, |
| limit=args.limit, |
| rpm=args.rpm, |
| concurrency=args.concurrency, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|