Skip to content

Commit 036a3da

Browse files
committed
Upgrade to Python 3.9
1 parent f7b1cfa commit 036a3da

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

80 files changed

+690
-679
lines changed

torchvision/datasets/_optical_flow.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
from .utils import _read_pfm, verify_str_arg
1414
from .vision import VisionDataset
1515

16-
T1 = Tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]]
17-
T2 = Tuple[Image.Image, Image.Image, Optional[np.ndarray]]
16+
T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]]
17+
T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]]
1818

1919

2020
__all__ = (
@@ -37,8 +37,8 @@ def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None
3737
super().__init__(root=root)
3838
self.transforms = transforms
3939

40-
self._flow_list: List[str] = []
41-
self._image_list: List[List[str]] = []
40+
self._flow_list: list[str] = []
41+
self._image_list: list[list[str]] = []
4242

4343
def _read_img(self, file_name: str) -> Image.Image:
4444
img = Image.open(file_name)
@@ -225,7 +225,7 @@ def __getitem__(self, index: int) -> Union[T1, T2]:
225225
"""
226226
return super().__getitem__(index)
227227

228-
def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
228+
def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]:
229229
return _read_16bits_png_with_flow_and_valid_mask(file_name)
230230

231231

@@ -443,7 +443,7 @@ def __init__(self, root: Union[str, Path], split: str = "train", transforms: Opt
443443
"Could not find the HD1K images. Please make sure the directory structure is correct."
444444
)
445445

446-
def _read_flow(self, file_name: str) -> Tuple[np.ndarray, np.ndarray]:
446+
def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]:
447447
return _read_16bits_png_with_flow_and_valid_mask(file_name)
448448

449449
def __getitem__(self, index: int) -> Union[T1, T2]:
@@ -479,7 +479,7 @@ def _read_flo(file_name: str) -> np.ndarray:
479479
return data.reshape(h, w, 2).transpose(2, 0, 1)
480480

481481

482-
def _read_16bits_png_with_flow_and_valid_mask(file_name: str) -> Tuple[np.ndarray, np.ndarray]:
482+
def _read_16bits_png_with_flow_and_valid_mask(file_name: str) -> tuple[np.ndarray, np.ndarray]:
483483

484484
flow_and_valid = decode_png(read_file(file_name)).to(torch.float32)
485485
flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :]

torchvision/datasets/_stereo_matching.py

+18-18
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
from .utils import _read_pfm, download_and_extract_archive, verify_str_arg
1515
from .vision import VisionDataset
1616

17-
T1 = Tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray]
18-
T2 = Tuple[Image.Image, Image.Image, Optional[np.ndarray]]
17+
T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray]
18+
T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]]
1919

2020
__all__ = ()
2121

@@ -65,11 +65,11 @@ def _scan_pairs(
6565
self,
6666
paths_left_pattern: str,
6767
paths_right_pattern: Optional[str] = None,
68-
) -> List[Tuple[str, Optional[str]]]:
68+
) -> list[tuple[str, Optional[str]]]:
6969

7070
left_paths = list(sorted(glob(paths_left_pattern)))
7171

72-
right_paths: List[Union[None, str]]
72+
right_paths: list[Union[None, str]]
7373
if paths_right_pattern:
7474
right_paths = list(sorted(glob(paths_right_pattern)))
7575
else:
@@ -92,7 +92,7 @@ def _scan_pairs(
9292
return paths
9393

9494
@abstractmethod
95-
def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
95+
def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], Optional[np.ndarray]]:
9696
# function that returns a disparity map and an occlusion map
9797
pass
9898

@@ -178,7 +178,7 @@ def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None
178178
disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
179179
self._disparities = disparities
180180

181-
def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
181+
def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
182182
disparity_map = _read_pfm_file(file_path)
183183
disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
184184
valid_mask = None
@@ -257,7 +257,7 @@ def __init__(self, root: Union[str, Path], split: str = "train", transforms: Opt
257257
else:
258258
self._disparities = list((None, None) for _ in self._images)
259259

260-
def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], None]:
260+
def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]:
261261
# test split has no disparity maps
262262
if file_path is None:
263263
return None, None
@@ -345,7 +345,7 @@ def __init__(self, root: Union[str, Path], split: str = "train", transforms: Opt
345345
else:
346346
self._disparities = list((None, None) for _ in self._images)
347347

348-
def _read_disparity(self, file_path: str) -> Tuple[Optional[np.ndarray], None]:
348+
def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]:
349349
# test split has no disparity maps
350350
if file_path is None:
351351
return None, None
@@ -549,7 +549,7 @@ def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
549549
When ``use_ambient_views`` is True, the dataset will return at random one of ``[im1.png, im1E.png, im1L.png]``
550550
as the right image.
551551
"""
552-
ambient_file_paths: List[Union[str, Path]] # make mypy happy
552+
ambient_file_paths: list[Union[str, Path]] # make mypy happy
553553

554554
if not isinstance(file_path, Path):
555555
file_path = Path(file_path)
@@ -565,7 +565,7 @@ def _read_img(self, file_path: Union[str, Path]) -> Image.Image:
565565
file_path = random.choice(ambient_file_paths) # type: ignore
566566
return super()._read_img(file_path)
567567

568-
def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
568+
def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
569569
# test split has not disparity maps
570570
if file_path is None:
571571
return None, None
@@ -694,7 +694,7 @@ def __init__(
694694
disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
695695
self._disparities += disparities
696696

697-
def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
697+
def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
698698
disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
699699
# unsqueeze the disparity map into (C, H, W) format
700700
disparity_map = disparity_map[None, :, :] / 32.0
@@ -788,13 +788,13 @@ def __init__(self, root: Union[str, Path], variant: str = "single", transforms:
788788
right_disparity_pattern = str(root / s / split_prefix[s] / "*.right.depth.png")
789789
self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
790790

791-
def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
791+
def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
792792
# (H, W) image
793793
depth = np.asarray(Image.open(file_path))
794794
# as per https://research.nvidia.com/sites/default/files/pubs/2018-06_Falling-Things/readme_0.txt
795795
# in order to extract disparity from depth maps
796796
camera_settings_path = Path(file_path).parent / "_camera_settings.json"
797-
with open(camera_settings_path, "r") as f:
797+
with open(camera_settings_path) as f:
798798
# inverse of depth-from-disparity equation: depth = (baseline * focal) / (disparity * pixel_constant)
799799
intrinsics = json.load(f)
800800
focal = intrinsics["camera_settings"][0]["intrinsic_settings"]["fx"]
@@ -911,7 +911,7 @@ def __init__(
911911
right_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "right" / "*.pfm")
912912
self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
913913

914-
def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
914+
def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
915915
disparity_map = _read_pfm_file(file_path)
916916
disparity_map = np.abs(disparity_map) # ensure that the disparity is positive
917917
valid_mask = None
@@ -999,7 +999,7 @@ def __init__(self, root: Union[str, Path], pass_name: str = "final", transforms:
999999
disparity_pattern = str(root / "training" / "disparities" / "*" / "*.png")
10001000
self._disparities += self._scan_pairs(disparity_pattern, None)
10011001

1002-
def _get_occlussion_mask_paths(self, file_path: str) -> Tuple[str, str]:
1002+
def _get_occlussion_mask_paths(self, file_path: str) -> tuple[str, str]:
10031003
# helper function to get the occlusion mask paths
10041004
# a path will look like .../.../.../training/disparities/scene1/img1.png
10051005
# we want to get something like .../.../.../training/occlusions/scene1/img1.png
@@ -1020,7 +1020,7 @@ def _get_occlussion_mask_paths(self, file_path: str) -> Tuple[str, str]:
10201020

10211021
return occlusion_path, outofframe_path
10221022

1023-
def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
1023+
def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
10241024
if file_path is None:
10251025
return None, None
10261026

@@ -1101,7 +1101,7 @@ def __init__(self, root: Union[str, Path], split: str = "train", transforms: Opt
11011101
right_disparity_pattern = str(root / "*" / "right_disp.png")
11021102
self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern)
11031103

1104-
def _read_disparity(self, file_path: str) -> Tuple[np.ndarray, None]:
1104+
def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]:
11051105
disparity_map = np.asarray(Image.open(file_path), dtype=np.float32)
11061106
# unsqueeze disparity to (C, H, W)
11071107
disparity_map = disparity_map[None, :, :] / 1024.0
@@ -1195,7 +1195,7 @@ def __init__(self, root: Union[str, Path], split: str = "train", transforms: Opt
11951195
disparity_pattern = str(root / anot_dir / "*" / "disp0GT.pfm")
11961196
self._disparities = self._scan_pairs(disparity_pattern, None)
11971197

1198-
def _read_disparity(self, file_path: str) -> Union[Tuple[None, None], Tuple[np.ndarray, np.ndarray]]:
1198+
def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]:
11991199
# test split has no disparity maps
12001200
if file_path is None:
12011201
return None, None

torchvision/datasets/caltech.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class Caltech101(VisionDataset):
4040
def __init__(
4141
self,
4242
root: Union[str, Path],
43-
target_type: Union[List[str], str] = "category",
43+
target_type: Union[list[str], str] = "category",
4444
transform: Optional[Callable] = None,
4545
target_transform: Optional[Callable] = None,
4646
download: bool = False,
@@ -71,14 +71,14 @@ def __init__(
7171
}
7272
self.annotation_categories = list(map(lambda x: name_map[x] if x in name_map else x, self.categories))
7373

74-
self.index: List[int] = []
74+
self.index: list[int] = []
7575
self.y = []
7676
for (i, c) in enumerate(self.categories):
7777
n = len(os.listdir(os.path.join(self.root, "101_ObjectCategories", c)))
7878
self.index.extend(range(1, n + 1))
7979
self.y.extend(n * [i])
8080

81-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
81+
def __getitem__(self, index: int) -> tuple[Any, Any]:
8282
"""
8383
Args:
8484
index (int): Index
@@ -181,7 +181,7 @@ def __init__(
181181
raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
182182

183183
self.categories = sorted(os.listdir(os.path.join(self.root, "256_ObjectCategories")))
184-
self.index: List[int] = []
184+
self.index: list[int] = []
185185
self.y = []
186186
for (i, c) in enumerate(self.categories):
187187
n = len(
@@ -194,7 +194,7 @@ def __init__(
194194
self.index.extend(range(1, n + 1))
195195
self.y.extend(n * [i])
196196

197-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
197+
def __getitem__(self, index: int) -> tuple[Any, Any]:
198198
"""
199199
Args:
200200
index (int): Index

torchvision/datasets/celeba.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def __init__(
6666
self,
6767
root: Union[str, Path],
6868
split: str = "train",
69-
target_type: Union[List[str], str] = "attr",
69+
target_type: Union[list[str], str] = "attr",
7070
transform: Optional[Callable] = None,
7171
target_transform: Optional[Callable] = None,
7272
download: bool = False,
@@ -155,7 +155,7 @@ def download(self) -> None:
155155

156156
extract_archive(os.path.join(self.root, self.base_folder, "img_align_celeba.zip"))
157157

158-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
158+
def __getitem__(self, index: int) -> tuple[Any, Any]:
159159
X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index]))
160160

161161
target: Any = []

torchvision/datasets/cifar.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def _load_meta(self) -> None:
101101
self.classes = data[self.meta["key"]]
102102
self.class_to_idx = {_class: i for i, _class in enumerate(self.classes)}
103103

104-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
104+
def __getitem__(self, index: int) -> tuple[Any, Any]:
105105
"""
106106
Args:
107107
index (int): Index

torchvision/datasets/cityscapes.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def __init__(
107107
root: Union[str, Path],
108108
split: str = "train",
109109
mode: str = "fine",
110-
target_type: Union[List[str], str] = "instance",
110+
target_type: Union[list[str], str] = "instance",
111111
transform: Optional[Callable] = None,
112112
target_transform: Optional[Callable] = None,
113113
transforms: Optional[Callable] = None,
@@ -172,7 +172,7 @@ def __init__(
172172
self.images.append(os.path.join(img_dir, file_name))
173173
self.targets.append(target_types)
174174

175-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
175+
def __getitem__(self, index: int) -> tuple[Any, Any]:
176176
"""
177177
Args:
178178
index (int): Index
@@ -206,7 +206,7 @@ def extra_repr(self) -> str:
206206
lines = ["Split: {split}", "Mode: {mode}", "Type: {target_type}"]
207207
return "\n".join(lines).format(**self.__dict__)
208208

209-
def _load_json(self, path: str) -> Dict[str, Any]:
209+
def _load_json(self, path: str) -> dict[str, Any]:
210210
with open(path) as file:
211211
data = json.load(file)
212212
return data

torchvision/datasets/clevr.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def __init__(
4949

5050
self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*"))
5151

52-
self._labels: List[Optional[int]]
52+
self._labels: list[Optional[int]]
5353
if self._split != "test":
5454
with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file:
5555
content = json.load(file)
@@ -61,7 +61,7 @@ def __init__(
6161
def __len__(self) -> int:
6262
return len(self._image_files)
6363

64-
def __getitem__(self, idx: int) -> Tuple[Any, Any]:
64+
def __getitem__(self, idx: int) -> tuple[Any, Any]:
6565
image_file = self._image_files[idx]
6666
label = self._labels[idx]
6767

torchvision/datasets/coco.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ def _load_image(self, id: int) -> Image.Image:
4141
path = self.coco.loadImgs(id)[0]["file_name"]
4242
return Image.open(os.path.join(self.root, path)).convert("RGB")
4343

44-
def _load_target(self, id: int) -> List[Any]:
44+
def _load_target(self, id: int) -> list[Any]:
4545
return self.coco.loadAnns(self.coco.getAnnIds(id))
4646

47-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
47+
def __getitem__(self, index: int) -> tuple[Any, Any]:
4848

4949
if not isinstance(index, int):
5050
raise ValueError(f"Index must be of type integer, got {type(index)} instead.")
@@ -105,5 +105,5 @@ class CocoCaptions(CocoDetection):
105105
106106
"""
107107

108-
def _load_target(self, id: int) -> List[str]:
108+
def _load_target(self, id: int) -> list[str]:
109109
return [ann["caption"] for ann in super()._load_target(id)]

torchvision/datasets/dtd.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def __init__(
7676
def __len__(self) -> int:
7777
return len(self._image_files)
7878

79-
def __getitem__(self, idx: int) -> Tuple[Any, Any]:
79+
def __getitem__(self, idx: int) -> tuple[Any, Any]:
8080
image_file, label = self._image_files[idx], self._labels[idx]
8181
image = PIL.Image.open(image_file).convert("RGB")
8282

torchvision/datasets/fakedata.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class FakeData(VisionDataset):
2525
def __init__(
2626
self,
2727
size: int = 1000,
28-
image_size: Tuple[int, int, int] = (3, 224, 224),
28+
image_size: tuple[int, int, int] = (3, 224, 224),
2929
num_classes: int = 10,
3030
transform: Optional[Callable] = None,
3131
target_transform: Optional[Callable] = None,
@@ -37,7 +37,7 @@ def __init__(
3737
self.image_size = image_size
3838
self.random_offset = random_offset
3939

40-
def __getitem__(self, index: int) -> Tuple[Any, Any]:
40+
def __getitem__(self, index: int) -> tuple[Any, Any]:
4141
"""
4242
Args:
4343
index (int): Index

torchvision/datasets/fer2013.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def get_label(row):
9292
else:
9393
return None
9494

95-
with open(data_file, "r", newline="") as file:
95+
with open(data_file, newline="") as file:
9696
rows = (row for row in csv.DictReader(file))
9797

9898
if use_fer_file or use_icml_file:
@@ -104,7 +104,7 @@ def get_label(row):
104104
def __len__(self) -> int:
105105
return len(self._samples)
106106

107-
def __getitem__(self, idx: int) -> Tuple[Any, Any]:
107+
def __getitem__(self, idx: int) -> tuple[Any, Any]:
108108
image_tensor, target = self._samples[idx]
109109
image = Image.fromarray(image_tensor.numpy())
110110

0 commit comments

Comments
 (0)