🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Update constants to infer types from `get` (#2047)
João Gustavo A. Amorim9adbeef87fe5
diff --git a/kornia/constants.py b/kornia/constants.pyindex 048f06e98..b3e32a7d4 100644--- a/kornia/constants.py+++ b/kornia/constants.py@@ -1,22 +1,27 @@from enum import Enum, EnumMeta-from typing import Any, Iterator, Union+from typing import Iterator, Type, TypeVar, Unionimport torchfrom kornia.core import Tensor-__all__ = ['pi', 'DType', 'Resample', 'BorderType', 'SamplePadding']+__all__ = ['pi', 'DType', 'Resample', 'BorderType', 'SamplePadding', 'TKEnum']pi = torch.tensor(3.14159265358979323846)-class EnumMetaFlags(EnumMeta):+T = TypeVar('T', bound=Enum)+TKEnum = Union[str, int, T]+++class _KORNIA_EnumMeta(EnumMeta):def __iter__(self) -> Iterator[Enum]: # type: ignore[override]return super().__iter__()- def __contains__(self, other: Union[str, int, Enum]) -> bool: # type: ignore[override]+ def __contains__(self, other: TKEnum[Enum]) -> bool: # type: ignore[override]if isinstance(other, str):- return any(val.name == other.upper() for val in self)+ return any(val.name.upper() == other.upper() for val in self)+elif isinstance(other, int):return any(val.value == other for val in self)@@ -26,38 +31,53 @@ class EnumMetaFlags(EnumMeta):return ' | '.join(f"{self.__name__}.{val.name}" for val in self)-class ConstantBase(Enum, metaclass=EnumMetaFlags):- @classmethod- def get(cls, value: Union[str, int, Any]) -> Any:- if isinstance(value, str):- return cls[value.upper()]- if isinstance(value, int):- return cls(value)- if isinstance(value, cls):- return value- raise TypeError()+def _get(cls: Type[T], value: TKEnum[T]) -> T:+ if isinstance(value, str):+ return cls[value.upper()]+ elif isinstance(value, int):+ return cls(value)-class Resample(ConstantBase):+ elif isinstance(value, cls):+ return value++ raise TypeError(+ f'The `.get` method from `{cls}` expects a value with type `str`, `int` or `{cls}`. Gotcha {type(value)}'+ )+++class Resample(Enum, metaclass=_KORNIA_EnumMeta):NEAREST = 0BILINEAR = 1BICUBIC = 2+ @classmethod+ def get(cls, value: TKEnum['Resample']) -> 'Resample':+ return _get(cls, value)-class BorderType(ConstantBase):++class BorderType(Enum, metaclass=_KORNIA_EnumMeta):CONSTANT = 0REFLECT = 1REPLICATE = 2CIRCULAR = 3+ @classmethod+ def get(cls, value: TKEnum['BorderType']) -> 'BorderType':+ return _get(cls, value)+-class SamplePadding(ConstantBase):+class SamplePadding(Enum, metaclass=_KORNIA_EnumMeta):ZEROS = 0BORDER = 1REFLECTION = 2+ @classmethod+ def get(cls, value: TKEnum['SamplePadding']) -> 'SamplePadding':+ return _get(cls, value)+-class DType(ConstantBase):+class DType(Enum, metaclass=_KORNIA_EnumMeta):INT64 = 0FLOAT16 = 1FLOAT32 = 2@@ -65,38 +85,45 @@ class DType(ConstantBase):@classmethoddef get(cls, value: Union[str, int, torch.dtype, Tensor, 'DType']) -> 'DType':+if isinstance(value, torch.dtype):- value = str(value).upper() # Convert to str- if isinstance(value, Tensor):- value = int(value.item()) # Convert to int+ return cls[str(value).upper()[6:]]++ elif isinstance(value, Tensor):+ return cls(int(value.item()))- if isinstance(value, str):- if value.upper().startswith("TORCH."):- return cls[value.upper()[6:]]+ elif isinstance(value, str):return cls[value.upper()]- if isinstance(value, int):+ elif isinstance(value, int):return cls(value)- if isinstance(value, cls):++ elif isinstance(value, cls):return value- raise TypeError(f"Invalid identifier {value}.")++ raise TypeError(f"Invalid identifier {value} with type {type(value)}.")@classmethod- def to_torch(cls, value: Union[str, int, 'DType']) -> torch.dtype:+ def to_torch(cls, value: TKEnum['DType']) -> torch.dtype:data = cls.get(value=value)+if data == DType.INT64:return torch.long- if data == DType.FLOAT16:++ elif data == DType.FLOAT16:return torch.float16- if data == DType.FLOAT32:++ elif data == DType.FLOAT32:return torch.float32- if data == DType.FLOAT64:++ elif data == DType.FLOAT64:return torch.float64+raise ValueError()# TODO: (low-priority) add INPUT3D, MASK3D, BBOX3D, LAFs etc.-class DataKey(ConstantBase):+class DataKey(Enum, metaclass=_KORNIA_EnumMeta):INPUT = 0MASK = 1BBOX = 2@@ -104,3 +131,7 @@ class DataKey(ConstantBase):BBOX_XYWH = 4KEYPOINTS = 5CLASS = 6++ @classmethod+ def get(cls, value: TKEnum['DataKey']) -> 'DataKey':+ return _get(cls, value)