Coverage for collectra/tasks/object_detection/base.py: 100.00%
122 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"""What every object detector has in common.
3The detectors (YOLO, RF-DETR, DETR) share their settings, the way a setting
4given for one run beats the task's own, how old option names are still read,
5how a device is chosen, and how predictions for many images are made in batches
6and kept for ``run``. A backend adds only what is really its own.
7"""
9from __future__ import annotations
11import platform
12import warnings
13from pathlib import Path
14from typing import Annotated, Any, ClassVar
16from cappa import Arg
17from pydantic import Field, PrivateAttr, field_validator, model_validator
19from collectra.types.images import Image, ImageCrop, Orientation
20from collectra.utils import threading_locked
22from ..base import Task
23from .batching import image_cache_key
25# Command-line options the detectors share. Leaving one out keeps the task's
26# own setting (from pipeline.yaml, or the default).
27RunResolution = Annotated[
28 int | None,
29 Arg(
30 help="Image size in pixels to run at. Omit to use the one chosen for the task, or else the model's own."
31 ),
32]
33TrainResolution = Annotated[
34 int | None,
35 Arg(help="Image size in pixels to train at. Omit to use the task's setting."),
36]
37Threshold = Annotated[
38 float | None,
39 Arg(
40 help="Minimum confidence for a detection, from 0 to 1. Omit to use the task's setting."
41 ),
42]
43Epochs = Annotated[
44 int | None, Arg(help="Number of training epochs. Omit to use the task's setting.")
45]
46Batch = Annotated[
47 int | None,
48 Arg(help="Training batch size. Omit to use the task's setting."),
49]
50LearningRate = Annotated[
51 float | None, Arg(help="Learning rate. Omit to use the task's setting.")
52]
53WeightDecay = Annotated[
54 float | None,
55 Arg(help="Weight decay used for regularization. Omit to use the task's setting."),
56]
59class ObjectDetector(Task):
60 """Settings and behaviour shared by all object detectors.
62 Attributes:
63 resolution: Image size in pixels. Training uses it (1280 unless set).
64 Running uses it only when it was set explicitly, so a model keeps
65 the size it was trained with unless you ask for another.
66 threshold: Minimum confidence for a detection, from 0 to 1.
67 epochs: Number of training epochs.
68 batch: Training batch size.
69 learning_rate: Training learning rate.
70 weight_decay: Training weight decay.
71 orient: Output classes whose crops are oriented with an ImageOrienter.
72 orienter_model: The orientation checkpoint for ``orient``; without it
73 the published default model is used.
75 A backend overrides a default where its own library needs another value.
76 Names that used to be accepted (``imgsz``) are still read, with a warning.
77 """
79 resolution: int = Field(default=1280, gt=0)
80 threshold: float = Field(default=0.25, ge=0, le=1)
81 epochs: int = Field(default=100, ge=1)
82 batch: int = Field(default=4, ge=1)
83 learning_rate: float = Field(default=1e-4, gt=0)
84 weight_decay: float = Field(default=1e-4, ge=0)
85 orient: list[str] = Field(default_factory=list)
86 orienter_model: str | None = None
88 # Crops oriented in one pass of the orientation model.
89 ORIENT_BATCH: ClassVar[int] = 16
91 # Old name -> current name. A backend adds its own.
92 RENAMED_SETTINGS: ClassVar[dict[str, str]] = {"imgsz": "resolution"}
93 # Keys a pipeline entry has besides settings: they say what the task reads
94 # and writes, and are not mistakes.
95 WIRING: ClassVar[frozenset[str]] = frozenset({"input", "output"})
97 _prefetched: dict = PrivateAttr(default_factory=dict)
98 _orienter: Any = PrivateAttr(default=None)
100 @field_validator("orient", mode="before")
101 @classmethod
102 def _orient_one_class(cls, value: Any) -> Any:
103 return [value] if isinstance(value, str) else value
105 @model_validator(mode="before")
106 @classmethod
107 def _read_old_setting_names(cls, data: Any) -> Any:
108 if not isinstance(data, dict):
109 return data
110 data = dict(data)
111 for old, new in cls.RENAMED_SETTINGS.items():
112 if old not in data:
113 continue
114 if new in data:
115 raise ValueError(
116 f"{cls.__name__} was given both {old!r} and {new!r}; "
117 f"use only {new!r}"
118 )
119 warnings.warn(
120 f"{old!r} is deprecated; use {new!r} instead",
121 FutureWarning,
122 stacklevel=2,
123 )
124 data[new] = data.pop(old)
125 return data
127 def model_post_init(self, context: Any) -> None:
128 super().model_post_init(context)
129 unknown = sorted(set(self.model_extra or {}) - self.WIRING)
130 if unknown:
131 known = sorted(set(type(self).model_fields) - {"pipeline", "context"})
132 warnings.warn(
133 f"{type(self).__name__} {self.name!r} ignores unknown "
134 f"setting(s): {', '.join(unknown)}. Settings it understands: "
135 f"{', '.join(known)}",
136 UserWarning,
137 stacklevel=2,
138 )
139 outputs = getattr(self, "output", None)
140 outputs = [outputs] if isinstance(outputs, str) else outputs
141 missing = [name for name in self.orient if outputs and name not in outputs]
142 if missing:
143 raise ValueError(
144 f"{type(self).__name__} {self.name!r} cannot orient "
145 f"{', '.join(missing)}: not among its outputs ({', '.join(outputs)})"
146 )
148 # --- orienting crops -------------------------------------------------------------
150 def _get_orienter(self):
151 """The ImageOrienter for ``orient``, made once and loaded when first needed."""
152 if self._orienter is None:
153 from ..machine_learning.orienters import ImageOrienter
155 model = None
156 if self.orienter_model:
157 model = Path(self.orienter_model).expanduser()
158 if not model.is_absolute() and self.pipeline is not None:
159 model = Path(self.pipeline.path) / model
160 self._orienter = ImageOrienter(f"{self.name}_orienter", model=model)
161 self._orienter._init_model()
162 return self._orienter
164 def _orient_crops(self, crops: list[ImageCrop]) -> list[ImageCrop]:
165 """Orient the crops of the classes in ``orient``, in place; return ``crops``.
167 The orienter sees each crop as already turned by the orientation it
168 has (its image's), so the predicted turn is added to that one.
169 """
170 chosen = [crop for crop in crops if crop.name in self.orient]
171 if not chosen:
172 return crops
173 orienter = self._get_orienter()
174 for start in range(0, len(chosen), self.ORIENT_BATCH):
175 batch = chosen[start : start + self.ORIENT_BATCH]
176 for crop, turn in zip(batch, orienter._predict_batch(batch)):
177 crop.orientation = Orientation(
178 (crop.orientation.value + turn.value) % 4
179 )
180 return crops
182 # --- settings for one run -------------------------------------------------------
184 @property
185 def inference_resolution(self) -> int | None:
186 """The size to run at, or None to let the model use its own."""
187 return self.resolution if "resolution" in self.model_fields_set else None
189 def _settings_for_run(self, **given: Any) -> dict[str, Any]:
190 """Each value given for this run, else the task's own setting."""
191 return {
192 name: getattr(self, name) if value is None else value
193 for name, value in given.items()
194 }
196 @staticmethod
197 def _current_name(old: str, new: str, old_value: Any, new_value: Any) -> Any:
198 """The value of an option that has been renamed, from either name."""
199 if old_value is None:
200 return new_value
201 if new_value is not None:
202 raise ValueError(f"Give {new!r}, not both {old!r} and {new!r}")
203 warnings.warn(
204 f"{old!r} is deprecated; use {new!r} instead", FutureWarning, stacklevel=3
205 )
206 return old_value
208 def _select_device(self) -> str:
209 import torch
211 return (
212 "mps"
213 if platform.system() == "Darwin"
214 else "cuda" if torch.cuda.is_available() else "cpu"
215 )
217 # --- predicting many images at once ---------------------------------------------
219 def _predict_batch(self, images: list[Image]) -> list:
220 """Run the model over ``images`` together, one prediction each."""
221 raise NotImplementedError
223 def _before_prefetch(self) -> None:
224 """Called once before a prefetch; a backend can report its settings."""
226 def _prefetch_key(self, image: Image) -> tuple:
227 return image_cache_key(image, self.inference_resolution)
229 @threading_locked()
230 def prefetch(self, entries: list[list]) -> None:
231 """Run the model over many images in batches, caching results for ``run``.
233 A backend that does not predict in batches (it has no ``_predict_batch``)
234 does nothing here, and ``run`` predicts each image itself.
235 """
236 if type(self)._predict_batch is ObjectDetector._predict_batch:
237 return
238 self._init_model()
239 images = [
240 entry[0]
241 for entry in entries
242 if len(entry) == 1 and isinstance(entry[0], Image)
243 ]
244 self._prefetched = {}
245 self._before_prefetch()
246 for start in range(0, len(images), self.batch_size):
247 batch = images[start : start + self.batch_size]
248 for image, predicted in zip(batch, self._predict_batch(batch)):
249 self._prefetched[self._prefetch_key(image)] = predicted
251 def clear_prefetch(self) -> None:
252 self._prefetched = {}
254 def _take_prefetched(self, image: Image):
255 """The cached prediction for ``image``, if prefetch made one."""
256 return self._prefetched.pop(self._prefetch_key(image), None)
258 def _init_model(self) -> None:
259 raise NotImplementedError
262# The former name of ObjectDetector.
263ObjectDetectionTask = ObjectDetector