Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

datasets_utils.py 41 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
  1. import contextlib
  2. import functools
  3. import importlib
  4. import inspect
  5. import itertools
  6. import os
  7. import pathlib
  8. import platform
  9. import random
  10. import shutil
  11. import string
  12. import struct
  13. import tarfile
  14. import unittest
  15. import unittest.mock
  16. import zipfile
  17. from collections import defaultdict
  18. from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
  19. import numpy as np
  20. import PIL
  21. import PIL.Image
  22. import pytest
  23. import torch
  24. import torchvision.datasets
  25. import torchvision.io
  26. from common_utils import disable_console_output, get_tmp_dir
  27. from torch.utils._pytree import tree_any
  28. from torch.utils.data import DataLoader
  29. from torchvision import tv_tensors
  30. from torchvision.datasets import wrap_dataset_for_transforms_v2
  31. from torchvision.transforms.functional import get_dimensions
  32. from torchvision.transforms.v2.functional import get_size
  33. __all__ = [
  34. "UsageError",
  35. "lazy_importer",
  36. "test_all_configs",
  37. "DatasetTestCase",
  38. "ImageDatasetTestCase",
  39. "VideoDatasetTestCase",
  40. "create_image_or_video_tensor",
  41. "create_image_file",
  42. "create_image_folder",
  43. "create_video_file",
  44. "create_video_folder",
  45. "make_tar",
  46. "make_zip",
  47. "create_random_string",
  48. ]
  49. class UsageError(Exception):
  50. """Should be raised in case an error happens in the setup rather than the test."""
  51. class LazyImporter:
  52. r"""Lazy importer for additional dependencies.
  53. Some datasets require additional packages that are no direct dependencies of torchvision. Instances of this class
  54. provide modules listed in MODULES as attributes. They are only imported when accessed.
  55. """
  56. MODULES = (
  57. "av",
  58. "lmdb",
  59. "pycocotools",
  60. "requests",
  61. "scipy.io",
  62. "scipy.sparse",
  63. "h5py",
  64. )
  65. def __init__(self):
  66. modules = defaultdict(list)
  67. for module in self.MODULES:
  68. module, *submodules = module.split(".", 1)
  69. if submodules:
  70. modules[module].append(submodules[0])
  71. else:
  72. # This introduces the module so that it is known when we later iterate over the dictionary.
  73. modules.__missing__(module)
  74. for module, submodules in modules.items():
  75. # We need the quirky 'module=module' and submodules=submodules arguments to the lambda since otherwise the
  76. # lookup for these would happen at runtime rather than at definition. Thus, without it, every property
  77. # would try to import the last item in 'modules'
  78. setattr(
  79. type(self),
  80. module,
  81. property(lambda self, module=module, submodules=submodules: LazyImporter._import(module, submodules)),
  82. )
  83. @staticmethod
  84. def _import(package, subpackages):
  85. try:
  86. module = importlib.import_module(package)
  87. except ImportError as error:
  88. raise UsageError(
  89. f"Failed to import module '{package}'. "
  90. f"This probably means that the current test case needs '{package}' installed, "
  91. f"but it is not a dependency of torchvision. "
  92. f"You need to install it manually, for example 'pip install {package}'."
  93. ) from error
  94. for name in subpackages:
  95. importlib.import_module(f".{name}", package=package)
  96. return module
  97. lazy_importer = LazyImporter()
  98. def requires_lazy_imports(*modules):
  99. def outer_wrapper(fn):
  100. @functools.wraps(fn)
  101. def inner_wrapper(*args, **kwargs):
  102. for module in modules:
  103. getattr(lazy_importer, module.replace(".", "_"))
  104. return fn(*args, **kwargs)
  105. return inner_wrapper
  106. return outer_wrapper
  107. def test_all_configs(test):
  108. """Decorator to run test against all configurations.
  109. Add this as decorator to an arbitrary test to run it against all configurations. This includes
  110. :attr:`DatasetTestCase.DEFAULT_CONFIG` and :attr:`DatasetTestCase.ADDITIONAL_CONFIGS`.
  111. The current configuration is provided as the first parameter for the test:
  112. .. code-block::
  113. @test_all_configs()
  114. def test_foo(self, config):
  115. pass
  116. .. note::
  117. This will try to remove duplicate configurations. During this process it will not preserve a potential
  118. ordering of the configurations or an inner ordering of a configuration.
  119. """
  120. def maybe_remove_duplicates(configs):
  121. try:
  122. return [dict(config_) for config_ in {tuple(sorted(config.items())) for config in configs}]
  123. except TypeError:
  124. # A TypeError will be raised if a value of any config is not hashable, e.g. a list. In that case duplicate
  125. # removal would be a lot more elaborate, and we simply bail out.
  126. return configs
  127. @functools.wraps(test)
  128. def wrapper(self):
  129. configs = []
  130. if self.DEFAULT_CONFIG is not None:
  131. configs.append(self.DEFAULT_CONFIG)
  132. if self.ADDITIONAL_CONFIGS is not None:
  133. configs.extend(self.ADDITIONAL_CONFIGS)
  134. if not configs:
  135. configs = [self._KWARG_DEFAULTS.copy()]
  136. else:
  137. configs = maybe_remove_duplicates(configs)
  138. for config in configs:
  139. with self.subTest(**config):
  140. test(self, config)
  141. return wrapper
  142. class DatasetTestCase(unittest.TestCase):
  143. """Abstract base class for all dataset testcases.
  144. You have to overwrite the following class attributes:
  145. - DATASET_CLASS (torchvision.datasets.VisionDataset): Class of dataset to be tested.
  146. - FEATURE_TYPES (Sequence[Any]): Types of the elements returned by index access of the dataset. Instead of
  147. providing these manually, you can instead subclass ``ImageDatasetTestCase`` or ``VideoDatasetTestCase```to
  148. get a reasonable default, that should work for most cases. Each entry of the sequence may be a tuple,
  149. to indicate multiple possible values.
  150. Optionally, you can overwrite the following class attributes:
  151. - DEFAULT_CONFIG (Dict[str, Any]): Config that will be used by default. If omitted, this defaults to all
  152. keyword arguments of the dataset minus ``transform``, ``target_transform``, ``transforms``, and
  153. ``download``. Overwrite this if you want to use a default value for a parameter for which the dataset does
  154. not provide one.
  155. - ADDITIONAL_CONFIGS (Sequence[Dict[str, Any]]): Additional configs that should be tested. Each dictionary can
  156. contain an arbitrary combination of dataset parameters that are **not** ``transform``, ``target_transform``,
  157. ``transforms``, or ``download``.
  158. - REQUIRED_PACKAGES (Iterable[str]): Additional dependencies to use the dataset. If these packages are not
  159. available, the tests are skipped.
  160. Additionally, you need to overwrite the ``inject_fake_data()`` method that provides the data that the tests rely on.
  161. The fake data should resemble the original data as close as necessary, while containing only few examples. During
  162. the creation of the dataset check-, download-, and extract-functions from ``torchvision.datasets.utils`` are
  163. disabled.
  164. Without further configuration, the testcase will test if
  165. 1. the dataset raises a :class:`FileNotFoundError` or a :class:`RuntimeError` if the data files are not found or
  166. corrupted,
  167. 2. the dataset inherits from `torchvision.datasets.VisionDataset`,
  168. 3. the dataset can be turned into a string,
  169. 4. the feature types of a returned example matches ``FEATURE_TYPES``,
  170. 5. the number of examples matches the injected fake data, and
  171. 6. the dataset calls ``transform``, ``target_transform``, or ``transforms`` if available when accessing data.
  172. Case 3. to 6. are tested against all configurations in ``CONFIGS``.
  173. To add dataset-specific tests, create a new method that takes no arguments with ``test_`` as a name prefix:
  174. .. code-block::
  175. def test_foo(self):
  176. pass
  177. If you want to run the test against all configs, add the ``@test_all_configs`` decorator to the definition and
  178. accept a single argument:
  179. .. code-block::
  180. @test_all_configs
  181. def test_bar(self, config):
  182. pass
  183. Within the test you can use the ``create_dataset()`` method that yields the dataset as well as additional
  184. information provided by the ``ìnject_fake_data()`` method:
  185. .. code-block::
  186. def test_baz(self):
  187. with self.create_dataset() as (dataset, info):
  188. pass
  189. """
  190. DATASET_CLASS = None
  191. FEATURE_TYPES = None
  192. DEFAULT_CONFIG = None
  193. ADDITIONAL_CONFIGS = None
  194. REQUIRED_PACKAGES = None
  195. # These keyword arguments are checked by test_transforms in case they are available in DATASET_CLASS.
  196. _TRANSFORM_KWARGS = {
  197. "transform",
  198. "target_transform",
  199. "transforms",
  200. }
  201. # These keyword arguments get a 'special' treatment and should not be set in DEFAULT_CONFIG or ADDITIONAL_CONFIGS.
  202. _SPECIAL_KWARGS = {
  203. *_TRANSFORM_KWARGS,
  204. "download",
  205. }
  206. # These fields are populated during setupClass() within _populate_private_class_attributes()
  207. # This will be a dictionary containing all keyword arguments with their respective default values extracted from
  208. # the dataset constructor.
  209. _KWARG_DEFAULTS = None
  210. # This will be a set of all _SPECIAL_KWARGS that the dataset constructor takes.
  211. _HAS_SPECIAL_KWARG = None
  212. # These functions are disabled during dataset creation in create_dataset().
  213. _CHECK_FUNCTIONS = {
  214. "check_md5",
  215. "check_integrity",
  216. }
  217. _DOWNLOAD_EXTRACT_FUNCTIONS = {
  218. "download_url",
  219. "download_file_from_google_drive",
  220. "extract_archive",
  221. "download_and_extract_archive",
  222. }
  223. def dataset_args(self, tmpdir: str, config: Dict[str, Any]) -> Sequence[Any]:
  224. """Define positional arguments passed to the dataset.
  225. .. note::
  226. The default behavior is only valid if the dataset to be tested has ``root`` as the only required parameter.
  227. Otherwise, you need to overwrite this method.
  228. Args:
  229. tmpdir (str): Path to a temporary directory. For most cases this acts as root directory for the dataset
  230. to be created and in turn also for the fake data injected here.
  231. config (Dict[str, Any]): Configuration that will be passed to the dataset constructor. It provides at least
  232. fields for all dataset parameters with default values.
  233. Returns:
  234. (Tuple[str]): ``tmpdir`` which corresponds to ``root`` for most datasets.
  235. """
  236. return (tmpdir,)
  237. def inject_fake_data(self, tmpdir: str, config: Dict[str, Any]) -> Union[int, Dict[str, Any]]:
  238. """Inject fake data for dataset into a temporary directory.
  239. During the creation of the dataset the download and extract logic is disabled. Thus, the fake data injected
  240. here needs to resemble the raw data, i.e. the state of the dataset directly after the files are downloaded and
  241. potentially extracted.
  242. Args:
  243. tmpdir (str): Path to a temporary directory. For most cases this acts as root directory for the dataset
  244. to be created and in turn also for the fake data injected here.
  245. config (Dict[str, Any]): Configuration that will be passed to the dataset constructor. It provides at least
  246. fields for all dataset parameters with default values.
  247. Needs to return one of the following:
  248. 1. (int): Number of examples in the dataset to be created, or
  249. 2. (Dict[str, Any]): Additional information about the injected fake data. Must contain the field
  250. ``"num_examples"`` that corresponds to the number of examples in the dataset to be created.
  251. """
  252. raise NotImplementedError("You need to provide fake data in order for the tests to run.")
  253. @contextlib.contextmanager
  254. def create_dataset(
  255. self,
  256. config: Optional[Dict[str, Any]] = None,
  257. inject_fake_data: bool = True,
  258. patch_checks: Optional[bool] = None,
  259. **kwargs: Any,
  260. ) -> Iterator[Tuple[torchvision.datasets.VisionDataset, Dict[str, Any]]]:
  261. r"""Create the dataset in a temporary directory.
  262. The configuration passed to the dataset is populated to contain at least all parameters with default values.
  263. For this the following order of precedence is used:
  264. 1. Parameters in :attr:`kwargs`.
  265. 2. Configuration in :attr:`config`.
  266. 3. Configuration in :attr:`~DatasetTestCase.DEFAULT_CONFIG`.
  267. 4. Default parameters of the dataset.
  268. Args:
  269. config (Optional[Dict[str, Any]]): Configuration that will be used to create the dataset.
  270. inject_fake_data (bool): If ``True`` (default) inject the fake data with :meth:`.inject_fake_data` before
  271. creating the dataset.
  272. patch_checks (Optional[bool]): If ``True`` disable integrity check logic while creating the dataset. If
  273. omitted defaults to the same value as ``inject_fake_data``.
  274. **kwargs (Any): Additional parameters passed to the dataset. These parameters take precedence in case they
  275. overlap with ``config``.
  276. Yields:
  277. dataset (torchvision.dataset.VisionDataset): Dataset.
  278. info (Dict[str, Any]): Additional information about the injected fake data. See :meth:`.inject_fake_data`
  279. for details.
  280. """
  281. if patch_checks is None:
  282. patch_checks = inject_fake_data
  283. special_kwargs, other_kwargs = self._split_kwargs(kwargs)
  284. complete_config = self._KWARG_DEFAULTS.copy()
  285. if self.DEFAULT_CONFIG:
  286. complete_config.update(self.DEFAULT_CONFIG)
  287. if config:
  288. complete_config.update(config)
  289. if other_kwargs:
  290. complete_config.update(other_kwargs)
  291. if "download" in self._HAS_SPECIAL_KWARG and special_kwargs.get("download", False):
  292. # override download param to False param if its default is truthy
  293. special_kwargs["download"] = False
  294. patchers = self._patch_download_extract()
  295. if patch_checks:
  296. patchers.update(self._patch_checks())
  297. with get_tmp_dir() as tmpdir:
  298. args = self.dataset_args(tmpdir, complete_config)
  299. info = self._inject_fake_data(tmpdir, complete_config) if inject_fake_data else None
  300. with self._maybe_apply_patches(patchers), disable_console_output():
  301. dataset = self.DATASET_CLASS(*args, **complete_config, **special_kwargs)
  302. yield dataset, info
  303. @classmethod
  304. def setUpClass(cls):
  305. cls._verify_required_public_class_attributes()
  306. cls._populate_private_class_attributes()
  307. cls._process_optional_public_class_attributes()
  308. super().setUpClass()
  309. @classmethod
  310. def _verify_required_public_class_attributes(cls):
  311. if cls.DATASET_CLASS is None:
  312. raise UsageError(
  313. "The class attribute 'DATASET_CLASS' needs to be overwritten. "
  314. "It should contain the class of the dataset to be tested."
  315. )
  316. if cls.FEATURE_TYPES is None:
  317. raise UsageError(
  318. "The class attribute 'FEATURE_TYPES' needs to be overwritten. "
  319. "It should contain a sequence of types that the dataset returns when accessed by index."
  320. )
  321. @classmethod
  322. def _populate_private_class_attributes(cls):
  323. defaults = []
  324. for cls_ in cls.DATASET_CLASS.__mro__:
  325. if cls_ is torchvision.datasets.VisionDataset:
  326. break
  327. argspec = inspect.getfullargspec(cls_.__init__)
  328. if not argspec.defaults:
  329. continue
  330. defaults.append(
  331. {
  332. kwarg: default
  333. for kwarg, default in zip(argspec.args[-len(argspec.defaults) :], argspec.defaults)
  334. if not kwarg.startswith("_")
  335. }
  336. )
  337. if not argspec.varkw:
  338. break
  339. kwarg_defaults = dict()
  340. for config in reversed(defaults):
  341. kwarg_defaults.update(config)
  342. has_special_kwargs = set()
  343. for name in cls._SPECIAL_KWARGS:
  344. if name not in kwarg_defaults:
  345. continue
  346. del kwarg_defaults[name]
  347. has_special_kwargs.add(name)
  348. cls._KWARG_DEFAULTS = kwarg_defaults
  349. cls._HAS_SPECIAL_KWARG = has_special_kwargs
  350. @classmethod
  351. def _process_optional_public_class_attributes(cls):
  352. def check_config(config, name):
  353. special_kwargs = tuple(f"'{name}'" for name in cls._SPECIAL_KWARGS if name in config)
  354. if special_kwargs:
  355. raise UsageError(
  356. f"{name} contains a value for the parameter(s) {', '.join(special_kwargs)}. "
  357. f"These are handled separately by the test case and should not be set here. "
  358. f"If you need to test some custom behavior regarding these parameters, "
  359. f"you need to write a custom test (*not* test case), e.g. test_custom_transform()."
  360. )
  361. if cls.DEFAULT_CONFIG is not None:
  362. check_config(cls.DEFAULT_CONFIG, "DEFAULT_CONFIG")
  363. if cls.ADDITIONAL_CONFIGS is not None:
  364. for idx, config in enumerate(cls.ADDITIONAL_CONFIGS):
  365. check_config(config, f"CONFIGS[{idx}]")
  366. if cls.REQUIRED_PACKAGES:
  367. missing_pkgs = []
  368. for pkg in cls.REQUIRED_PACKAGES:
  369. try:
  370. importlib.import_module(pkg)
  371. except ImportError:
  372. missing_pkgs.append(f"'{pkg}'")
  373. if missing_pkgs:
  374. raise unittest.SkipTest(
  375. f"The package(s) {', '.join(missing_pkgs)} are required to load the dataset "
  376. f"'{cls.DATASET_CLASS.__name__}', but are not installed."
  377. )
  378. def _split_kwargs(self, kwargs):
  379. special_kwargs = kwargs.copy()
  380. other_kwargs = {key: special_kwargs.pop(key) for key in set(special_kwargs.keys()) - self._SPECIAL_KWARGS}
  381. return special_kwargs, other_kwargs
  382. def _inject_fake_data(self, tmpdir, config):
  383. info = self.inject_fake_data(tmpdir, config)
  384. if info is None:
  385. raise UsageError(
  386. "The method 'inject_fake_data' needs to return at least an integer indicating the number of "
  387. "examples for the current configuration."
  388. )
  389. elif isinstance(info, int):
  390. info = dict(num_examples=info)
  391. elif not isinstance(info, dict):
  392. raise UsageError(
  393. f"The additional information returned by the method 'inject_fake_data' must be either an "
  394. f"integer indicating the number of examples for the current configuration or a dictionary with "
  395. f"the same content. Got {type(info)} instead."
  396. )
  397. elif "num_examples" not in info:
  398. raise UsageError(
  399. "The information dictionary returned by the method 'inject_fake_data' must contain a "
  400. "'num_examples' field that holds the number of examples for the current configuration."
  401. )
  402. return info
  403. def _patch_download_extract(self):
  404. module = inspect.getmodule(self.DATASET_CLASS).__name__
  405. return {unittest.mock.patch(f"{module}.{function}") for function in self._DOWNLOAD_EXTRACT_FUNCTIONS}
  406. def _patch_checks(self):
  407. module = inspect.getmodule(self.DATASET_CLASS).__name__
  408. return {unittest.mock.patch(f"{module}.{function}", return_value=True) for function in self._CHECK_FUNCTIONS}
  409. @contextlib.contextmanager
  410. def _maybe_apply_patches(self, patchers):
  411. with contextlib.ExitStack() as stack:
  412. mocks = {}
  413. for patcher in patchers:
  414. with contextlib.suppress(AttributeError):
  415. mocks[patcher.target] = stack.enter_context(patcher)
  416. yield mocks
  417. def test_not_found_or_corrupted(self):
  418. with pytest.raises((FileNotFoundError, RuntimeError)):
  419. with self.create_dataset(inject_fake_data=False):
  420. pass
  421. def test_smoke(self):
  422. with self.create_dataset() as (dataset, _):
  423. assert isinstance(dataset, torchvision.datasets.VisionDataset)
  424. @test_all_configs
  425. def test_str_smoke(self, config):
  426. with self.create_dataset(config) as (dataset, _):
  427. assert isinstance(str(dataset), str)
  428. @test_all_configs
  429. def test_feature_types(self, config):
  430. with self.create_dataset(config) as (dataset, _):
  431. example = dataset[0]
  432. if len(self.FEATURE_TYPES) > 1:
  433. actual = len(example)
  434. expected = len(self.FEATURE_TYPES)
  435. assert (
  436. actual == expected
  437. ), "The number of the returned features does not match the the number of elements in FEATURE_TYPES: "
  438. f"{actual} != {expected}"
  439. else:
  440. example = (example,)
  441. for idx, (feature, expected_feature_type) in enumerate(zip(example, self.FEATURE_TYPES)):
  442. with self.subTest(idx=idx):
  443. assert isinstance(feature, expected_feature_type)
  444. @test_all_configs
  445. def test_num_examples(self, config):
  446. with self.create_dataset(config) as (dataset, info):
  447. assert len(list(dataset)) == len(dataset) == info["num_examples"]
  448. @test_all_configs
  449. def test_transforms(self, config):
  450. mock = unittest.mock.Mock(wraps=lambda *args: args[0] if len(args) == 1 else args)
  451. for kwarg in self._TRANSFORM_KWARGS:
  452. if kwarg not in self._HAS_SPECIAL_KWARG:
  453. continue
  454. mock.reset_mock()
  455. with self.subTest(kwarg=kwarg):
  456. with self.create_dataset(config, **{kwarg: mock}) as (dataset, _):
  457. dataset[0]
  458. mock.assert_called()
  459. @test_all_configs
  460. def test_transforms_v2_wrapper(self, config):
  461. try:
  462. with self.create_dataset(config) as (dataset, info):
  463. for target_keys in [None, "all"]:
  464. if target_keys is not None and self.DATASET_CLASS not in {
  465. torchvision.datasets.CocoDetection,
  466. torchvision.datasets.VOCDetection,
  467. torchvision.datasets.Kitti,
  468. torchvision.datasets.WIDERFace,
  469. }:
  470. with self.assertRaisesRegex(ValueError, "`target_keys` is currently only supported for"):
  471. wrap_dataset_for_transforms_v2(dataset, target_keys=target_keys)
  472. continue
  473. wrapped_dataset = wrap_dataset_for_transforms_v2(dataset, target_keys=target_keys)
  474. assert isinstance(wrapped_dataset, self.DATASET_CLASS)
  475. assert len(wrapped_dataset) == info["num_examples"]
  476. wrapped_sample = wrapped_dataset[0]
  477. assert tree_any(
  478. lambda item: isinstance(item, (tv_tensors.TVTensor, PIL.Image.Image)), wrapped_sample
  479. )
  480. except TypeError as error:
  481. msg = f"No wrapper exists for dataset class {type(dataset).__name__}"
  482. if str(error).startswith(msg):
  483. pytest.skip(msg)
  484. raise error
  485. except RuntimeError as error:
  486. if "currently not supported by this wrapper" in str(error):
  487. pytest.skip("Config is currently not supported by this wrapper")
  488. raise error
  489. class ImageDatasetTestCase(DatasetTestCase):
  490. """Abstract base class for image dataset testcases.
  491. - Overwrites the FEATURE_TYPES class attribute to expect a :class:`PIL.Image.Image` and an integer label.
  492. """
  493. FEATURE_TYPES = (PIL.Image.Image, int)
  494. SUPPORT_TV_IMAGE_DECODE: bool = False
  495. @contextlib.contextmanager
  496. def create_dataset(
  497. self,
  498. config: Optional[Dict[str, Any]] = None,
  499. inject_fake_data: bool = True,
  500. patch_checks: Optional[bool] = None,
  501. **kwargs: Any,
  502. ) -> Iterator[Tuple[torchvision.datasets.VisionDataset, Dict[str, Any]]]:
  503. with super().create_dataset(
  504. config=config,
  505. inject_fake_data=inject_fake_data,
  506. patch_checks=patch_checks,
  507. **kwargs,
  508. ) as (dataset, info):
  509. # PIL.Image.open() only loads the image metadata upfront and keeps the file open until the first access
  510. # to the pixel data occurs. Trying to delete such a file results in an PermissionError on Windows. Thus, we
  511. # force-load opened images.
  512. # This problem only occurs during testing since some tests, e.g. DatasetTestCase.test_feature_types open an
  513. # image, but never use the underlying data. During normal operation it is reasonable to assume that the
  514. # user wants to work with the image he just opened rather than deleting the underlying file.
  515. with self._force_load_images(loader=(config or {}).get("loader", None)):
  516. yield dataset, info
  517. @contextlib.contextmanager
  518. def _force_load_images(self, loader: Optional[Callable[[str], Any]] = None):
  519. open = loader or PIL.Image.open
  520. def new(fp, *args, **kwargs):
  521. image = open(fp, *args, **kwargs)
  522. if isinstance(fp, (str, pathlib.Path)) and isinstance(image, PIL.Image.Image):
  523. image.load()
  524. return image
  525. with unittest.mock.patch(open.__module__ + "." + open.__qualname__, new=new):
  526. yield
  527. def test_tv_decode_image_support(self):
  528. if not self.SUPPORT_TV_IMAGE_DECODE:
  529. pytest.skip(f"{self.DATASET_CLASS.__name__} does not support torchvision.io.decode_image.")
  530. with self.create_dataset(
  531. config=dict(
  532. loader=torchvision.io.decode_image,
  533. )
  534. ) as (dataset, _):
  535. image = dataset[0][0]
  536. assert isinstance(image, torch.Tensor)
  537. class VideoDatasetTestCase(DatasetTestCase):
  538. """Abstract base class for video dataset testcases.
  539. - Overwrites the 'FEATURE_TYPES' class attribute to expect two :class:`torch.Tensor` s for the video and audio as
  540. well as an integer label.
  541. - Overwrites the 'REQUIRED_PACKAGES' class attribute to require PyAV (``av``).
  542. - Adds the 'DEFAULT_FRAMES_PER_CLIP' class attribute. If no 'frames_per_clip' is provided by 'inject_fake_data()'
  543. and it is the last parameter without a default value in the dataset constructor, the value of the
  544. 'DEFAULT_FRAMES_PER_CLIP' class attribute is appended to the output.
  545. """
  546. FEATURE_TYPES = (torch.Tensor, torch.Tensor, int)
  547. REQUIRED_PACKAGES = ("av",)
  548. FRAMES_PER_CLIP = 1
  549. def __init__(self, *args, **kwargs):
  550. super().__init__(*args, **kwargs)
  551. self.dataset_args = self._set_default_frames_per_clip(self.dataset_args)
  552. def _set_default_frames_per_clip(self, dataset_args):
  553. argspec = inspect.getfullargspec(self.DATASET_CLASS.__init__)
  554. args_without_default = argspec.args[1 : (-len(argspec.defaults) if argspec.defaults else None)]
  555. frames_per_clip_last = args_without_default[-1] == "frames_per_clip"
  556. @functools.wraps(dataset_args)
  557. def wrapper(tmpdir, config):
  558. args = dataset_args(tmpdir, config)
  559. if frames_per_clip_last and len(args) == len(args_without_default) - 1:
  560. args = (*args, self.FRAMES_PER_CLIP)
  561. return args
  562. return wrapper
  563. def test_output_format(self):
  564. for output_format in ["TCHW", "THWC"]:
  565. with self.create_dataset(output_format=output_format) as (dataset, _):
  566. for video, *_ in dataset:
  567. if output_format == "TCHW":
  568. num_frames, num_channels, *_ = video.shape
  569. else: # output_format == "THWC":
  570. num_frames, *_, num_channels = video.shape
  571. assert num_frames == self.FRAMES_PER_CLIP
  572. assert num_channels == 3
  573. @test_all_configs
  574. def test_transforms_v2_wrapper(self, config):
  575. # `output_format == "THWC"` is not supported by the wrapper. Thus, we skip the `config` if it is set explicitly
  576. # or use the supported `"TCHW"`
  577. if config.setdefault("output_format", "TCHW") == "THWC":
  578. return
  579. super().test_transforms_v2_wrapper.__wrapped__(self, config)
  580. def _no_collate(batch):
  581. return batch
  582. def check_transforms_v2_wrapper_spawn(dataset, expected_size):
  583. # This check ensures that the wrapped datasets can be used with multiprocessing_context="spawn" in the DataLoader.
  584. # We also check that transforms are applied correctly as a non-regression test for
  585. # https://github.com/pytorch/vision/issues/8066
  586. # Implicitly, this also checks that the wrapped datasets are pickleable.
  587. # To save CI/test time, we only check on Windows where "spawn" is the default
  588. if platform.system() != "Windows":
  589. pytest.skip("Multiprocessing spawning is only checked on macOS.")
  590. wrapped_dataset = wrap_dataset_for_transforms_v2(dataset)
  591. dataloader = DataLoader(wrapped_dataset, num_workers=2, multiprocessing_context="spawn", collate_fn=_no_collate)
  592. def resize_was_applied(item):
  593. # Checking the size of the output ensures that the Resize transform was correctly applied
  594. return isinstance(item, (tv_tensors.Image, tv_tensors.Video, PIL.Image.Image)) and get_size(item) == list(
  595. expected_size
  596. )
  597. for wrapped_sample in dataloader:
  598. assert tree_any(resize_was_applied, wrapped_sample)
  599. def create_image_or_video_tensor(size: Sequence[int]) -> torch.Tensor:
  600. r"""Create a random uint8 tensor.
  601. Args:
  602. size (Sequence[int]): Size of the tensor.
  603. """
  604. return torch.randint(0, 256, size, dtype=torch.uint8)
  605. def create_image_file(
  606. root: Union[pathlib.Path, str], name: Union[pathlib.Path, str], size: Union[Sequence[int], int] = 10, **kwargs: Any
  607. ) -> pathlib.Path:
  608. """Create an image file from random data.
  609. Args:
  610. root (Union[str, pathlib.Path]): Root directory the image file will be placed in.
  611. name (Union[str, pathlib.Path]): Name of the image file.
  612. size (Union[Sequence[int], int]): Size of the image that represents the ``(num_channels, height, width)``. If
  613. scalar, the value is used for the height and width. If not provided, three channels are assumed.
  614. kwargs (Any): Additional parameters passed to :meth:`PIL.Image.Image.save`.
  615. Returns:
  616. pathlib.Path: Path to the created image file.
  617. """
  618. if isinstance(size, int):
  619. size = (size, size)
  620. if len(size) == 2:
  621. size = (3, *size)
  622. if len(size) != 3:
  623. raise UsageError(
  624. f"The 'size' argument should either be an int or a sequence of length 2 or 3. Got {len(size)} instead"
  625. )
  626. image = create_image_or_video_tensor(size)
  627. file = pathlib.Path(root) / name
  628. # torch (num_channels x height x width) -> PIL (width x height x num_channels)
  629. image = image.permute(2, 1, 0)
  630. # For grayscale images PIL doesn't use a channel dimension
  631. if image.shape[2] == 1:
  632. image = torch.squeeze(image, 2)
  633. PIL.Image.fromarray(image.numpy()).save(file, **kwargs)
  634. return file
  635. def create_image_folder(
  636. root: Union[pathlib.Path, str],
  637. name: Union[pathlib.Path, str],
  638. file_name_fn: Callable[[int], str],
  639. num_examples: int,
  640. size: Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]] = None,
  641. **kwargs: Any,
  642. ) -> List[pathlib.Path]:
  643. """Create a folder of random images.
  644. Args:
  645. root (Union[str, pathlib.Path]): Root directory the image folder will be placed in.
  646. name (Union[str, pathlib.Path]): Name of the image folder.
  647. file_name_fn (Callable[[int], str]): Should return a file name if called with the file index.
  648. num_examples (int): Number of images to create.
  649. size (Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]]): Size of the images. If
  650. callable, will be called with the index of the corresponding file. If omitted, a random height and width
  651. between 3 and 10 pixels is selected on a per-image basis.
  652. kwargs (Any): Additional parameters passed to :func:`create_image_file`.
  653. Returns:
  654. List[pathlib.Path]: Paths to all created image files.
  655. .. seealso::
  656. - :func:`create_image_file`
  657. """
  658. if size is None:
  659. def size(idx: int) -> Tuple[int, int, int]:
  660. num_channels = 3
  661. height, width = torch.randint(3, 11, size=(2,), dtype=torch.int).tolist()
  662. return (num_channels, height, width)
  663. root = pathlib.Path(root) / name
  664. os.makedirs(root, exist_ok=True)
  665. return [
  666. create_image_file(root, file_name_fn(idx), size=size(idx) if callable(size) else size, **kwargs)
  667. for idx in range(num_examples)
  668. ]
  669. def shape_test_for_stereo(
  670. left: PIL.Image.Image,
  671. right: PIL.Image.Image,
  672. disparity: Optional[np.ndarray] = None,
  673. valid_mask: Optional[np.ndarray] = None,
  674. ):
  675. left_dims = get_dimensions(left)
  676. right_dims = get_dimensions(right)
  677. c, h, w = left_dims
  678. # check that left and right are the same size
  679. assert left_dims == right_dims
  680. assert c == 3
  681. # check that the disparity has the same spatial dimensions
  682. # as the input
  683. if disparity is not None:
  684. assert disparity.ndim == 3
  685. assert disparity.shape == (1, h, w)
  686. if valid_mask is not None:
  687. # check that valid mask is the same size as the disparity
  688. _, dh, dw = disparity.shape
  689. mh, mw = valid_mask.shape
  690. assert dh == mh
  691. assert dw == mw
  692. @requires_lazy_imports("av")
  693. def create_video_file(
  694. root: Union[pathlib.Path, str],
  695. name: Union[pathlib.Path, str],
  696. size: Union[Sequence[int], int] = (1, 3, 10, 10),
  697. fps: float = 25,
  698. **kwargs: Any,
  699. ) -> pathlib.Path:
  700. """Create a video file from random data.
  701. Args:
  702. root (Union[str, pathlib.Path]): Root directory the video file will be placed in.
  703. name (Union[str, pathlib.Path]): Name of the video file.
  704. size (Union[Sequence[int], int]): Size of the video that represents the
  705. ``(num_frames, num_channels, height, width)``. If scalar, the value is used for the height and width.
  706. If not provided, ``num_frames=1`` and ``num_channels=3`` are assumed.
  707. fps (float): Frame rate in frames per second.
  708. kwargs (Any): Additional parameters passed to :func:`torchvision.io.write_video`.
  709. Returns:
  710. pathlib.Path: Path to the created image file.
  711. Raises:
  712. UsageError: If PyAV is not available.
  713. """
  714. if isinstance(size, int):
  715. size = (size, size)
  716. if len(size) == 2:
  717. size = (3, *size)
  718. if len(size) == 3:
  719. size = (1, *size)
  720. if len(size) != 4:
  721. raise UsageError(
  722. f"The 'size' argument should either be an int or a sequence of length 2, 3, or 4. Got {len(size)} instead"
  723. )
  724. video = create_image_or_video_tensor(size)
  725. file = pathlib.Path(root) / name
  726. torchvision.io.write_video(str(file), video.permute(0, 2, 3, 1), fps, **kwargs)
  727. return file
  728. @requires_lazy_imports("av")
  729. def create_video_folder(
  730. root: Union[str, pathlib.Path],
  731. name: Union[str, pathlib.Path],
  732. file_name_fn: Callable[[int], str],
  733. num_examples: int,
  734. size: Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]] = None,
  735. fps=25,
  736. **kwargs,
  737. ) -> List[pathlib.Path]:
  738. """Create a folder of random videos.
  739. Args:
  740. root (Union[str, pathlib.Path]): Root directory the video folder will be placed in.
  741. name (Union[str, pathlib.Path]): Name of the video folder.
  742. file_name_fn (Callable[[int], str]): Should return a file name if called with the file index.
  743. num_examples (int): Number of videos to create.
  744. size (Optional[Union[Sequence[int], int, Callable[[int], Union[Sequence[int], int]]]]): Size of the videos. If
  745. callable, will be called with the index of the corresponding file. If omitted, a random even height and
  746. width between 4 and 10 pixels is selected on a per-video basis.
  747. fps (float): Frame rate in frames per second.
  748. kwargs (Any): Additional parameters passed to :func:`create_video_file`.
  749. Returns:
  750. List[pathlib.Path]: Paths to all created video files.
  751. Raises:
  752. UsageError: If PyAV is not available.
  753. .. seealso::
  754. - :func:`create_video_file`
  755. """
  756. if size is None:
  757. def size(idx):
  758. num_frames = 1
  759. num_channels = 3
  760. # The 'libx264' video codec, which is the default of torchvision.io.write_video, requires the height and
  761. # width of the video to be divisible by 2.
  762. height, width = (torch.randint(2, 6, size=(2,), dtype=torch.int) * 2).tolist()
  763. return (num_frames, num_channels, height, width)
  764. root = pathlib.Path(root) / name
  765. os.makedirs(root, exist_ok=True)
  766. return [
  767. create_video_file(root, file_name_fn(idx), size=size(idx) if callable(size) else size, **kwargs)
  768. for idx in range(num_examples)
  769. ]
  770. def _split_files_or_dirs(root, *files_or_dirs):
  771. files = set()
  772. dirs = set()
  773. for file_or_dir in files_or_dirs:
  774. path = pathlib.Path(file_or_dir)
  775. if not path.is_absolute():
  776. path = root / path
  777. if path.is_file():
  778. files.add(path)
  779. else:
  780. dirs.add(path)
  781. for sub_file_or_dir in path.glob("**/*"):
  782. if sub_file_or_dir.is_file():
  783. files.add(sub_file_or_dir)
  784. else:
  785. dirs.add(sub_file_or_dir)
  786. if root in dirs:
  787. dirs.remove(root)
  788. return files, dirs
  789. def _make_archive(root, name, *files_or_dirs, opener, adder, remove=True):
  790. archive = pathlib.Path(root) / name
  791. if not files_or_dirs:
  792. # We need to invoke `Path.with_suffix("")`, since call only applies to the last suffix if multiple suffixes are
  793. # present. For example, `pathlib.Path("foo.tar.gz").with_suffix("")` results in `foo.tar`.
  794. file_or_dir = archive
  795. for _ in range(len(archive.suffixes)):
  796. file_or_dir = file_or_dir.with_suffix("")
  797. if file_or_dir.exists():
  798. files_or_dirs = (file_or_dir,)
  799. else:
  800. raise ValueError("No file or dir provided.")
  801. files, dirs = _split_files_or_dirs(root, *files_or_dirs)
  802. with opener(archive) as fh:
  803. for file in sorted(files):
  804. adder(fh, file, file.relative_to(root))
  805. if remove:
  806. for file in files:
  807. os.remove(file)
  808. for dir in dirs:
  809. shutil.rmtree(dir, ignore_errors=True)
  810. return archive
  811. def make_tar(root, name, *files_or_dirs, remove=True, compression=None):
  812. # TODO: detect compression from name
  813. return _make_archive(
  814. root,
  815. name,
  816. *files_or_dirs,
  817. opener=lambda archive: tarfile.open(archive, f"w:{compression}" if compression else "w"),
  818. adder=lambda fh, file, relative_file: fh.add(file, arcname=relative_file),
  819. remove=remove,
  820. )
  821. def make_zip(root, name, *files_or_dirs, remove=True):
  822. return _make_archive(
  823. root,
  824. name,
  825. *files_or_dirs,
  826. opener=lambda archive: zipfile.ZipFile(archive, "w"),
  827. adder=lambda fh, file, relative_file: fh.write(file, arcname=relative_file),
  828. remove=remove,
  829. )
  830. def create_random_string(length: int, *digits: str) -> str:
  831. """Create a random string.
  832. Args:
  833. length (int): Number of characters in the generated string.
  834. *digits (str): Characters to sample from. If omitted defaults to :attr:`string.ascii_lowercase`.
  835. """
  836. if not digits:
  837. digits = string.ascii_lowercase
  838. else:
  839. digits = "".join(itertools.chain(*digits))
  840. return "".join(random.choice(digits) for _ in range(length))
  841. def make_fake_pfm_file(h, w, file_name):
  842. values = list(range(3 * h * w))
  843. # Note: we pack everything in little endian: -1.0, and "<"
  844. content = f"PF \n{w} {h} \n-1.0\n".encode() + struct.pack("<" + "f" * len(values), *values)
  845. with open(file_name, "wb") as f:
  846. f.write(content)
  847. def make_fake_flo_file(h, w, file_name):
  848. """Creates a fake flow file in .flo format."""
  849. # Everything needs to be in little Endian according to
  850. # https://vision.middlebury.edu/flow/code/flow-code/README.txt
  851. values = list(range(2 * h * w))
  852. content = (
  853. struct.pack("<4c", *(c.encode() for c in "PIEH"))
  854. + struct.pack("<i", w)
  855. + struct.pack("<i", h)
  856. + struct.pack("<" + "f" * len(values), *values)
  857. )
  858. with open(file_name, "wb") as f:
  859. f.write(content)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...