Spaces:
Sleeping
Sleeping
Download src/coveragecheck/evals/questions.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/evals/questions.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/evals/questions.py
-
curl -L -o questions.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/evals/questions.py
10.6 kB
| """Step 4a: the eval question set (evals/questions.jsonl): schema, loader, validation. | |
| uv run python -m coveragecheck.evals.questions [path] | |
| The gold set is written by hand (owner). This module never edits it: the schema | |
| rejects malformed lines with the line number, and check_questions() returns readable | |
| problems for the owner to fix. Two layers on purpose: a schema error means the file | |
| cannot be used at all; a content problem (an unknown section, a wrong n_docs) still | |
| lets the harness run on a partial draft while it is being written. | |
| """ | |
| import json | |
| import sys | |
| from collections import Counter | |
| from dataclasses import dataclass | |
| from datetime import date | |
| from pathlib import Path | |
| from typing import Annotated, Literal | |
| import pandas as pd | |
| from pydantic import BaseModel, ConfigDict, Field, StringConstraints | |
| from coveragecheck import config | |
| from coveragecheck.index.hybrid import Doc, documents, families, version_filter | |
| # Non-empty, no leading or trailing whitespace: " Q001" would escape the duplicate-id | |
| # check and "" would be a question nobody can grade (4a audit). Rejected, not stripped: | |
| # the code never changes what the owner wrote. | |
| Text = Annotated[str, StringConstraints(pattern=r"^\S(?s:.*\S)?$")] | |
| class Evidence(BaseModel): | |
| """A verbatim quote proving the gold answer (for the reviewer, not the systems).""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| source: Text | |
| quote: Text | |
| class Review(BaseModel): | |
| """Notes for the human grader (never shown to a system). Optional: the owner's own | |
| questions may leave it out. key_points are what grade.py shows next to the gold.""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| key_points: list[Text] = [] | |
| evidence: list[Evidence] = [] | |
| why_hard: str | None = None | |
| unanswerable_type: str | None = None | |
| traps: str | None = None | |
| class Question(BaseModel): | |
| """One gold question, exactly SPEC Step 4's fields. extra="forbid": a misspelt key | |
| (e.g. "gold_source") fails loudly instead of silently becoming an empty default.""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| id: Text | |
| question: Text | |
| policy_effective_date: date | None | |
| answerable: bool | |
| gold_answer: Text | |
| gold_sources: list[Text] | |
| n_docs: Annotated[int, Field(ge=0)] | |
| cost_class: Literal["high", "low"] | |
| category: Literal["single", "multi", "date", "unanswerable"] | |
| review: Review | None = None | |
| def expected(self) -> frozenset[str]: | |
| """The gold sources in the form hits.first_hit takes.""" | |
| return frozenset(self.gold_sources) | |
| def search_day(self, today: date) -> date: | |
| """The date the retriever filters versions by: the policy date, else today. The | |
| validator and run.py both use this, so gold and retrieval never disagree.""" | |
| return self.policy_effective_date or today | |
| def no_duplicate_keys(pairs: list[tuple[str, object]]) -> dict[str, object]: | |
| """json.loads hook: a key written twice raises, instead of the last one silently | |
| winning (a copy-pasted line with a second "id" would otherwise pass).""" | |
| keys = [k for k, _ in pairs] | |
| repeated = sorted({k for k in keys if keys.count(k) > 1}) | |
| if repeated: | |
| raise ValueError(f"key(s) written twice: {repeated}") | |
| return dict(pairs) | |
| def load_questions(path: Path = config.QUESTIONS_PATH) -> list[Question]: | |
| """One Question per non-blank JSONL line. A bad line raises ValueError naming the | |
| file, the line number and the field, so the owner can find it at once. | |
| utf-8-sig: Windows editors may start the file with a BOM. split("\\n"), not | |
| splitlines(): splitlines also breaks on characters like U+2028 that can sit inside a | |
| pasted JSON string. strict=True: no coercion, so "yes" or "1" is not a bool and | |
| "2" is not an int (JSON mode still reads "2026-08-01" as a date, but not a datetime). | |
| """ | |
| out = [] | |
| lines = path.read_text(encoding="utf-8-sig").split("\n") | |
| for number, line in enumerate(lines, start=1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| json.loads(line, object_pairs_hook=no_duplicate_keys) | |
| out.append(Question.model_validate_json(line, strict=True)) | |
| except ValueError as error: # JSONDecodeError and ValidationError are ValueErrors | |
| raise ValueError(f"{path}:{number}: {error}") from error | |
| return out | |
| def doc_of(source_id: str) -> str: | |
| """The document part of a gold source: "OAP1-2026#6.2" -> "OAP1-2026".""" | |
| return source_id.split("#", 1)[0] | |
| def shape_problems(q: Question) -> list[str]: | |
| """Rules about one question alone: answerability matches category and sources, | |
| date questions carry a date, 'single' means one source and 'multi' at least two | |
| (owner, 4a; otherwise "accuracy by category" would mix the two), n_docs counts the | |
| distinct gold documents, no source is listed twice.""" | |
| out = [] | |
| if q.answerable == (q.category == "unanswerable"): | |
| out.append("answerable must be false exactly when category is 'unanswerable'") | |
| if q.answerable and not q.gold_sources: | |
| out.append("answerable but no gold_sources") | |
| if not q.answerable and q.gold_sources: | |
| out.append("unanswerable but has gold_sources") | |
| if q.category == "date" and q.policy_effective_date is None: | |
| out.append("category 'date' needs a policy_effective_date") | |
| if q.category == "single" and len(q.gold_sources) != 1: | |
| out.append("category 'single' needs exactly 1 gold source") | |
| if q.category == "multi" and len(q.gold_sources) < 2: | |
| out.append("category 'multi' needs at least 2 gold sources") | |
| n_docs = len({doc_of(s) for s in q.gold_sources}) | |
| if q.n_docs != n_docs: | |
| out.append(f"n_docs is {q.n_docs} but gold_sources span {n_docs} document(s)") | |
| if len(set(q.gold_sources)) != len(q.gold_sources): | |
| out.append("a gold source is listed twice") | |
| return out | |
| class SectionFacts: | |
| """What the source rules need from sections.parquet, computed once per check.""" | |
| known: frozenset[str] # every source_id | |
| sectioned: frozenset[str] # doc_ids that have at least one section | |
| docs: list[Doc] | |
| family: dict[str, str] | |
| def from_sections(cls, sections: pd.DataFrame) -> "SectionFacts": | |
| docs = documents(sections) | |
| sectioned = sections.loc[sections.parent_source_id.notna(), "doc_id"] | |
| return cls(frozenset(sections.source_id), frozenset(sectioned), docs, families(docs)) | |
| def source_problems(q: Question, facts: SectionFacts, today: date) -> list[str]: | |
| """Rules against the corpus: each gold source is a real section; a bare doc_id only | |
| for a document without sections (a bare doc_id is hit by ANY chunk of the document, | |
| so it would make recall trivially high); each source's document is the version | |
| the retriever allows on the question's date (no date -> today, as in search); and | |
| every review evidence source exists (the grader reads those quotes).""" | |
| day = q.search_day(today) | |
| allowed, flagged = version_filter(facts.docs, facts.family, day) | |
| out = [] | |
| evidence = {e.source for e in q.review.evidence} if q.review else set() | |
| out += [f"unknown evidence source {s}" for s in sorted(evidence) if s not in facts.known] | |
| for source in q.gold_sources: | |
| if source not in facts.known: | |
| out.append(f"unknown gold source {source}") | |
| continue | |
| doc = doc_of(source) | |
| if source == doc and doc in facts.sectioned: | |
| out.append(f"bare doc_id {source} for a document with sections: cite the section") | |
| if doc not in allowed: | |
| out.append(f"{source}: not in force on {day}; cite the version that is") | |
| elif doc in flagged: | |
| out.append(f"{source}: not in force on {day} (no other version in the corpus)") | |
| return out | |
| def set_problems( | |
| questions: list[Question], targets: dict[str, int] | None = None, min_total: int = 0 | |
| ) -> list[str]: | |
| """Rules about the whole file: unique ids, and the category counts the owner set | |
| (config.QUESTION_TARGETS by default; {} for none) or, for the held-out set, a | |
| minimum number of questions (its review may drop some).""" | |
| targets = config.QUESTION_TARGETS if targets is None else targets | |
| out = [] | |
| ids = Counter(q.id for q in questions) | |
| out += [f"id {i} is used {n} times" for i, n in sorted(ids.items()) if n > 1] | |
| if len(questions) < min_total: | |
| out.append(f"{len(questions)} questions, at least {min_total} required") | |
| counts = Counter(q.category for q in questions) | |
| for category, want in targets.items(): | |
| if counts[category] != want: | |
| out.append(f"category {category}: {counts[category]} questions, target {want}") | |
| return out | |
| def check_questions( | |
| questions: list[Question], | |
| sections: pd.DataFrame, | |
| today: date | None = None, | |
| targets: dict[str, int] | None = None, | |
| min_total: int = 0, | |
| ) -> list[str]: | |
| """Every problem in the set, as "<id>: <problem>" lines (set-level ones unprefixed). | |
| Reports only; never changes a question.""" | |
| today = today or date.today() | |
| facts = SectionFacts.from_sections(sections) | |
| out = set_problems(questions, targets, min_total) | |
| for q in questions: | |
| for problem in shape_problems(q) + source_problems(q, facts, today): | |
| out.append(f"{q.id}: {problem}") | |
| return out | |
| def main() -> None: | |
| """Exit codes: 0 no problems, 1 content problems (listed), 2 the file is unusable | |
| (missing, or a line breaks the schema).""" | |
| from coveragecheck.index.store import load_table | |
| path = Path(sys.argv[1]) if len(sys.argv) > 1 else config.QUESTIONS_PATH | |
| try: | |
| questions = load_questions(path) | |
| except (OSError, ValueError) as error: | |
| print(f"cannot use {path}: {error}") | |
| sys.exit(2) | |
| counts = Counter((q.category, q.cost_class) for q in questions) | |
| print(f"{len(questions)} questions in {path}") | |
| for (category, cost), n in sorted(counts.items()): | |
| print(f" {category:13} {cost:5} {n:>3}") | |
| # the held-out file has a floor, not the draft set's exact category targets | |
| heldout = path.name == config.HELDOUT_PATH.name | |
| problems = check_questions( | |
| questions, | |
| load_table(config.INDEX_DIR / "sections.parquet"), | |
| targets={} if heldout else None, | |
| min_total=config.HELDOUT_MIN_QUESTIONS if heldout else 0, | |
| ) | |
| print("\n".join(problems) if problems else "no problems") | |
| sys.exit(1 if problems else 0) | |
| if __name__ == "__main__": | |
| main() | |