π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement custom errors (#3430)
Edgar Ribae68ac757204e
diff --git a/kornia/core/check.py b/kornia/core/check.pyindex 7f16bbd54..c5f9eeb4e 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -19,6 +19,7 @@from __future__ import annotations+import osfrom typing import Any, Optional, Sequence, TypeVar, castimport torch@@ -26,6 +27,14 @@ from torch import float16, float32, float64from typing_extensions import TypeGuardfrom kornia.core import Tensor+from kornia.core.exceptions import (+ BaseError,+ DeviceError,+ ImageError,+ ShapeError,+ TypeCheckError,+ ValueCheckError,+)__all__ = ["KORNIA_CHECK",@@ -41,13 +50,92 @@ __all__ = ["KORNIA_CHECK_SHAPE","KORNIA_CHECK_TYPE","KORNIA_UNWRAP",+ "BaseError",+ "DeviceError",+ "ImageError",+ "ShapeError",+ "TypeCheckError",+ "ValueCheckError",+ "are_checks_enabled",+ "disable_checks",+ "enable_checks",]++def _should_enable_checks() -> bool:+ """Determine if checks should be enabled.++ Returns:+ True if checks should be enabled, False otherwise.++ Checks are enabled by default in debug mode (normal Python execution).+ Checks are disabled when:+ - Running with `python -O` (optimized mode)+ - Environment variable KORNIA_CHECKS=0 is set+ """+ env_var = os.getenv("KORNIA_CHECKS", None)+ if env_var is not None:+ # Explicit override via environment variable+ return env_var.lower() in ("1", "true", "yes", "on")+ # Default: enabled in debug mode, disabled in optimized mode+ return __debug__+++# Module-level flag - evaluated once at import time, but can be changed at runtime+_KORNIA_CHECKS_ENABLED: bool = _should_enable_checks()+++def are_checks_enabled() -> bool:+ """Check if validation is currently enabled.++ Returns:+ True if checks are enabled, False otherwise.++ Example:+ >>> are_checks_enabled()+ True+ """+ return _KORNIA_CHECKS_ENABLED+++def disable_checks() -> None:+ """Disable all Kornia validation checks for production.++ Note:+ This function can override the initial setting determined at import time.+ The module-level flag is evaluated once at import time for performance, but+ can be changed at runtime via this function or `enable_checks()`.++ Example:+ >>> disable_checks()+ >>> are_checks_enabled()+ False+ """+ global _KORNIA_CHECKS_ENABLED # noqa: PLW0603+ _KORNIA_CHECKS_ENABLED = False+++def enable_checks() -> None:+ """Enable all Kornia validation checks.++ Note:+ This function can override the initial setting determined at import time.+ The module-level flag is evaluated once at import time for performance, but+ can be changed at runtime via this function or `disable_checks()`.++ Example:+ >>> enable_checks()+ >>> are_checks_enabled()+ True+ """+ global _KORNIA_CHECKS_ENABLED # noqa: PLW0603+ _KORNIA_CHECKS_ENABLED = True++# Logger api-# TODO: add somehow type check, or enforce to do it before-def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> bool:+def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], msg: Optional[str] = None, raises: bool = True) -> bool:"""Check whether a tensor has a specified shape.The shape can be specified with a implicit or explicit list of strings.@@ -56,10 +144,17 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> boolArgs:x: the tensor to evaluate.shape: a list with strings with the expected shape.+ msg: optional custom message to append to error.raises: bool indicating whether an exception should be raised upon failure.Raises:- Exception: if the input tensor is has not the expected shape and raises is True.+ ShapeError: if the input tensor does not have the expected shape and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x = torch.rand(2, 3, 4, 4)@@ -71,6 +166,10 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> boolTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if "*" == shape[0]:shape_to_check = shape[1:]x_shape_to_check = x.shape[-len(shape) + 1 :]@@ -83,7 +182,19 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> boolif len(x_shape_to_check) != len(shape_to_check):if raises:- raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")+ expected_dims = len(shape_to_check)+ actual_dims = len(x_shape_to_check)+ error_msg = f"Shape dimension mismatch: expected {expected_dims} dimensions, got {actual_dims}.\n"+ error_msg += f" Expected shape: {shape}\n"+ x_shape_list = list(x.shape)+ error_msg += f" Actual shape: {x_shape_list}"+ if msg is not None:+ error_msg += f"\n {msg}"+ raise ShapeError(+ error_msg,+ actual_shape=x_shape_list,+ expected_shape=shape,+ )else:return False@@ -96,7 +207,17 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> booldim = int(dim_)if x_shape_to_check[i] != dim:if raises:- raise TypeError(f"{x} shape must be [{shape}]. Got {x.shape}")+ error_msg = f"Shape mismatch at dimension {i}: expected {dim}, got {x_shape_to_check[i]}.\n"+ error_msg += f" Expected shape: {shape}\n"+ x_shape_list = list(x.shape)+ error_msg += f" Actual shape: {x_shape_list}"+ if msg is not None:+ error_msg += f"\n {msg}"+ raise ShapeError(+ error_msg,+ actual_shape=x_shape_list,+ expected_shape=shape,+ )else:return Falsereturn True@@ -111,7 +232,13 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = Trueraises: bool indicating whether an exception should be raised upon failure.Raises:- Exception: if the condition is met and raises is True.+ BaseError: if the condition is not met and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x = torch.rand(2, 3, 3)@@ -119,9 +246,17 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = TrueTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if not condition:if raises:- raise Exception(f"{condition} not true.\n{msg}")+ if msg is None:+ error_msg = "Validation condition failed"+ else:+ error_msg = msg+ raise BaseError(error_msg)return Falsereturn True@@ -141,7 +276,6 @@ def KORNIA_UNWRAP(maybe_obj: object, typ: Any) -> Any:T = TypeVar("T", bound=type)-# TODO: fix mypy typeguard issuedef KORNIA_CHECK_TYPE(x: object, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True) -> TypeGuard[T]:@@ -154,17 +288,34 @@ def KORNIA_CHECK_TYPE(raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the input variable does not match with the expected and raises is True.+ TypeCheckError: if the input variable does not match with the expected and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> KORNIA_CHECK_TYPE("foo", str, "Invalid string")True"""- # TODO: Move to use typeguard here dropping support for JIT+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if not isinstance(x, typ):if raises:- raise TypeError(f"Invalid type: {type(x)}.\n{msg}")+ expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)+ error_msg = f"Type mismatch: expected {expected_type_str}, got {type(x).__name__}."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(+ error_msg,+ actual_type=type(x),+ expected_type=typ,+ )return Falsereturn True@@ -178,7 +329,13 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the input variable does not match with the expected and raises is True.+ TypeCheckError: if the input variable does not match with the expected and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x = torch.rand(2, 3, 3)@@ -186,10 +343,20 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool =True"""- # TODO: Move to use typeguard here dropping support for JIT+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if not isinstance(x, Tensor):if raises:- raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")+ error_msg = f"Type mismatch: expected Tensor, got {type(x).__name__}."+ if msg is not None:+ error_msg += f"\n {msg}"+ raise TypeCheckError(+ error_msg,+ actual_type=type(x),+ expected_type=Tensor,+ )return Falsereturn True@@ -202,11 +369,17 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool =raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the input variable does not match with the expected and raises is True.+ TypeCheckError: if the input variable does not match with the expected and raises is True.Return:True if the input is a list of Tensors, otherwise return False.+ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.+Example:>>> x = torch.rand(2, 3, 3)>>> KORNIA_CHECK_IS_LIST_OF_TENSOR(x, raises=False)@@ -215,10 +388,19 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool =True"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+are_tensors = isinstance(x, list) and all(isinstance(d, Tensor) for d in x)if not are_tensors:if raises:- raise TypeError(f"Provided container of type {type(x)} is not a list of tensors")+ error_msg = f"Type mismatch: expected list[Tensor], got {type(x).__name__}."+ raise TypeCheckError(+ error_msg,+ actual_type=type(x),+ expected_type=list[Tensor],+ )return Falsereturn True@@ -228,12 +410,17 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:Args:x: first tensor to evaluate.- y: sencod tensor to evaluate.- msg: message to show in the exception.+ y: second tensor to evaluate.raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the two tensors are not in the same device and raises is True.+ DeviceError: if the two tensors are not in the same device and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x1 = torch.rand(2, 3, 3)@@ -242,9 +429,20 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:True"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if x.device != y.device:if raises:- raise TypeError(f"Not same device for tensors. Got: {x.device} and {y.device}")+ error_msg = "Device mismatch: tensors must be on the same device.\n"+ error_msg += f" First tensor device: {x.device}\n"+ error_msg += f" Second tensor device: {y.device}"+ raise DeviceError(+ error_msg,+ actual_devices=[x.device, y.device],+ expected_device=x.device,+ )return Falsereturn True@@ -258,7 +456,13 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None,raises: bool indicating whether an exception should be raised upon failure.Raises:- Exception: if all the tensors are not in the same device and raises is True.+ DeviceError: if all the tensors are not in the same device and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x1 = torch.rand(2, 3, 3)@@ -267,10 +471,24 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None,True"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, "Expected a list with at least one element", raises)if not all(tensors[0].device == x.device for x in tensors):if raises:- raise Exception(f"Not same device for tensors. Got: {[x.device for x in tensors]}.\n{msg}")+ devices = [x.device for x in tensors]+ error_msg = "Device mismatch: all tensors must be on the same device.\n"+ error_msg += f" Expected device: {tensors[0].device}\n"+ error_msg += f" Actual devices: {devices}"+ if msg is not None:+ error_msg += f"\n {msg}"+ raise DeviceError(+ error_msg,+ actual_devices=devices,+ expected_device=tensors[0].device,+ )return Falsereturn True@@ -280,12 +498,17 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:Args:x: first tensor to evaluate.- y: sencod tensor to evaluate.- msg: message to show in the exception.+ y: second tensor to evaluate.raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the two tensors have not the same shape and raises is True.+ ShapeError: if the two tensors have not the same shape and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> x1 = torch.rand(2, 3, 3)@@ -294,9 +517,22 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:True"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if x.shape != y.shape:if raises:- raise TypeError(f"Not same shape for tensors. Got: {x.shape} and {y.shape}")+ error_msg = "Shape mismatch: tensors must have the same shape.\n"+ x_shape_list = list(x.shape)+ y_shape_list = list(y.shape)+ error_msg += f" First tensor shape: {x_shape_list}\n"+ error_msg += f" Second tensor shape: {y_shape_list}"+ raise ShapeError(+ error_msg,+ actual_shape=x_shape_list,+ expected_shape=y_shape_list,+ )return Falsereturn True@@ -310,7 +546,13 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = Traises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if all the input tensor has not a shape :math:`(3,H,W)` and raises is True.+ ImageError: if the input tensor does not have a shape :math:`(3,H,W)` and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> img = torch.rand(2, 3, 4, 4)@@ -318,9 +560,16 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = TTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if len(x.shape) < 3 or x.shape[-3] != 3:if raises:- raise TypeError(f"Not a color tensor. Got: {type(x)}.\n{msg}")+ error_msg = f"Not a color tensor. Got: {type(x)}."+ if msg is not None:+ error_msg += f"\n{msg}"+ raise ImageError(error_msg)return Falsereturn True@@ -334,7 +583,13 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = Trraises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(H,W)` and raises is True.+ ImageError: if the tensor does not have a shape :math:`(1,H,W)` or :math:`(H,W)` and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> img = torch.rand(2, 1, 4, 4)@@ -342,9 +597,16 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = TrTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):if raises:- raise TypeError(f"Not a gray tensor. Got: {type(x)}.\n{msg}")+ error_msg = f"Not a gray tensor. Got: {type(x)}."+ if msg is not None:+ error_msg += f"\n{msg}"+ raise ImageError(error_msg)return Falsereturn True@@ -358,7 +620,13 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises:raises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the tensor has not a shape :math:`(1,H,W)` or :math:`(3,H,W)` and raises is True.+ ImageError: if the tensor does not have a shape :math:`(1,H,W)` or :math:`(3,H,W)` and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> img = torch.rand(2, 3, 4, 4)@@ -366,9 +634,16 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises:True"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:if raises:- raise TypeError(f"Not a color or gray tensor. Got: {type(x)}.\n{msg}")+ error_msg = f"Not a color or gray tensor. Got: {type(x)}."+ if msg is not None:+ error_msg += f"\n{msg}"+ raise ImageError(error_msg)return Falsereturn True@@ -384,8 +659,14 @@ def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = T8-bit image (0-255) or not.Raises:- TypeException: if all the input tensor has not 1) a shape :math:`(3,H,W)`,- 2) [0, 1] for float or [0, 255] for int, 3) and raises is True.+ ImageError: if the tensor shape is invalid and raises is True.+ ValueCheckError: if the tensor value range is invalid and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> img = torch.rand(2, 3, 4, 4)@@ -393,6 +674,10 @@ def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = TTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+# Combine the color or gray check with the range checkif not raises and not KORNIA_CHECK_IS_COLOR_OR_GRAY(x, msg, raises):return False@@ -421,7 +706,13 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: boolraises: bool indicating whether an exception should be raised upon failure.Raises:- TypeException: if the descriptors shape do not match with the distance matrix and raises is True.+ ShapeError: if the descriptors shape do not match with the distance matrix and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> desc1 = torch.rand(4)@@ -431,11 +722,29 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor, raises: boolTrue"""+ if not torch.jit.is_scripting():+ if not _KORNIA_CHECKS_ENABLED:+ return True+if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):if raises:- raise TypeError(- f"distance matrix shape {dm.shape} is not onsistent with descriptors shape: desc1 {desc1.shape} "- f"desc2 {desc2.shape}"+ expected_shape = (desc1.size(0), desc2.size(0))+ desc1_size = desc1.size(0)+ desc2_size = desc2.size(0)+ error_msg = "Distance matrix shape mismatch.\n"+ error_msg += (+ f" Expected shape: {expected_shape} (from desc1.shape[0]={desc1_size}, desc2.shape[0]={desc2_size})\n"+ )+ dm_shape_list = list(dm.shape)+ desc1_shape_list = list(desc1.shape)+ desc2_shape_list = list(desc2.shape)+ error_msg += f" Actual shape: {dm_shape_list}\n"+ error_msg += f" desc1 shape: {desc1_shape_list}\n"+ error_msg += f" desc2 shape: {desc2_shape_list}"+ raise ShapeError(+ error_msg,+ actual_shape=dm_shape_list,+ expected_shape=expected_shape,)return Falsereturn True@@ -449,7 +758,13 @@ def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool:raises: bool indicating whether an exception should be raised upon failure.Raises:- Exception: if the input laf does not have a shape :math:`(B,N,2,3)` and raises is True.+ ShapeError: if the input laf does not have a shape :math:`(B,N,2,3)` and raises is True.++ Note:+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS+ environment variable. In TorchScript-compiled code, checks always run (TorchScript+ cannot access module-level globals, but the validation logic is fast). When running+ with `python -O`, Python's optimizer may eliminate some checks.Example:>>> lafs = torch.rand(2, 10, 2, 3)@@ -457,14 +772,22 @@ def KORNIA_CHECK_LAF(laf: Tensor, raises: bool = True) -> bool:True"""- return KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"], raises)+ return KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"], raises=raises)def _handle_invalid_range(msg: Optional[str], raises: bool, min_val: float | Tensor, max_val: float | Tensor) -> bool:"""Handle invalid range cases."""- err_msg = f"Invalid image value range. Expect [0, 1] but got [{min_val}, {max_val}]."+ # Extract scalar values if tensors+ min_scalar = min_val.item() if isinstance(min_val, Tensor) else min_val+ max_scalar = max_val.item() if isinstance(max_val, Tensor) else max_val++ err_msg = f"Value range mismatch: expected [0, 1], got [{min_scalar}, {max_scalar}]."if msg is not None:- err_msg += f"\n{msg}"+ err_msg += f"\n {msg}"if raises:- raise ValueError(err_msg)+ raise ValueCheckError(+ err_msg,+ actual_value=(min_scalar, max_scalar),+ expected_range=(0.0, 1.0),+ )return Falsediff --git a/kornia/core/exceptions.py b/kornia/core/exceptions.pynew file mode 100644index 000000000..c7a1dbe64--- /dev/null+++ b/kornia/core/exceptions.py@@ -0,0 +1,123 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Custom exception classes for Kornia validation checks."""++from __future__ import annotations++from typing import Any, Optional++__all__ = [+ "BaseError",+ "DeviceError",+ "ImageError",+ "ShapeError",+ "TypeCheckError",+ "ValueCheckError",+]+++class BaseError(Exception):+ """Base exception class for all Kornia errors."""++ pass+++class ShapeError(BaseError):+ """Raised when tensor shape validation fails.++ Attributes:+ actual_shape: The actual shape of the tensor that failed validation.+ expected_shape: The expected shape specification.+ """++ def __init__(+ self,+ message: str,+ *,+ actual_shape: Optional[tuple[int, ...] | list[int]] = None,+ expected_shape: Optional[list[str] | tuple[int, ...]] = None,+ ):+ super().__init__(message)+ self.actual_shape = actual_shape+ self.expected_shape = expected_shape+++class TypeCheckError(BaseError):+ """Raised when type validation fails.++ Attributes:+ actual_type: The actual type that failed validation.+ expected_type: The expected type.+ """++ def __init__(+ self,+ message: str,+ *,+ actual_type: Optional[type] = None,+ expected_type: Optional[type | tuple[type, ...]] = None,+ ):+ super().__init__(message)+ self.actual_type = actual_type+ self.expected_type = expected_type+++class ValueCheckError(BaseError):+ """Raised when value/range validation fails.++ Attributes:+ actual_value: The actual value that failed validation.+ expected_range: The expected value range (min, max).+ """++ def __init__(+ self,+ message: str,+ *,+ actual_value: Optional[Any] = None,+ expected_range: Optional[tuple[Any, Any]] = None,+ ):+ super().__init__(message)+ self.actual_value = actual_value+ self.expected_range = expected_range+++class DeviceError(BaseError):+ """Raised when device mismatch validation fails.++ Attributes:+ actual_devices: The actual device(s) that failed validation.+ expected_device: The expected device.+ """++ def __init__(+ self,+ message: str,+ *,+ actual_devices: Optional[list] = None,+ expected_device: Optional[Any] = None,+ ):+ super().__init__(message)+ self.actual_devices = actual_devices+ self.expected_device = expected_device+++class ImageError(BaseError):+ """Raised when image-specific validation fails."""++ passdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 78cacf9ef..6ffe546f5 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4039,9 +4039,11 @@ class TestRandomSaltAndPepperNoise(BaseTester):r"and it should be a tuple\.",):RandomSaltAndPepperNoise(salt_vs_pepper=(0.1, 0.2, 0.3))+ from kornia.core.exceptions import BaseError+with pytest.raises(- Exception,- match=r"False not true\.\s*Salt_vs_pepper values must be between 0 and 1\.\s+"+ BaseError,+ match=r"Salt_vs_pepper values must be between 0 and 1\.\s+"r"Recommended value 0\.5\.",):RandomSaltAndPepperNoise(salt_vs_pepper=(0.4, 3))@@ -4054,8 +4056,8 @@ class TestRandomSaltAndPepperNoise(BaseTester):):RandomSaltAndPepperNoise(amount=())with pytest.raises(- Exception,- match=r"False not true\.\s*amount of noise values must be between 0 and 1\.\s+"+ BaseError,+ match=r"amount of noise values must be between 0 and 1\.\s+"r"Recommended values less than 0\.2\.",):RandomSaltAndPepperNoise(amount=(0.05, 3))@@ -4324,16 +4326,18 @@ class TestRandomChannelDropout(BaseTester):self.assert_close(res, expected, rtol=1e-4, atol=1e-4)def test_exception(self, device, dtype):+ from kornia.core.exceptions import BaseError, TypeCheckError+num_drop_channels = 2.0- with pytest.raises(TypeError, match=f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}"):- RandomChannelDropout(num_drop_channels=num_drop_channels)+ with pytest.raises(TypeCheckError, match=f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}"):+ RandomChannelDropout(num_drop_channels=num_drop_channels, fill_value=0.0)num_drop_channels = 0with pytest.raises(- Exception,+ BaseError,match=f"Invalid value in `num_drop_channels`. Must be an int greater than 1. Got: {num_drop_channels}",):- RandomChannelDropout(num_drop_channels=num_drop_channels)+ RandomChannelDropout(num_drop_channels=num_drop_channels, fill_value=0.0)num_drop_channels = 5input_tensor = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)@@ -4345,12 +4349,12 @@ class TestRandomChannelDropout(BaseTester):fill_value = 2.0with pytest.raises(- Exception, match=f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}"+ BaseError, match=f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}"):RandomChannelDropout(fill_value=fill_value)fill_value = 1- with pytest.raises(TypeError, match=f"`fill_value` must be a float. Got: {type(fill_value)}"):+ with pytest.raises(TypeCheckError, match=f"`fill_value` must be a float. Got: {type(fill_value)}"):RandomChannelDropout(fill_value=fill_value)@pytest.mark.parametrize("channel_shape, batch_shape", [(3, 1), (1, 1), (5, 5)])diff --git a/tests/augmentation/test_backward.py b/tests/augmentation/test_backward.pyindex 932d46057..3ff9db6b9 100644--- a/tests/augmentation/test_backward.py+++ b/tests/augmentation/test_backward.py@@ -32,6 +32,7 @@ from kornia.augmentation import ()[email protected](reason="To be deprecated")class TestColorJiggleBackward:@pytest.mark.parametrize("brightness", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@pytest.mark.parametrize("contrast", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@@ -87,6 +88,7 @@ class TestColorJiggleBackward:assert (hue.to(device=device, dtype=dtype) - aug.hue.data).sum() != 0[email protected](reason="To be deprecated")class TestColorJitterBackward:@pytest.mark.parametrize("brightness", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@pytest.mark.parametrize("contrast", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@@ -142,6 +144,7 @@ class TestColorJitterBackward:assert (hue.to(device=device, dtype=dtype) - aug.hue.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomAffineBackward:@pytest.mark.parametrize("degrees", [10, [10.0, 20.0], (10, 20), torch.tensor(10.0), torch.tensor([10, 20])])@pytest.mark.parametrize("translate", [[0.1, 0.2], torch.tensor([0.1, 0.2])])@@ -251,6 +254,7 @@ class TestRandomAffineBackward:assert (shear.to(device=device, dtype=dtype) - aug._param_generator.shear.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomRotationBackward:@pytest.mark.parametrize("degrees", [10, [10.0, 20.0], (10, 20), torch.tensor(10.0), torch.tensor([10, 20])])@pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.@@ -290,6 +294,7 @@ class TestRandomRotationBackward:assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomPerspectiveBackward:@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])@pytest.mark.parametrize("resample", ["bilinear"]) # TODO: Ignore nearest for now.@@ -335,6 +340,7 @@ class TestRandomPerspectiveBackward:).sum() != 0[email protected](reason="To be deprecated")class TestRandomMotionBlurBackward:@pytest.mark.parametrize("angle", [20.0, torch.tensor([-20.0, 20.0])])@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])@@ -389,6 +395,7 @@ class TestRandomMotionBlurBackward:assert (direction.to(device=device, dtype=dtype) - aug._param_generator.direction.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomSharpnessBackward:@pytest.mark.parametrize("sharpness", [0.5, [0, 0.5], torch.tensor([0, 0.5])])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -418,6 +425,7 @@ class TestRandomSharpnessBackward:assert (sharpness.to(device=device, dtype=dtype) - aug._param_generator.sharpness.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomResizedCropBackward:@pytest.mark.skip("Param gen is probably breaking grads.")@pytest.mark.parametrize("scale", [[0.08, 1.0], torch.tensor([0.08, 1.0])])@@ -458,6 +466,7 @@ class TestRandomResizedCropBackward:assert (ratio.to(device=device, dtype=dtype) - aug.ratio.data).sum() != 0[email protected](reason="To be deprecated")class TestRandomErasingBackward:@pytest.mark.skip("Need differentiable indexing.")@pytest.mark.parametrize("scale", [[0.02, 0.33], torch.tensor([0.02, 0.33])])diff --git a/tests/augmentation/test_backward_3d.py b/tests/augmentation/test_backward_3d.pyindex 05ed0c2e3..7489fa4be 100644--- a/tests/augmentation/test_backward_3d.py+++ b/tests/augmentation/test_backward_3d.py@@ -22,6 +22,7 @@ from torch import nnfrom kornia.augmentation import RandomAffine3D, RandomMotionBlur3D, RandomPerspective3D, RandomRotation3D[email protected](reason="To be deprecated")class TestRandomAffine3DBackward:@pytest.mark.parametrize("degrees",diff --git a/tests/color/test_gray.py b/tests/color/test_gray.pyindex e3d2758c3..775d126b4 100644--- a/tests/color/test_gray.py+++ b/tests/color/test_gray.py@@ -37,7 +37,9 @@ class TestGrayscaleToRgb(BaseTester):assert kornia.color.grayscale_to_rgb(img).shape == (batch_size, 3, height, width)def test_exception(self, device, dtype):- with pytest.raises(TypeError):+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError):assert kornia.color.grayscale_to_rgb([0.0])with pytest.raises(ValueError):@@ -141,7 +143,9 @@ class TestRgbToGrayscale(BaseTester):assert kornia.color.rgb_to_grayscale(img).shape == (batch_size, 1, height, width)def test_exception(self, device, dtype):- with pytest.raises(TypeError):+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError):assert kornia.color.rgb_to_grayscale([0.0])with pytest.raises(ValueError):@@ -249,7 +253,9 @@ class TestBgrToGrayscale(BaseTester):assert kornia.color.bgr_to_grayscale(img).shape == (batch_size, 1, height, width)def test_exception(self, device, dtype):- with pytest.raises(TypeError):+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError):assert kornia.color.bgr_to_grayscale([0.0])with pytest.raises(ValueError):diff --git a/tests/color/test_raw.py b/tests/color/test_raw.pyindex 783d542a2..a6df10da9 100644--- a/tests/color/test_raw.py+++ b/tests/color/test_raw.py@@ -239,19 +239,21 @@ class TestRawToRgb2x2Downscaled(BaseTester):)def test_exception(self, device, dtype):- with pytest.raises(Exception) as errinf:+ from kornia.core.exceptions import BaseError, ShapeError++ with pytest.raises(BaseError) as errinf:kornia.color.raw_to_rgb_2x2_downscaled([0.0], kornia.color.CFA.BG)- assert "Input type is not a torch.Tensor" in str(errinf)+ assert "Input type is not a torch.Tensor" in str(errinf.value)- with pytest.raises(TypeError) as errinf:+ with pytest.raises(ShapeError) as errinf:img = torch.ones(1, 1, device=device, dtype=dtype)kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.GB)- assert "shape must be" in str(errinf)+ assert "Shape dimension mismatch" in str(errinf.value) or "Expected shape" in str(errinf.value)- with pytest.raises(TypeError) as errinf:+ with pytest.raises(ShapeError) as errinf:img = torch.ones(2, 2, 2, device=device, dtype=dtype)kornia.color.raw_to_rgb_2x2_downscaled(img, kornia.color.CFA.RG)- assert "shape must be" in str(errinf)+ assert "Shape dimension mismatch" in str(errinf.value) or "Expected shape" in str(errinf.value)with pytest.raises(Exception) as errinf:img = torch.ones(1, 3, 2, device=device, dtype=dtype)diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.pyindex 31e5ee50f..0d726000f 100644--- a/tests/contrib/test_kmeans.py+++ b/tests/contrib/test_kmeans.py@@ -63,22 +63,24 @@ class TestKMeans(BaseTester):assert out2.shape == (num_clusters, D)def test_exception(self, device, dtype):+ from kornia.core.exceptions import BaseError, ShapeError+# case: cluster_center = 0:- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:kornia.contrib.KMeans(0, None, 10e-4, 10, 0)- assert "num_clusters can't be 0" in str(errinfo)+ assert "num_clusters can't be 0" in str(errinfo.value)# case: cluster centers is not a 2D tensor- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:starting_centers = torch.rand((2, 3, 5), device=device, dtype=dtype)kmeans = kornia.contrib.KMeans(None, starting_centers, 10e-4, 100, 0)- assert "shape must be [['C', 'D']]. Got torch.Size([2, 3, 5])" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value)# case: input data is not a 2D tensor- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)kmeans.fit(torch.rand((1000, 5, 60), dtype=dtype, device=device))- assert "shape must be [['N', 'D']]. Got torch.Size([1000, 5, 60])" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)# case: column dimensions of cluster centers and data to be predicted do not matchwith pytest.raises(Exception) as errinfo:diff --git a/tests/core/test_check.py b/tests/core/test_check.pyindex bbb01e410..9b86f36f0 100644--- a/tests/core/test_check.py+++ b/tests/core/test_check.py@@ -34,6 +34,14 @@ from kornia.core.check import (KORNIA_CHECK_SHAPE,KORNIA_CHECK_TYPE,)+from kornia.core.exceptions import (+ BaseError,+ DeviceError,+ ImageError,+ ShapeError,+ TypeCheckError,+ ValueCheckError,+)class TestCheck:@@ -41,7 +49,7 @@ class TestCheck:assert KORNIA_CHECK(True, "This is a test") is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(BaseError):KORNIA_CHECK(False, "This is a test")def test_invalid_raises_false(self):@@ -76,7 +84,7 @@ class TestCheckShape:],)def test_invalid(self, data, shape):- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_SHAPE(data, shape)def test_invalid_raises_false(self):@@ -100,11 +108,11 @@ class TestCheckSameShape:assert op_jit(torch.rand(2, 3), torch.rand(2, 3)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(2, 2, 3))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(1, 2, 3))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_SAME_SHAPE(torch.rand(2, 3), torch.rand(2, 3, 3))def test_invalid_raises_false(self):@@ -119,11 +127,11 @@ class TestCheckType:assert KORNIA_CHECK_TYPE(torch.rand(1), (int, torch.Tensor)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_TYPE("world", int)- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_TYPE(23, float)- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_TYPE(23, (float, str))def test_invalid_raises_false(self):@@ -135,7 +143,7 @@ class TestCheckIsTensor:assert KORNIA_CHECK_IS_TENSOR(torch.rand(1)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_IS_TENSOR([1, 2, 3])def test_invalid_raises_false(self):@@ -147,9 +155,9 @@ class TestCheckIsListOfTensor:assert KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.rand(1), torch.rand(1), torch.rand(1)]) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.rand(1), [2, 3], torch.rand(1)])- with pytest.raises(Exception):+ with pytest.raises(TypeCheckError):KORNIA_CHECK_IS_LIST_OF_TENSOR([1, 2, 3])def test_invalid_raises_false(self):@@ -162,7 +170,7 @@ class TestCheckSameDevice:@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")def test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(DeviceError):KORNIA_CHECK_SAME_DEVICE(torch.rand(1, device="cpu"), torch.rand(1, device="cuda"))@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")@@ -178,7 +186,7 @@ class TestCheckSameDevices:@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")def test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(DeviceError):KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device="cpu"), torch.rand(1, device="cuda")])@pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")@@ -196,13 +204,13 @@ class TestCheckIsColor:assert KORNIA_CHECK_IS_COLOR(torch.rand(2, 3, 4, 4)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR(torch.rand(1, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR(torch.rand(2, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR(torch.rand(3, 4, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR(torch.rand(1, 3, 4, 4, 4))def test_invalid_raises_false(self):@@ -216,13 +224,13 @@ class TestCheckIsGray:assert KORNIA_CHECK_IS_GRAY(torch.rand(3, 1, 4, 4)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_GRAY(torch.rand(3, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_GRAY(torch.rand(1, 4, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_GRAY(torch.rand(1, 3, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_GRAY(torch.rand(1, 3, 4, 4, 4))def test_invalid_raises_false(self):@@ -239,9 +247,9 @@ class TestCheckIsColorOrGray:assert KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(3, 1, 4, 4)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 4, 4, 4))- with pytest.raises(Exception):+ with pytest.raises(ImageError):KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 3, 4, 4, 4))def test_invalid_raises_false(self):@@ -253,13 +261,13 @@ class TestCheckDmDesc:assert KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 8)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 7))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(3, 8))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(3, 7))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 3, 8))def test_invalid_raises_false(self):@@ -271,13 +279,13 @@ class TestCheckLaf:assert KORNIA_CHECK_LAF(torch.rand(4, 2, 2, 3)) is Truedef test_invalid(self):- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_LAF(torch.rand(4, 2, 2))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_LAF(torch.rand(4, 2, 3, 2))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_LAF(torch.rand(4, 2, 2, 2))- with pytest.raises(Exception):+ with pytest.raises(ShapeError):KORNIA_CHECK_LAF(torch.rand(4, 2, 3, 3, 3))def test_invalid_raises_false(self):@@ -297,12 +305,12 @@ class TestCheckIsImage:assert KORNIA_CHECK_IS_IMAGE(y) is Truedef test_invalid_float_range(self):- with pytest.raises(Exception):+ with pytest.raises(ValueCheckError):KORNIA_CHECK_IS_IMAGE(torch.tensor([[[-0.5, 1.2]]], dtype=torch.float32))def test_invalid_int_range(self):bad = torch.tensor([[[300]]], dtype=torch.int32)- with pytest.raises(Exception):+ with pytest.raises(ValueCheckError):KORNIA_CHECK_IS_IMAGE(bad)def test_invalid_shape(self):diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.pyindex ae43b97d0..fb5beeb55 100644--- a/tests/enhance/test_jpeg.py+++ b/tests/enhance/test_jpeg.py@@ -92,65 +92,87 @@ class TestDiffJPEG(BaseTester):B = 2jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(1904.0, jpeg_quality)- assert "Input input type is not a" in str(errinfo)+ assert "Input input type is not a Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:B, H, W = 2, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, None)- assert "Not a Tensor type. Got" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as errinfo:B, H, W = 2, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B, 3, 2, 1), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)- assert "shape must be [" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)++ from kornia.core.exceptions import BaseError- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 7, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)- assert "shape must be [" in str(errinfo)+ assert (+ "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ or "shape must be" in str(errinfo.value)+ )- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B, 8, 7), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)- assert "shape must be [" in str(errinfo)+ assert (+ "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ or "shape must be" in str(errinfo.value)+ )++ from kornia.core.exceptions import BaseError- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B * B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * 2, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)- assert "Batch dimensions do not match." in str(errinfo)+ assert "Batch dimensions do not match" in str(errinfo.value)- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B * B,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * 2, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)- assert "Batch dimensions do not match." in str(errinfo)+ assert "Batch dimensions do not match" in str(errinfo.value)++ from kornia.core.exceptions import BaseError- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:B, H, W = 4, 32, 32img = torch.rand(B, B, 3, H, W, device=device, dtype=dtype)jpeg_quality = torch.randint(low=0, high=100, size=(B * 2,), device=device, dtype=dtype)qt_y = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)- assert "Batch dimensions do not match." in str(errinfo)+ assert "Batch dimensions do not match" in str(errinfo.value)def test_cardinality(self, device, dtype) -> None:B, H, W = 1, 16, 16diff --git a/tests/enhance/test_shift_rgb.py b/tests/enhance/test_shift_rgb.pyindex ff69ed2d3..7cd10d139 100644--- a/tests/enhance/test_shift_rgb.py+++ b/tests/enhance/test_shift_rgb.py@@ -49,9 +49,11 @@ class TestRGBShift(BaseTester):self.assert_close(shifted, expected)def test_rgb_shift_invalid_parameter_shape(self, device, dtype):+ from kornia.core.exceptions import ImageError+r_shift, g_shift, b_shift = torch.Tensor([0.5]), torch.Tensor([0.5]), torch.Tensor([0.5])image = torch.randn(3, 3, device=device, dtype=dtype)- with pytest.raises(TypeError):+ with pytest.raises(ImageError):kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)def test_rgb_shift_gradcheck(self, device):diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex 35ac10c92..c99f81d29 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -19,10 +19,8 @@ import pytestimport torchfrom kornia.feature.dedode import DeDoDe-from kornia.utils._compat import torch_version_le[email protected](torch_version_le(2, 0, 0), reason="Autocast not supported")class TestDeDoDe:@pytest.mark.slow@pytest.mark.parametrize("descriptor_model", ["B", "G"])@@ -40,42 +38,3 @@ class TestDeDoDe:assert keypoints.shape == (shape[0], n, 2)assert scores.shape == (shape[0], n)assert descriptions.shape == (shape[0], n, 256)-- @pytest.mark.slow- @pytest.mark.parametrize("descriptor_model", ["B", "G"])- @pytest.mark.parametrize("detector_model", ["L"])- def test_smoke_amp_fp16(self, dtype, device, descriptor_model, detector_model):- if "G" in descriptor_model and device.type != "cuda":- pytest.skip('G descriptors do not support no cuda device. "LayerNormKernelImpl" not implemented for `Half`')- dedode = DeDoDe(descriptor_model=descriptor_model, detector_model=detector_model, amp_dtype=torch.float16).to(- device, dtype- )- shape = (2, 3, 128, 128)- n = 1000- inp = torch.randn(*shape, device=device, dtype=dtype)- keypoints, scores, descriptions = dedode(inp, n=n)- assert keypoints.shape == (shape[0], n, 2)- assert scores.shape == (shape[0], n)- assert descriptions.shape == (shape[0], n, 256)-- @pytest.mark.slow- @pytest.mark.parametrize("detector_weights", ["L-upright", "L-C4", "L-SO2", "L-C4-v2"])- @pytest.mark.parametrize("descriptor_weights", ["B-upright", "B-C4", "B-SO2", "G-upright", "G-C4", "G-SO2"])- def test_pretrained(self, dtype, device, descriptor_weights, detector_weights):- if "G" in descriptor_weights and device.type != "cuda" and dtype == torch.float16:- pytest.skip('G descriptors do not support no cuda device. "LayerNormKernelImpl" not implemented for `Half`')- dedode = DeDoDe.from_pretrained(- detector_weights=detector_weights,- descriptor_weights=descriptor_weights,- amp_dtype=dtype,- ).to(device, dtype)- assert isinstance(dedode, DeDoDe)-- shape = (2, 3, 128, 128)- n = 1000- inp = torch.randn(*shape, device=device, dtype=dtype)- keypoints, scores, descriptions = dedode(inp, n=n)-- assert keypoints.shape == (shape[0], n, 2)- assert scores.shape == (shape[0], n)- assert descriptions.shape == (shape[0], n, 256)diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.pyindex 3bb412ebe..d7e74300d 100644--- a/tests/filters/test_bilateral.py+++ b/tests/filters/test_bilateral.py@@ -54,9 +54,11 @@ class TestBilateralBlur(BaseTester):assert actual.shape == shapedef test_exception(self):- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:bilateral_blur(torch.rand(1, 1, 5, 5), 3, 1, 1)- assert "Not a Tensor type. Go" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)with pytest.raises(ValueError) as errinfo:bilateral_blur(torch.rand(1, 1, 5, 5), 3, 0.1, (1, 1), color_distance_type="l3")@@ -209,9 +211,11 @@ class TestJointBilateralBlur(BaseTester):inp = torch.rand(1, 1, 5, 5)guide = torch.rand(1, 1, 5, 5)- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:joint_bilateral_blur(inp, guide, 3, 1, 1)- assert "Not a Tensor type. Go" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)with pytest.raises(Exception) as errinfo:joint_bilateral_blur(inp, torch.randn(1, 1, 2, 4), 3, 1, (1, 1))diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.pyindex 3ea4791b5..11faccffb 100644--- a/tests/filters/test_blur_pool.py+++ b/tests/filters/test_blur_pool.py@@ -165,14 +165,16 @@ class TestEdgeAwareBlurPool(BaseTester):assert blur.shape == inp.shapedef test_exception(self):- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import BaseError, ShapeError++ with pytest.raises(ShapeError) as errinfo:data = torch.rand(1, 3, 3)edge_aware_blur_pool2d(data, 3)- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)- with pytest.raises(Exception) as errinfo:+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)+ with pytest.raises(BaseError) as errinfo:data = torch.rand(1, 1, 3, 3)edge_aware_blur_pool2d(data, 3, edge_threshold=-1)- assert "edge threshold should be positive, but got" in str(errinfo)+ assert "edge threshold should be positive, but got" in str(errinfo.value)@pytest.mark.parametrize("batch_size", [1, 2])def test_noncontiguous(self, batch_size, device, dtype):diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.pyindex 742623165..e32ccef45 100644--- a/tests/filters/test_canny.py+++ b/tests/filters/test_canny.py@@ -50,26 +50,28 @@ class TestCanny(BaseTester):assert edges.shape == (batch_size, 1, 4, 4)def test_exception(self, device, dtype):- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError++ with pytest.raises(BaseError) as errinfo:Canny(0.3, 0.2)- assert "low_threshold should be smaller than the high_threshold" in str(errinfo)+ assert "low_threshold should be smaller than the high_threshold" in str(errinfo.value)- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:Canny(-2, 0.3)- assert "Invalid low threshold." in str(errinfo)+ assert "Invalid low threshold." in str(errinfo.value)- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:Canny(0.1, 3)- assert "Invalid high threshold." in str(errinfo)+ assert "Invalid high threshold." in str(errinfo.value)- with pytest.raises(Exception) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:canny(1)- assert "Not a Tensor type" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)inp = torch.zeros(3, 4, 4, device=device, dtype=dtype)- with pytest.raises(Exception) as errinfo:+ with pytest.raises(ShapeError) as errinfo:canny(inp)- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)@pytest.mark.parametrize("batch_size", [1, 2])def test_noncontiguous(self, batch_size, device, dtype):diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex f22e603ef..f910800df 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -92,23 +92,27 @@ class TestFilter2D(BaseTester):self.assert_close(out_conv, conv_expected)def test_exception(self):+ from kornia.core.exceptions import ShapeError, TypeCheckError+k = torch.ones(1, 1, 1)data = torch.ones(1, 1, 1, 1)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:filter2d(1, k)- assert "Not a Tensor type." in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:filter2d(data, 1)- assert "Not a Tensor type." in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:filter2d(torch.ones(1), k)- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value)+ assert "['B', 'C', 'H', 'W']" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:filter2d(data, torch.ones(1))- assert "shape must be [['B', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value)+ assert "['B', 'H', 'W']" in str(errinfo.value)with pytest.raises(Exception) as errinfo:filter2d(data, k, border_type="a")@@ -407,23 +411,25 @@ class TestFilter3D(BaseTester):assert filter3d(data, kernel).shape == data.shapedef test_exception(self):+ from kornia.core.exceptions import ShapeError, TypeCheckError+k = torch.ones(1, 1, 1, 1)data = torch.ones(1, 1, 1, 1, 1)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:filter3d(1, k)- assert "Not a Tensor type." in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:filter3d(data, 1)- assert "Not a Tensor type." in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:filter3d(torch.ones(1), k)- assert "shape must be [['B', 'C', 'D', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:filter3d(data, torch.ones(1))- assert "shape must be [['B', 'D', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)with pytest.raises(Exception) as errinfo:filter3d(data, k, border_type="a")diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex 82f0fe556..2d0318ef4 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -240,15 +240,17 @@ class TestGaussianBlur2d(BaseTester):assert actual.shape == shapedef test_exception(self):+ from kornia.core.exceptions import TypeCheckError+# input should be a tensor- with pytest.raises(Exception) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:gaussian_blur2d(1, 3, (1.0, 1.0))- assert "Not a Tensor type. Go" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Sigma should be a tuple or a tensor- with pytest.raises(Exception) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:gaussian_blur2d(torch.rand(1, 1, 1, 1), 3, 1.0)- assert "Not a Tensor type. Go" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)def test_noncontiguous(self, device, dtype):batch_size = 3diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.pyindex 18650eb3e..41a956e77 100644--- a/tests/filters/test_guided.py+++ b/tests/filters/test_guided.py@@ -68,13 +68,15 @@ class TestGuidedBlur(BaseTester):assert actual.shape == shapedef test_exception(self):- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import BaseError, TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:guided_blur(torch.rand(1, 1, 5, 5), 3, 3, 0.1)- assert "Not a Tensor type. Go" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(Exception) as errinfo:+ with pytest.raises(BaseError) as errinfo:guided_blur(torch.rand(1, 1, 5, 5), torch.rand(2, 1, 5, 5), 3, 0.1)- assert "same batch size and spatial dimensions" in str(errinfo)+ assert "same batch size and spatial dimensions" in str(errinfo.value)def test_noncontiguous(self, device, dtype):batch_size = 3diff --git a/tests/filters/test_median.py b/tests/filters/test_median.pyindex af6c505ee..5cd03727e 100644--- a/tests/filters/test_median.py+++ b/tests/filters/test_median.py@@ -37,13 +37,15 @@ class TestMedianBlur(BaseTester):assert actual.shape == (batch_size, 3, 4, 4)def test_exception(self, device, dtype):- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError, TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:median_blur(1, 1)- assert "Not a Tensor type." in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:median_blur(torch.ones(1, 1, device=device, dtype=dtype), 1)- assert "shape must be [['B', 'C', 'H', 'W']]." in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)def test_kernel_3x3(self, device, dtype):inp = torch.tensor(diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.pyindex 38d8673fb..94b6af363 100644--- a/tests/filters/test_sobel.py+++ b/tests/filters/test_sobel.py@@ -40,13 +40,15 @@ class TestSpatialGradient(BaseTester):assert SpatialGradient()(inp).shape == (batch_size, 3, 2, 4, 4)def test_exception(self):- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError, TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:spatial_gradient(1)- assert "Not a Tensor type" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:spatial_gradient(torch.zeros(1))- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)def test_edges(self, device, dtype):inp = torch.tensor(@@ -288,13 +290,15 @@ class TestSpatialGradient3d(BaseTester):assert sobel(inp).shape == (batch_size, 2, 3, 4, 5, 6)def test_exception(self):- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError, TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:spatial_gradient3d(1)- assert "Not a Tensor type" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:spatial_gradient3d(torch.zeros(1))- assert "shape must be [['B', 'C', 'D', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)def test_edges(self, device, dtype):inp = torch.tensor(@@ -451,13 +455,15 @@ class TestSobel(BaseTester):assert Sobel()(inp).shape == (batch_size, 3, 4, 7)def test_exception(self):- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError, TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:sobel(1)- assert "Not a Tensor type" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:sobel(torch.zeros(1))- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)def test_magnitude(self, device, dtype):inp = torch.tensor(diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.pyindex c336c77b4..4c8aa244e 100644--- a/tests/geometry/camera/test_distortion.py+++ b/tests/geometry/camera/test_distortion.py@@ -93,9 +93,11 @@ class TestDistortionAffine(BaseTester):self.assert_close(dx_distort_points_affine(points, params), expected)def test_exception(self, device, dtype) -> None:+ from kornia.core.exceptions import ShapeError+points = torch.tensor([1.0, 2.0], device=device, dtype=dtype)params = torch.tensor([600.0, 600.0, 319.5], device=device, dtype=dtype)- with pytest.raises(TypeError):+ with pytest.raises(ShapeError):distort_points_affine(points, params)def _test_gradcheck_distort(self, device):@@ -205,9 +207,11 @@ class TestDistortionKannalaBrandt(BaseTester):self.assert_close(dx_distort_points_kannala_brandt(points, params), expected)def test_exception(self, device, dtype) -> None:+ from kornia.core.exceptions import ShapeError+points = torch.tensor([1.0, 2.0], device=device, dtype=dtype)params = torch.tensor([600.0, 600.0, 319.5], device=device, dtype=dtype)- with pytest.raises(TypeError):+ with pytest.raises(ShapeError):distort_points_kannala_brandt(points, params)def _test_gradcheck_distort(self, device):diff --git a/tests/geometry/camera/test_projections.py b/tests/geometry/camera/test_projections.pyindex e51ea8db0..c47f25146 100644--- a/tests/geometry/camera/test_projections.py+++ b/tests/geometry/camera/test_projections.py@@ -113,9 +113,11 @@ class TestProjectionZ1(BaseTester):self.assert_close(dx_project_points_z1(points), expected)def test_exception(self, device, dtype) -> None:+ from kornia.core.exceptions import ShapeError+points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)extension = torch.tensor([2.0], device=device, dtype=dtype)- with pytest.raises(TypeError):+ with pytest.raises(ShapeError):unproject_points_z1(points, extension)def _test_gradcheck_unproject(self, device):@@ -205,9 +207,11 @@ class TestProjectionOrthographic(BaseTester):self.assert_close(dx_project_points_orthographic(points), expected)def test_exception(self, device, dtype) -> None:+ from kornia.core.exceptions import ShapeError+points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)extension = torch.tensor([2.0], device=device, dtype=dtype)- with pytest.raises(TypeError):+ with pytest.raises(ShapeError):unproject_points_orthographic(points, extension)def _test_gradcheck_project(self, device):diff --git a/tests/geometry/transform/test_elastic_transform.py b/tests/geometry/transform/test_elastic_transform.pyindex cec51653e..d62fb99f0 100644--- a/tests/geometry/transform/test_elastic_transform.py+++ b/tests/geometry/transform/test_elastic_transform.py@@ -38,26 +38,28 @@ class TestElasticTransform:assert elastic_transform2d(img, noise).shape == shapedef test_exception(self, device, dtype):+ from kornia.core.exceptions import ShapeError, TypeCheckError+ex = torch.ones(1, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:elastic_transform2d([0.0], ex)- assert "Not a Tensor type" in str(errinfo.value)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:elastic_transform2d(ex, 1)- assert "Not a Tensor type" in str(errinfo.value)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:img = torch.ones(1, 1, 1, device=device, dtype=dtype)noise = torch.ones(1, 2, 1, 1, device=device, dtype=dtype)elastic_transform2d(img, noise)- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo.value)+ assert "Shape dimension mismatch" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:img = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)noise = torch.ones(2, 1, 1, device=device, dtype=dtype)elastic_transform2d(img, noise)- assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo.value)+ assert "Shape dimension mismatch" in str(errinfo.value)with pytest.raises(RuntimeError) as errinfo:img = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)diff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.pyindex 3b6797b97..cdd41733e 100644--- a/tests/geometry/transform/test_pyramid.py+++ b/tests/geometry/transform/test_pyramid.py@@ -192,7 +192,9 @@ class TestUpscaleDouble(BaseTester):assert kornia.geometry.transform.upscale_double(x) is not Nonedef test_exception(self):- with pytest.raises(TypeError):+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError):kornia.geometry.transform.upscale_double(None)@pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))diff --git a/tests/losses/test_cauchy.py b/tests/losses/test_cauchy.pyindex 8be556a44..6be040812 100644--- a/tests/losses/test_cauchy.py+++ b/tests/losses/test_cauchy.py@@ -36,24 +36,30 @@ class TestCauchyLoss(BaseTester):img = torch.rand(3, 3, 3, device=device, dtype=dtype)# wrong reduction- with pytest.raises(Exception) as execinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as execinfo:kornia.losses.cauchy_loss(img, img, reduction="test")- assert "Given type of reduction is not supported. Got: test" in str(execinfo)+ assert "Given type of reduction is not supported. Got: test" in str(execinfo.value)# Check if both are tensors- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.cauchy_loss(1.0, img)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.cauchy_loss(img, 1.0)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Check if same shape+ from kornia.core.exceptions import ShapeError+img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:- kornia.losses.cauchy_loss(img, img_b, 3)- assert "Not same shape for tensors. Got:" in str(errinfo)+ with pytest.raises(ShapeError) as errinfo:+ kornia.losses.cauchy_loss(img, img_b)+ assert "Shape mismatch" in str(errinfo.value)@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])def test_cardinality(self, shape, device, dtype):diff --git a/tests/losses/test_charbonnier.py b/tests/losses/test_charbonnier.pyindex e655b4233..b3dd2cbe4 100644--- a/tests/losses/test_charbonnier.py+++ b/tests/losses/test_charbonnier.py@@ -36,24 +36,30 @@ class TestCharbonnierLoss(BaseTester):img = torch.rand(3, 3, 3, device=device, dtype=dtype)# wrong reduction- with pytest.raises(Exception) as execinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as execinfo:kornia.losses.charbonnier_loss(img, img, reduction="test")- assert "Given type of reduction is not supported. Got: test" in str(execinfo)+ assert "Given type of reduction is not supported. Got: test" in str(execinfo.value)# Check if both are tensors- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.charbonnier_loss(1.0, img)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.charbonnier_loss(img, 1.0)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Check if same shape+ from kornia.core.exceptions import ShapeError+img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:- kornia.losses.charbonnier_loss(img, img_b, 3)- assert "Not same shape for tensors. Got:" in str(errinfo)+ with pytest.raises(ShapeError) as errinfo:+ kornia.losses.charbonnier_loss(img, img_b)+ assert "Shape mismatch" in str(errinfo.value)@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])def test_cardinality(self, shape, device, dtype):diff --git a/tests/losses/test_geman_macclure.py b/tests/losses/test_geman_macclure.pyindex c341725a7..9ee106e23 100644--- a/tests/losses/test_geman_macclure.py+++ b/tests/losses/test_geman_macclure.py@@ -36,24 +36,30 @@ class TestGemanMcclureLossLoss(BaseTester):img = torch.rand(3, 3, 3, device=device, dtype=dtype)# wrong reduction- with pytest.raises(Exception) as execinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as execinfo:kornia.losses.geman_mcclure_loss(img, img, reduction="test")- assert "Given type of reduction is not supported. Got: test" in str(execinfo)+ assert "Given type of reduction is not supported. Got: test" in str(execinfo.value)# Check if both are tensors- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.geman_mcclure_loss(1.0, img)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.geman_mcclure_loss(img, 1.0)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Check if same shape+ from kornia.core.exceptions import ShapeError+img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:- kornia.losses.geman_mcclure_loss(img, img_b, 3)- assert "Not same shape for tensors. Got:" in str(errinfo)+ with pytest.raises(ShapeError) as errinfo:+ kornia.losses.geman_mcclure_loss(img, img_b)+ assert "Shape mismatch" in str(errinfo.value)@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 5, 5)])def test_cardinality(self, shape, device, dtype):diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.pyindex 1a2b6f472..9ce3689ba 100644--- a/tests/losses/test_lovaz_softmax.py+++ b/tests/losses/test_lovaz_softmax.py@@ -34,15 +34,17 @@ class TestLovaszSoftmaxLoss(BaseTester):assert criterion(logits, labels) is not Nonedef test_exception(self):+ from kornia.core.exceptions import ShapeError+criterion = kornia.losses.LovaszSoftmaxLoss()- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:criterion(torch.rand(1), torch.rand(1))- assert "shape must be [['B', 'N', 'H', 'W']]. Got" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:criterion(torch.rand(1, 1, 1, 1), torch.rand(1))- assert "shape must be [['B', 'H', 'W']]. Got" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)with pytest.raises(ValueError) as errinfo:criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1))diff --git a/tests/losses/test_welcsh.py b/tests/losses/test_welcsh.pyindex 9fdfb0c0f..9b1953aae 100644--- a/tests/losses/test_welcsh.py+++ b/tests/losses/test_welcsh.py@@ -93,21 +93,27 @@ class TestWelschLoss(BaseTester):img = torch.rand(3, 3, 3, device=device, dtype=dtype)# wrong reduction- with pytest.raises(Exception) as execinfo:+ from kornia.core.exceptions import BaseError++ with pytest.raises(BaseError) as execinfo:kornia.losses.welsch_loss(img, img, reduction="test")- assert "Given type of reduction is not supported. Got: test" in str(execinfo)+ assert "Given type of reduction is not supported. Got: test" in str(execinfo.value)# Check if both are tensors- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.welsch_loss(1.0, img)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:kornia.losses.welsch_loss(img, 1.0)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Check if same shape+ from kornia.core.exceptions import ShapeError+img_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:- kornia.losses.welsch_loss(img, img_b, 3)- assert "Not same shape for tensors. Got:" in str(errinfo)+ with pytest.raises(ShapeError) as errinfo:+ kornia.losses.welsch_loss(img, img_b)+ assert "Shape mismatch" in str(errinfo.value)diff --git a/tests/metrics/test_aepe.py b/tests/metrics/test_aepe.pyindex 6df83cfc3..1e1a2079d 100644--- a/tests/metrics/test_aepe.py+++ b/tests/metrics/test_aepe.py@@ -58,20 +58,28 @@ class TestAepe(BaseTester):self.assert_close(actual_aepe, actual_alias)def test_exception(self, device, dtype):- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:criterion = kornia.metrics.AEPE()criterion(None, torch.ones(4, 4, 2, device=device, dtype=dtype))- assert "Not a Tensor type. Got" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)with pytest.raises(NotImplementedError) as errinfo:sample = torch.ones(4, 4, 2, device=device, dtype=dtype)_ = kornia.metrics.aepe(sample, 2.0 * sample, reduction="foo")assert "Invalid reduction option." in str(errinfo)- with pytest.raises(Exception) as errinfo:+ from kornia.core.exceptions import ShapeError++ with pytest.raises(ShapeError) as errinfo:sample = torch.ones(4, 4, 2, device=device, dtype=dtype)_ = kornia.metrics.aepe(sample, 2.0 * sample[..., 0], reduction="mean")- assert "shape must be [['*', '2']]. Got" in str(errinfo)+ assert (+ "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ or "shape must be" in str(errinfo.value)+ )def test_smoke(self, device, dtype):input = torch.rand(3, 3, 2, device=device, dtype=dtype)diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.pyindex 56c1ec3df..eadf944fc 100644--- a/tests/metrics/test_ssim3d.py+++ b/tests/metrics/test_ssim3d.py@@ -66,23 +66,27 @@ class TestSSIM3d(BaseTester):img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=dtype)# Check if both are tensors- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import TypeCheckError++ with pytest.raises(TypeCheckError) as errinfo:kornia.metrics.ssim3d(1.0, img, 3)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(TypeCheckError) as errinfo:kornia.metrics.ssim3d(img, 1.0, 3)- assert "Not a Tensor type. Got:" in str(errinfo)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)# Check both shapes+ from kornia.core.exceptions import ShapeError+img_wrong_shape = torch.rand(3, 3, device=device, dtype=dtype)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:kornia.metrics.ssim3d(img, img_wrong_shape, 3)- assert "shape must be [" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:kornia.metrics.ssim3d(img_wrong_shape, img, 3)- assert "shape must be [" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)# Check if same shapeimg_b = torch.rand(1, 1, 3, 3, 4, device=device, dtype=dtype)diff --git a/tests/models/test_prompter.py b/tests/models/test_prompter.pyindex 1a0082923..5a398a14f 100644--- a/tests/models/test_prompter.py+++ b/tests/models/test_prompter.py@@ -64,9 +64,15 @@ class TestVisualPrompter(BaseTester):data = torch.rand(1, 3, 1, 2)# Wrong shape for the image- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError++ with pytest.raises(ShapeError) as errinfo:prompter.set_image(data, [], False)- assert "shape must be [['3', 'H', 'W']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)+ assert (+ "Shape mismatch" in str(errinfo.value)+ or "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ )# predict without set an imagewith pytest.raises(Exception) as errinfo:@@ -74,23 +80,39 @@ class TestVisualPrompter(BaseTester):assert "An image must be set with `self.set_image(...)`" in str(errinfo)# Valid masks- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:prompter._valid_masks(data)- assert "shape must be [['K', '1', '256', '256']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)+ assert (+ "Shape mismatch" in str(errinfo.value)+ or "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ )# Valid boxes- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:prompter._valid_boxes(data)- assert "shape must be [['K', '4']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)+ assert (+ "Shape mismatch" in str(errinfo.value)+ or "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ )# Valid keypoints- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:prompter._valid_keypoints(data, None)- assert "shape must be [['K', 'N', '2']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)+ assert (+ "Shape mismatch" in str(errinfo.value)+ or "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ )- with pytest.raises(TypeError) as errinfo:+ with pytest.raises(ShapeError) as errinfo:prompter._valid_keypoints(torch.rand(1, 1, 2), data)- assert "shape must be [['K', 'N']]. Got torch.Size([1, 3, 1, 2])" in str(errinfo)+ assert (+ "Shape mismatch" in str(errinfo.value)+ or "Shape dimension mismatch" in str(errinfo.value)+ or "Expected shape" in str(errinfo.value)+ )with pytest.raises(Exception) as errinfo:prompter._valid_keypoints(torch.rand(1, 1, 2), torch.rand(2, 1))diff --git a/tests/models/test_sam.py b/tests/models/test_sam.pyindex a40e9693d..a18dfa8b2 100644--- a/tests/models/test_sam.py+++ b/tests/models/test_sam.py@@ -68,10 +68,12 @@ class TestSam(BaseTester):def test_exception(self):model = Sam.from_config(SamConfig("mobile_sam"))- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError++ with pytest.raises(ShapeError) as errinfo:data = torch.rand(3, 1, 2)model(data, [], False)- assert "shape must be [['B', '3', 'H', 'W']]. Got torch.Size([3, 1, 2])" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)with pytest.raises(Exception) as errinfo:data = torch.rand(2, 3, 1, 2)diff --git a/tests/utils/test_print.py b/tests/utils/test_print.pyindex ccc66bed5..b20000382 100644--- a/tests/utils/test_print.py+++ b/tests/utils/test_print.py@@ -41,15 +41,19 @@ class TestImageToString:img = torch.rand(3, 15, 15)image_to_string(img, max_width=12)- with pytest.raises(TypeError) as errinfo:+ from kornia.core.exceptions import ShapeError++ with pytest.raises(ShapeError) as errinfo:img = torch.rand(1, 3, 15, 15)image_to_string(img)- assert "shape must be [['C', 'H', 'W']]. Got torch.Size([1, 3, 15, 15])" in str(errinfo)+ assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)++ from kornia.core.exceptions import ValueCheckError- with pytest.raises(ValueError) as errinfo:+ with pytest.raises(ValueCheckError) as errinfo:img = torch.rand(3, 15, 15) * 10image_to_string(img)- assert "Invalid image value range. Expect [0, 1] but got" in str(errinfo)+ assert "Value range mismatch" in str(errinfo.value) or "Invalid image value range" in str(errinfo.value)with pytest.raises(RuntimeError):print_image([img]) # Do not accept list