Coverage for collectra/evaluator/base.py: 94.20%
224 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1__all__ = ["Evaluator"]
3import csv
4from typing import Any, ClassVar
5from pydantic import BaseModel, ConfigDict, Field
7from collectra.commons import PositionalFields
8from pathlib import Path
10import yaml
11from rich.table import Table
13from ..logger import get_logger
14from ..types import ArtefactNode
15from ..commons.results import pop_header
16from ..utils import change_dir
18logger = get_logger(__name__)
21class FileEvaluationResult(PositionalFields, BaseModel):
22 """Results for a single file pair evaluation."""
24 filename: str
25 label_metrics: dict[str, dict]
28class EvaluationReport(PositionalFields, BaseModel):
29 """Complete evaluation report across all files."""
31 model_config = ConfigDict(arbitrary_types_allowed=True)
33 file_results: list[FileEvaluationResult]
34 aggregate: dict
35 threshold: float
36 # Rich tables built from ``aggregate`` for display; not part of the data.
37 aggregate_tables: list = Field(default_factory=list, exclude=True, repr=False)
38 tables: list = Field(default_factory=list, exclude=True, repr=False)
40 _runtime_fields: ClassVar[frozenset[str]] = frozenset(
41 {"aggregate_tables", "tables"}
42 )
44 def model_post_init(self, __context: Any) -> None:
45 for data_type, metrics in self.aggregate.items():
46 """Turn the aggregate dict into a rich Table for display."""
47 table = Table(title=f"Aggregate Evaluation Metrics for {data_type}")
48 table.add_column("Metric", style="cyan", no_wrap=True)
49 table.add_column("Value", justify="right", style="green")
51 # Add overall metrics
52 overall = metrics.get("overall", {})
53 table.add_row("Precision (Overall)", f"{overall.get('precision', 0):.3f}")
54 table.add_row("Recall (Overall)", f"{overall.get('recall', 0):.3f}")
55 table.add_row("F1 Micro", f"{overall.get('f1_micro', 0):.3f}")
56 table.add_row(
57 "F1 File-Averaged", f"{overall.get('f1_file_averaged', 0):.3f}"
58 )
59 table.add_row("Total Files", str(overall.get("total_files", 0)))
60 self.aggregate_tables.append(table)
61 # Create per-label table
62 per_label = metrics.get("per_label", {})
63 if not per_label:
64 continue
65 table = Table(title=f"Per-Label Metrics for Artefact Type: {data_type}")
66 table.add_column("Label", style="magenta")
67 table.add_column("Precision", justify="right", style="green")
68 table.add_column("Recall", justify="right", style="green")
69 table.add_column("F1", justify="right", style="green")
70 table.add_column("Mean Score", justify="right", style="green")
71 table.add_column("Support", justify="right", style="blue")
72 for label_name, metrics in per_label.items():
73 table.add_row(
74 label_name,
75 f"{metrics.get('precision', 0):.3f}",
76 f"{metrics.get('recall', 0):.3f}",
77 f"{metrics.get('f1', 0):.3f}",
78 f"{metrics.get('mean_score', 0):.3f}",
79 str(metrics.get("support", 0)),
80 )
81 self.tables.append(table)
83 def save_csv(self, output: Path) -> None:
84 """Save file- and label-level evaluation metrics as a tidy CSV."""
85 output = Path(output).expanduser()
86 output.parent.mkdir(parents=True, exist_ok=True)
87 fieldnames = [
88 "filename",
89 "label",
90 "artefact_type",
91 "precision",
92 "recall",
93 "f1",
94 "mean_score",
95 "num_predicted",
96 "num_gold",
97 "true_positives",
98 "false_positives",
99 "false_negatives",
100 ]
101 with output.open("w", newline="") as stream:
102 writer = csv.DictWriter(stream, fieldnames=fieldnames)
103 writer.writeheader()
104 for result in self.file_results:
105 for label, metrics in result.label_metrics.items():
106 types = metrics.get("types", []) or [""]
107 for artefact_type in types:
108 writer.writerow(
109 {
110 "filename": result.filename,
111 "label": label,
112 "artefact_type": artefact_type,
113 "precision": metrics.get("precision", 0),
114 "recall": metrics.get("recall", 0),
115 "f1": metrics.get("f1", 0),
116 "mean_score": metrics.get("mean_score", 0),
117 "num_predicted": metrics.get("num_predicted", 0),
118 "num_gold": metrics.get("num_gold", 0),
119 "true_positives": metrics.get("num_matched", 0),
120 "false_positives": metrics.get(
121 "num_false_positives", 0
122 ),
123 "false_negatives": metrics.get(
124 "num_false_negatives", 0
125 ),
126 }
127 )
130class EvaluationError(Exception):
131 """Raised when evaluation cannot proceed (e.g., missing gold files)."""
133 pass
136class Evaluator:
137 """
138 End-to-end evaluation orchestrator for Collectra workflows.
140 Responsibilities:
141 1. Match input files to gold standard files by filename
142 2. Load and parse .grapto (or other ext) folder structures
143 3. Delegate per-label evaluation to ArtefactNode.evaluate()
144 4. Aggregate metrics across files and labels
145 5. Export results in tabular format
146 """
148 def __init__(
149 self,
150 predicted_folder: Path,
151 gold_folder: Path,
152 ext: str,
153 labels: set[str] | None = None,
154 match_by_order: bool = False,
155 ) -> None:
156 self.ext = ext.lower().replace(".", "")
157 self.labels = labels
158 predicted_folder = Path(predicted_folder).expanduser().resolve()
159 gold_folder = Path(gold_folder).expanduser().resolve()
160 direct_pair = self._is_collectra_folder(
161 predicted_folder
162 ) and self._is_collectra_folder(gold_folder)
163 if match_by_order or direct_pair:
164 self.entries = self._pair_folders_by_order(predicted_folder, gold_folder)
165 else:
166 entries = self._discover_collectra_folders(predicted_folder)
167 self.entries = self._discover_collectra_folders(
168 gold_folder, gold=True, entries=entries
169 )
170 self.results: list[FileEvaluationResult] = []
171 self.aggregate_metrics: dict = {}
173 def _is_collectra_folder(self, path: Path) -> bool:
174 return path.is_dir() and path.suffix == f".{self.ext}"
176 def _pair_folders_by_order(
177 self, predicted_folder: Path, gold_folder: Path
178 ) -> dict[str, list[Path | None]]:
179 """Pair independently sorted prediction and gold result folders."""
180 predicted_entries = self._discover_collectra_folders(predicted_folder)
181 gold_entries = self._discover_collectra_folders(gold_folder, gold=True)
182 predictions = sorted(
183 (paths[1] for paths in predicted_entries.values() if paths[1]),
184 key=lambda path: path.name,
185 )
186 golds = sorted(
187 (paths[0] for paths in gold_entries.values() if paths[0]),
188 key=lambda path: path.name,
189 )
190 return {
191 f"pair-{index:06d}": [
192 golds[index] if index < len(golds) else None,
193 predictions[index] if index < len(predictions) else None,
194 ]
195 for index in range(max(len(predictions), len(golds)))
196 }
198 def __call__(self) -> None:
199 self.evaluate()
201 def _discover_collectra_folders(
202 self,
203 folder: Path,
204 entries: dict[str, list[Path | None]] | None = None,
205 gold: bool = False,
206 ) -> dict[str, list[Path | None]]:
207 """
208 Find .{ext} directories (e.g., .grapto folders).
210 ``folder`` may be either one result directory or a parent containing
211 multiple result directories.
213 Args:
214 folder: Path to search for .{ext} directories
215 entries: dictionary of tuples base_name: (gold_path, predicted_path) to extend if empty, or to have entries updated.
216 gold: Whether to look for gold files (as opposed to predicted files)
218 Returns:
219 dictionary mapping base_name to tuples (gold_path, predicted_path) for each discovered .{ext} directory
220 """
221 if entries is None:
222 entries = {}
223 folder = Path(folder).expanduser().resolve()
224 if not folder.is_dir():
225 raise FileNotFoundError(f"Evaluation path is not a directory: {folder}")
227 items = [folder] if folder.suffix == f".{self.ext}" else list(folder.iterdir())
228 for item in items:
229 if not (item.is_dir() and item.suffix == f".{self.ext}"):
230 continue
231 base_name = item.stem
232 if base_name not in entries:
233 if gold:
234 entries[base_name] = [item, None]
235 else:
236 entries[base_name] = [None, item]
237 else:
238 existing_gold, existing_predicted = entries[base_name]
239 if gold:
240 entries[base_name] = [item, existing_predicted]
241 else:
242 entries[base_name] = [existing_gold, item]
243 return entries
245 def _validate_file_pairs(
246 self,
247 ) -> tuple[list[tuple[Path, Path]], list[Path], list[Path]]:
248 """
249 Match input files to gold files and identify mismatches.
251 Returns:
252 - matched_pairs: list of (input_path, gold_path, base_name)
253 - missing_gold: input files without corresponding gold
254 - extra_gold: gold files without corresponding input
255 """
257 matched_pairs: list[tuple[Path, Path]] = []
258 missing_golds: list[Path] = []
259 extra_golds: list[Path] = []
261 for key, (gold_path, predicted_path) in self.entries.items():
262 missing_gold = gold_path is None
263 missing_predicted = predicted_path is None
264 if not missing_gold and not missing_predicted:
265 matched_pairs.append((predicted_path, gold_path))
266 if missing_gold and missing_predicted:
267 raise ValueError(
268 f"Entry '{key}' has neither gold nor predicted file. This should not happen."
269 )
270 if missing_gold and predicted_path is not None:
271 missing_golds.append(predicted_path)
272 if missing_predicted and gold_path is not None:
273 extra_golds.append(gold_path)
275 return matched_pairs, list(missing_golds), list(extra_golds)
277 def _load_collectra_file(self, path: Path) -> dict[str, ArtefactNode]:
278 """
279 Parse a collectra file data into ArtefactNodes organized by label.
281 Each label (e.g., "registration_number", "local_text") becomes
282 a separate ArtefactNode containing its items (ImageCrops, Texts).
284 Returns:
285 dict mapping label_name -> ArtefactNode
286 """
287 labels = dict()
288 with change_dir(path):
289 with open("results.yaml", "r") as f:
290 data = yaml.safe_load(f)
291 pop_header(data, source=path)
292 node_names = list(data.keys())
293 for name in node_names:
294 node = ArtefactNode(name=name)
295 node.process(key=node.name, value=path, skip_type_check=True)
296 labels[name] = node
297 return labels
299 def _create_missing_prediction_metrics(self, gold_node: ArtefactNode) -> dict:
300 """
301 Generate metrics when predictions are entirely missing for a gold label.
303 Scenario: Gold has items for this label, but predictions have none.
304 Result:
305 - Precision = 0.0 (undefined 0/0, defaults to 0.0 for consistency)
306 - Recall = 0.0 (missed everything)
307 - F1 = 0.0
308 - All gold items are false negatives
310 This mirrors the edge case handling in ArtefactNode.evaluate()
311 when self.items is empty but gold_items is not.
312 """
313 gold_ids = list(gold_node.items.keys())
315 return {
316 "types": list(
317 set([type(item).__name__ for item in gold_node.items.values()])
318 ),
319 "precision": 0.0, # No predictions = undefined (0/0), defaults to 0.0
320 "recall": 0.0, # Missed all gold items
321 "f1": 0.0,
322 "mean_score": 0.0,
323 "num_predicted": 0,
324 "num_gold": len(gold_ids),
325 "num_matched": 0,
326 "num_false_positives": 0,
327 "num_false_negatives": len(gold_ids),
328 "matches": [],
329 "unmatched_predicted": [],
330 "unmatched_gold": gold_ids,
331 }
333 def _create_extra_prediction_metrics(self, input_node: ArtefactNode) -> dict:
334 """
335 Generate metrics when predictions exist for a label not in gold.
337 Scenario: Predictions have items for this label, but gold has none.
338 Result:
339 - Precision = 0.0 (all predictions are false positives)
340 - Recall = 1.0 (nothing to miss, vacuously true)
341 - F1 = 0.0
342 - All predicted items are false positives
344 This mirrors the edge case handling in ArtefactNode.evaluate()
345 when gold_items.items is empty but self.items is not.
347 Note: This typically indicates either:
348 1. Model hallucinated a label class
349 2. Mismatch in label naming conventions
350 3. Gold annotation is incomplete
351 Consider logging a warning when this occurs.
352 """
353 predicted_ids = list(input_node.items.keys())
355 return {
356 "types": list(
357 set([type(item).__name__ for item in input_node.items.values()])
358 ),
359 "precision": 0.0, # All predictions are wrong
360 "recall": 1.0, # Nothing to find = found everything
361 "f1": 0.0,
362 "mean_score": 0.0,
363 "num_predicted": len(predicted_ids),
364 "num_gold": 0,
365 "num_matched": 0,
366 "num_false_positives": len(predicted_ids),
367 "num_false_negatives": 0,
368 "matches": [],
369 "unmatched_predicted": predicted_ids,
370 "unmatched_gold": [],
371 }
373 def _evaluate_file_pair(
374 self, input_path: Path, gold_path: Path, threshold: float = 0.5
375 ) -> FileEvaluationResult:
376 """
377 Evaluate a single input file against its gold standard.
379 Process:
380 1. Load both files into label -> ArtefactNode mappings
381 2. For each label present in gold, evaluate predictions
382 3. Handle labels present in only one file (missing predictions or extra labels)
384 Returns:
385 FileEvaluationResult containing per-label metrics
386 """
387 input_labels = self._load_collectra_file(input_path)
388 gold_labels = self._load_collectra_file(gold_path)
390 file_result = FileEvaluationResult(filename=input_path.stem, label_metrics={})
392 all_labels = {
393 l
394 for l in (set(input_labels.keys()) | set(gold_labels.keys()))
395 if not l.endswith("_draft") and (self.labels is None or l in self.labels)
396 }
398 for label_name in all_labels:
399 input_node = input_labels.get(label_name)
400 gold_node = gold_labels.get(label_name)
402 if input_node is None and gold_node is None:
403 # This should not happen since label is in all_labels
404 continue
405 elif input_node is None:
406 # Missing predictions for this label
407 metrics = self._create_missing_prediction_metrics(gold_node)
408 elif gold_node is None:
409 # Extra predictions for non-existent gold label
410 metrics = self._create_extra_prediction_metrics(input_node)
411 else:
412 # Both exist - use ArtefactNode.evaluate()
413 metrics = input_node.evaluate(gold_node, threshold=threshold)
415 file_result.label_metrics[label_name] = metrics
417 return file_result
419 def _aggregate_results(self) -> dict:
420 """
421 Compute aggregate metrics across all files.
423 Aggregation strategy:
424 - Macro average: Average of per-file metrics (treats each file equally)
425 - Micro average: Pool all TP/FP/FN then compute (treats each item equally)
426 - Per-label aggregates: Metrics grouped by label class
427 """
428 from collections import defaultdict
430 metrics = ["precision", "recall", "f1", "mean_score"]
431 data_types_set = set()
432 for result in self.results:
433 for label_name, label_metrics in result.label_metrics.items():
434 data_types = label_metrics.get("types", [])
435 for data_type in data_types:
436 data_types_set.add(data_type)
438 data_types = list(data_types_set)
440 aggregated_results = dict()
442 for data_type in data_types:
443 # Initialize accumulators
444 label_pools = defaultdict(
445 lambda: {
446 "total_tp": 0,
447 "total_fp": 0,
448 "total_fn": 0,
449 "total_score": 0.0,
450 "total_matches": 0,
451 }
452 )
454 file_f1_scores = []
456 for file_result in self.results:
457 file_tp = file_fp = file_fn = 0
458 for label_name, metrics in file_result.label_metrics.items():
459 if data_type not in metrics.get("types", []):
460 continue
461 pool = label_pools[label_name]
462 pool["total_tp"] += metrics["num_matched"]
463 pool["total_fp"] += metrics["num_false_positives"]
464 pool["total_fn"] += metrics["num_false_negatives"]
465 pool["total_score"] += (
466 metrics["mean_score"] * metrics["num_matched"]
467 )
468 pool["total_matches"] += metrics["num_matched"]
469 pool["types"] = metrics.get("types", [])
471 file_tp += metrics["num_matched"]
472 file_fp += metrics["num_false_positives"]
473 file_fn += metrics["num_false_negatives"]
475 # Per-file F1
476 file_precision = (
477 file_tp / (file_tp + file_fp) if (file_tp + file_fp) > 0 else 0
478 )
479 file_recall = (
480 file_tp / (file_tp + file_fn) if (file_tp + file_fn) > 0 else 0
481 )
482 file_f1 = (
483 2 * file_precision * file_recall / (file_precision + file_recall)
484 if (file_precision + file_recall) > 0
485 else 0
486 )
487 # Issues 2 & 3: skip files with no items of this type (vacuous truth)
488 if (file_tp + file_fp + file_fn) == 0:
489 logger.warning(
490 "Skipping vacuous file-level metrics for '%s' (no items of "
491 "type '%s'). Excluded from file-averaged F1.",
492 file_result.filename,
493 data_type,
494 )
495 # Issue 5: skip files with predictions but no gold items for this type
496 elif (file_tp + file_fn) == 0:
497 logger.warning(
498 "File '%s' has predictions but no gold items for type '%s'. "
499 "Excluding from file-averaged F1 to avoid inflating recall.",
500 file_result.filename,
501 data_type,
502 )
503 else:
504 file_f1_scores.append(file_f1)
506 # Compute per-label micro metrics
507 per_label_metrics = {}
508 for label_name, pool in label_pools.items():
509 tp, fp, fn = pool["total_tp"], pool["total_fp"], pool["total_fn"]
510 precision = tp / (tp + fp) if (tp + fp) > 0 else 0
511 recall = tp / (tp + fn) if (tp + fn) > 0 else 0
512 f1 = (
513 2 * precision * recall / (precision + recall)
514 if (precision + recall) > 0
515 else 0
516 )
517 mean_score = (
518 pool["total_score"] / pool["total_matches"]
519 if pool["total_matches"] > 0
520 else 0
521 )
523 per_label_metrics[label_name] = {
524 "precision": precision,
525 "recall": recall,
526 "f1": f1,
527 "mean_score": mean_score,
528 "support": pool["total_tp"]
529 + pool["total_fn"], # Number of gold items
530 }
532 # Overall metrics
533 total_tp = sum(p["total_tp"] for p in label_pools.values())
534 total_fp = sum(p["total_fp"] for p in label_pools.values())
535 total_fn = sum(p["total_fn"] for p in label_pools.values())
537 overall_precision = (
538 total_tp / (total_tp + total_fp) if (total_tp + total_fp) > 0 else 0
539 )
540 overall_recall = (
541 total_tp / (total_tp + total_fn) if (total_tp + total_fn) > 0 else 0
542 )
543 overall_f1_micro = (
544 2
545 * overall_precision
546 * overall_recall
547 / (overall_precision + overall_recall)
548 if (overall_precision + overall_recall) > 0
549 else 0
550 )
551 overall_f1_file_averaged = (
552 sum(file_f1_scores) / len(file_f1_scores) if file_f1_scores else 0
553 )
554 aggregated_results[data_type] = {
555 "overall": {
556 "precision": overall_precision,
557 "recall": overall_recall,
558 "f1_micro": overall_f1_micro,
559 "f1_file_averaged": overall_f1_file_averaged,
560 "total_files": len(self.results),
561 },
562 "per_label": per_label_metrics,
563 }
565 return aggregated_results
567 def evaluate(self, threshold: float = 0.5) -> EvaluationReport:
568 """
569 Execute full evaluation across all matched file pairs.
571 Raises:
572 EvaluationError: If any input file lacks a corresponding gold file
573 """
574 self.results = []
575 matched_pairs, missing_gold, extra_gold = self._validate_file_pairs()
577 # Fail fast if gold files are missing
578 if missing_gold:
579 raise EvaluationError(f"Missing gold standard files for: {missing_gold}")
581 # Warn about extra gold files (not an error)
582 if extra_gold:
583 logger.warning(f"Gold files without predictions: {extra_gold}")
585 # Evaluate each pair
586 for input_path, gold_path in matched_pairs:
587 file_result = self._evaluate_file_pair(input_path, gold_path, threshold)
588 self.results.append(file_result)
590 # Aggregate across all files
591 self.aggregate_metrics = self._aggregate_results()
593 return EvaluationReport(
594 file_results=self.results,
595 aggregate=self.aggregate_metrics,
596 threshold=threshold,
597 )