π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(constants): raise a ValueError naming the valid names for an unknown enum name (#5908)
Dmytro Mishkine1ca0389b633
diff --git a/changelog.d/5908.fixed.md b/changelog.d/5908.fixed.mdnew file mode 100644index 000000000..196e815bd--- /dev/null+++ b/changelog.d/5908.fixed.md@@ -0,0 +1,7 @@+A misspelt name given to the `.get` of a `kornia.constants` enum (`Resample`, `BorderType`, `SamplePadding`, `DType`,+`DataKey`), and an unsupported `torch.dtype` given to `DType.get`, now raise an error that names the value and lists the+valid names. This covers the `kornia.augmentation` arguments that are looked up in these enums, such as `resample` and+`padding_mode` of `RandomAffine`, `border_type` of `RandomGaussianBlur` and `data_keys` of `AugmentationSequential`,+and the `format` of `kornia.contrib.object_detection.results_from_detections`. The error is a `ValueError`, like the+one for an out-of-range integer, and still a `KeyError`. A value of the wrong type raises a `TypeError` that names the+enum and the value, instead of listing every member of both enums.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 9d6523f00..9723b1647 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -126,11 +126,11 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential)::class:`~kornia.augmentation.AugmentationBase2D` convention.- ``data_keys`` names one entry per positional argument, case-insensitively: ``input`` (alias``image``), ``mask``, ``bbox``, ``bbox_xyxy``, ``bbox_xywh``, ``keypoints`` and ``label`` (alias- ``class``); any other name raises ``KeyError``. With ``data_keys=None`` the call takes a dict whose- keys are these names, optionally followed by a ``_`` or ``-`` suffix (``mask_2``, ``class_id``). The- longest matching name wins and a suffix needs its separator: ``bbox_xyxy2`` is a ``bbox`` key and must- hold vertices. Unrecognized keys (``images``, ``masks``, ``labels``) are returned unchanged, without a- warning. The input dict is not modified.+ ``class``); any other name raises a ``ValueError`` that is also a ``KeyError``. With ``data_keys=None``+ the call takes a dict whose keys are these names, optionally followed by a ``_`` or ``-`` suffix+ (``mask_2``, ``class_id``). The longest matching name wins and a suffix needs its separator:+ ``bbox_xyxy2`` is a ``bbox`` key and must hold vertices. Unrecognized keys (``images``, ``masks``,+ ``labels``) are returned unchanged, without a warning. The input dict is not modified.- the layouts are ``(B, C, H, W)`` for images and masks, ``(B, N, 4, 2)`` vertices for ``bbox``,``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``;``N = 0`` is accepted. 3D inputs are ``(D, H, W)`` or ``(B, C, D, H, W)``; rank 4 is rejected asdiff --git a/kornia/constants.py b/kornia/constants.pyindex 13d114f55..226666dcb 100644--- a/kornia/constants.py+++ b/kornia/constants.py@@ -48,9 +48,33 @@ class _KORNIA_EnumMeta(EnumMeta):return " | ".join(f"{self.__name__}.{val.name}" for val in self)+class _UnknownNameError(KeyError, ValueError):+ """Raised by the ``.get`` of a kornia enum for a name that names no member.++ It is a :exc:`ValueError`, like the error for an integer that is no member's value, and a :exc:`KeyError`, like a+ failed ``Enum[name]`` lookup, so either ``except`` clause catches it.+ """++ def __str__(self) -> str:+ # `KeyError.__str__` would repr-quote the whole message+ return Exception.__str__(self)+++def _get_by_name(cls: Type[_T], name: str, value: object) -> _T:+ # try/except, not ``name in cls.__members__``: dynamo on torch 2.5.1 cannot trace ``in`` on the members mapping,+ # and augmentations look names up inside ``forward`` (a per-call ``border_type``, ``data_keys``).+ try:+ return cls[name.upper()]+ except KeyError:+ valid = ", ".join(repr(member_name.lower()) for member_name in cls.__members__)+ raise _UnknownNameError(+ f"{value!r} is not a valid {cls.__name__}. Expected one of {valid} (case-insensitive)."+ ) from None++def _get(cls: Type[_T], value: TKEnum[_T]) -> _T:if isinstance(value, str):- return cls[value.upper()]+ return _get_by_name(cls, value, value)if isinstance(value, int):return cls(value)@@ -59,7 +83,8 @@ def _get(cls: Type[_T], value: TKEnum[_T]) -> _T:return valueraise TypeError(- f"The `.get` method from `{cls}` expects a value with type `str`, `int` or `{cls}`. Got {type(value)}"+ f"`{cls.__name__}.get` expects a `str`, `int` or `{cls.__name__}` value. "+ f"Got {value!r} of type `{type(value).__name__}`.")@@ -113,13 +138,13 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):@classmethoddef get(cls, value: Union[str, int, torch.dtype, torch.Tensor, "DType"]) -> "DType":if isinstance(value, torch.dtype):- return cls[str(value).upper()[6:]]+ return _get_by_name(cls, str(value)[6:], value)if isinstance(value, torch.Tensor):return cls(int(value.item()))if isinstance(value, str):- return cls[value.upper()]+ return _get_by_name(cls, value, value)if isinstance(value, int):return cls(value)@@ -127,7 +152,10 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):if isinstance(value, cls):return value- raise TypeError(f"Invalid identifier {value} with type {type(value)}.")+ raise TypeError(+ "`DType.get` expects a `str`, `int`, `torch.dtype`, `torch.Tensor` or `DType` value. "+ f"Got {value!r} of type `{type(value).__name__}`."+ )@classmethoddef to_torch(cls, value: TKEnum["DType"]) -> torch.dtype:diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex c77421314..b8c04f161 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -24,6 +24,7 @@ from typing import Any, ClassVar, List, Optional, Tuple, Unionimport torchfrom torch import nn+from kornia.constants import _get_by_namefrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnx@@ -108,7 +109,7 @@ def results_from_detections(KORNIA_CHECK_SHAPE(detections, ["D", "6"])if isinstance(format, str):- format = BoundingBoxDataFormat[format.upper()]+ format = _get_by_name(BoundingBoxDataFormat, format, format)results: list[ObjectDetectorResult] = []for det in detections:diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex e0080c2a8..844582482 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -60,10 +60,10 @@ class TestAugmentationSequential:@pytest.mark.parametrize("data_keys,error_type,match",[- ("input", KeyError, "I"),- ("image", KeyError, "I"),+ ("input", KeyError, "'i' is not a valid DataKey"),+ ("image", KeyError, "'i' is not a valid DataKey"),(["mask", "input"], NotImplementedError, "first input must be DataKey.IMAGE"),- (["input", "bbox_yxyx"], KeyError, "BBOX_YXYX"),+ (["input", "bbox_yxyx"], KeyError, "'bbox_yxyx' is not a valid DataKey"),([0, 10], ValueError, "10 is not a valid DataKey"),([BorderType.REFLECT], TypeError, "DataKey"),],diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.pyindex e0e152915..854a5e0ee 100644--- a/tests/models/test_object_detector.py+++ b/tests/models/test_object_detector.py@@ -108,6 +108,12 @@ class TestObjectDetector(BaseTester):assert model_path.is_file()+ def test_results_from_detections_misspelt_format_5907(self, device, dtype):+ detections = torch.zeros(1, 6, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="'xywhh' is not a valid BoundingBoxDataFormat") as excinfo:+ kornia.contrib.object_detection.results_from_detections(detections, format="xywhh")+ assert isinstance(excinfo.value, KeyError)+def test_results_from_detections(self, device, dtype):# label_id, confidence, datadetections = torch.tensor(diff --git a/tests/test_constants.py b/tests/test_constants.pynew file mode 100644index 000000000..15e5dbd40--- /dev/null+++ b/tests/test_constants.py@@ -0,0 +1,154 @@+# 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.+#++import re++import pytest+import torch++import kornia.augmentation as K+from kornia.constants import BorderType, DataKey, DType, Resample, SamplePadding++from testing.base import BaseTester++_ENUMS = (Resample, BorderType, SamplePadding, DType, DataKey)+++class TestEnumGet(BaseTester):+ @pytest.mark.parametrize("enum", _ENUMS)+ def test_names_values_and_members_resolve(self, enum):+ for name, member in enum.__members__.items():+ assert enum.get(name) is member+ assert enum.get(name.lower()) is member+ assert enum.get(member) is member+ assert enum.get(member.value) is member++ @pytest.mark.parametrize("enum", _ENUMS)+ def test_unknown_name_is_both_a_key_error_and_a_value_error_5907(self, enum):+ with pytest.raises(ValueError) as excinfo:+ enum.get("bogus")+ assert isinstance(excinfo.value, KeyError)++ @pytest.mark.parametrize("enum", _ENUMS)+ def test_unknown_name_message_names_the_value_and_the_valid_names_5907(self, enum):+ with pytest.raises(KeyError) as excinfo:+ enum.get("Bogus")+ message = str(excinfo.value)+ # the value as given, and no repr quoting of the whole message as a plain KeyError's str() would add+ assert message.startswith(f"'Bogus' is not a valid {enum.__name__}")+ for name in enum.__members__:+ assert repr(name.lower()) in message++ def test_unknown_name_traceback_shows_one_error_5907(self):+ with pytest.raises(ValueError) as excinfo:+ Resample.get("bogus")+ # raised ``from None``: no "During handling of the above exception" with the lookup's bare KeyError('BOGUS')+ assert excinfo.value.__cause__ is None+ assert excinfo.value.__suppress_context__++ def test_out_of_range_int_is_a_value_error(self):+ with pytest.raises(ValueError, match="7 is not a valid Resample"):+ Resample.get(7)++ @pytest.mark.parametrize("enum", _ENUMS)+ @pytest.mark.parametrize("value", [BorderType.REFLECT, Resample.BILINEAR, 1.5, None])+ def test_wrong_type_message_names_the_enum_and_the_value_5907(self, enum, value):+ if isinstance(value, enum):+ pytest.skip("a member of the enum itself is accepted")+ with pytest.raises(TypeError) as excinfo:+ enum.get(value)+ message = str(excinfo.value)+ assert enum.__name__ in message+ assert repr(value) in message+ # `_KORNIA_EnumMeta.__repr__` joins every member of an enum with " | "+ assert " | " not in message++ def test_dtype_rejects_an_unsupported_torch_dtype_5907(self):+ with pytest.raises(ValueError) as excinfo:+ DType.get(torch.uint8)+ assert isinstance(excinfo.value, KeyError)+ message = str(excinfo.value)+ assert message.startswith("torch.uint8 is not a valid DType")+ assert "'float32'" in message++ def test_dynamo_name_lookup_fullgraph_5907(self, device, dtype, torch_optimizer):+ # augmentations look names up in their forward too (a per-call `border_type`, `data_keys`)+ def op(x):+ return x * (BorderType.get("reflect").value + Resample.get("Bilinear").value + DType.get(x.dtype).value)++ x = torch.ones(2, device=device, dtype=dtype)+ self.assert_close(torch_optimizer(op, fullgraph=True)(x), op(x))+++class TestMisspeltNameThroughThePublicAPI(BaseTester):+ @pytest.mark.parametrize(+ "make,match",+ [+ pytest.param(+ lambda: K.RandomAffine(10.0, resample="bilinera"),+ "'bilinera' is not a valid Resample",+ id="RandomAffine-resample",+ ),+ pytest.param(+ lambda: K.RandomAffine(10.0, padding_mode="zero"),+ "'zero' is not a valid SamplePadding",+ id="RandomAffine-padding_mode",+ ),+ pytest.param(+ lambda: K.CenterCrop(4, resample="bicubik"),+ "'bicubik' is not a valid Resample",+ id="CenterCrop-resample",+ ),+ pytest.param(+ lambda: K.RandomRotation3D(10.0, resample="nearst"),+ "'nearst' is not a valid Resample",+ id="RandomRotation3D-resample",+ ),+ pytest.param(+ lambda: K.RandomGaussianBlur((3, 3), (0.1, 2.0), border_type="reflct"),+ "'reflct' is not a valid BorderType",+ id="RandomGaussianBlur-border_type",+ ),+ pytest.param(+ lambda: K.RandomMotionBlur(3, 35.0, 0.5, border_type="replcate"),+ "'replcate' is not a valid BorderType",+ id="RandomMotionBlur-border_type",+ ),+ pytest.param(+ lambda: K.AugmentationSequential(K.ColorJiggle(0.1, p=1.0), data_keys=["input", "bbox_yxyx"]),+ "'bbox_yxyx' is not a valid DataKey",+ id="AugmentationSequential-data_keys",+ ),+ ],+ )+ def test_constructor_raises_a_value_error_that_except_key_error_still_catches_5907(self, make, match):+ with pytest.raises(ValueError, match=re.escape(match)) as excinfo:+ make()+ assert isinstance(excinfo.value, KeyError)++ def test_misspelt_per_call_border_type_override_5907(self, device, dtype):+ img = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)+ aug = K.RandomBoxBlur((3, 3), p=1.0)+ with pytest.raises(ValueError, match=re.escape("'reflct' is not a valid BorderType")):+ aug(img, border_type="reflct")++ def test_valid_names_are_listed_5907(self):+ with pytest.raises(ValueError) as excinfo:+ K.RandomAffine(10.0, padding_mode="zero")+ message = str(excinfo.value)+ for name in ("'zeros'", "'border'", "'reflection'", "'fill'"):+ assert name in message