Predictors API
culicidaelab.predictors
    This package contains the predictor classes for the culicidaelab library.
__all__ = ['MosquitoClassifier', 'MosquitoDetector', 'MosquitoSegmenter', 'ModelWeightsManager']
  
      module-attribute
  
    
MosquitoClassifier
    Classifies mosquito species from an image.
This class provides methods to load a pre-trained model, predict species from single or batches of images, evaluate model performance, and visualize the classification results.
Attributes:
| Name | Type | Description | 
|---|---|---|
| arch | str | The model architecture (e.g., 'convnext_tiny'). | 
| data_dir | Path | The directory where datasets are stored. | 
| species_map | dict[int, str] | A mapping from class indices to species names. | 
| num_classes | int | The total number of species classes. | 
Source code in culicidaelab\predictors\classifier.py
                | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |  | 
settings = settings
  
      instance-attribute
  
    
predictor_type = predictor_type
  
      instance-attribute
  
    
backend = backend
  
      instance-attribute
  
    
config: PredictorConfig
  
      property
  
    Get the predictor configuration Pydantic model.
Returns:
| Name | Type | Description | 
|---|---|---|
| PredictorConfig | PredictorConfig | The configuration object for this predictor. | 
model_loaded: bool
  
      property
  
    Check if the model is loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| bool | bool | True if the model is loaded, False otherwise. | 
arch: str | None = self.config.model_arch
  
      instance-attribute
  
    
data_dir: Path = self.settings.dataset_dir
  
      instance-attribute
  
    
species_map: dict[int, str] = self.settings.species_config.species_map
  
      instance-attribute
  
    
labels_map: dict[str, str] = self.settings.species_config.class_to_full_name_map
  
      instance-attribute
  
    
num_classes: int = len(self.species_map)
  
      instance-attribute
  
    
__call__(input_data: InputDataType, **kwargs: Any) -> Any
    Convenience method that calls predict().
This allows the predictor instance to be called as a function.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | InputDataType | The input data for the prediction. | required | 
| **kwargs | Any | Additional arguments to pass to the  | {} | 
Returns:
| Name | Type | Description | 
|---|---|---|
| Any | Any | The result of the prediction. | 
Source code in culicidaelab\core\base_predictor.py
              
__enter__()
    Context manager entry.
Loads the model if it is not already loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance. | 
__exit__(exc_type, exc_val, exc_tb)
    Context manager exit.
This default implementation does nothing, but can be overridden to handle resource cleanup.
model_context()
    A context manager for temporary model loading.
Ensures the model is loaded upon entering the context and unloaded upon exiting if it was not loaded before. This is useful for managing memory in pipelines.
Yields:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance itself. | 
Example
with predictor.model_context(): ... predictions = predictor.predict(data)
Source code in culicidaelab\core\base_predictor.py
              
evaluate(ground_truth: GroundTruthType, prediction: PredictionType | None = None, input_data: InputDataType | None = None, **predict_kwargs: Any) -> dict[str, float]
    Evaluate a prediction against a ground truth.
Either prediction or input_data must be provided. If prediction
is provided, it is used directly. If prediction is None, input_data
is used to generate a new prediction.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth | GroundTruthType | The ground truth annotation. | required | 
| prediction | PredictionType | A pre-computed prediction. | None | 
| input_data | InputDataType | Input data to generate a prediction from, if one isn't provided. | None | 
| **predict_kwargs | Any | Additional arguments passed to the  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, float] | dict[str, float]: Dictionary containing evaluation metrics for a | 
| dict[str, float] | single item. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If neither  | 
Source code in culicidaelab\core\base_predictor.py
              
evaluate_batch(ground_truth_batch: Sequence[GroundTruthType], predictions_batch: Sequence[PredictionType] | None = None, input_data_batch: Sequence[InputDataType] | None = None, num_workers: int = 1, show_progress: bool = False, **predict_kwargs: Any) -> dict[str, Any]
    Evaluate on a batch of items using parallel processing.
Either predictions_batch or input_data_batch must be provided.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth_batch | Sequence[GroundTruthType] | List of corresponding ground truth annotations. | required | 
| predictions_batch | Sequence[PredictionType] | A pre-computed list of predictions. | None | 
| input_data_batch | Sequence[InputDataType] | List of input data to generate predictions from. | None | 
| num_workers | int | Number of parallel workers for calculating metrics. | 1 | 
| show_progress | bool | Whether to show a progress bar. | False | 
| **predict_kwargs | Any | Additional arguments passed to  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: Dictionary containing aggregated evaluation metrics. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If the number of predictions does not match the number of ground truths, or if required inputs are missing. | 
Source code in culicidaelab\core\base_predictor.py
              
get_model_info() -> dict[str, Any]
    Gets information about the loaded model.
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: A dictionary containing details about the model, such | 
| dict[str, Any] | as architecture, path, etc. | 
Source code in culicidaelab\core\base_predictor.py
              
load_model() -> None
    Delegates model loading to the configured backend.
Source code in culicidaelab\core\base_predictor.py
              
predict(input_data: InputDataType, **kwargs: Any) -> PredictionType
    Makes a prediction on a single input data sample.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | InputDataType | The input data (e.g., an image as a NumPy array) to make a prediction on. | required | 
| **kwargs | Any | Additional predictor-specific arguments. | {} | 
Returns:
| Name | Type | Description | 
|---|---|---|
| PredictionType | PredictionType | The prediction result, with a format specific to the | 
| PredictionType | predictor type. | 
Raises:
| Type | Description | 
|---|---|
| RuntimeError | If the model is not loaded before calling this method. | 
Source code in culicidaelab\core\base_predictor.py
              
predict_batch(input_data_batch: Sequence[InputDataType], show_progress: bool = False, **kwargs: Any) -> list[PredictionType]
    Makes predictions on a batch of inputs by delegating to the backend.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data_batch | Sequence[InputDataType] | A sequence of inputs. | required | 
| show_progress | bool | If True, displays a progress bar. | False | 
| **kwargs | Any | Additional arguments for the backend's  | {} | 
Returns:
| Type | Description | 
|---|---|
| list[PredictionType] | list[PredictionType]: A list of prediction results. | 
Source code in culicidaelab\core\base_predictor.py
              
unload_model() -> None
    
__init__(settings: Settings, predictor_type='classifier', mode: Literal['torch', 'serve'] | None = None, load_model: bool = False, backend: BaseInferenceBackend | None = None) -> None
    Initializes the MosquitoClassifier.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| settings | Settings | The main settings object for the library. | required | 
| predictor_type | The type of predictor. Defaults to "classifier". | 'classifier' | |
| mode | Literal['torch', 'serve'] | None | The mode to run the predictor in, 'torch' or 'serve'. If None, it's determined by the environment. | None | 
| load_model | bool | If True, load the model upon initialization. | False | 
| backend | BaseInferenceBackend | None | An optional backend instance. If not provided, one will be created based on the mode and settings. | None | 
Source code in culicidaelab\predictors\classifier.py
              
get_class_index(species_name: str) -> int | None
    Retrieves the class index for a given species name.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| species_name | str | The name of the species. | required | 
Returns:
| Type | Description | 
|---|---|
| int | None | The corresponding class index if found, otherwise None. | 
Source code in culicidaelab\predictors\classifier.py
              
get_species_names() -> list[str]
    Gets a sorted list of all species names known to the classifier.
The list is ordered by the class index.
Returns:
| Type | Description | 
|---|---|
| list[str] | A list of species names. | 
Source code in culicidaelab\predictors\classifier.py
              
            
visualize(input_data: ImageInput, predictions: ClassificationPrediction, save_path: str | Path | None = None) -> np.ndarray
    Creates a composite image with results and the input image.
This method generates a visualization by placing the top-k predictions in a separate panel to the left of the image.
Example
from culicidaelab.settings import Settings from culicidaelab.predictors import MosquitoClassifier
This example assumes you have a configured settings object
settings = Settings() classifier = MosquitoClassifier(settings, load_model=True) image = "path/to/your/image.jpg" prediction = classifier.predict(image) viz_image = classifier.visualize(image, prediction, save_path="viz.jpg")
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | ImageInput | The input image (NumPy array, path, or PIL Image). | required | 
| predictions | ClassificationPrediction | The prediction output from the  | required | 
| save_path | str | Path | None | If provided, the image is saved to this path. | None | 
Returns:
| Type | Description | 
|---|---|
| ndarray | A new image array containing the text panel and original image. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If the input data is invalid or predictions are empty. | 
| FileNotFoundError | If the image file path doesn't exist. | 
Source code in culicidaelab\predictors\classifier.py
              
visualize_report(report_data: dict[str, Any], save_path: str | Path | None = None) -> None
    Generates a visualization of the evaluation report.
This function creates a figure with a text summary of key performance metrics and a heatmap of the confusion matrix.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| report_data | dict[str, Any] | The evaluation report from the  | required | 
| save_path | str | Path | None | If provided, the figure is saved to this path. | None | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If  | 
Source code in culicidaelab\predictors\classifier.py
              | 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |  | 
MosquitoDetector
    Detects mosquitos in images using a YOLO model.
This class loads a model and provides methods for predicting bounding boxes on single or batches of images, visualizing results, and evaluating detection performance against ground truth data.
Attributes:
| Name | Type | Description | 
|---|---|---|
| confidence_threshold | float | The minimum confidence score for a detection to be considered valid. | 
| iou_threshold | float | The IoU threshold for non-maximum suppression. | 
| max_detections | int | The maximum number of detections to return per image. | 
Source code in culicidaelab\predictors\detector.py
                | 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |  | 
settings = settings
  
      instance-attribute
  
    
predictor_type = predictor_type
  
      instance-attribute
  
    
backend = backend
  
      instance-attribute
  
    
config: PredictorConfig
  
      property
  
    Get the predictor configuration Pydantic model.
Returns:
| Name | Type | Description | 
|---|---|---|
| PredictorConfig | PredictorConfig | The configuration object for this predictor. | 
model_loaded: bool
  
      property
  
    Check if the model is loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| bool | bool | True if the model is loaded, False otherwise. | 
confidence_threshold: float = self.config.confidence or 0.5
  
      instance-attribute
  
    
iou_threshold: float = self.config.params.get('iou_threshold', 0.45)
  
      instance-attribute
  
    
max_detections: int = self.config.params.get('max_detections', 300)
  
      instance-attribute
  
    
__call__(input_data: InputDataType, **kwargs: Any) -> Any
    Convenience method that calls predict().
This allows the predictor instance to be called as a function.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | InputDataType | The input data for the prediction. | required | 
| **kwargs | Any | Additional arguments to pass to the  | {} | 
Returns:
| Name | Type | Description | 
|---|---|---|
| Any | Any | The result of the prediction. | 
Source code in culicidaelab\core\base_predictor.py
              
__enter__()
    Context manager entry.
Loads the model if it is not already loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance. | 
__exit__(exc_type, exc_val, exc_tb)
    Context manager exit.
This default implementation does nothing, but can be overridden to handle resource cleanup.
model_context()
    A context manager for temporary model loading.
Ensures the model is loaded upon entering the context and unloaded upon exiting if it was not loaded before. This is useful for managing memory in pipelines.
Yields:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance itself. | 
Example
with predictor.model_context(): ... predictions = predictor.predict(data)
Source code in culicidaelab\core\base_predictor.py
              
evaluate(ground_truth: GroundTruthType, prediction: PredictionType | None = None, input_data: InputDataType | None = None, **predict_kwargs: Any) -> dict[str, float]
    Evaluate a prediction against a ground truth.
Either prediction or input_data must be provided. If prediction
is provided, it is used directly. If prediction is None, input_data
is used to generate a new prediction.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth | GroundTruthType | The ground truth annotation. | required | 
| prediction | PredictionType | A pre-computed prediction. | None | 
| input_data | InputDataType | Input data to generate a prediction from, if one isn't provided. | None | 
| **predict_kwargs | Any | Additional arguments passed to the  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, float] | dict[str, float]: Dictionary containing evaluation metrics for a | 
| dict[str, float] | single item. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If neither  | 
Source code in culicidaelab\core\base_predictor.py
              
evaluate_batch(ground_truth_batch: Sequence[GroundTruthType], predictions_batch: Sequence[PredictionType] | None = None, input_data_batch: Sequence[InputDataType] | None = None, num_workers: int = 1, show_progress: bool = False, **predict_kwargs: Any) -> dict[str, Any]
    Evaluate on a batch of items using parallel processing.
Either predictions_batch or input_data_batch must be provided.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth_batch | Sequence[GroundTruthType] | List of corresponding ground truth annotations. | required | 
| predictions_batch | Sequence[PredictionType] | A pre-computed list of predictions. | None | 
| input_data_batch | Sequence[InputDataType] | List of input data to generate predictions from. | None | 
| num_workers | int | Number of parallel workers for calculating metrics. | 1 | 
| show_progress | bool | Whether to show a progress bar. | False | 
| **predict_kwargs | Any | Additional arguments passed to  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: Dictionary containing aggregated evaluation metrics. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If the number of predictions does not match the number of ground truths, or if required inputs are missing. | 
Source code in culicidaelab\core\base_predictor.py
              
get_model_info() -> dict[str, Any]
    Gets information about the loaded model.
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: A dictionary containing details about the model, such | 
| dict[str, Any] | as architecture, path, etc. | 
Source code in culicidaelab\core\base_predictor.py
              
load_model() -> None
    Delegates model loading to the configured backend.
Source code in culicidaelab\core\base_predictor.py
              
predict_batch(input_data_batch: Sequence[InputDataType], show_progress: bool = False, **kwargs: Any) -> list[PredictionType]
    Makes predictions on a batch of inputs by delegating to the backend.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data_batch | Sequence[InputDataType] | A sequence of inputs. | required | 
| show_progress | bool | If True, displays a progress bar. | False | 
| **kwargs | Any | Additional arguments for the backend's  | {} | 
Returns:
| Type | Description | 
|---|---|
| list[PredictionType] | list[PredictionType]: A list of prediction results. | 
Source code in culicidaelab\core\base_predictor.py
              
unload_model() -> None
    
__init__(settings: Settings, predictor_type='detector', mode: Literal['torch', 'serve'] | None = None, load_model: bool = False, backend: BaseInferenceBackend | None = None) -> None
    Initializes the MosquitoDetector.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| settings | Settings | The main settings object for the library. | required | 
| predictor_type | The type of predictor. Defaults to "detector". | 'detector' | |
| mode | Literal['torch', 'serve'] | None | The mode to run the predictor in, 'torch' or 'serve'. If None, it's determined by the environment. | None | 
| load_model | bool | If True, load the model upon initialization. | False | 
| backend | BaseInferenceBackend | None | An optional backend instance. If not provided, one will be created based on the mode and settings. | None | 
Source code in culicidaelab\predictors\detector.py
              
predict(input_data: ImageInput, **kwargs: Any) -> DetectionPrediction
    Detects mosquitos in a single image.
Example
from culicidaelab.settings import Settings from culicidaelab.predictors import MosquitoDetector
This example assumes you have a configured settings object
settings = Settings() detector = MosquitoDetector(settings, load_model=True) image = "path/to/your/image.jpg" detections = detector.predict(image) for detection in detections.detections: ... print(detection.box, detection.confidence)
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | ImageInput | The input image as a NumPy array or other supported format. | required | 
| **kwargs | Any | Optional keyword arguments, including: confidence_threshold (float): Override the default confidence threshold for this prediction. | {} | 
Returns:
| Type | Description | 
|---|---|
| DetectionPrediction | A  | 
| DetectionPrediction | 
 | 
Raises:
| Type | Description | 
|---|---|
| RuntimeError | If the model fails to load or if prediction fails. | 
Source code in culicidaelab\predictors\detector.py
              
visualize(input_data: ImageInput, predictions: DetectionPrediction, save_path: str | Path | None = None) -> np.ndarray
    Draws predicted bounding boxes on an image.
Example
from culicidaelab.settings import Settings from culicidaelab.predictors import MosquitoDetector
This example assumes you have a configured settings object
settings = Settings() detector = MosquitoDetector(settings, load_model=True) image = "path/to/your/image.jpg" detections = detector.predict(image) viz_image = detector.visualize(image, detections, save_path="viz.jpg")
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | ImageInput | The original image. | required | 
| predictions | DetectionPrediction | The  | required | 
| save_path | str | Path | None | If provided, the output image is saved to this path. | None | 
Returns:
| Type | Description | 
|---|---|
| ndarray | A new image array with bounding boxes and confidence scores drawn on it. | 
Source code in culicidaelab\predictors\detector.py
              
MosquitoSegmenter
    Segments mosquitos in images using a SAM model.
This class provides methods to load a SAM model, generate segmentation masks for entire images or specific regions defined by bounding boxes, and visualize the resulting masks.
Example
from culicidaelab.core.settings import Settings from culicidaelab.predictors import MosquitoSegmenter import numpy as np
This example assumes you have a configured settings object
settings = Settings() segmenter = MosquitoSegmenter(settings, load_model=True) image = np.random.randint(0, 256, (1024, 1024, 3), dtype=np.uint8)
Predict without prompts (might not be effective for all backends)
prediction = segmenter.predict(image) print(f"Generated mask with {prediction.pixel_count} pixels.")
Source code in culicidaelab\predictors\segmenter.py
                | 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |  | 
settings = settings
  
      instance-attribute
  
    
predictor_type = predictor_type
  
      instance-attribute
  
    
backend = backend
  
      instance-attribute
  
    
config: PredictorConfig
  
      property
  
    Get the predictor configuration Pydantic model.
Returns:
| Name | Type | Description | 
|---|---|---|
| PredictorConfig | PredictorConfig | The configuration object for this predictor. | 
model_loaded: bool
  
      property
  
    Check if the model is loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| bool | bool | True if the model is loaded, False otherwise. | 
__call__(input_data: InputDataType, **kwargs: Any) -> Any
    Convenience method that calls predict().
This allows the predictor instance to be called as a function.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | InputDataType | The input data for the prediction. | required | 
| **kwargs | Any | Additional arguments to pass to the  | {} | 
Returns:
| Name | Type | Description | 
|---|---|---|
| Any | Any | The result of the prediction. | 
Source code in culicidaelab\core\base_predictor.py
              
__enter__()
    Context manager entry.
Loads the model if it is not already loaded.
Returns:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance. | 
__exit__(exc_type, exc_val, exc_tb)
    Context manager exit.
This default implementation does nothing, but can be overridden to handle resource cleanup.
model_context()
    A context manager for temporary model loading.
Ensures the model is loaded upon entering the context and unloaded upon exiting if it was not loaded before. This is useful for managing memory in pipelines.
Yields:
| Name | Type | Description | 
|---|---|---|
| BasePredictor | The predictor instance itself. | 
Example
with predictor.model_context(): ... predictions = predictor.predict(data)
Source code in culicidaelab\core\base_predictor.py
              
evaluate(ground_truth: GroundTruthType, prediction: PredictionType | None = None, input_data: InputDataType | None = None, **predict_kwargs: Any) -> dict[str, float]
    Evaluate a prediction against a ground truth.
Either prediction or input_data must be provided. If prediction
is provided, it is used directly. If prediction is None, input_data
is used to generate a new prediction.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth | GroundTruthType | The ground truth annotation. | required | 
| prediction | PredictionType | A pre-computed prediction. | None | 
| input_data | InputDataType | Input data to generate a prediction from, if one isn't provided. | None | 
| **predict_kwargs | Any | Additional arguments passed to the  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, float] | dict[str, float]: Dictionary containing evaluation metrics for a | 
| dict[str, float] | single item. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If neither  | 
Source code in culicidaelab\core\base_predictor.py
              
evaluate_batch(ground_truth_batch: Sequence[GroundTruthType], predictions_batch: Sequence[PredictionType] | None = None, input_data_batch: Sequence[InputDataType] | None = None, num_workers: int = 1, show_progress: bool = False, **predict_kwargs: Any) -> dict[str, Any]
    Evaluate on a batch of items using parallel processing.
Either predictions_batch or input_data_batch must be provided.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| ground_truth_batch | Sequence[GroundTruthType] | List of corresponding ground truth annotations. | required | 
| predictions_batch | Sequence[PredictionType] | A pre-computed list of predictions. | None | 
| input_data_batch | Sequence[InputDataType] | List of input data to generate predictions from. | None | 
| num_workers | int | Number of parallel workers for calculating metrics. | 1 | 
| show_progress | bool | Whether to show a progress bar. | False | 
| **predict_kwargs | Any | Additional arguments passed to  | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: Dictionary containing aggregated evaluation metrics. | 
Raises:
| Type | Description | 
|---|---|
| ValueError | If the number of predictions does not match the number of ground truths, or if required inputs are missing. | 
Source code in culicidaelab\core\base_predictor.py
              
get_model_info() -> dict[str, Any]
    Gets information about the loaded model.
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: A dictionary containing details about the model, such | 
| dict[str, Any] | as architecture, path, etc. | 
Source code in culicidaelab\core\base_predictor.py
              
load_model() -> None
    Delegates model loading to the configured backend.
Source code in culicidaelab\core\base_predictor.py
              
predict(input_data: InputDataType, **kwargs: Any) -> PredictionType
    Makes a prediction on a single input data sample.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | InputDataType | The input data (e.g., an image as a NumPy array) to make a prediction on. | required | 
| **kwargs | Any | Additional predictor-specific arguments. | {} | 
Returns:
| Name | Type | Description | 
|---|---|---|
| PredictionType | PredictionType | The prediction result, with a format specific to the | 
| PredictionType | predictor type. | 
Raises:
| Type | Description | 
|---|---|
| RuntimeError | If the model is not loaded before calling this method. | 
Source code in culicidaelab\core\base_predictor.py
              
predict_batch(input_data_batch: Sequence[InputDataType], show_progress: bool = False, **kwargs: Any) -> list[PredictionType]
    Makes predictions on a batch of inputs by delegating to the backend.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data_batch | Sequence[InputDataType] | A sequence of inputs. | required | 
| show_progress | bool | If True, displays a progress bar. | False | 
| **kwargs | Any | Additional arguments for the backend's  | {} | 
Returns:
| Type | Description | 
|---|---|
| list[PredictionType] | list[PredictionType]: A list of prediction results. | 
Source code in culicidaelab\core\base_predictor.py
              
unload_model() -> None
    
__init__(settings: Settings, predictor_type='segmenter', mode: Literal['torch', 'serve'] | None = None, load_model: bool = False, backend: BaseInferenceBackend | None = None) -> None
    Initializes the MosquitoSegmenter.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| settings | Settings | The main settings object for the library. | required | 
| predictor_type | The type of predictor. Defaults to "segmenter". | 'segmenter' | |
| mode | Literal['torch', 'serve'] | None | The mode to run the predictor in, 'torch' or 'serve'. If None, it's determined by the environment. | None | 
| load_model | bool | If True, load the model upon initialization. | False | 
| backend | BaseInferenceBackend | None | An optional backend instance. If not provided, one will be created based on the mode and settings. | None | 
Source code in culicidaelab\predictors\segmenter.py
              
visualize(input_data: ImageInput, predictions: SegmentationPrediction, save_path: str | Path | None = None) -> np.ndarray
    Overlays a segmentation mask on the original image.
Example
from culicidaelab.settings import Settings from culicidaelab.predictors import MosquitoSegmenter
This example assumes you have a configured settings object
settings = Settings() segmenter = MosquitoSegmenter(settings, load_model=True) image = "path/to/your/image.jpg"
Assuming you have a prediction from segmenter.predict()
prediction = segmenter.predict(image) viz_image = segmenter.visualize(image, prediction, save_path="viz.jpg")
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| input_data | ImageInput | The original image. | required | 
| predictions | SegmentationPrediction | The  | required | 
| save_path | str | Path | None | If provided, the output image is saved to this path. | None | 
Returns:
| Type | Description | 
|---|---|
| ndarray | A numpy array of the image with the segmentation mask overlaid. | 
Source code in culicidaelab\predictors\segmenter.py
              
ModelWeightsManager
    Manages the download and local availability of model weights.
This class implements the WeightsManagerProtocol and serves as the bridge between a predictor and the provider service that can download model files.
Attributes:
| Name | Type | Description | 
|---|---|---|
| settings | Settings | The application's global settings object. | 
| provider_service | ProviderService | The service used to access and download model weights from various providers. | 
Source code in culicidaelab\predictors\model_weights_manager.py
                
settings = settings
  
      instance-attribute
  
    
provider_service = ProviderService(settings)
  
      instance-attribute
  
    
__init__(settings: Settings)
    Initializes the ModelWeightsManager.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| settings | Settings | The application's global settings object. | required | 
Source code in culicidaelab\predictors\model_weights_manager.py
              
            
ensure_weights(predictor_type: str, backend_type: str) -> Path
    Ensures weights for a given predictor and backend are available.
This method checks if the model weights for the specified predictor and backend type exist locally. If they don't, it downloads them using the provider service.
Example
from culicidaelab.settings import Settings from culicidaelab.predictors import ModelWeightsManager
This example assumes you have a configured settings object
settings = Settings() manager = ModelWeightsManager(settings) weights_path = manager.ensure_weights("classifier", "torch") print(weights_path.exists()) True
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| predictor_type | str | The type of predictor (e.g., 'classifier'). | required | 
| backend_type | str | The type of backend (e.g., 'torch', 'onnx'). | required | 
Returns:
| Type | Description | 
|---|---|
| Path | The absolute path to the local model weights file. | 
Raises:
| Type | Description | 
|---|---|
| RuntimeError | If the weights cannot be resolved or downloaded. | 
| ValueError | If the configuration for the weights is missing 'repository_id' or 'filename'. | 
Source code in culicidaelab\predictors\model_weights_manager.py
              selection:
members: true