π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: repair deprecation hygiene found by the stability-policy audit (#3898)
Dmytro Mishkin29750da093e1
diff --git a/docs/source/core.rst b/docs/source/core.rstindex a538831e0..3d83ce3bc 100644--- a/docs/source/core.rst+++ b/docs/source/core.rst@@ -10,3 +10,5 @@ kornia.core.. autoclass:: TensorWrapper:members::undoc-members:++.. autofunction:: kornia.core.utils.batched_forwarddiff --git a/docs/source/index.rst b/docs/source/index.rstindex 711456afe..f37720fdf 100644--- a/docs/source/index.rst+++ b/docs/source/index.rst@@ -19,15 +19,21 @@ DexiNed edge detection model... code-block:: python- image = kornia.utils.sample.get_sample_images()[0][None]- model = DexiNedBuilder.build()+ import kornia+ from kornia.contrib import EdgeDetectorBuilder++ image = kornia.io.get_sample_images()[0][None]+ model = EdgeDetectorBuilder.build()model.save(image)RTDETRDetector for object detection... code-block:: python- image = kornia.utils.sample.get_sample_images()[0][None]+ import kornia+ from kornia.contrib import RTDETRDetectorBuilder++ image = kornia.io.get_sample_images()[0][None]model = RTDETRDetectorBuilder.build()model.save(image)@@ -36,7 +42,9 @@ BoxMotTracker for object tracking... code-block:: pythonimport kornia- image = kornia.utils.sample.get_sample_images()[0][None]+ from kornia.contrib import BoxMotTracker++ image = kornia.io.get_sample_images()[0][None]model = BoxMotTracker()for i in range(4):model.update(image)diff --git a/docs/source/io.rst b/docs/source/io.rstindex 3a21f4467..3c40c8d17 100644--- a/docs/source/io.rst+++ b/docs/source/io.rst@@ -44,6 +44,7 @@ natively in Rust to reduce the memory footprint during the decoding and types co.. autofunction:: load_image.. autofunction:: write_image+.. autofunction:: get_sample_images.. autoclass:: ImageLoadType:members:diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex 3e0e50317..bdf0d7242 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -397,3 +397,51 @@ def dict_to_dataclass(dict_obj: Dict[str, Any], dataclass_type: Type[T]) -> T:constructor_args[key] = value# TODO: remove type ignore when https://github.com/python/mypy/issues/14941 be andressedreturn dataclass_type(**constructor_args)+++def batched_forward(+ model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargs: Any+) -> torch.Tensor:+ r"""Run the forward in micro-batches.++ When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.+ In the end, it transfers the output to the device of the input data tensor.+ E.g. running HardNet on 8000x1x32x32 tensor.++ Removed from ``kornia.utils.memory`` in 0.8.3 and restored here as public API.++ Args:+ model: Any torch model, which outputs a single tensor as an output.+ data: Input data of Bx(Any) shape.+ device: which device should we run on.+ batch_size: "micro-batch" size.+ **kwargs: any other arguments, which accepts model.++ Returns:+ output of the model.++ Example:+ >>> import torch+ >>> from kornia.core.utils import batched_forward+ >>> model = torch.nn.Identity()+ >>> x = torch.rand(300, 2)+ >>> out = batched_forward(model, x, torch.device("cpu"), batch_size=128)+ >>> bool(torch.allclose(out, x))+ True++ """+ model_dev = model.to(device)+ B: int = len(data)+ bs: int = batch_size+ if B > batch_size:+ out_list = []+ n_batches = int(B // bs + 1)+ for batch_idx in range(n_batches):+ st = batch_idx * bs+ end = min((batch_idx + 1) * bs, B)+ if st >= end:+ continue+ out_list.append(model_dev(data[st:end].to(device), **kwargs))+ out = torch.cat(out_list, 0)+ return out.to(data.device)+ return model_dev(data.to(device), **kwargs).to(data.device)diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 5a654f9ed..e6cfcec14 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -195,6 +195,6 @@ class GaussianBlur2d(nn.Module):return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type, self.separable)-@deprecated(replace_with="gaussian_blur2d", version="6.9.10")+@deprecated(replace_with="gaussian_blur2d", version="0.6.10")def gaussian_blur2d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103return gaussian_blur2d(*args, **kwargs)diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 453c0be9e..893aef618 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -1034,16 +1034,16 @@ def get_hanning_kernel2d(return kernel2d-@deprecated(replace_with="get_gaussian_kernel1d", version="6.9.10")+@deprecated(replace_with="get_gaussian_kernel1d", version="0.6.10")def get_gaussian_kernel1d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103return get_gaussian_kernel1d(*args, **kwargs)-@deprecated(replace_with="get_gaussian_kernel2d", version="6.9.10")+@deprecated(replace_with="get_gaussian_kernel2d", version="0.6.10")def get_gaussian_kernel2d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103return get_gaussian_kernel2d(*args, **kwargs)-@deprecated(replace_with="get_gaussian_kernel3d", version="6.9.10")+@deprecated(replace_with="get_gaussian_kernel3d", version="0.6.10")def get_gaussian_kernel3d_t(*args: Any, **kwargs: Any) -> torch.Tensor: # noqa: D103return get_gaussian_kernel3d(*args, **kwargs)diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex dbfddf0df..05ad2f91f 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -17,7 +17,6 @@from __future__ import annotations-import warningsfrom typing import Optionalimport torch@@ -497,7 +496,9 @@ def transform_bbox(``xmin, ymin, xmax, ymax``. If set to 'xywh' the boxes are assumed to be in the format``xmin, ymin, width, height``restore_coordinates: In case the boxes are flipped, adding a post processing step to restore the- coordinates to a valid bounding box.+ coordinates to a valid bounding box. Enabled by default (``None`` behaves as ``True``); pass+ ``False`` to keep the raw transformed corners (the pre-2022 behavior, which yields invalid+ boxes under flips).Returns:The set of transformed points in the specified mode@@ -509,16 +510,6 @@ def transform_bbox(if mode not in ("xyxy", "xywh"):raise ValueError(f"Mode must be one of 'xyxy', 'xywh'. Got {mode}")- # (B, N, 4, 2) shaped polygon boxes do not need to be restored.- if restore_coordinates is None and not (boxes.shape[-2:] == torch.Size([4, 2])):- warnings.warn(- "Previous behaviour produces incorrect box coordinates if a flip transformation performed on boxes."- "The previous wrong behaviour has been corrected and will be removed in the future versions."- "If you wish to keep the previous behaviour, please set `restore_coordinates=False`."- "Otherwise, set `restore_coordinates=True` as an acknowledgement.",- stacklevel=1,- )-# convert boxes to format xyxyif mode == "xywh":boxes[..., 2] = boxes[..., 0] + boxes[..., 2] # x + wdiff --git a/kornia/io/__init__.py b/kornia/io/__init__.pyindex 32ceece8d..870504dd5 100644--- a/kornia/io/__init__.py+++ b/kornia/io/__init__.py@@ -21,5 +21,6 @@ This package provides image input/output utilities, including image loading and"""from .io import ImageLoadType, load_image, write_image+from .sample import get_sample_images-__all__ = ["ImageLoadType", "load_image", "write_image"]+__all__ = ["ImageLoadType", "get_sample_images", "load_image", "write_image"]diff --git a/kornia/io/sample.py b/kornia/io/sample.pynew file mode 100644index 000000000..e681a3d67--- /dev/null+++ b/kornia/io/sample.py@@ -0,0 +1,122 @@+# 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.+#++from __future__ import annotations++import logging+import os+from typing import Any, List, Optional, Tuple, Union++import torch++from kornia.core.external import PILImage as Image+from kornia.core.external import requests++from .io import load_image++__all__ = [+ "get_sample_images",+]++IMAGE_URLS: List[str] = [+ "https://raw.githubusercontent.com/kornia/data/main/panda.jpg",+ "https://raw.githubusercontent.com/kornia/data/main/simba.png",+ "https://raw.githubusercontent.com/kornia/data/main/girona.png",+ "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png",+ "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg",+ "https://raw.githubusercontent.com/kornia/data/main/delorean.png",+]+++def download_image(url: str, save_to: str) -> None:+ """Download an image from a given URL and save it to a specified file path.++ Args:+ url: The URL of the image to download.+ save_to: The file path where the downloaded image will be saved.++ """+ im = Image.open(requests.get(url, stream=True, timeout=30).raw) # type:ignore+ im.save(save_to)+++def get_sample_images(+ resize: Optional[Tuple[int, int]] = None,+ paths: List[str] = IMAGE_URLS,+ download: bool = True,+ cache_dir: Optional[str] = None,+ as_list: Optional[bool] = None,+ divisible_factor: Optional[int] = None,+ **kwargs: Any,+) -> Union[torch.Tensor, List[torch.Tensor]]:+ """Load multiple images from the given URLs.++ Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.++ Removed from ``kornia.utils.sample`` in 0.8.3 and restored here as public API β the docs and downstream+ demos rely on it.++ Args:+ paths: A list of path or URL from which to load or download images.+ Defaults to a pre-defined constant `IMAGE_URLS` if not provided.+ resize: Optional target size for resizing all images as a tuple (height, width).+ If not provided, the images will not be resized, and their original sizes will be retained.+ download: Whether to download the images if they are not already cached. Defaults to True.+ cache_dir: The directory where the downloaded images will be cached.+ Defaults to ".kornia_hub/images".+ as_list: if to keep the output as a list. If None and `resize` is None, the output will be a list.+ If None and `resize` is not None, the output will be a single tensor.+ divisible_factor:+ If not None, the images will be resized to the nearest multiple of `divisible_factor`.+ **kwargs: Additional keyword arguments to pass to `kornia.geometry.resize`.++ Returns:+ torch.Tensor | list[torch.Tensor]:+ If `resize` is provided, returns a single stacked tensor with shape (B, C, H, W).+ Otherwise, returns a list of tensors, each with its original shape (C, H, W).++ """+ import kornia.geometry # local import to avoid a circular dependency at import time++ if cache_dir is None:+ cache_dir = ".kornia_hub/images"+ os.makedirs(cache_dir, exist_ok=True)+ tensors = []+ for path in paths:+ if path.startswith("http"):+ name = os.path.basename(path)+ fname = os.path.join(cache_dir, name)+ if not os.path.exists(fname) and download:+ logging.info(f"Downloading `{path}` to `{fname}`.")+ download_image(path, fname)+ elif not os.path.exists(fname) and not download:+ logging.error(+ f"Image `{path}` not found at `{fname}`. You may want to set `download=True` to download it."+ )+ else:+ fname = path+ img_tensor = load_image(fname)+ if resize is not None:+ img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)+ if divisible_factor is not None:+ img_tensor = kornia.geometry.transform.resize_to_be_divisible(img_tensor, divisible_factor, **kwargs)+ tensors.append(img_tensor)++ if not as_list and resize is not None:+ return torch.stack(tensors)++ return tensorsdiff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 653cf1f41..3e5b09ddb 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -21,9 +21,47 @@ This module has been deprecated. Functions have been moved to their respective mImport from the new locations instead (e.g., `kornia.image.draw_line` instead of `kornia.utils.draw_line`)."""+from __future__ import annotations+from typing import Any-from kornia.core._compat import deprecated+from kornia.core._compat import _emit_deprecation_warning, deprecated+from kornia.core.ops import (+ eye_like as _eye_like,+)+from kornia.core.ops import (+ vec_like as _vec_like,+)+from kornia.core.utils import (+ dataclass_to_dict as _dataclass_to_dict,+)+from kornia.core.utils import (+ dict_to_dataclass as _dict_to_dataclass,+)+from kornia.core.utils import (+ get_cuda_device_if_available as _get_cuda_device_if_available,+)+from kornia.core.utils import (+ get_cuda_or_mps_device_if_available as _get_cuda_or_mps_device_if_available,+)+from kornia.core.utils import (+ get_mps_device_if_available as _get_mps_device_if_available,+)+from kornia.core.utils import (+ is_autocast_enabled as _is_autocast_enabled,+)+from kornia.core.utils import (+ is_mps_tensor_safe as _is_mps_tensor_safe,+)+from kornia.core.utils import (+ safe_inverse_with_mask as _safe_inverse_with_mask,+)+from kornia.core.utils import (+ safe_solve_with_mask as _safe_solve_with_mask,+)+from kornia.core.utils import (+ xla_is_available as _xla_is_available,+)from kornia.geometry import (create_meshgrid as _create_meshgrid,)@@ -36,6 +74,9 @@ from kornia.geometry import (from kornia.geometry import (save_pointcloud_ply as _save_pointcloud_ply,)+from kornia.image import (+ ImageToTensor as _ImageToTensor,+)from kornia.image import (draw_convex_polygon as _draw_convex_polygon,)@@ -48,6 +89,9 @@ from kornia.image import (from kornia.image import (draw_rectangle as _draw_rectangle,)+from kornia.image import (+ image_list_to_tensor as _image_list_to_tensor,+)from kornia.image import (image_to_string as _image_to_string,)@@ -194,18 +238,250 @@ def one_hot(*args: Any, **kwargs: Any) -> Any:return _one_hot(*args, **kwargs)+# The 0.8.3 removal shipped without shims for these public names, breaking+# `kornia.utils.<name>` with no deprecation window. Restored here with the+# standard warning so the documented deprecation policy holds.+++@deprecated(+ replace_with="kornia.core.ops.eye_like",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.ops` instead.",+)+def eye_like(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.ops.eye_like` instead."""+ return _eye_like(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.ops.vec_like",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.ops` instead.",+)+def vec_like(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.ops.vec_like` instead."""+ return _vec_like(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.safe_solve_with_mask",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def safe_solve_with_mask(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.safe_solve_with_mask` instead."""+ return _safe_solve_with_mask(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.safe_inverse_with_mask",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def safe_inverse_with_mask(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.safe_inverse_with_mask` instead."""+ return _safe_inverse_with_mask(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.is_mps_tensor_safe",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def is_mps_tensor_safe(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.is_mps_tensor_safe` instead."""+ return _is_mps_tensor_safe(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.dataclass_to_dict",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def dataclass_to_dict(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.dataclass_to_dict` instead."""+ return _dataclass_to_dict(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.dict_to_dataclass",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def dict_to_dataclass(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.dict_to_dataclass` instead."""+ return _dict_to_dataclass(*args, **kwargs)+++@deprecated(+ replace_with="kornia.image.image_list_to_tensor",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+)+def image_list_to_tensor(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.image.image_list_to_tensor` instead."""+ return _image_list_to_tensor(*args, **kwargs)+++class ImageToTensor(_ImageToTensor):+ """Deprecated: Use `kornia.image.ImageToTensor` instead.++ A real subclass (not the `@deprecated` decorator, which turns classes into plain+ callables) so `isinstance` checks and further subclassing keep working.+ """++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ _emit_deprecation_warning(+ "ImageToTensor",+ "kornia.image.ImageToTensor",+ "0.8.3",+ " The `kornia.utils` module has been removed. Import from `kornia.image` instead.",+ )+ super().__init__(*args, **kwargs)+++@deprecated(+ replace_with="kornia.io.get_sample_images",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.io` instead.",+)+def get_sample_images(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.io.get_sample_images` instead."""+ from kornia.io import get_sample_images as _get_sample_images++ return _get_sample_images(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.batched_forward",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def batched_forward(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.batched_forward` instead."""+ from kornia.core.utils import batched_forward as _batched_forward++ return _batched_forward(*args, **kwargs)+++@deprecated(+ replace_with="torch.meshgrid",+ version="0.8.3",+ extra_reason=" This compatibility wrapper predates torch 1.10; call `torch.meshgrid(tensors, indexing=...)`.",+)+def torch_meshgrid(tensors: Any, indexing: str) -> Any:+ """Deprecated: Use `torch.meshgrid` directly."""+ import torch++ return torch.meshgrid(tensors, indexing=indexing)+++@deprecated(+ replace_with='torch.load(..., map_location="cpu")',+ version="0.8.3",+ extra_reason=" This identity hook predates `map_location` accepting device strings.",+)+def map_location_to_cpu(storage: Any, *args: Any, **kwargs: Any) -> Any:+ """Deprecated: Pass `map_location="cpu"` to `torch.load` instead."""+ return storage+++@deprecated(+ replace_with="kornia.core.utils.get_cuda_device_if_available",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def get_cuda_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_cuda_device_if_available` instead."""+ return _get_cuda_device_if_available(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.get_mps_device_if_available",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def get_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_mps_device_if_available` instead."""+ return _get_mps_device_if_available(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.get_cuda_or_mps_device_if_available",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def get_cuda_or_mps_device_if_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.get_cuda_or_mps_device_if_available` instead."""+ return _get_cuda_or_mps_device_if_available(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.is_autocast_enabled",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def is_autocast_enabled(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.is_autocast_enabled` instead."""+ return _is_autocast_enabled(*args, **kwargs)+++@deprecated(+ replace_with="kornia.core.utils.xla_is_available",+ version="0.8.3",+ extra_reason=" The `kornia.utils` module has been removed. Import from `kornia.core.utils` instead.",+)+def xla_is_available(*args: Any, **kwargs: Any) -> Any:+ """Deprecated: Use `kornia.core.utils.xla_is_available` instead."""+ return _xla_is_available(*args, **kwargs)+++def __getattr__(name: str) -> Any:+ # Lazy so that `import kornia.utils` never pulls in the onnx machinery.+ if name == "CachedDownloader":+ from kornia.onnx.download import CachedDownloader as _CachedDownloader++ _emit_deprecation_warning(+ "CachedDownloader",+ "kornia.onnx.download.CachedDownloader",+ "0.8.3",+ " The `kornia.utils` module has been removed. Import from `kornia.onnx.download` instead.",+ )+ return _CachedDownloader+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++__all__ = [+ "CachedDownloader",+ "ImageToTensor",+ "batched_forward","create_meshgrid","create_meshgrid3d",+ "dataclass_to_dict",+ "dict_to_dataclass","draw_convex_polygon","draw_line","draw_point2d","draw_rectangle",+ "eye_like",+ "get_cuda_device_if_available",+ "get_cuda_or_mps_device_if_available",+ "get_mps_device_if_available",+ "get_sample_images",+ "image_list_to_tensor","image_to_string","image_to_tensor",+ "is_autocast_enabled",+ "is_mps_tensor_safe","load_pointcloud_ply",+ "map_location_to_cpu","one_hot","print_image",+ "safe_inverse_with_mask",+ "safe_solve_with_mask","save_pointcloud_ply","tensor_to_image",+ "torch_meshgrid",+ "vec_like",+ "xla_is_available",]diff --git a/tests/api_surface.json b/tests/api_surface.jsonnew file mode 100644index 000000000..33e777e76--- /dev/null+++ b/tests/api_surface.json@@ -0,0 +1,743 @@+{+ "kornia.augmentation": [+ "AugmentationBase2D",+ "AugmentationBase3D",+ "AugmentationSequential",+ "CenterCrop",+ "CenterCrop3D",+ "ColorJiggle",+ "ColorJitter",+ "Denormalize",+ "GeometricAugmentationBase2D",+ "GeometricAugmentationBase3D",+ "ImageSequential",+ "IntensityAugmentationBase2D",+ "IntensityAugmentationBase3D",+ "LongestMaxSize",+ "ManyToManyAugmentationDispather",+ "ManyToOneAugmentationDispather",+ "MixAugmentationBaseV2",+ "Normalize",+ "PadTo",+ "PatchMix",+ "PatchSequential",+ "RandomAffine",+ "RandomAffine3D",+ "RandomAutoContrast",+ "RandomBoxBlur",+ "RandomBrightness",+ "RandomChannelDropout",+ "RandomChannelShuffle",+ "RandomContrast",+ "RandomCrop",+ "RandomCrop3D",+ "RandomCutMixV2",+ "RandomDepthicalFlip3D",+ "RandomDissolving",+ "RandomElasticTransform",+ "RandomEqualize",+ "RandomEqualize3D",+ "RandomErasing",+ "RandomFisheye",+ "RandomGamma",+ "RandomGaussianBlur",+ "RandomGaussianIllumination",+ "RandomGaussianNoise",+ "RandomGrayscale",+ "RandomHorizontalFlip",+ "RandomHorizontalFlip3D",+ "RandomHue",+ "RandomInvert",+ "RandomJigsaw",+ "RandomLinearCornerIllumination",+ "RandomLinearIllumination",+ "RandomMedianBlur",+ "RandomMixUpV2",+ "RandomMosaic",+ "RandomMotionBlur",+ "RandomMotionBlur3D",+ "RandomPerspective",+ "RandomPerspective3D",+ "RandomPlanckianJitter",+ "RandomPlasmaBrightness",+ "RandomPlasmaContrast",+ "RandomPlasmaShadow",+ "RandomPosterize",+ "RandomRGBShift",+ "RandomRain",+ "RandomResizedCrop",+ "RandomRotation",+ "RandomRotation3D",+ "RandomRotation90",+ "RandomSaltAndPepperNoise",+ "RandomSaturation",+ "RandomSharpness",+ "RandomShear",+ "RandomSnow",+ "RandomSolarize",+ "RandomThinPlateSpline",+ "RandomTranslate",+ "RandomVerticalFlip",+ "RandomVerticalFlip3D",+ "Resize",+ "RigidAffineAugmentationBase2D",+ "RigidAffineAugmentationBase3D",+ "SmallestMaxSize",+ "VideoSequential",+ "auto",+ "container"+ ],+ "kornia.color": [+ "AUTUMN",+ "ApplyColorMap",+ "BgrToGrayscale",+ "BgrToRgb",+ "BgrToRgba",+ "CFA",+ "ColorMap",+ "ColorMapType",+ "GrayscaleToRgb",+ "HlsToRgb",+ "HsvToRgb",+ "LabToRgb",+ "LinearRgbToRgb",+ "LuvToRgb",+ "NormalsToRgb255",+ "RGBColor",+ "RawToRgb",+ "RawToRgb2x2Downscaled",+ "Rgb255ToNormals",+ "Rgb255ToRgb",+ "RgbToBgr",+ "RgbToGrayscale",+ "RgbToHls",+ "RgbToHsv",+ "RgbToLab",+ "RgbToLinearRgb",+ "RgbToLuv",+ "RgbToRaw",+ "RgbToRgb255",+ "RgbToRgba",+ "RgbToXyz",+ "RgbToYcbcr",+ "RgbToYuv",+ "RgbToYuv420",+ "RgbToYuv422",+ "RgbaToBgr",+ "RgbaToRgb",+ "Sepia",+ "XyzToRgb",+ "YcbcrToRgb",+ "Yuv420ToRgb",+ "Yuv422ToRgb",+ "YuvToRgb",+ "apply_colormap",+ "bgr_to_grayscale",+ "bgr_to_rgb",+ "bgr_to_rgba",+ "grayscale_to_rgb",+ "hls_to_rgb",+ "hsv_to_rgb",+ "lab_to_rgb",+ "linear_rgb_to_rgb",+ "luv_to_rgb",+ "normals_to_rgb255",+ "raw_to_rgb",+ "raw_to_rgb_2x2_downscaled",+ "rgb255_to_normals",+ "rgb255_to_rgb",+ "rgb_to_bgr",+ "rgb_to_grayscale",+ "rgb_to_hls",+ "rgb_to_hsv",+ "rgb_to_lab",+ "rgb_to_linear_rgb",+ "rgb_to_luv",+ "rgb_to_raw",+ "rgb_to_rgb255",+ "rgb_to_rgba",+ "rgb_to_xyz",+ "rgb_to_y",+ "rgb_to_ycbcr",+ "rgb_to_yuv",+ "rgb_to_yuv420",+ "rgb_to_yuv422",+ "rgba_to_bgr",+ "rgba_to_rgb",+ "sepia",+ "xyz_to_rgb",+ "ycbcr_to_rgb",+ "yuv420_to_rgb",+ "yuv422_to_rgb",+ "yuv_to_rgb"+ ],+ "kornia.core": [+ "ImageModule",+ "ImageModuleMixIn",+ "ImageSequential",+ "ONNXExportMixin",+ "ONNXMixin",+ "ONNXRuntimeMixin",+ "TensorWrapper",+ "external",+ "eye_like",+ "vec_like"+ ],+ "kornia.enhance": [+ "AddWeighted",+ "AdjustBrightness",+ "AdjustBrightnessAccumulative",+ "AdjustContrast",+ "AdjustContrastWithMeanSubtraction",+ "AdjustGamma",+ "AdjustHue",+ "AdjustLog",+ "AdjustSaturation",+ "AdjustSaturationWithGraySubtraction",+ "AdjustSigmoid",+ "Denormalize",+ "IntegralImage",+ "IntegralTensor",+ "Invert",+ "JPEGCodecDifferentiable",+ "Normalize",+ "Rescale",+ "Threshold",+ "ThresholdType",+ "ZCAWhitening",+ "add_weighted",+ "adjust_brightness",+ "adjust_brightness_accumulative",+ "adjust_contrast",+ "adjust_contrast_with_mean_subtraction",+ "adjust_gamma",+ "adjust_hue",+ "adjust_hue_raw",+ "adjust_log",+ "adjust_saturation",+ "adjust_saturation_raw",+ "adjust_saturation_with_gray_subtraction",+ "adjust_sigmoid",+ "denormalize",+ "equalize",+ "equalize3d",+ "equalize_clahe",+ "histogram",+ "histogram2d",+ "image_histogram2d",+ "integral_image",+ "integral_tensor",+ "invert",+ "jpeg_codec_differentiable",+ "linear_transform",+ "normalize",+ "normalize_min_max",+ "posterize",+ "sharpness",+ "shift_rgb",+ "solarize",+ "threshold",+ "zca_mean",+ "zca_whiten"+ ],+ "kornia.filters": [+ "BilateralBlur",+ "BlurPool2D",+ "BoxBlur",+ "Canny",+ "EdgeAwareBlurPool2D",+ "GaussianBlur2d",+ "GuidedBlur",+ "InRange",+ "JointBilateralBlur",+ "Laplacian",+ "MaxBlurPool2D",+ "MedianBlur",+ "MotionBlur",+ "MotionBlur3D",+ "OtsuThreshold",+ "Sobel",+ "SpatialGradient",+ "SpatialGradient3d",+ "StableDiffusionDissolving",+ "UnsharpMask",+ "bilateral_blur",+ "blur_pool2d",+ "box_blur",+ "canny",+ "edge_aware_blur_pool2d",+ "fft_conv",+ "filter2d",+ "filter2d_separable",+ "filter3d",+ "gaussian",+ "gaussian_blur2d",+ "gaussian_blur2d_t",+ "get_binary_kernel2d",+ "get_box_kernel1d",+ "get_box_kernel2d",+ "get_diff_kernel2d",+ "get_gaussian_discrete_kernel1d",+ "get_gaussian_erf_kernel1d",+ "get_gaussian_kernel1d",+ "get_gaussian_kernel1d_t",+ "get_gaussian_kernel2d",+ "get_gaussian_kernel2d_t",+ "get_gaussian_kernel3d",+ "get_gaussian_kernel3d_t",+ "get_hanning_kernel1d",+ "get_hanning_kernel2d",+ "get_laplacian_kernel1d",+ "get_laplacian_kernel2d",+ "get_motion_kernel2d",+ "get_motion_kernel3d",+ "get_sobel_kernel2d",+ "get_spatial_gradient_kernel2d",+ "get_spatial_gradient_kernel3d",+ "guided_blur",+ "in_range",+ "joint_bilateral_blur",+ "laplacian",+ "laplacian_1d",+ "max_blur_pool2d",+ "median_blur",+ "motion_blur",+ "motion_blur3d",+ "otsu_threshold",+ "sobel",+ "spatial_gradient",+ "spatial_gradient3d",+ "unsharp_mask"+ ],+ "kornia.geometry": [+ "ARKitQTVecs_to_ColmapQTVecs",+ "AdaptiveQuadInterp3d",+ "Affine",+ "BaseModel",+ "BaseWarper",+ "CenterCrop2D",+ "ConvQuadInterp3d",+ "ConvSoftArgmax2d",+ "ConvSoftArgmax3d",+ "DepthWarper",+ "Hflip",+ "Homography",+ "HomographyWarper",+ "Hyperplane",+ "ImageRegistrator",+ "IterativeQuadInterp3d",+ "KORNIA_CHECK_SHAPE",+ "KRt_from_projection",+ "NamedPose",+ "NonMaximaSuppression2d",+ "NonMaximaSuppression3d",+ "Optional",+ "ParametrizedLine",+ "PinholeCamera",+ "PyrDown",+ "PyrUp",+ "Quaternion",+ "RANSAC",+ "Rescale",+ "Resize",+ "Rot180",+ "Rotate",+ "Rt_to_matrix4x4",+ "Scale",+ "ScalePyramid",+ "Se2",+ "Se3",+ "Shear",+ "Similarity",+ "So2",+ "So3",+ "SpatialSoftArgmax2d",+ "StereoCamera",+ "Translate",+ "Tuple",+ "TupleTensor",+ "Vflip",+ "affine",+ "affine3d",+ "affwarp",+ "angle_axis_to_quaternion",+ "angle_axis_to_rotation_matrix",+ "angle_to_rotation_matrix",+ "annotations",+ "axis_angle_to_quaternion",+ "axis_angle_to_rotation_matrix",+ "batched_dot_product",+ "batched_squared_norm",+ "bbox",+ "bbox_generator",+ "bbox_generator3d",+ "bbox_to_mask",+ "bbox_to_mask3d",+ "boxes",+ "build_laplacian_pyramid",+ "build_pyramid",+ "calibration",+ "cam2pixel",+ "camera",+ "camtoworld_graphics_to_vision_4x4",+ "camtoworld_graphics_to_vision_Rt",+ "camtoworld_to_worldtocam_Rt",+ "camtoworld_vision_to_graphics_4x4",+ "camtoworld_vision_to_graphics_Rt",+ "cart2pol",+ "center_crop",+ "center_crop3d",+ "check_matrix_shape",+ "compose_transformations",+ "compute_correspond_epilines",+ "conv_quad_interp3d",+ "conv_soft_argmax2d",+ "conv_soft_argmax3d",+ "conversions",+ "convert_affinematrix_to_homography",+ "convert_affinematrix_to_homography3d",+ "convert_points_from_homogeneous",+ "convert_points_to_homogeneous",+ "create_meshgrid",+ "create_meshgrid3d",+ "crop2d",+ "crop3d",+ "crop_and_resize",+ "crop_and_resize3d",+ "crop_by_boxes",+ "crop_by_boxes3d",+ "crop_by_indices",+ "crop_by_transform_mat",+ "crop_by_transform_mat3d",+ "cross_product_matrix",+ "decompose_essential_matrix",+ "decompose_essential_matrix_no_svd",+ "deg2rad",+ "denormalize_homography",+ "denormalize_pixel_coordinates",+ "denormalize_pixel_coordinates3d",+ "denormalize_points_with_intrinsics",+ "depth",+ "depth_from_disparity",+ "depth_from_plane_equation",+ "depth_from_point",+ "depth_to_3d",+ "depth_to_3d_v2",+ "depth_to_normals",+ "depth_warp",+ "determinant_to_polynomial",+ "distort_points",+ "distort_points_affine",+ "distort_points_kannala_brandt",+ "dx_distort_points_affine",+ "dx_distort_points_kannala_brandt",+ "dx_project_points_orthographic",+ "dx_project_points_z1",+ "elastic_transform",+ "elastic_transform2d",+ "epipolar",+ "essential_from_Rt",+ "essential_from_fundamental",+ "euclidean_distance",+ "euler_from_quaternion",+ "find_essential",+ "find_fundamental",+ "find_homography_dlt",+ "find_homography_dlt_iterated",+ "find_homography_lines_dlt",+ "find_homography_lines_dlt_iterated",+ "fit_line",+ "fit_plane",+ "flips",+ "fundamental_from_essential",+ "fundamental_from_projections",+ "generate_scene",+ "get_affine_matrix2d",+ "get_affine_matrix3d",+ "get_closest_point_on_epipolar_line",+ "get_perpendicular",+ "get_perspective_transform",+ "get_perspective_transform3d",+ "get_projective_transform",+ "get_rotation_matrix2d",+ "get_shear_matrix2d",+ "get_shear_matrix3d",+ "get_tps_transform",+ "get_translation_matrix2d",+ "grid",+ "hflip",+ "homography",+ "homography_warp",+ "homography_warp3d",+ "homography_warper",+ "image_registrator",+ "imgwarp",+ "infer_bbox_shape",+ "infer_bbox_shape3d",+ "intrinsics_like",+ "inverse_transformation",+ "invert_affine_transform",+ "iterative_quad_interp3d",+ "keypoints",+ "left_to_right_epipolar_distance",+ "liegroup",+ "linalg",+ "line",+ "line_segment_transfer_error_one_way",+ "load_pointcloud_ply",+ "matrix4x4_to_Rt",+ "motion_from_essential",+ "motion_from_essential_choose_solution",+ "multiply_deg_one_poly",+ "multiply_deg_two_one_poly",+ "nms",+ "nms2d",+ "nms3d",+ "nms3d_minmax",+ "normal_transform_pixel",+ "normal_transform_pixel3d",+ "normalize_homography",+ "normalize_homography3d",+ "normalize_pixel_coordinates",+ "normalize_pixel_coordinates3d",+ "normalize_points",+ "normalize_points_with_intrinsics",+ "normalize_quaternion",+ "normalize_transformation",+ "null_vector_3x4",+ "oneway_transfer_error",+ "os",+ "pixel2cam",+ "plane",+ "point_line_distance",+ "pointcloud",+ "pol2cart",+ "pose",+ "project_points",+ "project_points_orthographic",+ "project_points_z1",+ "projection_from_KRt",+ "projection_from_Rt",+ "projections_from_fundamental",+ "pyramid",+ "pyrdown",+ "pyrup",+ "quaternion",+ "quaternion_exp_to_log",+ "quaternion_from_euler",+ "quaternion_log_to_exp",+ "quaternion_to_angle_axis",+ "quaternion_to_axis_angle",+ "quaternion_to_rotation_matrix",+ "rad2deg",+ "random_intrinsics",+ "ransac",+ "relative_camera_motion",+ "relative_transformation",+ "remap",+ "render_gaussian2d",+ "rescale",+ "resize",+ "resize_to_be_divisible",+ "right_to_left_epipolar_distance",+ "rot180",+ "rotate",+ "rotate3d",+ "rotation_matrix_to_angle_axis",+ "rotation_matrix_to_axis_angle",+ "rotation_matrix_to_quaternion",+ "safe_inverse_with_mask",+ "safe_solve_with_mask",+ "sample_is_valid_for_homography",+ "sampson_epipolar_distance",+ "save_pointcloud_ply",+ "scale",+ "scale_intrinsics",+ "shear",+ "solve_cubic",+ "solve_pnp_dlt",+ "solve_quadratic",+ "solve_quartic",+ "solvers",+ "spatial_expectation2d",+ "spatial_soft_argmax2d",+ "spatial_softmax2d",+ "squared_norm",+ "subpix",+ "symmetric_transfer_error",+ "symmetrical_epipolar_distance",+ "thin_plate_spline",+ "tilt_projection",+ "torch",+ "transform",+ "transform_bbox",+ "transform_points",+ "translate",+ "triangulate_points",+ "undistort_image",+ "undistort_points",+ "undistort_points_affine",+ "undistort_points_kannala_brandt",+ "unproject_meshgrid",+ "unproject_points",+ "unproject_points_orthographic",+ "unproject_points_z1",+ "uuid",+ "validate_bbox",+ "validate_bbox3d",+ "vector",+ "vector_to_skew_symmetric_matrix",+ "vflip",+ "warnings",+ "warp_affine",+ "warp_affine3d",+ "warp_frame_depth",+ "warp_grid",+ "warp_grid3d",+ "warp_image_tps",+ "warp_perspective",+ "warp_perspective3d",+ "warp_points_tps",+ "worldtocam_to_camtoworld_Rt"+ ],+ "kornia.image": [+ "ChannelsOrder",+ "Image",+ "ImageLayout",+ "ImageSize",+ "ImageToTensor",+ "PixelFormat",+ "draw_convex_polygon",+ "draw_line",+ "draw_point2d",+ "draw_rectangle",+ "image_list_to_tensor",+ "image_to_string",+ "image_to_tensor",+ "make_grid",+ "perform_keep_shape_image",+ "perform_keep_shape_video",+ "print_image",+ "tensor_to_image"+ ],+ "kornia.io": [+ "ImageLoadType",+ "get_sample_images",+ "load_image",+ "write_image"+ ],+ "kornia.losses": [+ "BinaryFocalLossWithLogits",+ "CauchyLoss",+ "CharbonnierLoss",+ "DiceLoss",+ "FocalLoss",+ "GemanMcclureLoss",+ "HausdorffERLoss",+ "HausdorffERLoss3D",+ "InverseDepthSmoothnessLoss",+ "LovaszHingeLoss",+ "LovaszSoftmaxLoss",+ "MIKernel",+ "MILossFromRef",+ "MILossFromRef2D",+ "MILossFromRef3D",+ "MS_SSIMLoss",+ "NMILossFromRef",+ "NMILossFromRef2D",+ "NMILossFromRef3D",+ "PSNRLoss",+ "SSIM3DLoss",+ "SSIMLoss",+ "TotalVariation",+ "TverskyLoss",+ "WelschLoss",+ "binary_focal_loss_with_logits",+ "cauchy_loss",+ "charbonnier_loss",+ "dice_loss",+ "focal_loss",+ "geman_mcclure_loss",+ "inverse_depth_smoothness_loss",+ "js_div_loss_2d",+ "kl_div_loss_2d",+ "lovasz_hinge_loss",+ "lovasz_softmax_loss",+ "mutual_information_loss",+ "mutual_information_loss_2d",+ "mutual_information_loss_3d",+ "normalized_mutual_information_loss",+ "normalized_mutual_information_loss_2d",+ "normalized_mutual_information_loss_3d",+ "one_hot",+ "psnr_loss",+ "ssim3d_loss",+ "ssim_loss",+ "total_variation",+ "tversky_loss",+ "welsch_loss"+ ],+ "kornia.metrics": [+ "AEPE",+ "AverageMeter",+ "SSIM",+ "SSIM3D",+ "accuracy",+ "aepe",+ "average_endpoint_error",+ "confusion_matrix",+ "mean_absolute_disparity_error",+ "mean_average_precision",+ "mean_bad_pixel_error",+ "mean_iou",+ "mean_iou_bbox",+ "psnr",+ "root_mean_squared_disparity_error",+ "ssim",+ "ssim3d"+ ],+ "kornia.morphology": [+ "bottom_hat",+ "closing",+ "dilation",+ "erosion",+ "gradient",+ "morphology",+ "opening",+ "top_hat"+ ],+ "kornia.utils": [+ "CachedDownloader",+ "ImageToTensor",+ "batched_forward",+ "create_meshgrid",+ "create_meshgrid3d",+ "dataclass_to_dict",+ "dict_to_dataclass",+ "draw_convex_polygon",+ "draw_line",+ "draw_point2d",+ "draw_rectangle",+ "eye_like",+ "get_cuda_device_if_available",+ "get_cuda_or_mps_device_if_available",+ "get_mps_device_if_available",+ "get_sample_images",+ "image_list_to_tensor",+ "image_to_string",+ "image_to_tensor",+ "is_autocast_enabled",+ "is_mps_tensor_safe",+ "load_pointcloud_ply",+ "map_location_to_cpu",+ "one_hot",+ "print_image",+ "safe_inverse_with_mask",+ "safe_solve_with_mask",+ "save_pointcloud_ply",+ "tensor_to_image",+ "torch_meshgrid",+ "vec_like",+ "xla_is_available"+ ]+}diff --git a/tests/test_api_surface.py b/tests/test_api_surface.pynew file mode 100644index 000000000..363da87c1--- /dev/null+++ b/tests/test_api_surface.py@@ -0,0 +1,73 @@+# 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.+#++"""Guard the public API surface of the stable-core modules.++The 0.8.3 release removed 20 of the 34 public ``kornia.utils`` names with no+deprecation window β nobody noticed until an audit months later, because+nothing in CI compared the public surface against the previous state. This+test is that comparison: ``tests/api_surface.json`` is the checked-in+inventory, and removing a public name fails here until the inventory is+edited in the same PR β which is exactly the deliberate review moment the+stability policy (docs/source/get-started/stability.rst) requires.++Additions are fine and do not fail the test; run this file with+``--update-api-surface`` semantics by regenerating the JSON (see+``regenerate()`` below) whenever new public API lands.+"""++import importlib+import json+from pathlib import Path++import pytest++INVENTORY = Path(__file__).parent / "api_surface.json"+++def _current_surface(module_name: str) -> set:+ mod = importlib.import_module(module_name)+ names = getattr(mod, "__all__", None)+ if names is None:+ names = [n for n in dir(mod) if not n.startswith("_")]+ return set(names)+++def regenerate() -> None:+ """Rewrite the inventory from the live library (run manually after adding public API)."""+ recorded = json.loads(INVENTORY.read_text())+ surface = {name: sorted(_current_surface(name)) for name in recorded}+ INVENTORY.write_text(json.dumps(surface, indent=2, sort_keys=True) + "\n")++[email protected]("module_name", sorted(json.loads(INVENTORY.read_text())))+def test_no_public_name_removed(module_name):+ recorded = set(json.loads(INVENTORY.read_text())[module_name])+ current = _current_surface(module_name)+ removed = sorted(recorded - current)+ assert not removed, (+ f"Public names removed from {module_name}: {removed}. Per the API stability policy "+ "(docs/source/get-started/stability.rst), a public symbol must spend at least one minor "+ "release as a deprecated shim before removal. If this removal is deliberate and the "+ "deprecation window has passed, update tests/api_surface.json in this PR (run "+ "tests.test_api_surface.regenerate()) and list the removal in the release notes."+ )+++if __name__ == "__main__":+ regenerate()+ print(f"regenerated {INVENTORY}")diff --git a/tests/test_import.py b/tests/test_import.pyindex 93908b816..3c85b8bc1 100644--- a/tests/test_import.py+++ b/tests/test_import.py@@ -57,12 +57,13 @@ def test_import_without_jit_script_deprecation():def test_import_emits_no_warnings():"""Importing kornia must not emit ANY warning, whatever module raises it.- Stricter companion to the jit-script guard above: torch is imported first so its own- import-time warnings (outside kornia's control, and version-dependent) are excluded,- then every warning is promoted to an error for the kornia import itself. This is the- honest form of the ``python -W error -c "import kornia"`` gate from- https://github.com/kornia/kornia/issues/3727 β it fails on any warning kornia's import- path emits or triggers, protecting downstream users who run with ``-W error``.+ Stricter companion to the jit-script guard above: torch β and onnxruntime, when+ installed β are imported first so their own import-time warnings (outside kornia's+ control, and platform/version-dependent) are excluded, then every warning is promoted+ to an error for the kornia import itself. This is the honest form of the+ ``python -W error -c "import kornia"`` gate from+ https://github.com/kornia/kornia/issues/3727 β it fails on any warning kornia's own+ import path emits or triggers, protecting downstream users who run with ``-W error``.``resetwarnings`` first, so filters inherited from the environment (``PYTHONWARNINGS``,a ``-W`` flag propagated by the test runner) cannot make the torch import fail anddiff --git a/tests/utils/test_deprecated.py b/tests/utils/test_deprecated.pyindex 522e41c68..92ca35c73 100644--- a/tests/utils/test_deprecated.py+++ b/tests/utils/test_deprecated.py@@ -115,3 +115,196 @@ class TestDeprecatedWrappers:utils.create_meshgrid(2, 2)dep_warnings = [w for w in caught if issubclass(w.category, DeprecationWarning)]assert len(dep_warnings) == 2+++class TestRestoredWrappers:+ """Names removed in 0.8.3 without a deprecation window, restored as warning shims.++ See https://github.com/kornia/kornia/pull/3891 follow-up audit: of the 34 public+ `kornia.utils` names in v0.8.2, 20 were removed with no shim. These are the ones+ whose implementations still exist elsewhere in the library.+ """++ def test_eye_like_warns(self):+ with pytest.warns(DeprecationWarning, match="kornia.core.ops.eye_like"):+ out = utils.eye_like(3, torch.rand(2, 4, 4))+ assert out.shape == (2, 3, 3)++ def test_vec_like_warns(self):+ with pytest.warns(DeprecationWarning, match="kornia.core.ops.vec_like"):+ out = utils.vec_like(3, torch.rand(2, 4, 4))+ assert out.shape == (2, 3, 1)++ def test_safe_solve_with_mask_warns(self):+ A = torch.eye(3)[None]+ b = torch.rand(1, 3, 3)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.safe_solve_with_mask"):+ sol, _, mask = utils.safe_solve_with_mask(b, A)+ assert sol.shape == b.shape+ assert bool(mask.all())++ def test_safe_inverse_with_mask_warns(self):+ A = torch.eye(3)[None]+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.safe_inverse_with_mask"):+ inv, mask = utils.safe_inverse_with_mask(A)+ assert inv.shape == A.shape+ assert bool(mask.all())++ def test_is_mps_tensor_safe_warns(self):+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.is_mps_tensor_safe"):+ out = utils.is_mps_tensor_safe(torch.rand(1))+ assert out is False++ def test_dataclass_roundtrip_warns(self):+ from dataclasses import dataclass++ @dataclass+ class _Cfg:+ a: int++ with pytest.warns(DeprecationWarning, match="kornia.core.utils.dataclass_to_dict"):+ d = utils.dataclass_to_dict(_Cfg(a=1))+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.dict_to_dataclass"):+ cfg = utils.dict_to_dataclass(d, _Cfg)+ assert cfg == _Cfg(a=1)++ def test_image_list_to_tensor_warns(self):+ arrs = [np.zeros((8, 8, 3), dtype=np.uint8)] * 2+ with pytest.warns(DeprecationWarning, match="kornia.image.image_list_to_tensor"):+ t = utils.image_list_to_tensor(arrs)+ assert t.shape == (2, 3, 8, 8)++ def test_image_to_tensor_module_warns(self):+ with pytest.warns(DeprecationWarning, match="kornia.image.ImageToTensor"):+ mod = utils.ImageToTensor()+ out = mod(np.zeros((8, 8, 3), dtype=np.uint8))+ assert isinstance(out, torch.Tensor)++ def test_image_to_tensor_is_a_real_class(self):+ """The shim must stay a type: isinstance checks and subclassing worked in 0.8.2."""+ from kornia.image import ImageToTensor as NewImageToTensor++ assert isinstance(utils.ImageToTensor, type)+ assert issubclass(utils.ImageToTensor, NewImageToTensor)+ with pytest.warns(DeprecationWarning):+ inst = utils.ImageToTensor()+ assert isinstance(inst, NewImageToTensor)++ def test_cached_downloader_warns(self):+ with pytest.warns(DeprecationWarning, match="kornia.onnx.download.CachedDownloader"):+ cls = utils.CachedDownloader+ from kornia.onnx.download import CachedDownloader++ assert cls is CachedDownloader++ def test_batched_forward_warns(self):+ x = torch.rand(300, 2)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.batched_forward"):+ out = utils.batched_forward(torch.nn.Identity(), x, torch.device("cpu"), batch_size=128)+ assert torch.allclose(out, x)++ def test_get_sample_images_no_download_warns(self, tmp_path):+ # empty path list: warns and returns an empty list without touching the network+ with pytest.warns(DeprecationWarning, match="kornia.io.get_sample_images"):+ out = utils.get_sample_images(paths=[], download=False, cache_dir=str(tmp_path))+ assert out == []++ def test_torch_meshgrid_warns(self):+ with pytest.warns(DeprecationWarning, match="torch.meshgrid"):+ xs, _ys = utils.torch_meshgrid([torch.arange(2), torch.arange(3)], indexing="ij")+ assert xs.shape == (2, 3)++ def test_map_location_to_cpu_warns(self):+ t = torch.rand(2)+ with pytest.warns(DeprecationWarning, match="map_location"):+ out = utils.map_location_to_cpu(t, "cuda:0")+ assert out is t++ def test_device_and_env_helpers_warn(self):+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.get_cuda_device_if_available"):+ dev = utils.get_cuda_device_if_available()+ assert isinstance(dev, torch.device)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.get_mps_device_if_available"):+ dev = utils.get_mps_device_if_available()+ assert isinstance(dev, torch.device)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.get_cuda_or_mps_device_if_available"):+ dev = utils.get_cuda_or_mps_device_if_available()+ assert isinstance(dev, torch.device)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.is_autocast_enabled"):+ out = utils.is_autocast_enabled()+ assert isinstance(out, bool)+ with pytest.warns(DeprecationWarning, match="kornia.core.utils.xla_is_available"):+ out = utils.xla_is_available()+ assert isinstance(out, bool)++ def test_v082_public_surface_fully_restored(self):+ """Every public name from v0.8.2's kornia.utils.__all__ must still resolve.++ Frozen copy of `git show v0.8.2:kornia/utils/__init__.py` __all__, minus the+ underscore-prefixed `_extract_device_dtype` (private per the stability policy).+ This is the closure of the 0.8.3 hard-removal audit: if any name here stops+ resolving, the deprecation window was skipped again.+ """+ v082_public_all = [+ "CachedDownloader",+ "ImageToTensor",+ "batched_forward",+ "create_meshgrid",+ "create_meshgrid3d",+ "dataclass_to_dict",+ "deprecated",+ "dict_to_dataclass",+ "draw_convex_polygon",+ "draw_line",+ "draw_point2d",+ "draw_rectangle",+ "eye_like",+ "get_cuda_device_if_available",+ "get_cuda_or_mps_device_if_available",+ "get_mps_device_if_available",+ "get_sample_images",+ "image_list_to_tensor",+ "image_to_string",+ "image_to_tensor",+ "is_autocast_enabled",+ "is_mps_tensor_safe",+ "load_pointcloud_ply",+ "map_location_to_cpu",+ "one_hot",+ "print_image",+ "safe_inverse_with_mask",+ "safe_solve_with_mask",+ "save_pointcloud_ply",+ "tensor_to_image",+ "torch_meshgrid",+ "vec_like",+ "xla_is_available",+ ]+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ unresolvable = [n for n in v082_public_all if not hasattr(utils, n)]+ assert not unresolvable, f"v0.8.2 public names no longer resolvable: {unresolvable}"++ def test_restored_wrappers_in_all(self):+ expected = {+ "CachedDownloader",+ "ImageToTensor",+ "batched_forward",+ "dataclass_to_dict",+ "dict_to_dataclass",+ "eye_like",+ "get_cuda_device_if_available",+ "get_cuda_or_mps_device_if_available",+ "get_mps_device_if_available",+ "get_sample_images",+ "image_list_to_tensor",+ "is_autocast_enabled",+ "is_mps_tensor_safe",+ "map_location_to_cpu",+ "safe_inverse_with_mask",+ "safe_solve_with_mask",+ "torch_meshgrid",+ "vec_like",+ "xla_is_available",+ }+ assert expected.issubset(set(utils.__all__))