We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
DatasetFolder incorrectly specifies required folder structure
## 📚 Documentation

<!-- A clear and concise description of what content in https://pytorch.org/docs is an issue. If this has to do with the general https://pytorch.org website, please file an issue at https://github.com/pytorch/pytorch.github.io/issues/new/choose instead. If this has to do with https://pytorch.org/tutorials, please file an issue at https://github.com/pytorch/tutorials/issues/new -->

The documentation for [DatasetFolder](https://pytorch.org/docs/stable/torchvision/datasets.html#datasetfolder) specifies the following required folder organization:

```
root/class_x/xxx.ext
root/class_x/xxy.ext
root/class_x/xxz.ext

root/class_y/123.ext
root/class_y/nsdf3.ext
root/class_y/asd932_.ext
```

However, the [source code for DatasetFolder](https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#DatasetFolder) shows that `make_dataset()` uses `os.walk()` to discover the files in each class' folder. This means that any file within the class folder **or its subfolders** that passes `is_valid_file()` will be included. To me, this behavior was unexpected.

A more complete specification of the format could be:

```
root/class_x/xxx.ext
root/class_x/xxy.ext
root/class_x/[...]/xxz.ext

root/class_y/123.ext
root/class_y/nsdf3.ext
root/class_y/[...]/asd932_.ext
```

cc @pmeier
DatasetFolder incorrectly specifies required folder structure
## 📚 Documentation

<!-- A clear and concise description of what content in https://pytorch.org/docs is an issue. If this has to do with the general https://pytorch.org website, please file an issue at https://github.com/pytorch/pytorch.github.io/issues/new/choose instead. If this has to do with https://pytorch.org/tutorials, please file an issue at https://github.com/pytorch/tutorials/issues/new -->

The documentation for [DatasetFolder](https://pytorch.org/docs/stable/torchvision/datasets.html#datasetfolder) specifies the following required folder organization:

```
root/class_x/xxx.ext
root/class_x/xxy.ext
root/class_x/xxz.ext

root/class_y/123.ext
root/class_y/nsdf3.ext
root/class_y/asd932_.ext
```

However, the [source code for DatasetFolder](https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#DatasetFolder) shows that `make_dataset()` uses `os.walk()` to discover the files in each class' folder. This means that any file within the class folder **or its subfolders** that passes `is_valid_file()` will be included. To me, this behavior was unexpected.

A more complete specification of the format could be:

```
root/class_x/xxx.ext
root/class_x/xxy.ext
root/class_x/[...]/xxz.ext

root/class_y/123.ext
root/class_y/nsdf3.ext
root/class_y/[...]/asd932_.ext
```

cc @pmeier

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `torchvision/datasets/folder.py`
Content:
```
1 from .vision import VisionDataset
2 
3 from PIL import Image
4 
5 import os
6 import os.path
7 from typing import Any, Callable, cast, Dict, List, Optional, Tuple
8 
9 
10 def has_file_allowed_extension(filename: str, extensions: Tuple[str, ...]) -> bool:
11     """Checks if a file is an allowed extension.
12 
13     Args:
14         filename (string): path to a file
15         extensions (tuple of strings): extensions to consider (lowercase)
16 
17     Returns:
18         bool: True if the filename ends with one of given extensions
19     """
20     return filename.lower().endswith(extensions)
21 
22 
23 def is_image_file(filename: str) -> bool:
24     """Checks if a file is an allowed image extension.
25 
26     Args:
27         filename (string): path to a file
28 
29     Returns:
30         bool: True if the filename ends with a known image extension
31     """
32     return has_file_allowed_extension(filename, IMG_EXTENSIONS)
33 
34 
35 def make_dataset(
36     directory: str,
37     class_to_idx: Dict[str, int],
38     extensions: Optional[Tuple[str, ...]] = None,
39     is_valid_file: Optional[Callable[[str], bool]] = None,
40 ) -> List[Tuple[str, int]]:
41     """Generates a list of samples of a form (path_to_sample, class).
42 
43     Args:
44         directory (str): root dataset directory
45         class_to_idx (Dict[str, int]): dictionary mapping class name to class index
46         extensions (optional): A list of allowed extensions.
47             Either extensions or is_valid_file should be passed. Defaults to None.
48         is_valid_file (optional): A function that takes path of a file
49             and checks if the file is a valid file
50             (used to check of corrupt files) both extensions and
51             is_valid_file should not be passed. Defaults to None.
52 
53     Raises:
54         ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
55 
56     Returns:
57         List[Tuple[str, int]]: samples of a form (path_to_sample, class)
58     """
59     instances = []
60     directory = os.path.expanduser(directory)
61     both_none = extensions is None and is_valid_file is None
62     both_something = extensions is not None and is_valid_file is not None
63     if both_none or both_something:
64         raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
65     if extensions is not None:
66         def is_valid_file(x: str) -> bool:
67             return has_file_allowed_extension(x, cast(Tuple[str, ...], extensions))
68     is_valid_file = cast(Callable[[str], bool], is_valid_file)
69     for target_class in sorted(class_to_idx.keys()):
70         class_index = class_to_idx[target_class]
71         target_dir = os.path.join(directory, target_class)
72         if not os.path.isdir(target_dir):
73             continue
74         for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
75             for fname in sorted(fnames):
76                 path = os.path.join(root, fname)
77                 if is_valid_file(path):
78                     item = path, class_index
79                     instances.append(item)
80     return instances
81 
82 
83 class DatasetFolder(VisionDataset):
84     """A generic data loader where the samples are arranged in this way: ::
85 
86         root/class_x/xxx.ext
87         root/class_x/xxy.ext
88         root/class_x/xxz.ext
89 
90         root/class_y/123.ext
91         root/class_y/nsdf3.ext
92         root/class_y/asd932_.ext
93 
94     Args:
95         root (string): Root directory path.
96         loader (callable): A function to load a sample given its path.
97         extensions (tuple[string]): A list of allowed extensions.
98             both extensions and is_valid_file should not be passed.
99         transform (callable, optional): A function/transform that takes in
100             a sample and returns a transformed version.
101             E.g, ``transforms.RandomCrop`` for images.
102         target_transform (callable, optional): A function/transform that takes
103             in the target and transforms it.
104         is_valid_file (callable, optional): A function that takes path of a file
105             and check if the file is a valid file (used to check of corrupt files)
106             both extensions and is_valid_file should not be passed.
107 
108      Attributes:
109         classes (list): List of the class names sorted alphabetically.
110         class_to_idx (dict): Dict with items (class_name, class_index).
111         samples (list): List of (sample path, class_index) tuples
112         targets (list): The class_index value for each image in the dataset
113     """
114 
115     def __init__(
116             self,
117             root: str,
118             loader: Callable[[str], Any],
119             extensions: Optional[Tuple[str, ...]] = None,
120             transform: Optional[Callable] = None,
121             target_transform: Optional[Callable] = None,
122             is_valid_file: Optional[Callable[[str], bool]] = None,
123     ) -> None:
124         super(DatasetFolder, self).__init__(root, transform=transform,
125                                             target_transform=target_transform)
126         classes, class_to_idx = self._find_classes(self.root)
127         samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)
128         if len(samples) == 0:
129             msg = "Found 0 files in subfolders of: {}\n".format(self.root)
130             if extensions is not None:
131                 msg += "Supported extensions are: {}".format(",".join(extensions))
132             raise RuntimeError(msg)
133 
134         self.loader = loader
135         self.extensions = extensions
136 
137         self.classes = classes
138         self.class_to_idx = class_to_idx
139         self.samples = samples
140         self.targets = [s[1] for s in samples]
141 
142     def _find_classes(self, dir: str) -> Tuple[List[str], Dict[str, int]]:
143         """
144         Finds the class folders in a dataset.
145 
146         Args:
147             dir (string): Root directory path.
148 
149         Returns:
150             tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
151 
152         Ensures:
153             No class is a subdirectory of another.
154         """
155         classes = [d.name for d in os.scandir(dir) if d.is_dir()]
156         classes.sort()
157         class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
158         return classes, class_to_idx
159 
160     def __getitem__(self, index: int) -> Tuple[Any, Any]:
161         """
162         Args:
163             index (int): Index
164 
165         Returns:
166             tuple: (sample, target) where target is class_index of the target class.
167         """
168         path, target = self.samples[index]
169         sample = self.loader(path)
170         if self.transform is not None:
171             sample = self.transform(sample)
172         if self.target_transform is not None:
173             target = self.target_transform(target)
174 
175         return sample, target
176 
177     def __len__(self) -> int:
178         return len(self.samples)
179 
180 
181 IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
182 
183 
184 def pil_loader(path: str) -> Image.Image:
185     # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
186     with open(path, 'rb') as f:
187         img = Image.open(f)
188         return img.convert('RGB')
189 
190 
191 # TODO: specify the return type
192 def accimage_loader(path: str) -> Any:
193     import accimage
194     try:
195         return accimage.Image(path)
196     except IOError:
197         # Potentially a decoding problem, fall back to PIL.Image
198         return pil_loader(path)
199 
200 
201 def default_loader(path: str) -> Any:
202     from torchvision import get_image_backend
203     if get_image_backend() == 'accimage':
204         return accimage_loader(path)
205     else:
206         return pil_loader(path)
207 
208 
209 class ImageFolder(DatasetFolder):
210     """A generic data loader where the images are arranged in this way: ::
211 
212         root/dog/xxx.png
213         root/dog/xxy.png
214         root/dog/xxz.png
215 
216         root/cat/123.png
217         root/cat/nsdf3.png
218         root/cat/asd932_.png
219 
220     Args:
221         root (string): Root directory path.
222         transform (callable, optional): A function/transform that  takes in an PIL image
223             and returns a transformed version. E.g, ``transforms.RandomCrop``
224         target_transform (callable, optional): A function/transform that takes in the
225             target and transforms it.
226         loader (callable, optional): A function to load an image given its path.
227         is_valid_file (callable, optional): A function that takes path of an Image file
228             and check if the file is a valid file (used to check of corrupt files)
229 
230      Attributes:
231         classes (list): List of the class names sorted alphabetically.
232         class_to_idx (dict): Dict with items (class_name, class_index).
233         imgs (list): List of (image path, class_index) tuples
234     """
235 
236     def __init__(
237             self,
238             root: str,
239             transform: Optional[Callable] = None,
240             target_transform: Optional[Callable] = None,
241             loader: Callable[[str], Any] = default_loader,
242             is_valid_file: Optional[Callable[[str], bool]] = None,
243     ):
244         super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,
245                                           transform=transform,
246                                           target_transform=target_transform,
247                                           is_valid_file=is_valid_file)
248         self.imgs = self.samples
249
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py
--- a/torchvision/datasets/folder.py
+++ b/torchvision/datasets/folder.py
@@ -85,11 +85,11 @@
 
         root/class_x/xxx.ext
         root/class_x/xxy.ext
-        root/class_x/xxz.ext
+        root/class_x/[...]/xxz.ext
 
         root/class_y/123.ext
         root/class_y/nsdf3.ext
-        root/class_y/asd932_.ext
+        root/class_y/[...]/asd932_.ext
 
     Args:
         root (string): Root directory path.
@@ -211,11 +211,11 @@
 
         root/dog/xxx.png
         root/dog/xxy.png
-        root/dog/xxz.png
+        root/dog/[...]/xxz.png
 
         root/cat/123.png
         root/cat/nsdf3.png
-        root/cat/asd932_.png
+        root/cat/[...]/asd932_.png
 
     Args:
         root (string): Root directory path.

{"golden_diff": "diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py\n--- a/torchvision/datasets/folder.py\n+++ b/torchvision/datasets/folder.py\n@@ -85,11 +85,11 @@\n \n         root/class_x/xxx.ext\n         root/class_x/xxy.ext\n-        root/class_x/xxz.ext\n+        root/class_x/[...]/xxz.ext\n \n         root/class_y/123.ext\n         root/class_y/nsdf3.ext\n-        root/class_y/asd932_.ext\n+        root/class_y/[...]/asd932_.ext\n \n     Args:\n         root (string): Root directory path.\n@@ -211,11 +211,11 @@\n \n         root/dog/xxx.png\n         root/dog/xxy.png\n-        root/dog/xxz.png\n+        root/dog/[...]/xxz.png\n \n         root/cat/123.png\n         root/cat/nsdf3.png\n-        root/cat/asd932_.png\n+        root/cat/[...]/asd932_.png\n \n     Args:\n         root (string): Root directory path.\n", "issue": "DatasetFolder incorrectly specifies required folder structure\n## \ud83d\udcda Documentation\r\n\r\n<!-- A clear and concise description of what content in https://pytorch.org/docs is an issue. If this has to do with the general https://pytorch.org website, please file an issue at https://github.com/pytorch/pytorch.github.io/issues/new/choose instead. If this has to do with https://pytorch.org/tutorials, please file an issue at https://github.com/pytorch/tutorials/issues/new -->\r\n\r\nThe documentation for [DatasetFolder](https://pytorch.org/docs/stable/torchvision/datasets.html#datasetfolder) specifies the following required folder organization:\r\n\r\n```\r\nroot/class_x/xxx.ext\r\nroot/class_x/xxy.ext\r\nroot/class_x/xxz.ext\r\n\r\nroot/class_y/123.ext\r\nroot/class_y/nsdf3.ext\r\nroot/class_y/asd932_.ext\r\n```\r\n\r\nHowever, the [source code for DatasetFolder](https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#DatasetFolder) shows that `make_dataset()` uses `os.walk()` to discover the files in each class' folder. This means that any file within the class folder **or its subfolders** that passes `is_valid_file()` will be included. To me, this behavior was unexpected.\r\n\r\nA more complete specification of the format could be:\r\n\r\n```\r\nroot/class_x/xxx.ext\r\nroot/class_x/xxy.ext\r\nroot/class_x/[...]/xxz.ext\r\n\r\nroot/class_y/123.ext\r\nroot/class_y/nsdf3.ext\r\nroot/class_y/[...]/asd932_.ext\r\n```\n\ncc @pmeier\nDatasetFolder incorrectly specifies required folder structure\n## \ud83d\udcda Documentation\r\n\r\n<!-- A clear and concise description of what content in https://pytorch.org/docs is an issue. If this has to do with the general https://pytorch.org website, please file an issue at https://github.com/pytorch/pytorch.github.io/issues/new/choose instead. If this has to do with https://pytorch.org/tutorials, please file an issue at https://github.com/pytorch/tutorials/issues/new -->\r\n\r\nThe documentation for [DatasetFolder](https://pytorch.org/docs/stable/torchvision/datasets.html#datasetfolder) specifies the following required folder organization:\r\n\r\n```\r\nroot/class_x/xxx.ext\r\nroot/class_x/xxy.ext\r\nroot/class_x/xxz.ext\r\n\r\nroot/class_y/123.ext\r\nroot/class_y/nsdf3.ext\r\nroot/class_y/asd932_.ext\r\n```\r\n\r\nHowever, the [source code for DatasetFolder](https://pytorch.org/docs/stable/_modules/torchvision/datasets/folder.html#DatasetFolder) shows that `make_dataset()` uses `os.walk()` to discover the files in each class' folder. This means that any file within the class folder **or its subfolders** that passes `is_valid_file()` will be included. To me, this behavior was unexpected.\r\n\r\nA more complete specification of the format could be:\r\n\r\n```\r\nroot/class_x/xxx.ext\r\nroot/class_x/xxy.ext\r\nroot/class_x/[...]/xxz.ext\r\n\r\nroot/class_y/123.ext\r\nroot/class_y/nsdf3.ext\r\nroot/class_y/[...]/asd932_.ext\r\n```\n\ncc @pmeier\n", "before_files": [{"content": "from .vision import VisionDataset\n\nfrom PIL import Image\n\nimport os\nimport os.path\nfrom typing import Any, Callable, cast, Dict, List, Optional, Tuple\n\n\ndef has_file_allowed_extension(filename: str, extensions: Tuple[str, ...]) -> bool:\n    \"\"\"Checks if a file is an allowed extension.\n\n    Args:\n        filename (string): path to a file\n        extensions (tuple of strings): extensions to consider (lowercase)\n\n    Returns:\n        bool: True if the filename ends with one of given extensions\n    \"\"\"\n    return filename.lower().endswith(extensions)\n\n\ndef is_image_file(filename: str) -> bool:\n    \"\"\"Checks if a file is an allowed image extension.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    return has_file_allowed_extension(filename, IMG_EXTENSIONS)\n\n\ndef make_dataset(\n    directory: str,\n    class_to_idx: Dict[str, int],\n    extensions: Optional[Tuple[str, ...]] = None,\n    is_valid_file: Optional[Callable[[str], bool]] = None,\n) -> List[Tuple[str, int]]:\n    \"\"\"Generates a list of samples of a form (path_to_sample, class).\n\n    Args:\n        directory (str): root dataset directory\n        class_to_idx (Dict[str, int]): dictionary mapping class name to class index\n        extensions (optional): A list of allowed extensions.\n            Either extensions or is_valid_file should be passed. Defaults to None.\n        is_valid_file (optional): A function that takes path of a file\n            and checks if the file is a valid file\n            (used to check of corrupt files) both extensions and\n            is_valid_file should not be passed. Defaults to None.\n\n    Raises:\n        ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.\n\n    Returns:\n        List[Tuple[str, int]]: samples of a form (path_to_sample, class)\n    \"\"\"\n    instances = []\n    directory = os.path.expanduser(directory)\n    both_none = extensions is None and is_valid_file is None\n    both_something = extensions is not None and is_valid_file is not None\n    if both_none or both_something:\n        raise ValueError(\"Both extensions and is_valid_file cannot be None or not None at the same time\")\n    if extensions is not None:\n        def is_valid_file(x: str) -> bool:\n            return has_file_allowed_extension(x, cast(Tuple[str, ...], extensions))\n    is_valid_file = cast(Callable[[str], bool], is_valid_file)\n    for target_class in sorted(class_to_idx.keys()):\n        class_index = class_to_idx[target_class]\n        target_dir = os.path.join(directory, target_class)\n        if not os.path.isdir(target_dir):\n            continue\n        for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):\n            for fname in sorted(fnames):\n                path = os.path.join(root, fname)\n                if is_valid_file(path):\n                    item = path, class_index\n                    instances.append(item)\n    return instances\n\n\nclass DatasetFolder(VisionDataset):\n    \"\"\"A generic data loader where the samples are arranged in this way: ::\n\n        root/class_x/xxx.ext\n        root/class_x/xxy.ext\n        root/class_x/xxz.ext\n\n        root/class_y/123.ext\n        root/class_y/nsdf3.ext\n        root/class_y/asd932_.ext\n\n    Args:\n        root (string): Root directory path.\n        loader (callable): A function to load a sample given its path.\n        extensions (tuple[string]): A list of allowed extensions.\n            both extensions and is_valid_file should not be passed.\n        transform (callable, optional): A function/transform that takes in\n            a sample and returns a transformed version.\n            E.g, ``transforms.RandomCrop`` for images.\n        target_transform (callable, optional): A function/transform that takes\n            in the target and transforms it.\n        is_valid_file (callable, optional): A function that takes path of a file\n            and check if the file is a valid file (used to check of corrupt files)\n            both extensions and is_valid_file should not be passed.\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        samples (list): List of (sample path, class_index) tuples\n        targets (list): The class_index value for each image in the dataset\n    \"\"\"\n\n    def __init__(\n            self,\n            root: str,\n            loader: Callable[[str], Any],\n            extensions: Optional[Tuple[str, ...]] = None,\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            is_valid_file: Optional[Callable[[str], bool]] = None,\n    ) -> None:\n        super(DatasetFolder, self).__init__(root, transform=transform,\n                                            target_transform=target_transform)\n        classes, class_to_idx = self._find_classes(self.root)\n        samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n        if len(samples) == 0:\n            msg = \"Found 0 files in subfolders of: {}\\n\".format(self.root)\n            if extensions is not None:\n                msg += \"Supported extensions are: {}\".format(\",\".join(extensions))\n            raise RuntimeError(msg)\n\n        self.loader = loader\n        self.extensions = extensions\n\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.samples = samples\n        self.targets = [s[1] for s in samples]\n\n    def _find_classes(self, dir: str) -> Tuple[List[str], Dict[str, int]]:\n        \"\"\"\n        Finds the class folders in a dataset.\n\n        Args:\n            dir (string): Root directory path.\n\n        Returns:\n            tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.\n\n        Ensures:\n            No class is a subdirectory of another.\n        \"\"\"\n        classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n        classes.sort()\n        class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n        return classes, class_to_idx\n\n    def __getitem__(self, index: int) -> Tuple[Any, Any]:\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (sample, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.samples[index]\n        sample = self.loader(path)\n        if self.transform is not None:\n            sample = self.transform(sample)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return sample, target\n\n    def __len__(self) -> int:\n        return len(self.samples)\n\n\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')\n\n\ndef pil_loader(path: str) -> Image.Image:\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        img = Image.open(f)\n        return img.convert('RGB')\n\n\n# TODO: specify the return type\ndef accimage_loader(path: str) -> Any:\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path: str) -> Any:\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(DatasetFolder):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n        is_valid_file (callable, optional): A function that takes path of an Image file\n            and check if the file is a valid file (used to check of corrupt files)\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(\n            self,\n            root: str,\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            loader: Callable[[str], Any] = default_loader,\n            is_valid_file: Optional[Callable[[str], bool]] = None,\n    ):\n        super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,\n                                          transform=transform,\n                                          target_transform=target_transform,\n                                          is_valid_file=is_valid_file)\n        self.imgs = self.samples\n", "path": "torchvision/datasets/folder.py"}], "after_files": [{"content": "from .vision import VisionDataset\n\nfrom PIL import Image\n\nimport os\nimport os.path\nfrom typing import Any, Callable, cast, Dict, List, Optional, Tuple\n\n\ndef has_file_allowed_extension(filename: str, extensions: Tuple[str, ...]) -> bool:\n    \"\"\"Checks if a file is an allowed extension.\n\n    Args:\n        filename (string): path to a file\n        extensions (tuple of strings): extensions to consider (lowercase)\n\n    Returns:\n        bool: True if the filename ends with one of given extensions\n    \"\"\"\n    return filename.lower().endswith(extensions)\n\n\ndef is_image_file(filename: str) -> bool:\n    \"\"\"Checks if a file is an allowed image extension.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    return has_file_allowed_extension(filename, IMG_EXTENSIONS)\n\n\ndef make_dataset(\n    directory: str,\n    class_to_idx: Dict[str, int],\n    extensions: Optional[Tuple[str, ...]] = None,\n    is_valid_file: Optional[Callable[[str], bool]] = None,\n) -> List[Tuple[str, int]]:\n    \"\"\"Generates a list of samples of a form (path_to_sample, class).\n\n    Args:\n        directory (str): root dataset directory\n        class_to_idx (Dict[str, int]): dictionary mapping class name to class index\n        extensions (optional): A list of allowed extensions.\n            Either extensions or is_valid_file should be passed. Defaults to None.\n        is_valid_file (optional): A function that takes path of a file\n            and checks if the file is a valid file\n            (used to check of corrupt files) both extensions and\n            is_valid_file should not be passed. Defaults to None.\n\n    Raises:\n        ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.\n\n    Returns:\n        List[Tuple[str, int]]: samples of a form (path_to_sample, class)\n    \"\"\"\n    instances = []\n    directory = os.path.expanduser(directory)\n    both_none = extensions is None and is_valid_file is None\n    both_something = extensions is not None and is_valid_file is not None\n    if both_none or both_something:\n        raise ValueError(\"Both extensions and is_valid_file cannot be None or not None at the same time\")\n    if extensions is not None:\n        def is_valid_file(x: str) -> bool:\n            return has_file_allowed_extension(x, cast(Tuple[str, ...], extensions))\n    is_valid_file = cast(Callable[[str], bool], is_valid_file)\n    for target_class in sorted(class_to_idx.keys()):\n        class_index = class_to_idx[target_class]\n        target_dir = os.path.join(directory, target_class)\n        if not os.path.isdir(target_dir):\n            continue\n        for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):\n            for fname in sorted(fnames):\n                path = os.path.join(root, fname)\n                if is_valid_file(path):\n                    item = path, class_index\n                    instances.append(item)\n    return instances\n\n\nclass DatasetFolder(VisionDataset):\n    \"\"\"A generic data loader where the samples are arranged in this way: ::\n\n        root/class_x/xxx.ext\n        root/class_x/xxy.ext\n        root/class_x/[...]/xxz.ext\n\n        root/class_y/123.ext\n        root/class_y/nsdf3.ext\n        root/class_y/[...]/asd932_.ext\n\n    Args:\n        root (string): Root directory path.\n        loader (callable): A function to load a sample given its path.\n        extensions (tuple[string]): A list of allowed extensions.\n            both extensions and is_valid_file should not be passed.\n        transform (callable, optional): A function/transform that takes in\n            a sample and returns a transformed version.\n            E.g, ``transforms.RandomCrop`` for images.\n        target_transform (callable, optional): A function/transform that takes\n            in the target and transforms it.\n        is_valid_file (callable, optional): A function that takes path of a file\n            and check if the file is a valid file (used to check of corrupt files)\n            both extensions and is_valid_file should not be passed.\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        samples (list): List of (sample path, class_index) tuples\n        targets (list): The class_index value for each image in the dataset\n    \"\"\"\n\n    def __init__(\n            self,\n            root: str,\n            loader: Callable[[str], Any],\n            extensions: Optional[Tuple[str, ...]] = None,\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            is_valid_file: Optional[Callable[[str], bool]] = None,\n    ) -> None:\n        super(DatasetFolder, self).__init__(root, transform=transform,\n                                            target_transform=target_transform)\n        classes, class_to_idx = self._find_classes(self.root)\n        samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n        if len(samples) == 0:\n            msg = \"Found 0 files in subfolders of: {}\\n\".format(self.root)\n            if extensions is not None:\n                msg += \"Supported extensions are: {}\".format(\",\".join(extensions))\n            raise RuntimeError(msg)\n\n        self.loader = loader\n        self.extensions = extensions\n\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.samples = samples\n        self.targets = [s[1] for s in samples]\n\n    def _find_classes(self, dir: str) -> Tuple[List[str], Dict[str, int]]:\n        \"\"\"\n        Finds the class folders in a dataset.\n\n        Args:\n            dir (string): Root directory path.\n\n        Returns:\n            tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.\n\n        Ensures:\n            No class is a subdirectory of another.\n        \"\"\"\n        classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n        classes.sort()\n        class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n        return classes, class_to_idx\n\n    def __getitem__(self, index: int) -> Tuple[Any, Any]:\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (sample, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.samples[index]\n        sample = self.loader(path)\n        if self.transform is not None:\n            sample = self.transform(sample)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return sample, target\n\n    def __len__(self) -> int:\n        return len(self.samples)\n\n\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')\n\n\ndef pil_loader(path: str) -> Image.Image:\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        img = Image.open(f)\n        return img.convert('RGB')\n\n\n# TODO: specify the return type\ndef accimage_loader(path: str) -> Any:\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path: str) -> Any:\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(DatasetFolder):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/[...]/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/[...]/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n        is_valid_file (callable, optional): A function that takes path of an Image file\n            and check if the file is a valid file (used to check of corrupt files)\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(\n            self,\n            root: str,\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            loader: Callable[[str], Any] = default_loader,\n            is_valid_file: Optional[Callable[[str], bool]] = None,\n    ):\n        super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,\n                                          transform=transform,\n                                          target_transform=target_transform,\n                                          is_valid_file=is_valid_file)\n        self.imgs = self.samples\n", "path": "torchvision/datasets/folder.py"}]}