Coverage for collectra/tasks/machine_learning/class_names.py: 100.00%
15 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"""The class names a trained model was given, saved in a file beside its checkpoint.
3The file is YAML (``<checkpoint stem>.classes.yaml`` or ``classes.yaml``). The older
4JSON files with the same names are still read.
5"""
7from pathlib import Path
9import yaml
11SUFFIXES = (".yaml", ".json")
14def sidecar_candidates(checkpoint: Path) -> list[Path]:
15 """Where the class names for a checkpoint may be, most specific first."""
16 folder = Path(checkpoint).parent
17 stems = (f"{Path(checkpoint).stem}.classes", "classes")
18 return [folder / f"{stem}{suffix}" for stem in stems for suffix in SUFFIXES]
21def read_class_names(checkpoint: Path) -> list[str] | None:
22 """The class names saved beside ``checkpoint``, or None if there are none."""
23 for path in sidecar_candidates(checkpoint):
24 if path.exists():
25 # JSON is YAML, so one reader serves both.
26 data = yaml.safe_load(path.read_text()) or {}
27 return data.get("classes")
28 return None
31def write_class_names(path: Path, classes: list[str]) -> None:
32 """Save the class names, in order, as YAML."""
33 path.write_text(yaml.safe_dump({"classes": list(classes)}, sort_keys=False))