🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
enable `check_untyped_defs` on mypy (#2086)
João Gustavo A. Amorimf8bbafcd0c0d
diff --git a/kornia/__tmp__.py b/kornia/__tmp__.pydeleted file mode 100644index bb801fd87..000000000--- a/kornia/__tmp__.py+++ /dev/null@@ -1,19 +0,0 @@-import warnings-from functools import wraps-from typing import Callable---def __deprecation_warning(name: str, replacement: str):- warnings.warn(- f"`{name}` will be renamed to `{replacement}` in the future versions. " f"Please use `{replacement}` instead.",- category=FutureWarning,- )---def _deprecation_wrapper(new_func: Callable, old_func: str) -> Callable:- @wraps(new_func)- def wrapper(*args, **kwargs):- __deprecation_warning(old_func, new_func.__name__)- return new_func(*args, **kwargs)-- return wrapperdiff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.pyindex 9111dc445..4ad8e70ab 100644--- a/kornia/feature/adalam/ransac.py+++ b/kornia/feature/adalam/ransac.py@@ -1,5 +1,9 @@+from typing import Tuple+import torch+from kornia.core import Tensor+from .utils import arange_sequence, batch_2x2_ellipse, batch_2x2_inv, draw_first_k_couples, piecewise_arange@@ -73,8 +77,16 @@ def confidence_based_inlier_selection(residuals, ransidx, rdims, idxoffsets, dv,return inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_counts.float() / expected_extra_inl-def sample_padded_inliers(xsamples, ysamples, inlier_counts, inl_ransidx, inl_sampleidx, numransacs, dv):- maxinliers = torch.max(inlier_counts).item()+def sample_padded_inliers(+ xsamples: Tensor,+ ysamples: Tensor,+ inlier_counts: Tensor,+ inl_ransidx: Tensor,+ inl_sampleidx: Tensor,+ numransacs: int,+ dv: torch.device,+) -> Tuple[Tensor, Tensor]:+ maxinliers = int(torch.max(inlier_counts).item())dtype = xsamples.dtypepadded_inlier_x = torch.zeros(size=(numransacs, maxinliers, 2), device=dv, dtype=dtype)padded_inlier_y = torch.zeros(size=(numransacs, maxinliers, 2), device=dv, dtype=dtype)@@ -85,10 +97,10 @@ def sample_padded_inliers(xsamples, ysamples, inlier_counts, inl_ransidx, inl_sareturn padded_inlier_x, padded_inlier_y-def ransac(xsamples, ysamples, rdims, config, iters=128, refit=True):+def ransac(xsamples, ysamples, rdims: Tensor, config, iters=128, refit=True):DET_THR = config['detected_scale_rate_threshold']MIN_CONFIDENCE = config['min_confidence']- dv = config['device']+ dv: torch.device = config['device']numransacs = rdims.shape[0]ransidx = torch.arange(numransacs, device=dv).repeat_interleave(rdims)diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.pyindex fec29c041..36a2c9640 100644--- a/kornia/feature/adalam/utils.py+++ b/kornia/feature/adalam/utils.py@@ -2,6 +2,8 @@ import mathimport torch+from kornia.core import Tensor+def arange_sequence(ranges):"""@@ -34,7 +36,7 @@ def orientation_diff(o1, o2):return diff-def piecewise_arange(piecewise_idxer):+def piecewise_arange(piecewise_idxer: Tensor):"""count repeated indicesExample:@@ -42,9 +44,10 @@ def piecewise_arange(piecewise_idxer):"""dv = piecewise_idxer.device# print(piecewise_idxer)+ uni: Tensoruni, counts = torch.unique_consecutive(piecewise_idxer, return_counts=True)# print(counts)- maxcnt = torch.max(counts).item()+ maxcnt = int(torch.max(counts).item())numuni = uni.shape[0]tmp = torch.zeros(size=(numuni, maxcnt), device=dv).bool()ranges = torch.arange(maxcnt, device=dv).unsqueeze(0).expand(numuni, -1)@@ -108,7 +111,7 @@ def batch_2x2_ellipse(m):return eigenvals, eigenvecs-def draw_first_k_couples(k: int, rdims: int, dv: torch.device):+def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device):# exhaustive search over the first n samples:# n(n+1)/2 = n2/2 + n/2 couples# max n for which we can exhaustively sample with k couples:diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.pyindex e672da99e..ce2b71768 100644--- a/kornia/feature/loftr/utils/position_encoding.py+++ b/kornia/feature/loftr/utils/position_encoding.py@@ -1,12 +1,15 @@import mathimport torch-from torch import nn+from kornia.core import Module, Tensor, zeros-class PositionEncodingSine(nn.Module):++class PositionEncodingSine(Module):"""This is a sinusoidal position encoding that generalized to 2-dimensional images."""+ pe: Tensor+def __init__(self, d_model, max_shape=(256, 256), temp_bug_fix=True):"""Args:@@ -29,7 +32,7 @@ class PositionEncodingSine(nn.Module):For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shapeshould be (H//8, W//8)."""- pe = torch.zeros((self.d_model, *max_shape))+ pe = zeros((self.d_model, *max_shape))y_position = torch.ones(max_shape).cumsum(0).float().unsqueeze(0)x_position = torch.ones(max_shape).cumsum(1).float().unsqueeze(0)if self.temp_bug_fix:diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 7a887f6d7..27235472e 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -162,11 +162,13 @@ class SIFTDescriptor(Module):wo0_big = (1.0 - wo1_big_) * magwo1_big = wo1_big_ * mag- ang_bins = []- for i in range(0, self.num_ang_bins):- out = self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big)- ang_bins.append(out)- ang_bins = concatenate(ang_bins, 1)+ ang_bins = concatenate(+ [+ self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big)+ for i in range(0, self.num_ang_bins)+ ],+ 1,+ )ang_bins = ang_bins.view(B, -1)ang_bins = normalize(ang_bins, p=2)ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.pyindex 7be4ef6a3..782e50433 100644--- a/kornia/feature/sold2/backbones.py+++ b/kornia/feature/sold2/backbones.py@@ -1,15 +1,16 @@"""Implements several backbone networks."""-from typing import Dict, List, Optional, Tuple, Union+from typing import Dict, List, Optional, Tuple, Type, Unionimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.functional import pixel_shuffle, softmax-# [Hourglass backbone classes]+from kornia.core import Module-class HourglassBackbone(nn.Module):+# [Hourglass backbone classes]+class HourglassBackbone(Module):"""Hourglass network, taken from https://github.com/zhou13/lcnn.Args:@@ -40,7 +41,7 @@ class HourglassBackbone(nn.Module):return self.net(input_images)-class MultitaskHead(nn.Module):+class MultitaskHead(Module):def __init__(self, input_channels: int):super().__init__()@@ -61,13 +62,9 @@ class MultitaskHead(nn.Module):return torch.cat([head(x) for head in self.heads], dim=1)-class Bottleneck2D(nn.Module):+class Bottleneck2D(Module):def __init__(- self,- inplanes: int,- planes: int,- stride: Union[int, Tuple[int, int]] = 1,- downsample: Optional[torch.nn.Module] = None,+ self, inplanes: int, planes: int, stride: Union[int, Tuple[int, int]] = 1, downsample: Optional[Module] = None):super().__init__()@@ -104,21 +101,21 @@ class Bottleneck2D(nn.Module):return out-class Hourglass(nn.Module):- def __init__(self, block: torch.nn.Module, num_blocks: int, planes: int, depth: int, expansion: int = 2):+class Hourglass(Module):+ def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2):super().__init__()self.depth = depthself.block = blockself.expansion = expansionself.hg = self._make_hour_glass(block, num_blocks, planes, depth)- def _make_residual(self, block: torch.nn.Module, num_blocks: int, planes: int) -> torch.nn.Module:+ def _make_residual(self, block: Type[Bottleneck2D], num_blocks: int, planes: int) -> Module:layers = []for _ in range(0, num_blocks):layers.append(block(planes * self.expansion, planes))return nn.Sequential(*layers)- def _make_hour_glass(self, block: torch.nn.Module, num_blocks: int, planes: int, depth: int) -> torch.nn.ModuleList:+ def _make_hour_glass(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int) -> nn.ModuleList:hgl = []for i in range(depth):res = []@@ -147,13 +144,13 @@ class Hourglass(nn.Module):return self._hour_glass_forward(self.depth, x)-class HourglassNet(nn.Module):+class HourglassNet(Module):"""Hourglass model from Newell et al ECCV 2016."""def __init__(self,- block: torch.nn.Module,- head: torch.nn.Module,+ block: Type[Bottleneck2D],+ head: Module,depth: int,num_stacks: int,num_blocks: int,@@ -194,8 +191,8 @@ class HourglassNet(nn.Module):self.score_ = nn.ModuleList(score_)def _make_residual(- self, block: torch.nn.Module, planes: int, blocks: int, stride: Union[int, Tuple[int, int]] = 1- ) -> torch.nn.Module:+ self, block: Type[Bottleneck2D], planes: int, blocks: int, stride: Union[int, Tuple[int, int]] = 1+ ) -> Module:downsample = Noneif stride != 1 or self.inplanes != planes * self.expansion:downsample = nn.Sequential(nn.Conv2d(self.inplanes, planes * self.expansion, kernel_size=1, stride=stride))@@ -208,7 +205,7 @@ class HourglassNet(nn.Module):return nn.Sequential(*layers)- def _make_fc(self, inplanes: int, outplanes: int) -> torch.nn.Module:+ def _make_fc(self, inplanes: int, outplanes: int) -> Module:bn = nn.BatchNorm2d(inplanes)conv = nn.Conv2d(inplanes, outplanes, kernel_size=1)return nn.Sequential(conv, bn, self.relu)@@ -241,7 +238,7 @@ class HourglassNet(nn.Module):def hg(**kwargs):model = HourglassNet(Bottleneck2D,- head=kwargs.get("head", lambda c_in, c_out: nn.Conv2D(c_in, c_out, 1)),+ head=kwargs.get("head", lambda c_in, c_out: nn.Conv2d(c_in, c_out, 1)),depth=kwargs["depth"],num_stacks=kwargs["num_stacks"],num_blocks=kwargs["num_blocks"],@@ -252,7 +249,7 @@ def hg(**kwargs):# [Backbone decoders]-class SuperpointDecoder(nn.Module):+class SuperpointDecoder(Module):"""Junction decoder based on the SuperPoint architecture.Args:@@ -263,10 +260,10 @@ class SuperpointDecoder(nn.Module):def __init__(self, input_feat_dim: int = 128, grid_size: int = 8):super().__init__()- self.relu = torch.nn.ReLU(inplace=True)+ self.relu = nn.ReLU(inplace=True)# Perform strided convolution when using lcnn backbone.- self.convPa = torch.nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=2, padding=1)- self.convPb = torch.nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0)+ self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=2, padding=1)+ self.convPb = nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0)self.grid_size = grid_sizedef forward(self, input_features: torch.Tensor) -> torch.Tensor:@@ -279,7 +276,7 @@ class SuperpointDecoder(nn.Module):return junc_pred-class PixelShuffleDecoder(nn.Module):+class PixelShuffleDecoder(Module):"""Pixel shuffle decoder used to predict the line heatmap.Args:@@ -345,7 +342,7 @@ class PixelShuffleDecoder(nn.Module):return heatmap-class SuperpointDescriptor(nn.Module):+class SuperpointDescriptor(Module):"""Descriptor decoder based on the SuperPoint arcihtecture.Args:@@ -356,9 +353,9 @@ class SuperpointDescriptor(nn.Module):def __init__(self, input_feat_dim: int = 128):super().__init__()- self.relu = torch.nn.ReLU(inplace=True)- self.convPa = torch.nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1)- self.convPb = torch.nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)+ self.relu = nn.ReLU(inplace=True)+ self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1)+ self.convPb = nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)def forward(self, input_features: torch.Tensor) -> torch.Tensor:feat = self.relu(self.convPa(input_features))@@ -370,7 +367,7 @@ class SuperpointDescriptor(nn.Module):# [Combination of all previous models in one]-class SOLD2Net(nn.Module):+class SOLD2Net(Module):"""Full network for SOLD².Args:diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 1d2554092..fbaa48164 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -1,4 +1,5 @@# adapted from: https://github.com/xavysp/DexiNed/blob/d944b70eb6eaf40e22f8467c1e12919aa600d8e4/model.py+from collections import OrderedDictfrom typing import Listimport torch@@ -56,15 +57,18 @@ class CoFusion(Module):class _DenseLayer(nn.Sequential):def __init__(self, input_features, out_features):- super().__init__()- self.add_module('relu1', nn.ReLU(inplace=True)),- self.add_module(- 'conv1', nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)- ),- self.add_module('norm1', nn.BatchNorm2d(out_features)),- self.add_module('relu2', nn.ReLU(inplace=True)),- self.add_module('conv2', nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),- self.add_module('norm2', nn.BatchNorm2d(out_features))+ super().__init__(+ OrderedDict(+ [+ ('relu1', nn.ReLU(inplace=True)),+ ('conv1', nn.Conv2d(input_features, out_features, kernel_size=3, stride=1, padding=2, bias=True)),+ ('norm1', nn.BatchNorm2d(out_features)),+ ('relu2', nn.ReLU(inplace=True)),+ ('conv2', nn.Conv2d(out_features, out_features, kernel_size=3, stride=1, bias=True)),+ ('norm2', nn.BatchNorm2d(out_features)),+ ]+ )+ )def forward(self, x: List[Tensor]) -> List[Tensor]:x1, x2 = x[0], x[1]@@ -100,8 +104,8 @@ class UpConvBlock(Module):raise Exception("layers cannot be none")self.features = nn.Sequential(*layers)- def make_deconv_layers(self, in_features, up_scale):- layers = []+ def make_deconv_layers(self, in_features: int, up_scale: int) -> List[Module]:+ layers: List[Module] = []all_pads = [0, 0, 1, 3, 7]for i in range(up_scale):kernel_size = 2**up_scale@@ -113,7 +117,7 @@ class UpConvBlock(Module):in_features = out_featuresreturn layers- def compute_out_features(self, idx, up_scale):+ def compute_out_features(self, idx: int, up_scale: int):return 1 if idx == up_scale - 1 else self.constant_featuresdef forward(self, x: Tensor, out_shape: List[int]) -> Tensor:diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.pyindex b0d11d422..4c1928ae9 100644--- a/kornia/metrics/average_meter.py+++ b/kornia/metrics/average_meter.py@@ -1,6 +1,6 @@from typing import Union-import torch+from kornia.core import Tensorclass AverageMeter:@@ -14,6 +14,11 @@ class AverageMeter:tensor(0.9900)"""+ val: Union[int, float, bool, Tensor]+ avg: Union[int, float, Tensor]+ sum: Union[int, float, Tensor]+ count: int+def __init__(self) -> None:self.reset()@@ -23,7 +28,7 @@ class AverageMeter:self.sum = 0self.count = 0- def update(self, val: Union[int, float, bool, torch.Tensor], n: int = 1) -> None:+ def update(self, val: Union[int, float, bool, Tensor], n: int = 1) -> None:self.val = valself.sum += val * nself.count += ndiff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.pyindex e9e3880e1..b326f34db 100755--- a/kornia/nerf/data_utils.py+++ b/kornia/nerf/data_utils.py@@ -121,8 +121,10 @@ class RayDataset(Dataset):imgs.append(load_image(img_path, ImageLoadType.UNCHANGED))return imgs- def __len__(self):- return len(self._ray_sampler)+ def __len__(self) -> int:+ if isinstance(self._ray_sampler, RaySampler):+ return len(self._ray_sampler)+ return 0def __getitem__(self, idxs: Union[int, List[int]]) -> RayGroup:r"""Gets a dataset item.diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 99d90aca7..3f6536ca8 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -354,7 +354,7 @@ def KORNIA_UNWRAP(maybe_obj, typ):maybe_obj: the object to unwrap.typ: expected type after unwrap."""- return cast(typ, maybe_obj)+ return cast(typ, maybe_obj) # type: ignore # TODO: this function will change after kornia/pr#1987def KORNIA_CHECK_TYPE(x, typ, msg: Optional[str] = None):diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex f7bb73d6d..e95d465b9 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -1,5 +1,5 @@import warnings-from functools import partial, wraps+from functools import wrapsfrom inspect import isclass, isfunctionfrom typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union, overload@@ -43,13 +43,10 @@ def map_location_to_cpu(storage: Union[str, Tensor], *args: Any, **kwargs: Any)return storage-def _deprecated(func: Optional[Callable] = None, replace_with: Optional[str] = None):- if func is None:- return partial(_deprecated, replace_with=replace_with)-+def _deprecated(func: Callable[..., Any], replace_with: Optional[str] = None):@wraps(func)def wrapper(*args, **kwargs):- name: str = ""+ name = ""if isclass(func):name = func.__class__.__name__if isfunction(func):diff --git a/setup.cfg b/setup.cfgindex dacef5519..0069bec85 100644--- a/setup.cfg+++ b/setup.cfg@@ -119,6 +119,7 @@ ignore =[mypy]files = kornia/pretty = True+check_untyped_defs = Trueshow_error_codes = Trueignore_missing_imports = Trueno_implicit_optional = True