Coverage for collectra/types/base.py: 86.07%
359 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
1import uuid
2from abc import abstractmethod
3from pathlib import Path
4from typing import Any, ClassVar
6import numpy as np
7import yaml
8from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
9from rich import print
11from collectra.cli import command
13from ..commons import EntityMixin, Node, NodeStatus, PositionalFields
14from ..commons.results import peek_header, pop_header
15from ..utils import (
16 change_dir,
17 error_msg,
18 load_class_from_string,
19 traceback_error,
20)
22__all__ = ["Artefact", "ArtefactNode"]
24from ..logger import get_logger
26logger = get_logger(__name__)
29class ArtefactCommands:
30 """CLI capabilities for a named pipeline artefact node.
32 Concrete artefact classes can return a subclass from ``cli_commands`` to
33 expose commands applying to every matching item in that node.
34 """
36 def __init__(self, node: "ArtefactNode", ext: str) -> None:
37 self.node = node
38 self.ext = ext
40 @command
41 def evaluate(
42 self,
43 predicted_folder: Path,
44 gold_folder: Path,
45 threshold: float = 0.5,
46 match_by_order: bool = False,
47 output: Path | None = None,
48 ) -> None:
49 """Evaluate this artefact against ground-truth Collectra results."""
50 from collectra.evaluator.base import Evaluator
52 report = Evaluator(
53 predicted_folder,
54 gold_folder,
55 ext=self.ext,
56 labels={self.node.name},
57 match_by_order=match_by_order,
58 ).evaluate(threshold=threshold)
59 for table in [*report.aggregate_tables, *report.tables]:
60 print(table)
61 if output is not None:
62 report.save_csv(output)
65class ArtefactMeta(type(BaseModel)):
66 """Lets an artefact that stands in for another one pass its ``isinstance`` checks.
68 A ``Link`` is a soft reference; once bound it should satisfy
69 ``isinstance(link, ImageCrop)`` when it points at a crop. The real class of
70 the object is left alone, which pydantic relies on.
71 """
73 def __instancecheck__(cls, instance) -> bool:
74 if super().__instancecheck__(instance):
75 return True
76 stand_in = getattr(type(instance), "_stand_in_type", None)
77 return bool(stand_in) and issubclass(stand_in(instance), cls)
80class Artefact(PositionalFields, EntityMixin, BaseModel, metaclass=ArtefactMeta):
81 model_config = ConfigDict(
82 extra="allow",
83 validate_assignment=True,
84 arbitrary_types_allowed=True,
85 protected_namespaces=(),
86 )
88 name: str
89 id: str = ""
90 parents: list[str] = Field(default_factory=list)
91 partition: str = ""
92 embeddings: list[str] = Field(default_factory=list)
93 orientation: str = "north" # e.g., "landscape" or "portrait"
94 ensemble: list[str] = Field(default_factory=list)
95 source_file: Path | None = Field(default=None, exclude=True, repr=False)
97 # An automatic id is provisional: the pipeline renames it after the node
98 # (``node`` or ``node-k``) when the artefact joins its node.
99 _auto_id: bool = PrivateAttr(default=False)
100 # Fields left out when comparing artefacts: runtime state, not content.
101 _not_compared: ClassVar[frozenset[str]] = frozenset({"source_file"})
103 # Measured or set at runtime, never passed in: skipped for positional arguments.
104 _runtime_fields: ClassVar[frozenset[str]] = frozenset(
105 {"source_file", "raw_width", "raw_height", "source_parent"}
106 )
108 @field_validator("parents", "embeddings", mode="before")
109 @classmethod
110 def _as_list(cls, value):
111 """YAML writes a single reference as a bare value; always hold a list."""
112 if value is None:
113 return []
114 return value if isinstance(value, list) else [value]
116 @abstractmethod
117 def __call__(self):
118 """The artefact's content."""
120 @staticmethod
121 def file_extensions() -> set[str]:
122 """Lower-case file extensions, with the dot, that can hold this type."""
123 raise NotImplementedError(
124 "Artefact types must say which file extensions they can be read from."
125 )
127 def stored_files(self, folder: Path) -> list[Path]:
128 """Files this artefact owns, for removal before a forced rerun replaces it.
130 ``folder`` is the results folder that relative paths are read against.
131 Most artefacts own none: an image's ``data`` is a source file that must
132 never be deleted. Only artefacts whose content a task wrote to a file
133 of its own list it here.
134 """
135 return []
137 def finalise(self, folder: Path, node: str) -> None:
138 """Called once the artefact has its final id, before results are saved.
140 ``folder`` is the results folder and ``node`` the name of the node the
141 artefact belongs to. Artefacts that keep content in separate files
142 write them here. The default does nothing.
143 """
145 def _comparable(self) -> dict:
146 values = {**self.__dict__, **(self.__pydantic_extra__ or {})}
147 return {k: v for k, v in values.items() if k not in self._not_compared}
149 def __eq__(self, other: object) -> bool:
150 if type(self) is not type(other):
151 return False
152 return self._comparable() == other._comparable()
154 __hash__ = None
156 def set_parents(self, parents: list["Artefact"]) -> None:
157 self.parents = [parent.id for parent in parents]
159 def serialize(self) -> dict:
160 serialized = super().serialize()
161 if not self.partition:
162 serialized.pop("partition", None)
163 if "parents" in serialized:
164 if len(serialized["parents"]) == 0:
165 serialized.pop("parents")
166 elif len(serialized["parents"]) == 1:
167 serialized["parents"] = serialized["parents"][0]
168 return serialized
170 def evaluate(self, gold) -> float:
171 raise NotImplementedError(
172 "Eval method not implemented for base Artefact class."
173 )
175 def display(self, context) -> dict:
176 """Describe this artefact using the display protocol (see collectra.display).
178 Override to return an image, text, or properties view, or supply a
179 custom JavaScript module using ``context.renderer(module_path)``.
180 The context resolves related artefacts and publishes previews without
181 altering data. See docs/artefacts/display.rst for the renderer contract.
182 """
183 return {"kind": "properties", "data": self.serialize()}
185 def _extract(self, path: Path) -> None:
186 raise NotImplementedError(
187 "Extract method not implemented for base Artefact class."
188 )
190 def extract(self, path: Path | str) -> None:
191 path = Path(path)
192 path.parent.mkdir(parents=True, exist_ok=True)
193 self._extract(path)
195 @classmethod
196 def cli_commands(cls, node: "ArtefactNode", ext: str) -> ArtefactCommands:
197 """Return the CLI object representing this artefact type in ``node``."""
198 return ArtefactCommands(node, ext)
200 def _generate_id(self) -> str:
201 # Generate a unique ID based on the name and other attributes
202 return f"{self.name}-{uuid.uuid4()}"
204 def model_post_init(self, __context: Any) -> None:
205 self._auto_id = not self.id
206 if not self.id:
207 self.id = self._generate_id()
209 def attributes_to_ignore(self) -> set:
210 attributes = super().attributes_to_ignore()
211 attributes.add("name")
212 attributes.add("partition")
213 attributes.add("source_file")
214 attributes.add("_auto_id")
215 return attributes
217 @classmethod
218 def all_attributes(cls):
219 return set(
220 [
221 attribute
222 for attribute in dir(cls)
223 if not attribute.startswith("_") and not callable(attribute)
224 ]
225 )
228class ArtefactNode(Node):
230 items: dict[str, Artefact] = Field(default_factory=dict)
231 ensemble_items: dict[str, Artefact] = Field(default_factory=dict)
232 types: set[type] = Field(default_factory=set)
233 skip_type_check: bool = False
234 ensemble: bool = False
236 def model_post_init(self, __context: Any) -> None:
237 self.status = NodeStatus.READY if self.items else NodeStatus.NOT_READY
239 def add_item(self, item: Artefact) -> None:
240 try:
241 self.items[item.id] = item
242 self.status = NodeStatus.READY
243 except Exception as e:
244 raise RuntimeError(f"Error adding item to ArtefactNode: {str(e)}")
246 def get_item(self, item_id: str) -> Artefact | None:
247 return self.items.get(item_id, None)
249 def add_type(self, type_: type) -> None:
250 self.types.add(type_)
252 def check_type(self, type_: type) -> bool:
253 for t in self.types:
254 if issubclass(type_, t):
255 return True
256 return False
258 def __str__(self) -> str:
259 types_str = "\n".join([t.get_class_path() for t in self.types])
260 return f"{self.name}\n{types_str}"
262 def evaluate(
263 self, gold_items: "ArtefactNode", threshold: float = 0.5
264 ) -> dict[str, int | float]:
265 """
266 Evaluate predicted items against gold standard items.
268 This implements the Hungarian algorithm (optimal bipartite matching) that:
269 1. Validates type compatibility between predicted and gold items
270 2. Computes pairwise scores between all predicted and gold items
271 3. Finds optimal assignment that maximizes total matching score
272 4. Filters matches below threshold
273 5. Computes aggregate metrics (precision, recall, F1, mean score)
275 Args:
276 gold_items: ArtefactNode containing ground truth items
277 threshold: Minimum score for a valid match (default 0.5)
278 - For ImageCrop: IoU threshold
279 - For Text: similarity threshold
281 Returns:
282 dict: {
283 "precision": float, # TP / (TP + FP)
284 "recall": float, # TP / (TP + FN)
285 "f1": float, # 2 * (P * R) / (P + R)
286 "mean_score": float, # Average score of matched pairs
287 "num_predicted": int, # Total predicted items
288 "num_gold": int, # Total gold items
289 "num_matched": int, # Number of successful matches (TP)
290 "num_false_positives": int, # Predicted items not matched
291 "num_false_negatives": int, # Gold items not matched
292 "matches": [ # List of matched pairs
293 {
294 "predicted_id": str,
295 "gold_id": str,
296 "score": float
297 },
298 ...
299 ],
300 "unmatched_predicted": [str], # IDs of unmatched predictions
301 "unmatched_gold": [str] # IDs of unmatched gold items
302 }
304 Raises:
305 TypeError: If predicted and gold items are of incompatible types
306 """
308 if threshold > 1.0 or threshold < 0.0:
309 raise ValueError(f"Invalid threshold provided: {threshold}")
311 # Use gold items for type detection when self is empty, so labels with
312 # no predictions still appear in aggregated metrics (e.g. empty [] in YAML)
313 _type_source = self.items if self.items else gold_items.items
314 metrics = {
315 "types": list(set([type(item).__name__ for item in _type_source.values()])),
316 "precision": 0.0,
317 "recall": 0.0,
318 "f1": 0.0,
319 "mean_score": 0.0,
320 "num_predicted": 0,
321 "num_gold": 0,
322 "num_matched": 0,
323 "num_false_positives": 0,
324 "num_false_negatives": 0,
325 "matches": [],
326 "unmatched_predicted": [],
327 "unmatched_gold": [],
328 }
330 # Edge case: Empty inputs with explicit semantic definitions
331 if len(self.items) == 0 and len(gold_items.items) == 0:
332 # Vacuous truth: nothing to predict, nothing to find
333 metrics.update({"precision": 1.0, "recall": 1.0, "f1": 1.0})
334 return metrics
336 if len(self.items) == 0:
337 # No predictions: precision undefined (0/0), defaults to 0.0 for consistency
338 metrics.update(
339 {
340 "precision": 0.0,
341 "num_gold": len(gold_items.items),
342 "num_false_negatives": len(gold_items.items),
343 "unmatched_gold": list(gold_items.items.keys()),
344 }
345 )
346 return metrics
348 if len(gold_items.items) == 0:
349 # No gold items: zero precision (all FPs), perfect recall (nothing to miss)
350 metrics.update(
351 {
352 "recall": 1.0,
353 "num_predicted": len(self.items),
354 "num_false_positives": len(self.items),
355 "unmatched_predicted": list(self.items.keys()),
356 }
357 )
358 return metrics
360 # Step 0: Validate type compatibility upfront
361 predicted_types = set([type(value).__name__ for value in self.items.values()])
362 gold_types = set([type(value).__name__ for value in gold_items.items.values()])
363 compatible = predicted_types == gold_types
364 if not compatible:
365 raise TypeError(
366 f"Cannot evaluate {predicted_types} predictions against "
367 f"{gold_types} gold items. Types must match."
368 )
370 # Step 1: Build score matrix
371 # Shape: (num_predicted, num_gold)
372 predicted_ids = list(self.items.keys())
373 gold_ids = list(gold_items.items.keys())
374 n_pred = len(self.items.keys())
375 n_true = len(gold_items.items.keys())
376 score_matrix = np.zeros((n_pred, n_true))
378 if n_true > n_pred:
379 padding = np.full([n_true - n_pred, n_true], 1e-9)
380 score_matrix = np.vstack([score_matrix, padding])
381 elif n_true < n_pred:
382 padding = np.full([n_pred, n_pred - n_true], 1e-9)
383 score_matrix = np.hstack([score_matrix, padding])
385 for pred_idx, pred_id in enumerate(predicted_ids):
386 pred_item = self.items[pred_id]
387 for gold_idx, gold_id in enumerate(gold_ids):
388 try:
389 gold_item = gold_items.items[gold_id]
390 score = pred_item.evaluate(gold_item)
391 score_matrix[pred_idx, gold_idx] = score
392 except NotImplementedError as e:
393 logger.debug(f"Skipping evaluation for {pred_id} vs {gold_id}: {e}")
395 # Step 2: Hungarian algorithm for optimal bipartite matching
396 # Convert to cost matrix (minimize cost = maximize score)
397 # scipy.optimize.linear_sum_assignment minimizes total cost
398 # If cost_matrix has a shape of 1, skip this step
399 if score_matrix.size != 1:
400 from scipy.optimize import linear_sum_assignment
402 cost_matrix = 1.0 - score_matrix
404 # Note: When multiple predicted items have identical scores against the same
405 # gold item, the assignment is deterministic but arbitrary (based on internal
406 # algorithm traversal order). All such assignments are equally optimal.
407 try:
408 pred_indices, gold_indices = linear_sum_assignment(cost_matrix)
409 except Exception as e:
410 raise RuntimeError(f"Error during optimal assignment: {str(e)}")
411 else:
412 pred_indices = np.array([0])
413 gold_indices = np.array([0])
415 # Step 3: Filter matches by threshold and record results
416 matches = []
417 matched_predicted = set()
418 matched_gold = set()
420 for pred_idx, gold_idx in zip(pred_indices, gold_indices):
421 if pred_idx >= n_pred or gold_idx >= n_true:
422 continue
423 score = score_matrix[pred_idx, gold_idx]
424 # Only accept matches above the threshold
425 if score >= threshold:
426 predicted_id = predicted_ids[pred_idx]
427 gold_id = gold_ids[gold_idx]
428 matches.append(
429 {
430 "predicted_id": predicted_id,
431 "gold_id": gold_id,
432 "score": float(score),
433 }
434 )
435 matched_predicted.add(predicted_id)
436 matched_gold.add(gold_id)
438 # Step 4: Identify unmatched items
439 unmatched_predicted = [
440 predicted_id
441 for predicted_id in predicted_ids
442 if predicted_id not in matched_predicted
443 ]
445 unmatched_gold = [
446 gold_id for gold_id in gold_ids if gold_id not in matched_gold
447 ]
449 # Step 5: Compute metrics
450 num_true_positives = len(matches)
451 num_false_positives = len(unmatched_predicted)
452 num_false_negatives = len(unmatched_gold)
454 precision = (
455 num_true_positives / (num_true_positives + num_false_positives)
456 if (num_true_positives + num_false_positives) > 0
457 else 0.0
458 )
460 recall = (
461 num_true_positives / (num_true_positives + num_false_negatives)
462 if (num_true_positives + num_false_negatives) > 0
463 else 0.0
464 )
466 f1 = (
467 2 * (precision * recall) / (precision + recall)
468 if (precision + recall) > 0
469 else 0.0
470 )
472 mean_score = (
473 sum(match["score"] for match in matches) / len(matches) if matches else 0.0
474 )
476 # Step 6: Return comprehensive evaluation results
477 metrics.update(
478 {
479 "precision": precision,
480 "recall": recall,
481 "f1": f1,
482 "mean_score": mean_score,
483 "num_predicted": len(self.items),
484 "num_gold": len(gold_items.items),
485 "num_matched": num_true_positives,
486 "num_false_positives": num_false_positives,
487 "num_false_negatives": num_false_negatives,
488 "matches": matches,
489 "unmatched_predicted": unmatched_predicted,
490 "unmatched_gold": unmatched_gold,
491 }
492 )
493 return metrics
495 def _create_instance(
496 self, cls_: type, *, source_file: Path | None = None, **item
497 ) -> None:
498 try:
499 instance = cls_(**item)
500 if not instance:
501 raise ValueError(f"Failed to load {item} with {cls_}")
502 instance.source_file = source_file
503 self.add_item(instance)
504 except Exception as e:
505 logger.error(
506 "Failed to create instance of %s: %s", cls_.__name__, e, exc_info=True
507 )
509 def _create_ensemble_instances(self, base_path: Path, cls_: type, **item) -> None:
510 try:
511 item["id"] = f"{base_path.parent}::{item['id']}"
512 if "parents" in item:
513 for parent_idx, _ in enumerate(item["parents"]):
514 item["parents"][
515 parent_idx
516 ] = f"{base_path.parent}::{item['parents'][parent_idx]}"
517 instance = cls_(**item)
518 if not instance:
519 raise ValueError(f"Failed to load {item} with {cls_}")
520 self.ensemble_items[instance.id] = instance
521 self.status = NodeStatus.READY
522 except Exception as e:
523 raise RuntimeError(f"Error creating ensemble instances: {str(e)}")
525 def _create_instances(self, **item) -> None:
526 for cls_ in self.types:
527 self._create_instance(cls_, **item)
529 def process(
530 self,
531 key: str,
532 value: str | Path | None = None,
533 **kwargs,
534 ) -> None:
535 skip_type_check: bool = kwargs.get("skip_type_check", False)
536 ensemble: bool = kwargs.get("ensemble", False)
537 value = value if value else kwargs.get("file", None)
538 if value and Path(value).exists() and Path(value).is_dir():
539 value = Path(value)
540 with change_dir(value):
541 try:
542 result_file = Path("results.yaml")
543 with open(result_file, "r") as f:
544 results: dict = yaml.safe_load(f)
545 partition = pop_header(results, source=value).partition
546 if key not in results:
547 # Normal when the task producing this node hasn't run yet.
548 logger.info(
549 "No %s yet in %s; it will be created when its task runs.",
550 key,
551 value.name,
552 )
553 return
554 data = results[key]
555 if not data:
556 # Key exists but empty — pipeline processed it, found nothing
557 self.status = NodeStatus.READY
558 return
559 data = data if isinstance(data, list) else [data]
560 for item in data:
561 primitive_type = False
562 try:
563 primitive_type = not isinstance(item, dict) or not (
564 "type" in item
565 and (
566 "path" in item
567 or "data" in item
568 or item["type"].endswith(".Link")
569 )
570 )
571 if primitive_type:
572 raise ValueError(
573 f"Item must be a complex type with 'type' and ('path' or 'data')"
574 )
575 cls_ = load_class_from_string(item.pop("type"))
576 if not (
577 skip_type_check or ensemble
578 ) and not self.check_type(cls_):
579 raise TypeError(
580 f"{cls_} is not a subclass or not defined in {self.types}"
581 )
582 item["name"] = key
583 if (
584 "data" not in item
585 and "path" in item
586 and "path" not in cls_.model_fields
587 ):
588 item["data"] = item.pop("path")
589 if "parents" in item and not isinstance(
590 item["parents"], list
591 ):
592 item["parents"] = [item["parents"]]
593 if (
594 partition is not None
595 and "partition" in cls_.all_attributes()
596 ):
597 item["partition"] = partition
598 if ensemble:
599 self._create_ensemble_instances(value, cls_, **item)
600 else:
601 self._create_instance(
602 cls_, source_file=value, **item
603 )
604 except Exception as e:
605 if not primitive_type:
606 logger.error(
607 "Error processing item in %s: %s",
608 self.name,
609 e,
610 exc_info=True,
611 )
612 else:
613 self._create_instances(name=key, data=str(item))
615 except Exception as e:
616 logger.error(
617 "Error loading data for %s from %s: %s",
618 key,
619 value,
620 e,
621 exc_info=True,
622 )
623 elif key:
624 self._create_instances(name=key, data=value)
626 @staticmethod
627 def batch_process(
628 item_file: Path,
629 artefact_nodes: list["ArtefactNode"],
630 *,
631 include_unlabelled: bool = False,
632 ) -> list[Artefact]:
633 names = [artefact_node.name for artefact_node in artefact_nodes]
634 with change_dir(item_file):
635 try:
636 data: list[Artefact] = list()
637 result_file = Path("results.yaml")
638 if not result_file.exists():
639 print(error_msg(f"Invalid file: {Path.cwd()}. Ignoring..."))
640 return data
641 with open(result_file, "r") as f:
642 file_data: dict = yaml.safe_load(f)
643 partition = peek_header(file_data, source=item_file).partition
644 # With unlabelled samples allowed, an empty annotation list
645 # means the same as no annotations at all.
646 all_names_not_found = all(
647 name not in file_data
648 or (include_unlabelled and not file_data[name])
649 for name in names
650 )
651 # Object detection can opt into base images with no annotations
652 # as negative samples. Classification must not treat an
653 # unlabelled image as a training example.
654 if all_names_not_found and include_unlabelled:
655 found_base = False
656 for name, values in file_data.items():
657 values = values if isinstance(values, list) else [values]
658 for item in values:
659 if (
660 not isinstance(item, dict)
661 or "type" not in item
662 and ("data" not in item or "path" not in item)
663 ):
664 continue
665 cls_str = item.pop("type", "")
666 if cls_str == "collectra.Image":
667 cls_ = load_class_from_string(cls_str)
668 try:
669 item["name"] = name
670 item["data"] = (
671 item.pop("path")
672 if "path" in item
673 else item["data"]
674 )
675 if partition is not None:
676 item["partition"] = partition
677 instance = cls_(**item)
678 if not instance:
679 raise Warning(
680 f"Failed to load {item} with {cls_}"
681 )
682 found_base = True
683 data.append(instance)
684 break
685 except Exception as e:
686 traceback_error(
687 e,
688 f"Failed to load data item {name} from {item.get('data', '')}",
689 verbose=True,
690 )
691 if found_base:
692 break
693 elif all_names_not_found:
694 return data
695 for i, name in enumerate(names):
696 if name not in file_data:
697 continue
698 value = file_data[name]
699 if not value and include_unlabelled:
700 continue
701 if not value:
702 raise Warning(
703 f"Artefact seems to be empty for {name} in {item_file}. Provided: {value}"
704 )
705 value = value if isinstance(value, list) else [value]
706 for item in value:
707 if not isinstance(item, dict) or not (
708 "type" in item
709 and (
710 "data" in item
711 or "path" in item
712 or item["type"].endswith(".Link")
713 )
714 ):
715 continue
716 cls_ = load_class_from_string(item.pop("type"))
717 match = False
718 for type_ in artefact_nodes[i].types:
719 if issubclass(cls_, type_) or cls_ == type_:
720 match = True
721 break
722 if not match:
723 continue
724 item["name"] = name
725 if "path" in item and "path" not in cls_.model_fields:
726 item["data"] = item.pop("path")
727 if partition is not None:
728 item["partition"] = partition
729 try:
730 instance = cls_(**item)
731 if instance:
732 instance.source_file = item_file
733 data.append(instance)
734 except Exception as e:
735 traceback_error(
736 e,
737 f"Failed to load data item {name} from {item.get('data', '')}: {e}",
738 )
739 return data
740 except Exception as e:
741 traceback_error(e, verbose=True)
742 return list()
745def load_artefact(item: dict[str, Any]):
746 artefact_class = load_class_from_string(item.pop("type"))
748 return artefact_class(**item)