Coverage for rdgai/evaluate.py: 95.89%
292 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
1"""
2Evaluating the pipeline against the human labels of the sample's test units.
4The evaluation runs on a stripped working copy: the test units' labels and suggestions (including their rule
5labels, which are written again) are removed before the pipeline runs, so nothing about them can reach the model. The pipeline
6drafts the test units, its predictions are recorded, the review rounds run and the predictions are recorded again,
7and both are compared with the gold labels in the original file, which is never modified.
8"""
9import json
10import random
11import shutil
12from pathlib import Path
14import yaml
16from pydantic import BaseModel, Field
18from .annotation import AnnotationStore, AnnotationError
19from .search import verse_label
20from .tei import find_elements
21from .apparatus import unique, prune_empty_list
23SMALL_SUPPORT = 10
26# ---------------------------------------------------------------------------
27# metrics
28# ---------------------------------------------------------------------------
30class CategoryScore(BaseModel):
31 category: str
32 support: int = Field(description="Gold test pairs with this category.")
33 predicted: int
34 precision: float
35 recall: float
36 f1: float
37 indicative: bool = Field(description="Fewer than 10 test pairs: indicative only.")
40class Confusion(BaseModel):
41 labels: list[str]
42 matrix: list[list[int]] = Field(description="Rows: gold; columns: predicted.")
45class Metrics(BaseModel):
46 n: int
47 correct: int
48 missing: int = Field(description="Gold pairs the pipeline did not label.")
49 accuracy: float
50 macro_precision: float
51 macro_recall: float
52 macro_f1: float
53 per_category: list[CategoryScore]
54 confusion: Confusion
55 unit_accuracy: float = Field(default=0.0, description="The average over units of each unit's accuracy (every unit counts equally).")
56 accuracy_by_gold_cert: dict[str, float] = Field(default_factory=dict, description="Accuracy on the gold pairs of each certainty (high / medium / low / none).")
57 gold_cert_counts: dict[str, int] = Field(default_factory=dict)
60def metrics(gold:dict, predicted:dict, categories:list[str], gold_certs:dict|None=None) -> Metrics:
61 """
62 Accuracy (pair-weighted and unit-weighted), accuracy by the gold label's certainty, macro and per-category
63 precision/recall/F1 and the confusion matrix over the gold pairs. Keys are (unit_id, first, second).
64 """
65 keys = list(gold)
66 by_unit = {}
67 for key in keys:
68 by_unit.setdefault(key[0] if isinstance(key, tuple) else key, []).append(predicted.get(key) == gold[key])
69 by_cert = {}
70 for key in keys:
71 by_cert.setdefault((gold_certs or {}).get(key) or "none", []).append(predicted.get(key) == gold[key])
72 correct = sum(predicted.get(key) == gold[key] for key in keys)
73 used = [category for category in categories if any(gold[key] == category or predicted.get(key) == category for key in keys)]
74 rows = []
75 for category in used:
76 support = sum(gold[key] == category for key in keys)
77 guessed = sum(predicted.get(key) == category for key in keys)
78 hits = sum(gold[key] == category and predicted.get(key) == category for key in keys)
79 precision = hits / guessed if guessed else 0.0
80 recall = hits / support if support else 0.0
81 f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
82 rows.append(CategoryScore(category=category, support=support, predicted=guessed, precision=precision, recall=recall,
83 f1=f1, indicative=support < SMALL_SUPPORT))
84 scored = [row for row in rows if row.support]
85 labels = used
86 matrix = [[sum(gold[key] == actual and predicted.get(key) == guess for key in keys) for guess in labels] for actual in labels]
87 count = len(scored) or 1
88 return Metrics(
89 n=len(keys), correct=correct, missing=sum(key not in predicted for key in keys),
90 accuracy=correct / len(keys) if keys else 0.0,
91 macro_precision=sum(row.precision for row in scored) / count,
92 macro_recall=sum(row.recall for row in scored) / count,
93 macro_f1=sum(row.f1 for row in scored) / count,
94 per_category=rows, confusion=Confusion(labels=labels, matrix=matrix),
95 unit_accuracy=sum(sum(hits) / len(hits) for hits in by_unit.values()) / len(by_unit) if by_unit else 0.0,
96 accuracy_by_gold_cert={cert: sum(hits) / len(hits) for cert, hits in by_cert.items()} if gold_certs is not None else {},
97 gold_cert_counts={cert: len(hits) for cert, hits in by_cert.items()} if gold_certs is not None else {},
98 )
101# ---------------------------------------------------------------------------
102# gold labels, predictions and the stripped copy
103# ---------------------------------------------------------------------------
105def labels_in_display_direction(store:AnnotationStore, unit_ids:list[str], sources:tuple[str, ...]) -> dict:
106 """ {(unit_id, first, second): category} for the work pairs labelled by these sources, in display direction. """
107 result = {}
108 for unit_id in unit_ids:
109 app = store.get_app(unit_id)
110 work = {frozenset((pair.active.n, pair.passive.n)) for pair in store.work_pairs(app)}
111 for pair in store.ordered_pairs(app):
112 if frozenset((pair.active.n, pair.passive.n)) not in work:
113 continue
114 for directed, inverse in ((pair, False), (pair.get_inverse(), True)):
115 if directed.relation_element() is not None and store.label_source(directed) in sources:
116 category = store.current_category(directed)
117 if inverse:
118 category = store.get_relation_type(category).get_inverse().name
119 result[(unit_id, pair.active.n, pair.passive.n)] = category
120 break
121 return result
124def gold_labels(store:AnnotationStore, unit_ids:list[str]) -> dict:
125 return labels_in_display_direction(store, unit_ids, ("human",))
128def certainties(store:AnnotationStore, keys, sources:tuple[str, ...]) -> dict:
129 """ {(unit_id, first, second): @cert} of the labels by these sources on the given pairs (either direction). """
130 result = {}
131 for unit_id, first, second in keys:
132 pair = store.get_pair(store.get_app(unit_id), first, second)
133 for directed in (pair, pair.get_inverse()):
134 relation = directed.relation_element()
135 if relation is not None and store.label_source(directed) in sources:
136 result[(unit_id, first, second)] = store.provenance_from_relation(relation).cert or None
137 break
138 return result
141def predictions(store:AnnotationStore, unit_ids:list[str]) -> dict:
142 return labels_in_display_direction(store, unit_ids, ("pipeline",))
145def strip_test_units(source:Path, working:Path) -> Path:
146 """
147 Copies the file (and its sample) and removes every label and suggestion in the sample's test units, so the
148 pipeline cannot see them. Returns the path of the copy.
149 """
150 original = AnnotationStore(Path(source), read_only=True)
151 sample = original.load_sample()
152 if sample is None:
153 raise AnnotationError(f"Evaluation needs a sample of example and test units ({original.sample_path.name} not found).")
154 return strip_units(source, working, held_out=sample.ids("test"), hidden=[])
157def strip_units(source:Path, working:Path, held_out:list[str], hidden:list[str]) -> Path:
158 """
159 Copies the file and removes every label and suggestion in the held-out units (to be predicted and scored) and the
160 hidden units (never predicted, never visible). In the copy's sample both are test units, so every safeguard for
161 test units covers them; the other sampled units are examples. Returns the path of the copy.
162 """
163 source, working = Path(source), Path(working)
164 original = AnnotationStore(source, read_only=True)
165 sample = original.load_sample()
166 if sample is None:
167 raise AnnotationError(f"Evaluation needs a sample of example and test units ({original.sample_path.name} not found).")
168 stripped = set(held_out) | set(hidden)
169 working.parent.mkdir(parents=True, exist_ok=True)
170 shutil.copy(source, working)
171 from .sampling import save_sample, SampleUnit
172 copy = sample.model_copy(update={"units": [
173 SampleUnit(id=unit.id, role="test" if unit.id in stripped else "example") for unit in sample.units
174 ]})
175 save_sample(copy, working.with_name(f"{working.stem}.sample.yaml"))
176 store = AnnotationStore(working, annotator="evaluation", ignore_types=sorted(original.ignore_types))
177 for unit_id in sorted(stripped):
178 app = store.get_app(unit_id)
179 for list_type in ("transcriptional", "suggestion"):
180 for list_relation in unique(find_elements(app.element, f".//listRelation[@type='{list_type}']")):
181 for relation in list(list_relation):
182 list_relation.remove(relation)
183 prune_empty_list(list_relation)
184 store.save()
185 return working
188# ---------------------------------------------------------------------------
189# cross-validation folds over the example units
190# ---------------------------------------------------------------------------
192class FoldPlan(BaseModel):
193 seed: int
194 folds: int
195 source: str = Field(description="The sample file the folds were made from.")
196 pool: str = Field(default="example", description="'example': folds over the example units (the test units are hidden); 'all': over every sample unit.")
197 stratified: bool = Field(default=False, description="Units were dealt to folds largest first, so big units are spread out.")
198 units: list[list[str]] = Field(description="The held-out units of each fold (fold k is units[k-1]), in document order.")
201def make_folds(example_ids:list[str], folds:int, seed:int, document_order:list[str]|None=None,
202 sizes:dict[str, int]|None=None) -> list[list[str]]:
203 """
204 Splits the units into `folds` folds of (nearly) equal size. The result depends only on the set of ids, the number
205 of folds, the seed and the sizes. With `sizes` (e.g. pairs per unit) the units are dealt largest first, in a
206 back-and-forth order (ties in random order), so the largest units fall in different folds. Units within a fold are
207 in document order if it is given (else sorted).
208 """
209 if folds < 2:
210 raise AnnotationError("Cross-validation needs at least 2 folds.")
211 if folds > len(example_ids):
212 raise AnnotationError(f"Cannot make {folds} folds from {len(example_ids)} example units.")
213 shuffled = sorted(set(example_ids))
214 random.Random(seed).shuffle(shuffled)
215 if sizes:
216 shuffled.sort(key=lambda unit_id: -sizes.get(unit_id, 0)) # stable: ties keep their random order
217 result = [[] for _ in range(folds)]
218 for index, unit_id in enumerate(shuffled):
219 round_, position = divmod(index, folds)
220 result[position if round_ % 2 == 0 else folds - 1 - position].append(unit_id)
221 else:
222 result = [shuffled[index::folds] for index in range(folds)]
223 position = {unit_id: index for index, unit_id in enumerate(document_order)} if document_order else None
224 return [sorted(fold, key=(lambda unit_id: (position.get(unit_id, len(position)), unit_id)) if position else None) for fold in result]
227def load_or_create_folds(path:Path, sample, folds:int, seed:int, pool:str="example", sizes:dict[str, int]|None=None) -> FoldPlan:
228 """
229 The saved folds at `path` (checked against the sample, pool, folds and seed), or new ones saved there. `pool` is
230 'example' (the example units) or 'all' (every sample unit); `sizes` (pairs per unit) stratifies new folds.
231 """
232 path = Path(path)
233 if pool not in ("example", "all"):
234 raise AnnotationError(f"Unknown fold pool '{pool}': use 'example' or 'all'.")
235 examples = sample.ids("example") if pool == "example" else sample.ids()
236 if path.exists():
237 plan = FoldPlan.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")))
238 if plan.seed != seed:
239 raise AnnotationError(f"{path} was made with seed {plan.seed}, not {seed}.")
240 if plan.folds != folds:
241 raise AnnotationError(f"{path} has {plan.folds} folds, not {folds}.")
242 if plan.pool != pool:
243 raise AnnotationError(f"{path} was made over the pool '{plan.pool}', not '{pool}'.")
244 if sorted(unit for fold in plan.units for unit in fold) != sorted(examples):
245 raise AnnotationError(f"The folds in {path} do not match the sample's {'example ' if pool == 'example' else ''}units.")
246 return plan
247 plan = FoldPlan(seed=seed, folds=folds, source=sample.source, pool=pool, stratified=bool(sizes),
248 units=make_folds(examples, folds, seed, document_order=sample.ids(), sizes=sizes))
249 path.parent.mkdir(parents=True, exist_ok=True)
250 path.write_text(yaml.safe_dump(plan.model_dump(), sort_keys=False, allow_unicode=True), encoding="utf-8")
251 return plan
254# ---------------------------------------------------------------------------
255# the evaluation and its report
256# ---------------------------------------------------------------------------
258class EvaluatedPair(BaseModel):
259 unit_id: str
260 verse: str
261 before: str
262 lemma: str
263 after: str
264 first: str
265 second: str
266 first_text: str
267 second_text: str
268 change: str
269 gold: str
270 gold_cert: str | None = Field(default=None, description="The certainty of the gold label (high / medium / low), if recorded.")
271 draft: str | None
272 final: str | None
273 draft_cert: str | None = Field(default=None, description="The pipeline's stated certainty for its final label.")
274 alternative: str | None = Field(default=None, description="The second category the draft named when unsure (None if it was sure).")
275 expert: str | None = Field(default=None, description="The expert's choice, if the pair was escalated.")
276 justification: str = Field(description="The pipeline's final justification.")
279class EvaluationReport(BaseModel):
280 model: str
281 fold: int | None = Field(default=None, description="The cross-validation fold (1-based), if this is one.")
282 pool: str | None = Field(default=None, description="The fold pool ('example' or 'all'), if this is a fold.")
283 folds: int | None = None
284 seed: int | None = None
285 held_out_units: list[str] = Field(default_factory=list, description="The units predicted and scored.")
286 hidden_units: list[str] = Field(default_factory=list, description="Units whose labels were removed but which were not scored (the real test units in cross-validation).")
287 definitions_hash: str
288 references: list[str] = Field(default_factory=list)
289 test_units: int
290 gold_pairs: int
291 excluded_rule_pairs: int
292 unlabelled_test_pairs: int
293 draft: Metrics
294 final: Metrics | None = None
295 rounds: int
296 revisions: list = Field(default_factory=list)
297 notes: list[str] = Field(default_factory=list)
298 pairs: list[EvaluatedPair] = Field(default_factory=list)
299 draft_run: str = ""
300 review_run: str = ""
301 usage: dict = Field(default_factory=dict)
302 cost: float | None = Field(default=None, description="Total cost: the draft (and review) model plus the expert.")
303 escalation: dict = Field(default_factory=dict, description="Escalation to the expert: mode, model, pairs, groups, changes, usage and cost.")
306def evaluate(
307 path:Path,
308 model,
309 output_dir:Path,
310 rounds:int=3,
311 concurrency:int=4,
312 toolsets:list|None=None,
313 effort:str|None=None,
314 ignore_types:list[str]|None=None,
315 fold:int|None=None,
316 folds:int=5,
317 seed:int=0,
318 folds_path:Path|None=None,
319 pool:str="example",
320 expert=None,
321 expert_mode:str="after",
322 batch:bool=False,
323 batch_client=None,
324 poll_interval:float=60.0,
325) -> EvaluationReport:
326 """
327 Runs the pipeline on a stripped copy and compares it with the gold labels; writes the report.
329 Without `fold` the sample's test units are evaluated. With `fold` (1-based, of `folds`, split by `seed` and saved
330 at `folds_path`, default <output_dir>/../folds.yaml) that fold's example units are evaluated, the sample's test
331 units are hidden (labels and suggestions removed, never predicted) and only the other example units keep labels.
332 """
333 from .pipeline import draft, review, model_name, price, escalate
335 path, output_dir = Path(path), Path(output_dir)
336 original = AnnotationStore(path, read_only=True, **({"ignore_types": ignore_types} if ignore_types else {}))
337 sample = original.load_sample()
338 if sample is None:
339 raise AnnotationError(f"Evaluation needs a sample of example and test units ({original.sample_path.name} not found).")
340 hidden = []
341 if fold is not None:
342 sizes = {unit_id: len(original.work_pairs(original.get_app(unit_id))) for unit_id in sample.ids()}
343 plan = load_or_create_folds(Path(folds_path) if folds_path else output_dir.parent / "folds.yaml", sample, folds, seed,
344 pool=pool, sizes=sizes if pool == "all" else None)
345 if not 1 <= fold <= plan.folds:
346 raise AnnotationError(f"There is no fold {fold}: choose 1 to {plan.folds}.")
347 test_units = plan.units[fold - 1]
348 hidden = sample.ids("test") if pool == "example" else []
349 else:
350 test_units = sample.ids("test")
351 gold = gold_labels(original, test_units)
352 gold_certs = certainties(original, gold, ("human",))
354 working = strip_units(path, output_dir / f"{path.stem}.working.xml", held_out=test_units, hidden=hidden)
355 store = AnnotationStore(working, ignore_types=sorted(original.ignore_types))
356 if store.rules:
357 store.apply_rules()
358 definitions_hash = store.definitions().definitions_hash
359 categories = [category.name for category in store.definitions().categories]
361 if expert is not None and expert_mode not in ("after", "tool"):
362 raise AnnotationError(f"Unknown expert mode '{expert_mode}': use 'after' or 'tool'.")
363 if batch:
364 if expert is not None and expert_mode == "tool":
365 raise AnnotationError("The expert tool needs the interactive draft; use expert mode 'after' with --batch.")
366 from .batch import draft_batch
367 drafted = draft_batch(store, model, unit_ids=test_units, client=batch_client, poll_interval=poll_interval)
368 else:
369 drafted = draft(store, model, toolsets=toolsets, unit_ids=test_units, concurrency=concurrency, effort=effort,
370 expert=expert if expert_mode == "tool" else None, expert_mode=expert_mode)
371 draft_predictions = predictions(store, test_units)
372 draft_metrics = metrics(gold, draft_predictions, categories, gold_certs)
373 alternatives = {(item.unit_id, item.active, item.passive): item.alternative for item in drafted.uncertain}
375 final_metrics, reviewed, escalated = None, None, None
376 final_predictions = draft_predictions
377 escalation = {}
378 if expert is not None and expert_mode == "tool":
379 escalation = dict(mode="tool", model=model_name(expert), calls=drafted.expert_calls, flagged=len(drafted.uncertain),
380 usage=drafted.expert_usage, cost=drafted.expert_cost)
381 if expert is not None and expert_mode == "after":
382 escalated = escalate(store, expert, drafted.uncertain, concurrency=concurrency, effort=effort)
383 final_predictions = predictions(store, test_units)
384 final_metrics = metrics(gold, final_predictions, categories, gold_certs)
385 escalation = dict(mode="after", model=model_name(expert), flagged=len(drafted.uncertain), pairs=escalated.pairs,
386 groups=escalated.groups, changed=escalated.changed, kept=escalated.kept, skipped=escalated.skipped,
387 errors=escalated.errors, usage=escalated.usage, cost=escalated.cost)
388 experts = {(entry["unit_id"], entry["active"], entry["passive"]): entry["expert"] for entry in (escalated.decisions if escalated else [])}
389 if rounds > 0:
390 reviewed = review(store, model, toolsets=toolsets, rounds=rounds, unit_ids=test_units, effort=effort,
391 log_path=output_dir / "revisions.jsonl")
392 final_predictions = predictions(store, test_units)
393 final_metrics = metrics(gold, final_predictions, categories, gold_certs)
395 work_pairs = sum(len(store.work_pairs(store.get_app(unit_id))) for unit_id in test_units)
396 rule_pairs = sum(len(store.rule_pairs(store.get_app(unit_id))) for unit_id in test_units)
397 notes = [f"The gold set has {len(gold)} test pairs in {len(test_units)} test units."]
398 small = [row.category for row in (final_metrics or draft_metrics).per_category if row.indicative and row.support]
399 if small:
400 notes.append(f"Fewer than {SMALL_SUPPORT} test pairs (indicative only): {', '.join(small)}.")
401 if rule_pairs:
402 notes.append(f"{rule_pairs} pairs labelled by subreading rules are left out of the scores.")
404 predicted_certs = certainties(store, list(gold), ("pipeline",))
405 pairs = []
406 for (unit_id, first, second), category in gold.items():
407 app = store.get_app(unit_id)
408 pair = store.get_pair(app, first, second)
409 relation = pair.relation_element()
410 justification = store.provenance_from_relation(relation).justification if relation is not None and store.label_source(pair) == "pipeline" else ""
411 from .diff import describe_change
412 pairs.append(EvaluatedPair(
413 unit_id=unit_id, verse=verse_label(unit_id), before=app.text_before(), lemma=app.text(), after=app.text_after(),
414 first=first, second=second, first_text=str(pair.active), second_text=str(pair.passive),
415 change=describe_change(pair.active.text, pair.passive.text).text, gold=category,
416 gold_cert=gold_certs.get((unit_id, first, second)), draft_cert=predicted_certs.get((unit_id, first, second)),
417 alternative=directed_lookup(alternatives, unit_id, first, second, store), expert=directed_lookup(experts, unit_id, first, second, store),
418 draft=draft_predictions.get((unit_id, first, second)), final=final_predictions.get((unit_id, first, second)) if (reviewed or escalated) else None,
419 justification=justification,
420 ))
422 usage = dict(drafted.usage)
423 if reviewed:
424 for key, value in reviewed.usage.items():
425 usage[key] = usage.get(key, 0) + value
426 report = EvaluationReport(
427 model=model_name(model), fold=fold, pool=pool if fold is not None else None, folds=folds if fold is not None else None, seed=seed if fold is not None else None,
428 held_out_units=list(test_units), hidden_units=list(hidden),
429 definitions_hash=definitions_hash, test_units=len(test_units), gold_pairs=len(gold),
430 excluded_rule_pairs=rule_pairs, unlabelled_test_pairs=work_pairs - len(gold),
431 draft=draft_metrics, final=final_metrics, rounds=rounds,
432 revisions=list(reviewed.revisions) if reviewed else [], notes=notes, pairs=pairs,
433 draft_run=drafted.run_id, review_run=reviewed.run_id if reviewed else "",
434 usage=usage, cost=((drafted.cost if batch else price(model, usage)) or 0.0) + (escalation.get("cost") or 0.0), escalation=escalation,
435 )
436 output_dir.mkdir(parents=True, exist_ok=True)
437 (output_dir / "report.json").write_text(json.dumps(report.model_dump(mode="json"), ensure_ascii=False, indent=2))
438 (output_dir / "report.html").write_text(render_report(report))
439 return report
442def directed_lookup(values:dict, unit_id:str, first:str, second:str, store:AnnotationStore):
443 """ A value recorded for a pair in either direction; a category recorded for the inverse is turned around. """
444 if (unit_id, first, second) in values:
445 return values[(unit_id, first, second)]
446 value = values.get((unit_id, second, first))
447 return store.get_relation_type(value).get_inverse().name if value else None
450def render_report(report:EvaluationReport) -> str:
451 """ The HTML report, in the style of the original rdgai report (same frame, logo, icons and stylesheet). """
452 from jinja2 import Environment, FileSystemLoader, select_autoescape
453 import base64
454 templates = Path(__file__).parent / "templates"
455 environment = Environment(loader=FileSystemLoader(templates), autoescape=select_autoescape(["html"]))
456 favicon = base64.b64encode((templates / "assets" / "img" / "favicon.svg").read_bytes()).decode()
457 return environment.get_template("evaluation.html").render(report=report, favicon=favicon)