API Reference¶
Application Domain & Data¶
app.domain.categories
¶
Domain models and canonical category definitions for the MVTec AD dataset.
Provides centralized category constants, semantic splits (objects vs textures), and dynamic dataset discovery utilities.
ANOMALY_DINO_MASKED_CATEGORIES: frozenset[str] = frozenset({'capsule', 'hazelnut', 'pill', 'screw', 'toothbrush'})
module-attribute
¶
Categories where background suppression/masking improves DINO representation.
MVTEC_CATEGORIES: tuple[str, ...] = tuple(sorted(MVTEC_OBJECT_CATEGORIES + MVTEC_TEXTURE_CATEGORIES))
module-attribute
¶
All 15 official canonical benchmark categories of the MVTec AD dataset.
MVTEC_OBJECT_CATEGORIES: tuple[str, ...] = ('bottle', 'cable', 'capsule', 'hazelnut', 'metal_nut', 'pill', 'screw', 'toothbrush', 'transistor', 'zipper')
module-attribute
¶
Rigid industrial object categories in MVTec AD requiring orientation preservation.
MVTEC_TEXTURE_CATEGORIES: tuple[str, ...] = ('carpet', 'grid', 'leather', 'tile', 'wood')
module-attribute
¶
Spatially invariant surface texture categories in MVTec AD.
OBJECT_CATEGORIES: frozenset[str] = frozenset(MVTEC_OBJECT_CATEGORIES)
module-attribute
¶
Set representation of rigid object categories for fast O(1) membership checks.
TEXTURE_CATEGORIES: frozenset[str] = frozenset(MVTEC_TEXTURE_CATEGORIES)
module-attribute
¶
Set representation of surface texture categories for fast O(1) membership checks.
discover_dataset_categories(data_root: str | Path | None = None) -> list[str]
¶
Discover available MVTec categories dynamically from a dataset root directory.
If the specified directory exists and contains category subfolders, this function returns a sorted list of discovered folder names. If the directory does not exist, is unreadable, or contains no valid subfolders, it safely falls back to the canonical 15 MVTec AD benchmark categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
str | Path | None
|
Path or string pointing to the dataset root folder. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted list of discovered or fallback category names. |
Source code in app/domain/categories.py
app.domain.data
¶
Dataset helpers shared by modelling experiments.
FairEvaluationSplit
dataclass
¶
Shared fitting, validation, and test partitions for one MVTec category.
Source code in app/domain/data.py
fitting_paths: list[str]
property
¶
Return fitting paths in their protocol-defined order.
test_paths: list[str]
property
¶
Return official test paths in their protocol-defined order.
validation_paths: list[str]
property
¶
Return validation paths in their protocol-defined order.
evidence() -> dict[str, Any]
¶
Return serialisable protocol evidence for hashes and metadata.
Source code in app/domain/data.py
MVTecImageDataset
¶
Bases: Dataset[tuple[Tensor, int, str]]
Load manifest images as (tensor, anomaly label, path) tuples.
Attributes:
| Name | Type | Description |
|---|---|---|
frame |
Manifest rows containing |
|
transform |
Callable converting an RGB PIL image to a tensor. |
Source code in app/domain/data.py
__getitem__(index: int) -> tuple[Tensor, int, str]
¶
Load and transform one image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
The index of the image to load. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, int, str]
|
A tuple containing the transformed image tensor, the anomaly label, and the path to the image. |
Source code in app/domain/data.py
__init__(frame: pd.DataFrame, transform: Callable[[Image.Image], Tensor]) -> None
¶
Initialize the dataset from a manifest subset and image transform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Manifest rows containing |
required |
transform
|
Callable[[Image], Tensor]
|
Callable converting an RGB PIL image to a tensor. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a required manifest column is missing. |
Source code in app/domain/data.py
build_fair_evaluation_split(manifest: pd.DataFrame, category: str, *, validation_fraction: float = FAIR_EVALUATION_VALIDATION_FRACTION, seed: int = FAIR_EVALUATION_SPLIT_SEED) -> FairEvaluationSplit
¶
Build the deterministic shared baseline-evaluation split.
Only official normal training rows may enter fitting or validation. Official test rows retain the manifest's existing deterministic order.
Source code in app/domain/data.py
build_mvtec_manifest(root: str | Path) -> pd.DataFrame
¶
Build a deterministic manifest of MVTec AD train and test images.
Ground-truth masks are linked through mask_path rather than included as
samples. A missing mask is represented by None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
Directory containing MVTec product directories. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per input image. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the dataset root does not exist. |
NotADirectoryError
|
If the dataset root is not a directory. |
ValueError
|
If an image is unreadable or no images are found. |
Source code in app/domain/data.py
create_mvtec_dataset(manifest: pd.DataFrame, preprocessing_steps: list[dict[str, Any]] | None = None, image_size: tuple[int, int] = (256, 256)) -> MVTecImageDataset
¶
Create an MVTecImageDataset from a manifest and preprocessing steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
manifest
|
DataFrame
|
The manifest DataFrame. |
required |
preprocessing_steps
|
list[dict[str, Any]] | None
|
A list of preprocessing steps. |
None
|
image_size
|
tuple[int, int]
|
The size of the images. |
(256, 256)
|
Returns:
| Type | Description |
|---|---|
MVTecImageDataset
|
An MVTecImageDataset. |
Source code in app/domain/data.py
Command Line Interface¶
app.cli
¶
A command line interface for running pipelines.
This module provides a CLI for running different anomaly detection pipelines.
main() -> None
¶
Run the main CLI.
Source code in app/cli.py
preprocess_sys_argv() -> None
¶
Preprocess sys.argv to convert key=value positional args to --key value flags.
Source code in app/cli.py
Modelling Pipelines¶
app.pipelines.modelling.patchcore
¶
Canonical PatchCore modelling pipeline subpackage.
BaselineResult
¶
Bases: TypedDict
Schema for overall PatchCore execution results.
Attributes:
| Name | Type | Description |
|---|---|---|
category |
str
|
The specific category being evaluated. |
image_level |
MetricLevelResult
|
Image-level evaluation metrics. |
pixel_level |
MetricLevelResult
|
Pixel-level evaluation metrics. |
raw_results |
dict[str, float]
|
Raw evaluation results from the Anomalib engine. |
heatmap_overlays |
dict[int, dict[str, list[Any]]]
|
Dictionary of generated heatmap overlays. |
anomalous_indices |
list[int]
|
List of test dataset indices that are anomalous. |
preprocessing_steps |
list[dict[str, Any]]
|
List of active preprocessing step configurations. |
hyperparameters |
dict[str, Any]
|
Dictionary of model hyperparameters. |
dataset_split |
dict[str, Any]
|
Dictionary of dataset partition sample counts. |
model_hash |
str
|
Unique 12-char model hash. |
metadata |
dict[str, Any]
|
Full metadata dictionary. |
Source code in app/domain/evaluation.py
ConfusionMatrix
dataclass
¶
Confusion counts for anomalous detection at calibrated threshold.
Attributes:
| Name | Type | Description |
|---|---|---|
true_positives |
int
|
Count of correctly identified defective components. |
false_positives |
int
|
Count of healthy components incorrectly flagged. |
false_negatives |
int
|
Count of defective components missed. |
true_negatives |
int
|
Count of healthy components correctly identified. |
Source code in app/domain/evaluation.py
EvaluationArtifacts
dataclass
¶
Structured evaluation artifacts, metrics, and visual overlays.
Attributes:
| Name | Type | Description |
|---|---|---|
image_metrics |
ImageEvaluationMetrics
|
Detailed image-level classification performance metrics. |
pixel_metrics |
PixelEvaluationMetrics
|
Detailed pixel-level localization performance metrics. |
thresholds |
Thresholds
|
Calibrated frozen thresholds. |
heatmap_overlays |
dict[int, dict[str, list[Any]]]
|
Dictionary mapping test indices to overlay visual arrays. |
anomalous_indices |
list[int]
|
List of test dataset indices that are ground-truth anomalous. |
Source code in app/domain/evaluation.py
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 | |
__getitem__(index: int | slice) -> Any
¶
__iter__() -> Iterator[Any]
¶
Support backwards-compatible unpacking into the legacy 18-tuple.
Source code in app/domain/evaluation.py
__len__() -> int
¶
from_tuple(values: Any) -> EvaluationArtifacts
classmethod
¶
Construct EvaluationArtifacts from a legacy 18-element tuple or return if already EvaluationArtifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
An EvaluationArtifacts instance or a sequence of 18 values matching the legacy tuple layout. |
required |
Returns:
| Type | Description |
|---|---|
EvaluationArtifacts
|
An EvaluationArtifacts instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If values is not an EvaluationArtifacts and does not have exactly 18 elements. |
Source code in app/domain/evaluation.py
FairEvaluationSplit
dataclass
¶
Shared fitting, validation, and test partitions for one MVTec category.
Source code in app/domain/data.py
fitting_paths: list[str]
property
¶
Return fitting paths in their protocol-defined order.
test_paths: list[str]
property
¶
Return official test paths in their protocol-defined order.
validation_paths: list[str]
property
¶
Return validation paths in their protocol-defined order.
evidence() -> dict[str, Any]
¶
Return serialisable protocol evidence for hashes and metadata.
Source code in app/domain/data.py
ImageEvaluationMetrics
dataclass
¶
Image-level anomaly classification metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
auroc |
float
|
Area under the Receiver Operating Characteristic curve. |
f1_score |
float
|
Harmonic mean of precision and recall at calibrated threshold. |
precision |
float
|
Fraction of flagged components that are truly defective. |
recall |
float
|
Fraction of defective components correctly detected. |
threshold |
float
|
Frozen classification threshold applied. |
confusion |
ConfusionMatrix
|
Full confusion matrix counts. |
Source code in app/domain/evaluation.py
MetricLevelResult
¶
Bases: TypedDict
Schema for individual evaluation level metrics (image or pixel).
Attributes:
| Name | Type | Description |
|---|---|---|
auroc |
float
|
Area Under the Receiver Operating Characteristic Curve. |
average_precision |
float
|
Average Precision score. |
f1_score |
float
|
F1 score for the given metric level. |
precision |
float
|
Precision score. |
recall |
float
|
Recall score. |
threshold |
float
|
Decision threshold for classification. |
aupimo_score |
float
|
Integrated AUPIMO score. |
fpr_lower_bound |
float
|
Lower bound for FPR integration. |
fpr_upper_bound |
float
|
Upper bound for FPR integration. |
aupimo |
float
|
AUPIMO score. |
anomaly_map_min |
float
|
Minimum anomaly-map score over the test set. |
anomaly_map_max |
float
|
Maximum anomaly-map score over the test set. |
anomaly_map_range |
float
|
Difference between maximum and minimum map scores. |
metrics_path |
str
|
Path to the .npz file containing precision, recall, and thresholds. |
true_positives |
int
|
Count of true positive predictions. |
false_positives |
int
|
Count of false positive predictions. |
false_negatives |
int
|
Count of false negative predictions. |
true_negatives |
int
|
Count of true negative predictions. |
aupimo_num_thresholds |
int
|
Number of thresholds used in AUPIMO integration. |
canonical_height |
int
|
Canonical evaluation map height. |
canonical_width |
int
|
Canonical evaluation map width. |
Source code in app/domain/evaluation.py
PixelEvaluationMetrics
dataclass
¶
Pixel-level anomaly localization metrics computed on canonical 256x256 grids.
Attributes:
| Name | Type | Description |
|---|---|---|
auroc |
float
|
Pixel-level Area under the ROC curve. |
aupimo |
float
|
Strict Area under the Per-Image Overlap curve within standard bounds. |
f1_score |
float
|
Pixel-level binary segmentation F1 score. |
threshold |
float
|
Frozen segmentation threshold applied. |
anomaly_map_min |
float
|
Minimum raw continuous score over test set. |
anomaly_map_max |
float
|
Maximum raw continuous score over test set. |
anomaly_map_range |
float
|
Continuous score spread (max - min). |
Source code in app/domain/evaluation.py
Thresholds
dataclass
¶
Calibrated decision thresholds calibrated strictly on normal validation partition.
Attributes:
| Name | Type | Description |
|---|---|---|
image |
float
|
Image-level continuous score classification threshold. |
pixel |
float
|
Pixel-level anomaly map localization threshold. |
Source code in app/domain/evaluation.py
build_fair_evaluation_split(manifest: pd.DataFrame, category: str, *, validation_fraction: float = FAIR_EVALUATION_VALIDATION_FRACTION, seed: int = FAIR_EVALUATION_SPLIT_SEED) -> FairEvaluationSplit
¶
Build the deterministic shared baseline-evaluation split.
Only official normal training rows may enter fitting or validation. Official test rows retain the manifest's existing deterministic order.
Source code in app/domain/data.py
build_mvtec_manifest(root: str | Path) -> pd.DataFrame
¶
Build a deterministic manifest of MVTec AD train and test images.
Ground-truth masks are linked through mask_path rather than included as
samples. A missing mask is represented by None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
Directory containing MVTec product directories. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per input image. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the dataset root does not exist. |
NotADirectoryError
|
If the dataset root is not a directory. |
ValueError
|
If an image is unreadable or no images are found. |
Source code in app/domain/data.py
delete_cached_patchcore_model(model_hash: str, registry_base: str | Path, soft_delete: bool = True) -> bool
¶
Delete or move one cached model artifact directory to trash.
Source code in app/core/registry.py
extract_and_save_pr_metrics(engine: Engine, model: Any, validation_dataloader: Any, test_dataloader: Any, base_dir: Path, run_heatmap: bool = False, model_name: str = 'PatchCore') -> EvaluationArtifacts
¶
Extract model predictions and persist Precision-Recall metrics for visual analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
Engine
|
Anomalib engine instance. |
required |
model
|
Any
|
Trained model. |
required |
validation_dataloader
|
Any
|
Loader containing only shared normal validation images. |
required |
test_dataloader
|
Any
|
Loader containing the unchanged official test partition. |
required |
base_dir
|
Path
|
Output directory for metrics. |
required |
run_heatmap
|
bool
|
Whether to compute heatmap overlays. |
False
|
model_name
|
str
|
Human-readable model name used in diagnostics. |
'PatchCore'
|
Returns:
| Type | Description |
|---|---|
EvaluationArtifacts
|
Structured EvaluationArtifacts container (also unpackable as 18-tuple for backward compatibility). |
Source code in app/pipelines/modelling/patchcore/evaluation.py
find_cached_patchcore_model(category: str, backbone: str = 'resnet18', feature_layers: tuple[str, ...] = ('layer2', 'layer3'), coreset_sampling_ratio: float = 0.1, num_neighbors: int = 9, fpr_limit: float = 0.0001, pipeline: list[dict[str, Any]] | None = None, target_hash: str | None = None, registry_base: Path | str = 'data/models/patchcore', expected_split_evidence: dict[str, Any] | None = None) -> tuple[Path, dict[str, Any]] | None
¶
Find the newest cached PatchCore model matching either a specific hash or the given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
Component category name. |
required |
backbone
|
str
|
Feature extractor backbone name. |
'resnet18'
|
feature_layers
|
tuple[str, ...]
|
Layers to extract features from. |
('layer2', 'layer3')
|
coreset_sampling_ratio
|
float
|
Ratio for coreset subsampling. |
0.1
|
num_neighbors
|
int
|
Number of nearest neighbors for scoring. |
9
|
fpr_limit
|
float
|
Max allowable False Positive Rate. |
0.0001
|
pipeline
|
list[dict[str, Any]] | None
|
Optional preprocessing pipeline configuration. |
None
|
target_hash
|
str | None
|
Optional exact model hash to search for. |
None
|
registry_base
|
Path | str
|
Path to the patchcore model registry. |
'data/models/patchcore'
|
expected_split_evidence
|
dict[str, Any] | None
|
Required fair-protocol split evidence, when evaluating a cache hit. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Path, dict[str, Any]] | None
|
Tuple of (model_dir, metadata_dict) if found, else None. |
Source code in app/pipelines/modelling/patchcore/registry.py
format_results(test_results: list[Mapping[str, float]] | None, category: str, base_dir: Path, manual_image_f1: float = 0.0, manual_pixel_f1: float = 0.0, manual_image_prec: float = 0.0, manual_image_rec: float = 0.0, img_threshold: float = 0.0, pixel_threshold: float = 0.0, pixel_auroc: float = 0.0, pixel_aupimo: float = 0.0, anomaly_map_min: float = 0.0, anomaly_map_max: float = 0.0, anomaly_map_range: float = 0.0, heatmap_overlays: dict[int, dict[str, list[Any]]] | None = None, anomalous_indices: list[int] | None = None, fpr_limit: float = 0.0001, preprocessing_steps: list[dict[str, Any]] | None = None, hyperparameters: dict[str, Any] | None = None, dataset_split: dict[str, Any] | None = None, model_hash: str = '', metadata: dict[str, Any] | None = None, true_positives: int = 0, false_positives: int = 0, false_negatives: int = 0, true_negatives: int = 0, artifacts: EvaluationArtifacts | None = None) -> BaselineResult
¶
Format Anomalib engine evaluation output into a structured response schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_results
|
list[Mapping[str, float]] | None
|
A list of metric mappings from Anomalib. |
required |
category
|
str
|
The component category name. |
required |
base_dir
|
Path
|
Base directory to save metrics to. |
required |
manual_image_f1
|
float
|
Manually calculated image-level F1 score. |
0.0
|
manual_pixel_f1
|
float
|
Manually calculated pixel-level F1 score. |
0.0
|
manual_image_prec
|
float
|
Manually calculated image-level Precision score. |
0.0
|
manual_image_rec
|
float
|
Manually calculated image-level Recall score. |
0.0
|
img_threshold
|
float
|
Manually calculated image-level classification threshold. |
0.0
|
pixel_threshold
|
float
|
Normal-validation threshold used to create predicted masks. |
0.0
|
pixel_auroc
|
float
|
Pixel AUROC from the shared canonical metric path. |
0.0
|
pixel_aupimo
|
float
|
Full-map AUPIMO computed by Anomalib. |
0.0
|
anomaly_map_min
|
float
|
Minimum PatchCore anomaly-map value. |
0.0
|
anomaly_map_max
|
float
|
Maximum PatchCore anomaly-map value. |
0.0
|
anomaly_map_range
|
float
|
Range of PatchCore anomaly-map values. |
0.0
|
heatmap_overlays
|
dict[int, dict[str, list[Any]]] | None
|
Dictionary of precomputed heatmap overlays. |
None
|
anomalous_indices
|
list[int] | None
|
List of image indices corresponding to anomalies. |
None
|
fpr_limit
|
float
|
Maximum allowable False Positive Rate for AUPIMO threshold. |
0.0001
|
preprocessing_steps
|
list[dict[str, Any]] | None
|
Optional list of active preprocessing steps. |
None
|
hyperparameters
|
dict[str, Any] | None
|
Optional dictionary of model hyperparameters. |
None
|
dataset_split
|
dict[str, Any] | None
|
Optional dataset partition sample counts. |
None
|
model_hash
|
str
|
Unique 12-char model hash. |
''
|
metadata
|
dict[str, Any] | None
|
Full metadata dictionary. |
None
|
true_positives
|
int
|
Image-level true-positive count. |
0
|
false_positives
|
int
|
Image-level false-positive count. |
0
|
false_negatives
|
int
|
Image-level false-negative count. |
0
|
true_negatives
|
int
|
Image-level true-negative count. |
0
|
artifacts
|
EvaluationArtifacts | None
|
Optional strongly-typed EvaluationArtifacts container. If passed, individual metric values are automatically derived from it. |
None
|
Returns:
| Type | Description |
|---|---|
BaselineResult
|
A dictionary containing structured image_level and pixel_level results. |
Source code in app/pipelines/modelling/patchcore/evaluation.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
list_trashed_patchcore_models(registry_base: str | Path) -> list[dict[str, Any]]
¶
Return metadata for all artifact directories in trash.
Source code in app/core/registry.py
purge_patchcore_trash(registry_base: str | Path, model_hash: str | None = None) -> int
¶
Permanently remove cached artifact directorie(s) in trash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry_base
|
str | Path
|
Base directory for the registry. |
required |
model_hash
|
str | None
|
Optional specific model hash to purge. If None, all trash is purged. |
None
|
Source code in app/core/registry.py
restore_cached_patchcore_model(model_hash: str, registry_base: str | Path) -> bool
¶
Restore one soft-deleted artifact directory.
Source code in app/core/registry.py
run_patchcore_pipeline(data_root: Path | str = 'data/raw/mvtec_ad', category: str = 'bottle', pipeline: list[dict[str, Any]] | PreprocessingPipeline | None = None, fpr_limit: float = 0.0001, backbone: str = 'resnet18', feature_layers: tuple[str, ...] = ('layer2', 'layer3'), coreset_sampling_ratio: float = 0.1, num_neighbors: int = 9, run_heatmap: bool = False, force_retrain: bool = False, model_hash: str | None = None, registry_base: Path | str = 'data/models/patchcore', model_seed: int = PATCHCORE_MODEL_SEED) -> BaselineResult
¶
Run the PatchCore anomaly detection pipeline on the MVTec AD dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
Path | str
|
Root directory of MVTec AD. |
'data/raw/mvtec_ad'
|
category
|
str
|
Category to evaluate. |
'bottle'
|
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Optional list of preprocessing step configurations or pipeline. |
None
|
fpr_limit
|
float
|
Maximum allowable False Positive Rate. |
0.0001
|
backbone
|
str
|
Feature extractor backbone (e.g. 'resnet18', 'wide_resnet50_2'). |
'resnet18'
|
feature_layers
|
tuple[str, ...]
|
Layers to extract features from. |
('layer2', 'layer3')
|
coreset_sampling_ratio
|
float
|
Ratio for coreset subsampling. |
0.1
|
num_neighbors
|
int
|
Number of nearest neighbors for scoring. |
9
|
run_heatmap
|
bool
|
Whether to compute heatmap overlays. |
False
|
force_retrain
|
bool
|
If True, ignores cache and forces a full re-fit. |
False
|
model_hash
|
str | None
|
Optional target model hash to search for. |
None
|
registry_base
|
Path | str
|
Base directory path for Patchcore model registry. |
'data/models/patchcore'
|
model_seed
|
int
|
Seed controlling PatchCore coreset sampling and data-loader workers. |
PATCHCORE_MODEL_SEED
|
Returns:
| Type | Description |
|---|---|
BaselineResult
|
Structured evaluation metrics conforming to fair-eval-v1. |
Source code in app/pipelines/modelling/patchcore/pipeline.py
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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
app.pipelines.modelling.patchcore.optuna_study
¶
Category-Adaptive Optuna Optimization for PatchCore.
Performs Bayesian hyperparameter sweeps across backbone architectures, feature extraction layers, coreset sampling ratios, and domain preprocessing.
objective(trial: optuna.Trial, category_name: str, data_root: str = 'data/raw/mvtec_ad') -> float
¶
Optuna objective function for tuning PatchCore hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trial
|
Trial
|
Active Optuna trial instance. |
required |
category_name
|
str
|
MVTec AD category string. |
required |
data_root
|
str
|
Root dataset folder path. |
'data/raw/mvtec_ad'
|
Returns:
| Type | Description |
|---|---|
float
|
Objective evaluation metric score for the trial. |
Source code in app/pipelines/modelling/patchcore/optuna_study.py
run_study(category_name: str, n_trials: int = 30, data_root: str = 'data/raw/mvtec_ad') -> dict[str, Any]
¶
Execute Optuna optimization study for PatchCore on a specific category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_name
|
str
|
Target category to tune. |
required |
n_trials
|
int
|
Maximum number of trials to evaluate. |
30
|
data_root
|
str
|
Dataset root directory path. |
'data/raw/mvtec_ad'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Structured configuration dictionary of the best hyperparameter settings found. |
Source code in app/pipelines/modelling/patchcore/optuna_study.py
app.pipelines.modelling.keras_cae.cae_pipeline
¶
End-to-end orchestrator for the Keras Convolutional Autoencoder (CAE) pipeline.
Coordinates the complete anomaly detection workflow for MVTec AD categories under
the deterministic fair-eval-v1 evaluation protocol:
1. Data Loading & Partitioning: Loads dataset manifests and partitions normal
samples into 85% fit and 15% validation subsets with zero test leakage.
2. Preprocessing & Patching: Applies optional filters (CLAHE, blur, foreground
masks) and extracts sliding-window crops.
3. CAE Modeling: Builds and trains a convolutional autoencoder using Masked
Image Modeling (MIM) with joint SSIM and MSE reconstruction loss.
4. Scoring & Calibration: Generates pixel error maps, aggregates image scores
via Top-K spatial pooling, and calibrates decision thresholds strictly on
normal validation data.
5. Evaluation & Persistence: Computes canonical image AUROC, strict AUPIMO,
confusion matrices, and heatmaps, with deterministic caching and soft-delete
trash management.
run_keras_cae_pipeline(data_root: str = 'data/raw/mvtec_ad', category: str = 'bottle', img_size: int = 256, crop_size: int = 64, crop_stride: int = 32, latent_channels: int = 32, epochs: int = 20, batch_size: int = 16, mask_ratio: float = 0.25, mask_patch_size: int = 8, threshold_method: str = 'quantile', k_fraction: float = 0.002, pipeline: list[dict[str, Any]] | PreprocessingPipeline | None = None, run_heatmap: bool = False, force_retrain: bool = False, model_hash: str | None = None, trial: Any | None = None) -> dict[str, Any]
¶
Run the complete Keras CAE anomaly detection pipeline for one MVTec category.
This is the main entry point called by the Streamlit application. It: 1. Resolves cached model or configures new training parameters. 2. Loads train (normal only) and test images as numpy arrays using exact parameters. 3. Applies modular preprocessing transforms consistent with model state. 4. Normalises images to [0, 1]. 5. Builds and trains the Keras CAE with MIM + SSIM+MSE + AdamW (or loads from cache). 6. Scores all test images using Top-K pooling. 7. Computes an adaptive threshold from normal validation scores. 8. Evaluates with image-level AUROC and pixel-level AUPIMO. 9. Optionally computes Reconstruction Error Heatmap overlays for every anomalous test image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
str
|
Path to the MVTec AD dataset root directory. |
'data/raw/mvtec_ad'
|
category
|
str
|
MVTec category to train and evaluate on (e.g., 'bottle', 'wood'). |
'bottle'
|
img_size
|
int
|
Size (height and width) to resize base images to. |
256
|
crop_size
|
int
|
Size of the sliding window crops extracted from the base image. |
64
|
crop_stride
|
int
|
Stride of the sliding window. |
32
|
latent_channels
|
int
|
Number of channels in the convolutional bottleneck. |
32
|
epochs
|
int
|
Number of training epochs. |
20
|
batch_size
|
int
|
Training batch size (number of crops, not full images). |
16
|
mask_ratio
|
float
|
Fraction of patches to mask during Masked Image Modeling training. |
0.25
|
mask_patch_size
|
int
|
Side length of each masked region within a crop. |
8
|
threshold_method
|
str
|
|
'quantile'
|
k_fraction
|
float
|
Top-K fraction for image-level anomaly score pooling. |
0.002
|
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Optional configuration list or PreprocessingPipeline object. |
None
|
run_heatmap
|
bool
|
Whether to compute Reconstruction Error heatmap overlays for anomalous images. |
False
|
force_retrain
|
bool
|
If True, bypass the cache and force training of a new model. |
False
|
model_hash
|
str | None
|
Optional specific model hash to load directly from registry. |
None
|
trial
|
Any | None
|
Optional Optuna trial for hyperparameter optimization and pruning. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with all results (metrics, scores, heatmap, optional anomaly heatmaps). |
Source code in app/pipelines/modelling/keras_cae/cae_pipeline.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | |
app.pipelines.modelling.keras_cae.optuna_study
¶
objective(trial: optuna.Trial, category_name: str, data_root: str = 'data/raw/mvtec_ad') -> float
¶
Optuna objective function for optimizing Keras CAE hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trial
|
Trial
|
Optuna trial object. |
required |
category_name
|
str
|
MVTec category name to optimize. |
required |
data_root
|
str
|
Path to the MVTec AD dataset. |
'data/raw/mvtec_ad'
|
Returns:
| Type | Description |
|---|---|
float
|
Pixel AUPIMO score to maximize. |
Source code in app/pipelines/modelling/keras_cae/optuna_study.py
run_study(category_name: str, n_trials: int = 15, data_root: str = 'data/raw/mvtec_ad') -> dict[str, Any]
¶
Run the Optuna study and save the best parameters.
This function uses Optuna to find the best hyperparameters for the Keras CAE model for a specific MVTec AD category. It uses the fair-eval-v1 protocol to evaluate the model and prunes trials that are unlikely to yield good results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_name
|
str
|
MVTec category name to optimize. |
required |
n_trials
|
int
|
Number of trials to run (default: 15). |
15
|
data_root
|
str
|
Path to the MVTec AD dataset. |
'data/raw/mvtec_ad'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Best parameters dictionary. |
Source code in app/pipelines/modelling/keras_cae/optuna_study.py
app.pipelines.modelling.dino.v2
¶
Frozen DINOv2 patch-token nearest-neighbour baseline for MVTec AD.
run_dinov2_baseline(data_root: Path | str = 'data/raw/mvtec_ad', category: str = 'bottle', pipeline: list[dict[str, Any]] | PreprocessingPipeline | None = None, fpr_limit: float = 0.0001, encoder_name: str = DINO_V2_ENCODER, num_neighbors: int = 1, masking: MaskingMode = 'published', run_heatmap: bool = False, preprocessing_steps: list[dict[str, Any]] | None = None, registry_base: Path | str = 'data/models/dinov2', model_seed: int = PATCHCORE_MODEL_SEED, variant: DINOVariant = 'baseline', feature_layers: tuple[int, ...] = ENHANCED_DINO_LAYERS, position_radius: int = 1, spatial_weight: float = 0.05, density_neighbors: int = 5, reuse_complete: bool = False) -> BaselineResult | AllCategoriesResult
¶
Run one MVTec category or all canonical categories with frozen DINOv2.
category="all" orchestrates sequential evaluation across all 15 categories,
ensuring each receives its fixed split, normal feature bank, and threshold calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
Path | str
|
Root directory of MVTec AD dataset. |
'data/raw/mvtec_ad'
|
category
|
str
|
Category name or 'all' for full benchmark evaluation. |
'bottle'
|
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Preprocessing pipeline or list of step configs. |
None
|
fpr_limit
|
float
|
Fair-eval AUPIMO upper FPR bound (fixed at 1e-4). |
0.0001
|
encoder_name
|
str
|
Pretrained DINOv2 vision transformer encoder identifier. |
DINO_V2_ENCODER
|
num_neighbors
|
int
|
Number of normal patch neighbours to query. |
1
|
masking
|
MaskingMode
|
Foreground PCA masking policy ('off', 'on', or 'published'). |
'published'
|
run_heatmap
|
bool
|
Whether to render anomalous test-image heatmaps. |
False
|
preprocessing_steps
|
list[dict[str, Any]] | None
|
Legacy parameter preserved for backward compatibility. |
None
|
registry_base
|
Path | str
|
Output root directory for evaluation artifacts. |
'data/models/dinov2'
|
model_seed
|
int
|
Deterministic model and data loader seed. |
PATCHCORE_MODEL_SEED
|
variant
|
DINOVariant
|
Feature extractor variant ('baseline' or 'enhanced'). |
'baseline'
|
feature_layers
|
tuple[int, ...]
|
Transformer block indices for enhanced scoring. |
ENHANCED_DINO_LAYERS
|
position_radius
|
int
|
Patch search radius for enhanced spatial matching. |
1
|
spatial_weight
|
float
|
Penalty weight for spatial distance in enhanced scoring. |
0.05
|
density_neighbors
|
int
|
Number of neighbours for local density estimation. |
5
|
reuse_complete
|
bool
|
Return saved evaluation artifacts for an exact cache hit. |
False
|
Returns:
| Type | Description |
|---|---|
BaselineResult | AllCategoriesResult
|
BaselineResult for a single category, or AllCategoriesResult for 'all'. |
Source code in app/pipelines/modelling/dino/v2.py
app.pipelines.modelling.dino.v3
¶
Frozen DINOv3 patch-token nearest-neighbour baseline for MVTec AD.
run_dinov3_baseline(data_root: Path | str = 'data/raw/mvtec_ad', category: str = 'bottle', pipeline: list[dict[str, Any]] | PreprocessingPipeline | None = None, fpr_limit: float = 0.0001, encoder_name: str = DINO_V3_ENCODER, num_neighbors: int = 1, masking: MaskingMode = 'off', run_heatmap: bool = False, registry_base: Path | str = 'data/models/dinov3', model_seed: int = PATCHCORE_MODEL_SEED, reuse_complete: bool = False) -> BaselineResult | AllCategoriesResult
¶
Run the fair frozen-DINOv3 baseline for one or all MVTec categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
Path | str
|
Root directory of MVTec AD dataset. |
'data/raw/mvtec_ad'
|
category
|
str
|
MVTec category or 'all' for full benchmark evaluation. |
'bottle'
|
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Optional preprocessing pipeline or configuration list. |
None
|
fpr_limit
|
float
|
Fair-eval AUPIMO upper FPR bound (fixed at 1e-4). |
0.0001
|
encoder_name
|
str
|
Pretrained DINOv3 encoder identifier. |
DINO_V3_ENCODER
|
num_neighbors
|
int
|
Number of normal patch neighbours to query. |
1
|
masking
|
MaskingMode
|
Foreground masking policy (must be 'off' for DINOv3). |
'off'
|
run_heatmap
|
bool
|
Whether to render test-image heatmaps. |
False
|
registry_base
|
Path | str
|
Target artifact directory. |
'data/models/dinov3'
|
model_seed
|
int
|
Deterministic model and data loader seed. |
PATCHCORE_MODEL_SEED
|
reuse_complete
|
bool
|
Return saved evaluation artifacts for an exact cache hit. |
False
|
Returns:
| Type | Description |
|---|---|
BaselineResult | AllCategoriesResult
|
BaselineResult for a single category, or AllCategoriesResult for 'all'. |
Source code in app/pipelines/modelling/dino/v3.py
app.pipelines.modelling.dino.enhanced
¶
Multi-layer, position-aware DINOv2 anomaly scoring.
EnhancedAnomalyDINOModel
¶
Bases: AnomalyDINOModel
DINOv2 patch bank with multi-layer and spatially local density-aware kNN.
Source code in app/pipelines/modelling/dino/enhanced.py
12 13 14 15 16 17 18 19 20 21 22 23 24 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 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 | |
__init__(num_neighbours: int = 5, encoder_name: str = 'vit_small_patch14_dinov2', masking: bool = False, feature_layers: Sequence[int] = (8, 10, 11), position_radius: int = 1, spatial_weight: float = 0.05, density_neighbours: int = 5) -> None
¶
Configure the frozen layers and spatial-density kNN scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_neighbours
|
int
|
Neighbours averaged for each query patch. |
5
|
encoder_name
|
str
|
Pretrained timm DINOv2 encoder name. |
'vit_small_patch14_dinov2'
|
masking
|
bool
|
Whether to apply AnomalyDINO's PCA foreground mask. |
False
|
feature_layers
|
Sequence[int]
|
Zero-based transformer block indices to concatenate. |
(8, 10, 11)
|
position_radius
|
int
|
Maximum row/column offset for candidate patches. |
1
|
spatial_weight
|
float
|
Additive penalty per squared patch-grid offset. |
0.05
|
density_neighbours
|
int
|
Neighbours used for normal-density estimation. |
5
|
Source code in app/pipelines/modelling/dino/enhanced.py
extract_features(image_tensor: torch.Tensor) -> torch.Tensor
¶
Concatenate raw patch tokens from the selected transformer blocks.
Source code in app/pipelines/modelling/dino/enhanced.py
fit() -> None
¶
Finalize the structured bank and estimate normal density at each position.
Source code in app/pipelines/modelling/dino/enhanced.py
forward(input_tensor: torch.Tensor) -> torch.Tensor | InferenceBatch
¶
Collect structured normal tokens or score test tokens.
Source code in app/pipelines/modelling/dino/enhanced.py
patchcore_image_score(neighbour_scores: torch.Tensor) -> torch.Tensor
staticmethod
¶
Apply PatchCore-style neighborhood confidence to the worst patch.
Source code in app/pipelines/modelling/dino/enhanced.py
app.pipelines.modelling.dino.engine
¶
Shared execution and evaluation engine for DINO foundation model baselines.
build_dino_identity_and_hash(category: str, encoder_name: str, num_neighbors: int, masking: MaskingMode, use_masking: bool, raw_prep_list: list[dict[str, Any]], cache_evidence: dict[str, Any], model_generation: Literal['dinov2', 'dinov3'], variant: DINOVariant, feature_layers: tuple[int, ...], position_radius: int, spatial_weight: float, density_neighbors: int) -> tuple[dict[str, Any], str, dict[str, Any]]
¶
Build the serializable identity dictionary and unique hash for a DINO experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
MVTec category being evaluated. |
required |
encoder_name
|
str
|
Name of the pretrained feature encoder. |
required |
num_neighbors
|
int
|
Nearest neighbors count. |
required |
masking
|
MaskingMode
|
Active masking policy mode. |
required |
use_masking
|
bool
|
Evaluated boolean decision for masking. |
required |
raw_prep_list
|
list[dict[str, Any]]
|
Normalized preprocessing configurations. |
required |
cache_evidence
|
dict[str, Any]
|
Protocol split and metric version metadata. |
required |
model_generation
|
Literal['dinov2', 'dinov3']
|
Architectural generation ('dinov2' or 'dinov3'). |
required |
variant
|
DINOVariant
|
Feature extractor variant ('baseline' or 'enhanced'). |
required |
feature_layers
|
tuple[int, ...]
|
Block indices for enhanced scoring. |
required |
position_radius
|
int
|
Grid search radius for spatial matching. |
required |
spatial_weight
|
float
|
Weight factor for spatial distance penalty. |
required |
density_neighbors
|
int
|
Neighbor count for density estimation. |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], str, dict[str, Any]]
|
A tuple of (identity_dictionary, 12_char_hex_hash, enhanced_scorer_parameters). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If variant is invalid. |
Source code in app/pipelines/modelling/dino/engine.py
compute_macro_average(category_results: dict[str, BaselineResult]) -> dict[str, float]
¶
Compute unweighted macro averages across all evaluated categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_results
|
dict[str, BaselineResult]
|
Mapping of category names to BaselineResults. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary of mean values for image- and pixel-level metrics. |
Source code in app/pipelines/modelling/dino/engine.py
instantiate_dino_model(num_neighbors: int, encoder_name: str, use_masking: bool, model_generation: Literal['dinov2', 'dinov3'], variant: DINOVariant, input_size: int, feature_layers: tuple[int, ...], position_radius: int, spatial_weight: float, density_neighbors: int) -> AnomalyDINO
¶
Instantiate and configure the AnomalyDINO model with frozen feature extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_neighbors
|
int
|
Nearest neighbors count for memory bank lookup. |
required |
encoder_name
|
str
|
Identifier for the backbone encoder. |
required |
use_masking
|
bool
|
Whether foreground PCA patch masking is active. |
required |
model_generation
|
Literal['dinov2', 'dinov3']
|
Architectural generation ('dinov2' or 'dinov3'). |
required |
variant
|
DINOVariant
|
Model variant ('baseline' or 'enhanced'). |
required |
input_size
|
int
|
Canonical square input dimension. |
required |
feature_layers
|
tuple[int, ...]
|
Block indices for enhanced multi-layer feature extraction. |
required |
position_radius
|
int
|
Position search radius for enhanced spatial matching. |
required |
spatial_weight
|
float
|
Weight penalty for off-center matches. |
required |
density_neighbors
|
int
|
Neighbor count for density estimation. |
required |
Returns:
| Type | Description |
|---|---|
AnomalyDINO
|
Configured AnomalyDINO instance with gradient updates disabled on encoder. |
Source code in app/pipelines/modelling/dino/engine.py
load_completed_category_result(base_dir: Path, category: str, model_hash: str, run_heatmap: bool, load_heatmaps: bool = True) -> BaselineResult | None
¶
Load a complete category result without retaining saved heatmap pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
Path
|
Directory containing candidate evaluation artifacts. |
required |
category
|
str
|
MVTec category expected in the metadata. |
required |
model_hash
|
str
|
Unique SHA-256 fingerprint expected in the metadata. |
required |
run_heatmap
|
bool
|
Whether heatmap overlays are required to declare completion. |
required |
load_heatmaps
|
bool
|
Whether to deserialize heatmap pixels into the returned result. |
True
|
Returns:
| Type | Description |
|---|---|
BaselineResult | None
|
Reconstituted BaselineResult if complete artifacts exist, or None. |
Source code in app/pipelines/modelling/dino/artifacts.py
persist_dino_artifacts_and_format(category: str, base_dir: Path, model_hash: str, configuration_hash: str, model_generation: Literal['dinov2', 'dinov3'], variant: DINOVariant, encoder_name: str, num_neighbors: int, masking: MaskingMode, use_masking: bool, raw_prep_list: list[dict[str, Any]], hyperparameters: dict[str, Any], split_info: dict[str, Any], artifacts: EvaluationArtifacts, image_average_precision: float, fpr_limit: float, model_seed: int) -> BaselineResult
¶
Serialize DINO run metadata and format standardized baseline result dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
MVTec category evaluated. |
required |
base_dir
|
Path
|
Base directory where artifacts are saved. |
required |
model_hash
|
str
|
Unique run hash string. |
required |
configuration_hash
|
str
|
Stable hash for equivalent model configurations. |
required |
model_generation
|
Literal['dinov2', 'dinov3']
|
Encoder architecture family. |
required |
variant
|
DINOVariant
|
Scorer variant ('baseline' or 'enhanced'). |
required |
encoder_name
|
str
|
Model backbone identifier. |
required |
num_neighbors
|
int
|
Nearest neighbor count. |
required |
masking
|
MaskingMode
|
Foreground masking policy mode. |
required |
use_masking
|
bool
|
Evaluated boolean decision for masking. |
required |
raw_prep_list
|
list[dict[str, Any]]
|
Normalized preprocessing configuration list. |
required |
hyperparameters
|
dict[str, Any]
|
Model hyperparameter dictionary. |
required |
split_info
|
dict[str, Any]
|
Dataset partition sample counts. |
required |
artifacts
|
EvaluationArtifacts
|
Structured EvaluationArtifacts container. |
required |
image_average_precision
|
float
|
Computed area under Precision-Recall curve. |
required |
fpr_limit
|
float
|
Maximum false-positive rate for AUPIMO integration. |
required |
model_seed
|
int
|
Deterministic random seed used for the run. |
required |
Returns:
| Type | Description |
|---|---|
BaselineResult
|
Structured BaselineResult dictionary complying with fair-eval-v1. |
Source code in app/pipelines/modelling/dino/artifacts.py
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 | |
release_accelerator_memory() -> None
¶
Collect cyclic trainer state and release unused CUDA allocations.
Source code in app/pipelines/modelling/dino/engine.py
resolve_masking(masking: MaskingMode, category: str) -> bool
¶
Resolve an explicit or published full-shot AnomalyDINO masking policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
masking
|
MaskingMode
|
Active masking policy mode ('off', 'on', or 'published'). |
required |
category
|
str
|
MVTec object or texture category name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if foreground PCA masking should be applied, False otherwise. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If masking mode is invalid. |
Source code in app/pipelines/modelling/dino/engine.py
run_dino_all_categories(data_root: Path | str, pipeline: list[dict[str, Any]] | PreprocessingPipeline | None, fpr_limit: float, encoder_name: str, num_neighbors: int, masking: MaskingMode, run_heatmap: bool, registry_base: Path | str, model_seed: int, variant: DINOVariant, feature_layers: tuple[int, ...], position_radius: int, spatial_weight: float, density_neighbors: int, model_generation: Literal['dinov2', 'dinov3'], model_name: str, input_size: int, patch_size: int, batch_size: int, reuse_complete: bool = False, save_summary_files: bool = False) -> AllCategoriesResult
¶
Orchestrate sequential evaluation across all canonical MVTec categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
Path | str
|
Root directory of MVTec AD. |
required |
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Preprocessing pipeline or configuration list. |
required |
fpr_limit
|
float
|
Fixed fair-eval AUPIMO FPR limit. |
required |
encoder_name
|
str
|
Backbone encoder identifier. |
required |
num_neighbors
|
int
|
Nearest neighbor count. |
required |
masking
|
MaskingMode
|
Foreground masking policy mode. |
required |
run_heatmap
|
bool
|
Whether to render test-image overlays. |
required |
registry_base
|
Path | str
|
Target artifact directory. |
required |
model_seed
|
int
|
Deterministic random seed. |
required |
variant
|
DINOVariant
|
Scorer variant ('baseline' or 'enhanced'). |
required |
feature_layers
|
tuple[int, ...]
|
Multi-layer indices for enhanced scoring. |
required |
position_radius
|
int
|
Spatial search radius. |
required |
spatial_weight
|
float
|
Spatial distance penalty. |
required |
density_neighbors
|
int
|
Neighbor count for density estimation. |
required |
model_generation
|
Literal['dinov2', 'dinov3']
|
Architectural family ('dinov2' or 'dinov3'). |
required |
model_name
|
str
|
Label for logs and summaries. |
required |
input_size
|
int
|
Square model input dimension. |
required |
patch_size
|
int
|
Encoder patch dimension. |
required |
batch_size
|
int
|
DataLoader batch size. |
required |
reuse_complete
|
bool
|
Reuse complete artifacts for each category. |
False
|
save_summary_files
|
bool
|
If True, writes summary.json and category_metrics.csv. |
False
|
Returns:
| Type | Description |
|---|---|
AllCategoriesResult
|
AllCategoriesResult containing per-category results and macro averages. |
Source code in app/pipelines/modelling/dino/engine.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 | |
run_dino_category(data_root: Path | str = 'data/raw/mvtec_ad', category: str = 'bottle', pipeline: list[dict[str, Any]] | PreprocessingPipeline | None = None, fpr_limit: float = 0.0001, encoder_name: str = 'vit_small_patch14_dinov2', num_neighbors: int = 1, masking: MaskingMode = 'published', run_heatmap: bool = False, preprocessing_steps: list[dict[str, Any]] | None = None, registry_base: Path | str = 'data/models/dinov2', model_seed: int = PATCHCORE_MODEL_SEED, reuse_complete: bool = False, variant: DINOVariant = 'baseline', feature_layers: tuple[int, ...] = (8, 10, 11), position_radius: int = 1, spatial_weight: float = 0.05, density_neighbors: int = 5, model_generation: Literal['dinov2', 'dinov3'] = 'dinov2', model_name: str = 'DINOv2', input_size: int = 252, patch_size: int = 14, batch_size: int = 4, manifest: pd.DataFrame | None = None) -> BaselineResult
¶
Evaluate frozen DINO patch tokens with a normal-only nearest-neighbour bank.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_root
|
Path | str
|
Root directory of MVTec AD. |
'data/raw/mvtec_ad'
|
category
|
str
|
MVTec category to evaluate. |
'bottle'
|
pipeline
|
list[dict[str, Any]] | PreprocessingPipeline | None
|
Optional preprocessing pipeline or configuration list. |
None
|
fpr_limit
|
float
|
Upper AUPIMO false-positive-rate bound fixed by the fair protocol. |
0.0001
|
encoder_name
|
str
|
Pretrained DINO encoder exposed by Anomalib/timm. |
'vit_small_patch14_dinov2'
|
num_neighbors
|
int
|
Number of normal patch neighbours averaged per patch. |
1
|
masking
|
MaskingMode
|
PCA foreground-mask policy: disabled, enabled, or published. |
'published'
|
run_heatmap
|
bool
|
Whether to render overlays for anomalous test images. |
False
|
preprocessing_steps
|
list[dict[str, Any]] | None
|
Legacy parameter preserved for backward compatibility. |
None
|
registry_base
|
Path | str
|
Directory in which evaluation artifacts are written. |
'data/models/dinov2'
|
model_seed
|
int
|
Shared deterministic model and data-loader seed. |
PATCHCORE_MODEL_SEED
|
reuse_complete
|
bool
|
Reuse complete artifacts for this exact configuration. |
False
|
variant
|
DINOVariant
|
Stock final-block scorer or enhanced multi-layer scorer. |
'baseline'
|
feature_layers
|
tuple[int, ...]
|
Transformer block indices used by the enhanced scorer. |
(8, 10, 11)
|
position_radius
|
int
|
Patch-grid search radius used by the enhanced scorer. |
1
|
spatial_weight
|
float
|
Spatial-distance penalty used by the enhanced scorer. |
0.05
|
density_neighbors
|
int
|
Normal neighbours used to estimate local density. |
5
|
model_generation
|
Literal['dinov2', 'dinov3']
|
Encoder family ('dinov2' or 'dinov3'). |
'dinov2'
|
model_name
|
str
|
Human-readable model label used in logs. |
'DINOv2'
|
input_size
|
int
|
Square model input size recorded in the run metadata. |
252
|
patch_size
|
int
|
Encoder patch size recorded in the run metadata. |
14
|
batch_size
|
int
|
Batch size for training datamodule. |
4
|
manifest
|
DataFrame | None
|
Optional prebuilt dataset manifest for all-category orchestration. |
None
|
Returns:
| Type | Description |
|---|---|
BaselineResult
|
Results using the standardized BaselineResult schema. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If validation bounds or encoder specifications are invalid. |
RuntimeError
|
If memory bank fitting produces zero normal patches. |
Source code in app/pipelines/modelling/dino/engine.py
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 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | |
save_all_category_summary(registry_base: Path | str, encoder_name: str, masking: MaskingMode, num_neighbors: int, category_results: dict[str, BaselineResult], macro_average: dict[str, float], model_name: str = 'DINO') -> None
¶
Persist compact machine-readable summaries beside category artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry_base
|
Path | str
|
Target directory where summary files are placed. |
required |
encoder_name
|
str
|
Name of the encoder backbone used. |
required |
masking
|
MaskingMode
|
Foreground masking policy mode. |
required |
num_neighbors
|
int
|
Nearest neighbor count. |
required |
category_results
|
dict[str, BaselineResult]
|
Mapping of category names to their BaselineResults. |
required |
macro_average
|
dict[str, float]
|
Unweighted metric averages across categories. |
required |
model_name
|
str
|
Label used in the written JSON summary. |
'DINO'
|
Source code in app/pipelines/modelling/dino/artifacts.py
Preprocessing Subpackage¶
app.pipelines.preprocessing.factory
¶
Preprocessing factory module for building preprocessing pipelines.
build_pipeline_from_configs(configs: list[dict[str, Any]] | None) -> PreprocessingPipeline
¶
Build a PreprocessingPipeline from a list of dict configs.
Example input
[ {"name": "clahe", "params": {"clip_limit": 3.0}}, {"name": "gaussian_blur", "params": {"kernel_size": 3}} ]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
configs
|
list[dict[str, Any]] | None
|
List of preprocessing step configurations. |
required |
Returns:
| Type | Description |
|---|---|
PreprocessingPipeline
|
PreprocessingPipeline with steps added from configs. |
Source code in app/pipelines/preprocessing/factory.py
normalize_preprocessing_steps(steps: list[dict[str, Any]] | None) -> list[dict[str, Any]]
¶
Normalize a list of preprocessing step dicts for deterministic hashing and registry lookups.
Sorts parameter keys alphabetically and strips extraneous or unhashable attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
steps
|
list[dict[str, Any]] | None
|
List of raw preprocessing step dictionaries (e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of normalized step dictionaries with sorted param dictionaries. |
Source code in app/pipelines/preprocessing/factory.py
app.pipelines.preprocessing.augmentation
¶
Category-aware data augmentation for the Keras CAE anomaly detection pipeline.
Why Does Augmentation Strategy Matter for Anomaly Detection?¶
In industrial anomaly detection, the autoencoder is trained exclusively on defect-free normal images. The goal of augmentation is NOT to help the model generalise to new defect classes (that would be wrong), but to:
- Prevent overfitting to the exact photographic conditions of the training set (lighting angles, minor camera vibration, batch-to-batch variation).
- Make the model robust to permissible natural variance (e.g., slightly different grain orientation in wood), while still flagging genuine defects as anomalous.
The Critical Distinction: Textures vs. Rigid Objects¶
This is the most important design decision in augmentation:
Texture categories (wood, carpet, leather, tile, grid): These materials have spatial invariance - the statistical pattern of wood grain looks essentially the same whether you rotate it 90 degrees or not. Therefore, heavy geometric augmentations (random rotations, flips, scale jitter) are very effective. They teach the model "what does normal wood look like from any direction?".
Rigid object categories (transistor, pill, screw, capsule, metal_nut, bolt): These objects are directionally aligned on the conveyor belt or inspection jig. A transistor always arrives with its legs pointing down. If you rotate it 90 degrees during training, the model learns that an upside-down transistor is normal - which destroys the anomaly detection capability for orientation defects entirely. For these, only light colour/intensity augmentations are safe.
Module Contents¶
TEXTURE_CATEGORIES: Set of MVTec categories that are textures.OBJECT_CATEGORIES: Set of MVTec categories that are rigid objects.TextureAugmenter: Heavy augmentation pipeline for textures.ObjectAugmenter: Light augmentation pipeline for rigid objects.get_augmenter: Factory that returns the correct augmenter by category name.
OBJECT_CATEGORIES: frozenset[str] = frozenset(MVTEC_OBJECT_CATEGORIES)
module-attribute
¶
Set representation of rigid object categories for fast O(1) membership checks.
TEXTURE_CATEGORIES: frozenset[str] = frozenset(MVTEC_TEXTURE_CATEGORIES)
module-attribute
¶
Set representation of surface texture categories for fast O(1) membership checks.
ObjectAugmenter
¶
Light augmentation pipeline for directionally aligned rigid object categories.
These objects (e.g., transistors, pills, screws) are always positioned in a consistent orientation in the MVTec dataset. Applying rotations would teach the model that an upside-down transistor is "normal" - completely defeating anomaly detection for orientation-related defects.
Therefore, only photometric (colour/intensity) augmentations are applied: 1. Slight brightness jitter (±10%). 2. Slight contrast jitter (±10%). 3. Slight saturation jitter (±10%). 4. Light additive Gaussian noise (very small standard deviation, ±2% intensity).
Attributes:
| Name | Type | Description |
|---|---|---|
brightness_range |
Tuple (min, max) brightness multiplier. |
|
contrast_range |
Tuple (min, max) contrast multiplier. |
|
saturation_range |
Tuple (min, max) colour saturation multiplier. |
|
noise_std |
Standard deviation of additive Gaussian noise (0.0 to 1.0 scale). |
Source code in app/pipelines/preprocessing/augmentation.py
__call__(image: Image.Image) -> Image.Image
¶
Apply the light object augmentation pipeline to a single PIL image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Input PIL Image in RGB mode. |
required |
Returns:
| Type | Description |
|---|---|
Image
|
Augmented PIL Image in RGB mode, same size as input. |
Source code in app/pipelines/preprocessing/augmentation.py
__init__(brightness_range: tuple[float, float] = (0.9, 1.1), contrast_range: tuple[float, float] = (0.9, 1.1), saturation_range: tuple[float, float] = (0.9, 1.1), noise_std: float = 0.02) -> None
¶
Initialize the object augmenter with configurable photometric jitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
brightness_range
|
tuple[float, float]
|
(min, max) brightness multiplier. 1.0 = no change. |
(0.9, 1.1)
|
contrast_range
|
tuple[float, float]
|
(min, max) contrast multiplier. 1.0 = no change. |
(0.9, 1.1)
|
saturation_range
|
tuple[float, float]
|
(min, max) saturation multiplier. 1.0 = no change. |
(0.9, 1.1)
|
noise_std
|
float
|
Standard deviation of Gaussian noise added to normalised [0,1] pixels. |
0.02
|
Source code in app/pipelines/preprocessing/augmentation.py
TextureAugmenter
¶
Heavy augmentation pipeline for spatially invariant texture categories.
Spatial invariance means the visual statistics of the material do not fundamentally change under rotation or reflection. Wood grain rotated 90 degrees still looks like normal wood - so we exploit this to generate more training variety.
Augmentations applied in random order: 1. Random 90°/180°/270° rotation (or no rotation). 2. Random horizontal flip. 3. Random vertical flip. 4. Random scale crop (zooms into 80-100% of the image, then resizes back). 5. Slight brightness jitter (±20% brightness variation). 6. Slight contrast jitter (±20% contrast variation).
Attributes:
| Name | Type | Description |
|---|---|---|
brightness_range |
Tuple (min, max) multiplier for brightness jitter. |
|
contrast_range |
Tuple (min, max) multiplier for contrast jitter. |
|
scale_range |
Tuple (min_crop_fraction, max_crop_fraction) for scale jitter. |
Source code in app/pipelines/preprocessing/augmentation.py
__call__(image: Image.Image) -> Image.Image
¶
Apply the full texture augmentation pipeline to a single PIL image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Input PIL Image in RGB mode. |
required |
Returns:
| Type | Description |
|---|---|
Image
|
Augmented PIL Image in RGB mode, same size as input. |
Source code in app/pipelines/preprocessing/augmentation.py
__init__(brightness_range: tuple[float, float] = (0.8, 1.2), contrast_range: tuple[float, float] = (0.8, 1.2), scale_range: tuple[float, float] = (0.8, 1.0)) -> None
¶
Initialize the texture augmenter with configurable jitter ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
brightness_range
|
tuple[float, float]
|
(min, max) brightness multiplier. 1.0 = original. |
(0.8, 1.2)
|
contrast_range
|
tuple[float, float]
|
(min, max) contrast multiplier. 1.0 = original. |
(0.8, 1.2)
|
scale_range
|
tuple[float, float]
|
(min_fraction, max_fraction) of image area to crop before resize. |
(0.8, 1.0)
|
Source code in app/pipelines/preprocessing/augmentation.py
augment_batch(images: np.ndarray, augmenter: TextureAugmenter | ObjectAugmenter) -> np.ndarray
¶
Apply augmentation to a batch of numpy images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
ndarray
|
Batch of images as a numpy array of shape (N, H, W, 3), values in [0, 255]. |
required |
augmenter
|
TextureAugmenter | ObjectAugmenter
|
An instantiated augmenter (TextureAugmenter or ObjectAugmenter). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Augmented batch as numpy array of shape (N, H, W, 3), values in [0, 255]. |
Source code in app/pipelines/preprocessing/augmentation.py
get_augmenter(category: str) -> TextureAugmenter | ObjectAugmenter
¶
Factory that returns the correct augmenter for a given MVTec category.
This function automatically selects the appropriate augmentation strategy:
- Heavy spatial augmentation (TextureAugmenter) for texture categories.
- Light photometric augmentation (ObjectAugmenter) for object categories.
- Falls back to ObjectAugmenter (conservative) for unknown categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
|
str
|
MVTec AD category name (e.g., 'wood', 'bottle', 'screw'). |
required |
Returns:
| Type | Description |
|---|---|
TextureAugmenter | ObjectAugmenter
|
TextureAugmenter if the category is a texture, ObjectAugmenter otherwise. |
Source code in app/pipelines/preprocessing/augmentation.py
app.pipelines.preprocessing.segmentation
¶
Foreground extraction and background replacement for the Keras CAE pipeline.
Why Do We Need Foreground Extraction?¶
Industrial components photographed against a background introduce a fundamental problem: the autoencoder wastes representational capacity learning the background (conveyor belt, mounting jig, inspection stage). This background is not the object under inspection.
Even worse, subtle background variations (dust, lighting reflections, shadow changes) can drive up the reconstruction error and produce false positive anomaly detections.
The Two-Step Solution: Segmentation + Background Replacement (BGRP-G)¶
This module implements the BGRP-G (Background Replacement to Grey/Black) strategy:
- Segment the foreground: Use classical computer vision to find the component pixels.
- Zero-fill the background: Replace all background pixels with solid black (0, 0, 0).
Why Black (zero) as the Replacement Colour? Black = (0, 0, 0) is the most "out-of-distribution" value for typical industrial inspection images, which tend to be brighter and coloured. The autoencoder, trained only on images with black backgrounds, will learn to perfectly reconstruct black background regions with near-zero error. This means the background contributes nothing to the anomaly score - which is exactly what we want.
Important: We must keep colour information in the foreground intact, since colour
defects (e.g., surface discolouration) are valid anomaly types in MVTec.
Classical CV Approach: Otsu + Adaptive Canny¶
Rather than using SAM (Segment Anything Model, which requires ~2.5 GB model weights), we use a fast, dependency-free classical pipeline:
-
Otsu's Thresholding: A global binarization method that automatically finds the optimal greyscale threshold to separate foreground from background. It maximises the inter-class variance between foreground and background pixel distributions.
-
Adaptive Canny Edge Detection: Canny finds sharp pixel intensity transitions (edges). The "adaptive" variant sets high/low thresholds automatically from the image's median pixel intensity, making it robust across varying illumination.
-
Morphological Closing: Fills small holes in the combined binary mask (gaps between edges and the Otsu region) by dilating then eroding with a kernel.
-
Largest Connected Component: Selects only the single largest foreground blob, discarding small spurious fragments from dust or image noise.
Module Contents¶
OtsuCannySegmentor: Full foreground extraction pipeline.extract_largest_component: Helper to isolate the largest blob in a binary mask.
OtsuCannySegmentor
¶
Foreground segmentation combining Otsu thresholding with Adaptive Canny edge detection.
This class provides a fast, reliable foreground extraction pipeline that works well on the standard MVTec AD inspection setup (component on a uniform background).
Pipeline Steps
- Convert RGB to greyscale for efficient threshold computation.
- Apply Otsu's global threshold to create a coarse binary foreground mask.
- Compute adaptive Canny edge map using the image's median intensity as the threshold anchor.
- Combine (OR) the Otsu mask and Canny edges into one binary map.
- Apply morphological closing to fill gaps between adjacent edges.
- Extract the single largest connected component to remove noise artefacts.
- Replace all background pixels (mask = 0) in the original RGB image with black.
Attributes:
| Name | Type | Description |
|---|---|---|
morph_kernel_size |
Side length (pixels) of the square structuring element used for morphological closing. Larger = fills bigger gaps. |
|
canny_sigma |
Scaling factor applied to the median pixel intensity to derive the Canny low and high thresholds. Higher = fewer, stronger edges detected. |
Source code in app/pipelines/preprocessing/segmentation.py
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 | |
__init__(morph_kernel_size: int = 5, canny_sigma: float = 0.33) -> None
¶
Initialise the segmentor with morphological and edge detection parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
morph_kernel_size
|
int
|
Side length of the square kernel for morphological closing. 5 pixels works well for most MVTec categories. |
5
|
canny_sigma
|
float
|
Controls the spread of Canny threshold bounds around the image median. Larger values = more conservative edge detection. |
0.33
|
Source code in app/pipelines/preprocessing/segmentation.py
apply(image_rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray]
¶
Extract foreground and replace background with black (BGRP-G strategy).
The BGRP-G strategy (Background Replacement with a Guaranteed Out-of-Distribution colour) zeroes out all background pixels. This forces the autoencoder to learn only from the component surface, eliminating background as a source of false anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_rgb
|
ndarray
|
Input RGB image as numpy array (H, W, 3), dtype uint8. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple of: - masked_image: RGB image with background pixels zeroed, shape (H, W, 3). - foreground_mask: Binary foreground mask, shape (H, W), values 0 or 255. |
Source code in app/pipelines/preprocessing/segmentation.py
compute_mask(image_rgb: np.ndarray) -> np.ndarray
¶
Compute a binary foreground mask for the input RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_rgb
|
ndarray
|
Input image as a numpy array of shape (H, W, 3), dtype uint8, RGB order. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Binary mask as a 2D numpy array (H, W), dtype uint8, values 0 or 255. |
ndarray
|
255 = foreground (component), 0 = background. |
Source code in app/pipelines/preprocessing/segmentation.py
extract_largest_component(binary_mask: np.ndarray) -> np.ndarray
¶
Extract only the largest connected foreground region from a binary mask.
After Otsu + Canny segmentation, the mask may contain multiple disconnected blobs (e.g., the main component plus dust particles or image artefacts). This function keeps only the largest blob, which is almost always the actual component.
How it works
- Label all connected components in the binary mask.
- Count pixels in each component.
- Return a mask with only the largest component filled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_mask
|
ndarray
|
2D binary numpy array (dtype uint8), 255 = foreground, 0 = background. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Cleaned 2D binary mask with only the largest connected component kept (uint8, 0/255). |
Source code in app/pipelines/preprocessing/segmentation.py
Evaluation Subpackage¶
app.pipelines.evaluation.metrics
¶
Precision-recall metric calculation and persistence functions.
canonicalize_pixel_inputs(anomaly_maps: list[np.ndarray] | np.ndarray, masks: list[np.ndarray | None] | np.ndarray, image_labels: np.ndarray | list[int], size: tuple[int, int] = CANONICAL_MAP_SIZE) -> tuple[np.ndarray, np.ndarray]
¶
Validate and resize full pixel maps and masks to the shared canonical resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anomaly_maps
|
list[ndarray] | ndarray
|
Sequence of continuous 2D anomaly heatmaps. |
required |
masks
|
list[ndarray | None] | ndarray
|
Sequence of ground-truth binary masks (or None for normal images). |
required |
image_labels
|
ndarray | list[int]
|
Binary image-level defect labels (0 or 1). |
required |
size
|
tuple[int, int]
|
Target canonical resolution tuple (height, width). Defaults to 256x256. |
CANONICAL_MAP_SIZE
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
A tuple of stacked (canonical_maps, canonical_masks) NumPy arrays. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are empty, have mismatched lengths, or contain invalid labels. |
Source code in app/pipelines/evaluation/metrics.py
compute_and_save_pr_metrics(y_true: Any, y_score: Any, output_path: str | Path, level: str = 'pixel', aupimo: float | None = None, fpr_bounds: tuple[float, float] | None = None) -> Path
¶
Compute PR metrics and save them with an optional genuine AUPIMO score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Any
|
1D array of ground truth binary labels (0 or 1). |
required |
y_score
|
Any
|
1D array of predicted anomaly scores. |
required |
output_path
|
str | Path
|
Destination .npz file path. |
required |
level
|
str
|
Evaluation level ('pixel' for localization, 'image' for classification). |
'pixel'
|
aupimo
|
float | None
|
Genuine full-map AUPIMO score computed separately from 2D maps. |
None
|
fpr_bounds
|
tuple[float, float] | None
|
FPR integration bounds used for AUPIMO. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The saved Path object. |
Source code in app/pipelines/evaluation/metrics.py
compute_aupimo(anomaly_maps: list[np.ndarray], gt_masks: list[np.ndarray | None], fpr_bounds: tuple[float, float] = (1e-05, 0.0001)) -> float
¶
Compute pixel-level AUPIMO using anomalib's implementation.
AUPIMO (Area Under Per-Image Overlap) integrates per-image pixel overlap between predicted anomaly maps and ground truth defect masks. It does so only over an extremely narrow and industrially realistic FPR range (default: 10⁻⁵ to 10⁻⁴).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anomaly_maps
|
list[ndarray]
|
List of 2D pixel anomaly score maps, one per test image. Each map has shape (H, W) with float values >= 0 (higher = more anomalous). |
required |
gt_masks
|
list[ndarray | None]
|
List of 2D ground truth binary masks, one per test image. Each mask has shape (H, W) with values 0 (normal) or 1 (defect). Use None for images with no ground truth mask (normal images). |
required |
fpr_bounds
|
tuple[float, float]
|
Tuple (lower_fpr, upper_fpr) defining the integration interval. Default (1e-5, 1e-4) matches the MVTec AD benchmark standard. |
(1e-05, 0.0001)
|
Returns:
| Type | Description |
|---|---|
float
|
AUPIMO score in [0, 1]. Higher is better. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If anomalib or torch is unavailable. |
ValueError
|
If the maps or masks cannot define AUPIMO at the requested bounds. |
RuntimeError
|
If anomalib cannot compute the metric at the requested bounds. |
Source code in app/pipelines/evaluation/metrics.py
compute_image_auroc(scores: np.ndarray, binary_labels: np.ndarray) -> float
¶
Compute image-level Area Under the ROC Curve (AUROC).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
ndarray
|
1D array of image-level anomaly scores, shape (N,). Higher = more anomalous. |
required |
binary_labels
|
ndarray
|
1D binary array, shape (N,). 0 = normal, 1 = anomalous. |
required |
Returns:
| Type | Description |
|---|---|
float
|
AUROC value in [0, 1]. 1.0 = perfect; 0.5 = random; 0.0 = perfectly inverted. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 distinct classes are present in binary_labels. |
Source code in app/pipelines/evaluation/metrics.py
compute_image_confusion_metrics(labels: Any, scores: Any, threshold: float) -> dict[str, float | int]
¶
Calculate image confusion counts and derived metrics at a frozen threshold.
Source code in app/pipelines/evaluation/metrics.py
compute_shared_pixel_metrics(anomaly_maps: list[np.ndarray] | np.ndarray, masks: list[np.ndarray | None] | np.ndarray, image_labels: np.ndarray | list[int]) -> tuple[dict[str, Any], np.ndarray, np.ndarray]
¶
Compute canonical pixel AUROC and genuine full-map AUPIMO.
Source code in app/pipelines/evaluation/metrics.py
fair_metric_evidence() -> dict[str, Any]
¶
Return the metric and calibration fields required for a fair cache hit.
Source code in app/pipelines/evaluation/metrics.py
save_evaluation_metrics(output_path: str | Path, precisions: Any, recalls: Any, thresholds: Any, aupimo: float | None = None, fpr_bounds: tuple[float, float] | None = None, level: str = 'pixel') -> Path
¶
Save precision, recall, and threshold arrays to an .npz file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str | Path
|
Target filepath (e.g. 'results/Patchcore/bottle/pixel_metrics.npz'). |
required |
precisions
|
Any
|
Precision values array. |
required |
recalls
|
Any
|
Recall values array. |
required |
thresholds
|
Any
|
Binarization thresholds array. |
required |
aupimo
|
float | None
|
Genuine full-map AUPIMO score, when available. |
None
|
fpr_bounds
|
tuple[float, float] | None
|
FPR integration bounds used for AUPIMO, when available. |
None
|
level
|
str
|
Evaluation level ('pixel' for localization, 'image' for classification). |
'pixel'
|
Returns:
| Type | Description |
|---|---|
Path
|
The saved Path object. |
Source code in app/pipelines/evaluation/metrics.py
app.pipelines.evaluation.cae_metrics
¶
Evaluation metrics and heatmap generation for the Keras CAE pipeline.
Why Evaluation Methodology Matters¶
Getting the right evaluation metric is as important as the model itself. Using the wrong metric can make a terrible detector look great on paper, and vice versa.
Image-Level: AUROC (Area Under ROC Curve)¶
AUROC measures how well the model ranks anomalous images above normal ones across ALL possible thresholds simultaneously. An AUROC of 1.0 means perfect ranking; 0.5 means the model is no better than random guessing.
Advantages over plain accuracy: - Threshold-independent: does not require choosing a specific cut-off. - Handles class imbalance well (MVTec test sets are typically imbalanced).
Pixel-Level: AUPIMO vs. PRO-Score¶
For pixel-level evaluation (localising where the defect is), two metrics exist:
PRO-Score (Per-Region Overlap / AUPRO)
Integrates overlap between predicted anomaly maps and ground-truth masks across
thresholds up to a fixed FPR on normal images. In practice it over-weights
tiny label annotation errors, which are common in real industrial datasets.
AUPIMO (Area Under Per-Image Overlap) ← Used here
AUPIMO introduces two critical improvements:
1. **Normal-Only Validation**: Thresholds are calibrated exclusively on images
with zero defects. This prevents the metric from being "gamed" by correctly
identifying easy normal regions.
2. **Logarithmic FPR Bounds**: Integration happens only between FPR = 10⁻⁵ and
FPR = 10⁻⁴. This extremely tight range corresponds to real industrial reject
rates (maximum 1 false alarm per 10,000-100,000 inspected parts).
The result is a metric that honestly reflects real industrial performance, not
laboratory performance under lenient conditions.
Heatmap Generation¶
Raw pixel error maps need normalisation before visualisation, because: - Absolute error values depend on the model's training quality. - Different images have different baseline error levels.
We use quantile normalisation: clamp to the 1st and 99th percentile of the error distribution, then rescale to [0, 255]. This prevents a few outlier pixels from washing out the rest of the heatmap.
Module Contents¶
compute_image_auroc: Image-level ROC AUC from scores and binary labels.compute_aupimo: Pixel-level AUPIMO using anomalib's implementation.generate_heatmap_overlay: Creates an RGB overlay of error on the original image.evaluate_cae: Full evaluation pipeline returning all metrics.
evaluate_cae(model: Any, test_images: np.ndarray, test_labels: np.ndarray, gt_masks: list[np.ndarray | None], threshold: float, k_fraction: float = 0.002, output_dir: Path | None = None, reconstructions: np.ndarray | None = None) -> dict[str, Any]
¶
Run full evaluation of the trained CAE on the test set.
Computes: - Image-level anomaly scores using Top-K pooling. - AUROC across all test images. - Accuracy, precision, recall using the calibrated adaptive threshold. - AUPIMO for pixel-level localisation on images with ground truth masks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Trained Keras CAE model. |
required |
test_images
|
ndarray
|
Normalised test images, shape (N, H, W, 3), values in [0, 1]. |
required |
test_labels
|
ndarray
|
Binary labels, shape (N,). 0 = normal, 1 = anomalous. |
required |
gt_masks
|
list[ndarray | None]
|
List of ground truth defect masks (or None for normal images). |
required |
threshold
|
float
|
Decision threshold from |
required |
k_fraction
|
float
|
Top-K pooling fraction for image-level scoring. |
0.002
|
output_dir
|
Path | None
|
Directory to save detailed PR metrics (.npz files) for UI rendering. |
None
|
reconstructions
|
ndarray | None
|
Optional pre-computed full-image reconstructions. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing all evaluation results: |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
|
Source code in app/pipelines/evaluation/cae_metrics.py
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 | |
generate_heatmap_overlay(original_image: np.ndarray, error_map: np.ndarray, alpha: float = 0.6) -> np.ndarray
¶
Generate a colour heatmap overlay of the reconstruction error on the original image.
The error map is normalised using robust quantile clamping (1st-99th percentile) to prevent outlier pixels from dominating the colour scale. The heatmap is then blended with the original image.
Colour scheme: - Blue (cool) → low error → likely normal region. - Red (warm) → high error → likely anomalous region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_image
|
ndarray
|
RGB image as numpy array, shape (H, W, 3), values in [0, 255] uint8. |
required |
error_map
|
ndarray
|
2D pixel error map, shape (H, W), values ≥ 0. |
required |
alpha
|
float
|
Blend weight for the heatmap overlay (0=original only, 1=heatmap only). Default 0.6 → 60% heatmap, 40% original. |
0.6
|
Returns:
| Type | Description |
|---|---|
ndarray
|
RGB overlay image as numpy array, shape (H, W, 3), uint8. |
Source code in app/pipelines/evaluation/cae_metrics.py
app.pipelines.evaluation.scoring
¶
Anomaly scoring algorithms for the Keras CAE pipeline.
This module implements two key improvements over naive anomaly scoring that make the system significantly more robust for real-world industrial inspection:
- Top-K Pooling (replaces Max-Pooling for image-level scoring)
- Adaptive Thresholding (replaces a fixed hard-coded cut-off)
Why Image-Level Anomaly Scoring Matters¶
The autoencoder produces a 2D error map (pixel-wise reconstruction error). To decide "is this image anomalous?" we need to collapse this map into a single score.
Max-Pooling
Image score = max(error_map) Problem: A single noisy pixel (camera sensor spike, dust particle, JPEG artefact) can drive the max value very high, producing a false positive on a perfectly good part.
Top-K Pooling
Image score = mean(top K highest pixels) Rationale: Real industrial defects (cracks, scratches, contamination patches) always appear as clusters of elevated error pixels, not isolated spikes. By averaging the K highest values, isolated single-pixel noise is diluted, while genuine defect clusters (which affect many pixels together) still produce reliably high scores.
A commonly effective value is K = 0.2% of total pixels. For a 128x128 image = 16,384 pixels -> K ~= 33 pixels.
Why Adaptive Thresholds Are Essential¶
A fixed threshold (e.g., "score > 0.05 = anomalous") will fail when: - Different cameras / lighting conditions shift the absolute score range. - Different MVTec categories (leather vs. metal) have vastly different texture complexity. - Batch-to-batch variation in normal samples changes the baseline reconstruction quality.
Adaptive approaches calibrate the threshold on the normal training/validation data:
quantile method:
threshold = np.percentile(normal_scores, 95)
Interpretation: "The model is trained; 95% of normal images score below this value.
Anything higher is likely anomalous."
mahalanobis method:
Models the normal score distribution as a Gaussian. The threshold is set at
mean + n_sigma * std. This is more principled than a percentile and is closer to
a proper statistical test (rejecting the null hypothesis that the image is normal).
Module Contents¶
compute_pixel_error_map: Computes per-pixel reconstruction error.top_k_pooling: Aggregates error map to a single image-level score robustly.compute_image_scores: Scores an entire dataset using Top-K pooling.compute_adaptive_threshold: Derives a decision boundary from normal score statistics.
compute_adaptive_threshold(normal_scores: np.ndarray, method: Literal['quantile', 'mahalanobis'] = 'quantile', quantile: float = 0.95, n_sigma: float = 3.0) -> float
¶
Compute an adaptive anomaly decision threshold from normal image scores.
Rather than using a hand-tuned fixed threshold, this function calibrates the decision boundary using the statistical distribution of normal image scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normal_scores
|
ndarray
|
1D array of anomaly scores computed on known-good (normal) images. These are used as the calibration reference. |
required |
method
|
Literal['quantile', 'mahalanobis']
|
Threshold derivation method:
- |
'quantile'
|
quantile
|
float
|
Percentile to use for the quantile method (0 < quantile < 1). Default 0.95 → 95th percentile of normal scores becomes the threshold. |
0.95
|
n_sigma
|
float
|
Number of standard deviations above the mean for Mahalanobis method. Default 3.0 → corresponds to a false positive rate of ≈0.13% under Gaussian. |
3.0
|
Returns:
| Type | Description |
|---|---|
float
|
Threshold float value. Images scoring above this are classified as anomalous. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in app/pipelines/evaluation/scoring.py
compute_image_scores(model: Any, images: np.ndarray, k_fraction: float = 0.002, reconstructions: np.ndarray | None = None) -> tuple[np.ndarray, list[np.ndarray]]
¶
Compute image-level anomaly scores and pixel error maps for a dataset.
This function runs the trained CAE on every test image, computes the per-pixel error map, and aggregates to an image-level score using Top-K pooling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Trained Keras CAE model. Must have a |
required |
images
|
ndarray
|
Array of normalised test images, shape (N, H, W, 3), values in [0, 1]. |
required |
k_fraction
|
float
|
Top-K pooling fraction. See |
0.002
|
reconstructions
|
ndarray | None
|
Optional pre-computed reconstructions. If None, uses model.predict. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, list[ndarray]]
|
Tuple of: - scores: 1D numpy array of image-level anomaly scores, shape (N,). - error_maps: List of N 2D error maps, each shape (H, W). |
Source code in app/pipelines/evaluation/scoring.py
compute_pixel_error_map(original: np.ndarray, reconstruction: np.ndarray, alpha: float = 0.84, sigma: float = 2.0) -> np.ndarray
¶
Compute the per-pixel absolute reconstruction error map.
The error map is a weighted blend of Structural Similarity (SSIM) error and channel-wise Mean Absolute Error (MAE), aligned with the training loss. A Gaussian blur is applied to smooth noise and cluster anomaly predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original
|
ndarray
|
Original normalised image, shape (H, W, 3), values in [0, 1]. |
required |
reconstruction
|
ndarray
|
Reconstructed image from the CAE, same shape as original. |
required |
alpha
|
float
|
Weight for the SSIM component (default 0.84, matches loss). |
0.84
|
sigma
|
float
|
Standard deviation for Gaussian kernel (default 2.0). |
2.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
2D error map, shape (H, W), values ≥ 0. Higher values = more likely anomalous. |
Source code in app/pipelines/evaluation/scoring.py
top_k_pooling(error_map: np.ndarray, k: int | None = None, k_fraction: float = 0.002) -> float
¶
Compute the image-level anomaly score using Top-K pooling.
Top-K pooling is significantly more robust than max-pooling because: - Single noisy pixels (sensor spikes, JPEG artefacts) produce 1 high pixel. - Real defects (scratches, cracks) produce a cluster of many high pixels. Averaging the top-K pixels dilutes isolated spikes while keeping defect clusters high.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_map
|
ndarray
|
2D pixel error map, shape (H, W), values ≥ 0. |
required |
k
|
int | None
|
Explicit number of top pixels to average. If None, derived from |
None
|
k_fraction
|
float
|
Fraction of total pixels to use as K when |
0.002
|
Returns:
| Type | Description |
|---|---|
float
|
Single float representing the image-level anomaly score. Higher = more anomalous. |
Source code in app/pipelines/evaluation/scoring.py
app.pipelines.evaluation.heatmaps
¶
Reconstruction error heatmaps and explainability overlays for autoencoder models.
This module provides pixel-level reconstruction error calculation and visual overlay generation for autoencoder-based anomaly detection models (such as the fully convolutional Keras CAE and PyTorch Autoencoder).
Why Reconstruction Error Over Grad-CAM
Grad-CAM is an attribution technique originally designed for discriminative classification networks, where a scalar class score is backpropagated to intermediate convolutional feature maps to highlight the receptive fields influencing a decision. For autoencoder anomaly detection, direct pixel-wise reconstruction error is mathematically and practically superior:
- Native Generative Objective: Autoencoders are trained exclusively on normal patterns to reconstruct nominal image geometry and texture. The anomaly signal is fundamentally defined as the residual between the original image and its reconstruction (e.g., squared pixel error or structural dissimilarity). Because the decoder yields a full-resolution spatial reconstruction directly, no gradient attribution proxy is needed.
- Resolution and Spatial Locality: Backpropagating an aggregated scalar reconstruction loss via Grad-CAM pools gradients into coarse bottleneck feature maps (e.g., H/16 x W/16), yielding blurry, low-resolution saliency maps that require bilinear upsampling and can suffer from gradient saturation. In contrast, the per-pixel residual map preserves fine-grained defect contours at full spatial resolution without gradient artifacts.
To produce smooth, visually interpretable overlays analogous to Grad-CAM, the raw per-pixel reconstruction residual is regularized with a gentle Gaussian blur (default sigma=3.0), percentile-clipped to suppress outliers, and blended over the original image using a perceptual colormap.
Typical usage example
error_dict = compute_error_heatmap(model, input_image, sigma=3.0) overlay = overlay_heatmap(original_uint8_image, error_dict["heatmap"]) gt_overlay = overlay_ground_truth(overlay, binary_ground_truth_mask)
compute_error_heatmap(model: Any, image: np.ndarray, sigma: float = 3.0, reconstruction: np.ndarray | None = None) -> dict[str, np.ndarray]
¶
Compute a smoothed reconstruction error heatmap for a single image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
A compiled |
required |
image
|
ndarray
|
Single normalised image, shape (H, W, 3), float32 values in [0, 1]. |
required |
sigma
|
float
|
Standard deviation for the Gaussian blur (smoothness). |
3.0
|
reconstruction
|
ndarray | None
|
Optional precomputed reconstructed image, shape (H, W, 3). |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary containing:
- |
Source code in app/pipelines/evaluation/heatmaps.py
overlay_ground_truth(original_image: np.ndarray, gt_mask: np.ndarray | None, color: tuple[int, int, int] = (0, 255, 0), alpha: float = 0.4) -> np.ndarray[Any, Any]
¶
Blend a binary ground truth mask onto the original image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_image
|
ndarray
|
RGB image, shape (H, W, 3), uint8. |
required |
gt_mask
|
ndarray | None
|
Binary mask, shape (H, W), uint8 (0 or 1). Can be None. |
required |
color
|
tuple[int, int, int]
|
RGB color tuple to draw the mask (e.g. Red=(255,0,0), Green=(0,255,0)). |
(0, 255, 0)
|
alpha
|
float
|
Opacity of the mask overlay. |
0.4
|
Returns:
| Type | Description |
|---|---|
ndarray[Any, Any]
|
RGB overlay image, shape (H, W, 3), uint8. |
Source code in app/pipelines/evaluation/heatmaps.py
overlay_heatmap(original_image: np.ndarray, heatmap: np.ndarray, alpha: float = 0.35, colormap: str = 'jet') -> np.ndarray[Any, Any]
¶
Blend a heatmap onto the original image using a perceptual colourmap.
The heatmap is converted from greyscale → RGB via a colourmap (jet by default), then composited over the original image. Opacity is scaled per-pixel by the heatmap magnitude so regions with near-zero activation show the original image unchanged, while highly activated regions show a vivid colour tint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_image
|
ndarray
|
RGB image, shape (H, W, 3), uint8 values in [0, 255]. |
required |
heatmap
|
ndarray
|
Normalised heatmap, shape (H, W), float32 in [0, 1]. |
required |
alpha
|
float
|
Maximum overlay opacity for the highest-activation pixels. Default 0.35 keeps the original image clearly visible beneath the anomaly. |
0.35
|
colormap
|
str
|
Matplotlib colourmap name applied to the heatmap. |
'jet'
|
Returns:
| Type | Description |
|---|---|
ndarray[Any, Any]
|
RGB overlay image, shape (H, W, 3), uint8. |
Source code in app/pipelines/evaluation/heatmaps.py
User Interface & Reusable Components¶
app.ui.components.selectors
¶
Standardized Streamlit selectors for dataset directories and categories.
render_dataset_and_category_selector(key_prefix: str, default_root: str = 'data/raw/mvtec_ad', default_category: str = 'bottle', on_category_change: Callable[..., Any] | None = None) -> tuple[str, str]
¶
Render standardized two-column dataset root directory input and dynamic category selector.
Automatically scans the dataset root directory on disk to dynamically populate available category folders, while falling back cleanly to canonical MVTec AD benchmark categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_prefix
|
str
|
Prefix used for Streamlit widget keys and session state (e.g. 'kcae', 'b', 'dino'). |
required |
default_root
|
str
|
Default path string for the dataset root input. |
'data/raw/mvtec_ad'
|
default_category
|
str
|
Default category name if available. |
'bottle'
|
on_category_change
|
Callable[..., Any] | None
|
Optional callback function triggered when the user changes the category. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
A tuple of (dataset_root_directory_string, selected_category_string). |
Source code in app/ui/components/selectors.py
Core Configuration & Logging¶
app.core.config
¶
Validated runtime settings for the industrial component anomaly detection system.
AppSettings
¶
Bases: BaseSettings
Validated runtime settings for the application.
Attributes:
| Name | Type | Description |
|---|---|---|
model_config |
Model configuration for pydantic-settings. |
|
PROJECT_NAME |
str
|
Name of the project. |
ENVIRONMENT |
str
|
Environment in which the application is running. |
API_V1_STR |
str
|
API version 1 string. |
DEBUG |
bool
|
Whether the application is running in debug mode. |
Source code in app/core/config.py
app.core.logger
¶
Logging utilities module.
setup_logger(name: str = 'app') -> logging.Logger
¶
Set up and configure standard logger emitting to stdout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the logger. |
'app'
|
Returns:
| Type | Description |
|---|---|
Logger
|
Logger instance. |