We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Avoid pandas dependency for CelebA dataset
The CelebA dataset has a runtime dependency on `pandas`. Since all we need is `pandas.read_csv`, it would be interesting to see if we can replace `pandas.read_csv` by just the builtin `csv` module. The mergability of the PR would depend on how ugly / complex the code becomes... :)

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/celeba.py`
Content:
```
1 from functools import partial
2 import torch
3 import os
4 import PIL
5 from typing import Any, Callable, List, Optional, Union, Tuple
6 from .vision import VisionDataset
7 from .utils import download_file_from_google_drive, check_integrity, verify_str_arg
8 
9 
10 class CelebA(VisionDataset):
11     """`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.
12 
13     Args:
14         root (string): Root directory where images are downloaded to.
15         split (string): One of {'train', 'valid', 'test', 'all'}.
16             Accordingly dataset is selected.
17         target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``,
18             or ``landmarks``. Can also be a list to output a tuple with all specified target types.
19             The targets represent:
20 
21                 - ``attr`` (np.array shape=(40,) dtype=int): binary (0, 1) labels for attributes
22                 - ``identity`` (int): label for each person (data points with the same identity are the same person)
23                 - ``bbox`` (np.array shape=(4,) dtype=int): bounding box (x, y, width, height)
24                 - ``landmarks`` (np.array shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x,
25                   righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y)
26 
27             Defaults to ``attr``. If empty, ``None`` will be returned as target.
28 
29         transform (callable, optional): A function/transform that  takes in an PIL image
30             and returns a transformed version. E.g, ``transforms.ToTensor``
31         target_transform (callable, optional): A function/transform that takes in the
32             target and transforms it.
33         download (bool, optional): If true, downloads the dataset from the internet and
34             puts it in root directory. If dataset is already downloaded, it is not
35             downloaded again.
36     """
37 
38     base_folder = "celeba"
39     # There currently does not appear to be a easy way to extract 7z in python (without introducing additional
40     # dependencies). The "in-the-wild" (not aligned+cropped) images are only in 7z, so they are not available
41     # right now.
42     file_list = [
43         # File ID                                      MD5 Hash                            Filename
44         ("0B7EVK8r0v71pZjFTYXZWM3FlRnM", "00d2c5bc6d35e252742224ab0c1e8fcb", "img_align_celeba.zip"),
45         # ("0B7EVK8r0v71pbWNEUjJKdDQ3dGc","b6cd7e93bc7a96c2dc33f819aa3ac651", "img_align_celeba_png.7z"),
46         # ("0B7EVK8r0v71peklHb0pGdDl6R28", "b6cd7e93bc7a96c2dc33f819aa3ac651", "img_celeba.7z"),
47         ("0B7EVK8r0v71pblRyaVFSWGxPY0U", "75e246fa4810816ffd6ee81facbd244c", "list_attr_celeba.txt"),
48         ("1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS", "32bd1bd63d3c78cd57e08160ec5ed1e2", "identity_CelebA.txt"),
49         ("0B7EVK8r0v71pbThiMVRxWXZ4dU0", "00566efa6fedff7a56946cd1c10f1c16", "list_bbox_celeba.txt"),
50         ("0B7EVK8r0v71pd0FJY3Blby1HUTQ", "cc24ecafdb5b50baae59b03474781f8c", "list_landmarks_align_celeba.txt"),
51         # ("0B7EVK8r0v71pTzJIdlJWdHczRlU", "063ee6ddb681f96bc9ca28c6febb9d1a", "list_landmarks_celeba.txt"),
52         ("0B7EVK8r0v71pY0NSMzRuSXJEVkk", "d32c9cbf5e040fd4025c592c306e6668", "list_eval_partition.txt"),
53     ]
54 
55     def __init__(
56             self,
57             root: str,
58             split: str = "train",
59             target_type: Union[List[str], str] = "attr",
60             transform: Optional[Callable] = None,
61             target_transform: Optional[Callable] = None,
62             download: bool = False,
63     ) -> None:
64         import pandas
65         super(CelebA, self).__init__(root, transform=transform,
66                                      target_transform=target_transform)
67         self.split = split
68         if isinstance(target_type, list):
69             self.target_type = target_type
70         else:
71             self.target_type = [target_type]
72 
73         if not self.target_type and self.target_transform is not None:
74             raise RuntimeError('target_transform is specified but target_type is empty')
75 
76         if download:
77             self.download()
78 
79         if not self._check_integrity():
80             raise RuntimeError('Dataset not found or corrupted.' +
81                                ' You can use download=True to download it')
82 
83         split_map = {
84             "train": 0,
85             "valid": 1,
86             "test": 2,
87             "all": None,
88         }
89         split_ = split_map[verify_str_arg(split.lower(), "split",
90                                           ("train", "valid", "test", "all"))]
91 
92         fn = partial(os.path.join, self.root, self.base_folder)
93         splits = pandas.read_csv(fn("list_eval_partition.txt"), delim_whitespace=True, header=None, index_col=0)
94         identity = pandas.read_csv(fn("identity_CelebA.txt"), delim_whitespace=True, header=None, index_col=0)
95         bbox = pandas.read_csv(fn("list_bbox_celeba.txt"), delim_whitespace=True, header=1, index_col=0)
96         landmarks_align = pandas.read_csv(fn("list_landmarks_align_celeba.txt"), delim_whitespace=True, header=1)
97         attr = pandas.read_csv(fn("list_attr_celeba.txt"), delim_whitespace=True, header=1)
98 
99         mask = slice(None) if split_ is None else (splits[1] == split_)
100 
101         self.filename = splits[mask].index.values
102         self.identity = torch.as_tensor(identity[mask].values)
103         self.bbox = torch.as_tensor(bbox[mask].values)
104         self.landmarks_align = torch.as_tensor(landmarks_align[mask].values)
105         self.attr = torch.as_tensor(attr[mask].values)
106         self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}
107         self.attr_names = list(attr.columns)
108 
109     def _check_integrity(self) -> bool:
110         for (_, md5, filename) in self.file_list:
111             fpath = os.path.join(self.root, self.base_folder, filename)
112             _, ext = os.path.splitext(filename)
113             # Allow original archive to be deleted (zip and 7z)
114             # Only need the extracted images
115             if ext not in [".zip", ".7z"] and not check_integrity(fpath, md5):
116                 return False
117 
118         # Should check a hash of the images
119         return os.path.isdir(os.path.join(self.root, self.base_folder, "img_align_celeba"))
120 
121     def download(self) -> None:
122         import zipfile
123 
124         if self._check_integrity():
125             print('Files already downloaded and verified')
126             return
127 
128         for (file_id, md5, filename) in self.file_list:
129             download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5)
130 
131         with zipfile.ZipFile(os.path.join(self.root, self.base_folder, "img_align_celeba.zip"), "r") as f:
132             f.extractall(os.path.join(self.root, self.base_folder))
133 
134     def __getitem__(self, index: int) -> Tuple[Any, Any]:
135         X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index]))
136 
137         target: Any = []
138         for t in self.target_type:
139             if t == "attr":
140                 target.append(self.attr[index, :])
141             elif t == "identity":
142                 target.append(self.identity[index, 0])
143             elif t == "bbox":
144                 target.append(self.bbox[index, :])
145             elif t == "landmarks":
146                 target.append(self.landmarks_align[index, :])
147             else:
148                 # TODO: refactor with utils.verify_str_arg
149                 raise ValueError("Target type \"{}\" is not recognized.".format(t))
150 
151         if self.transform is not None:
152             X = self.transform(X)
153 
154         if target:
155             target = tuple(target) if len(target) > 1 else target[0]
156 
157             if self.target_transform is not None:
158                 target = self.target_transform(target)
159         else:
160             target = None
161 
162         return X, target
163 
164     def __len__(self) -> int:
165         return len(self.attr)
166 
167     def extra_repr(self) -> str:
168         lines = ["Target type: {target_type}", "Split: {split}"]
169         return '\n'.join(lines).format(**self.__dict__)
170
```
--- 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/celeba.py b/torchvision/datasets/celeba.py
--- a/torchvision/datasets/celeba.py
+++ b/torchvision/datasets/celeba.py
@@ -1,3 +1,5 @@
+from collections import namedtuple
+import csv
 from functools import partial
 import torch
 import os
@@ -6,6 +8,8 @@
 from .vision import VisionDataset
 from .utils import download_file_from_google_drive, check_integrity, verify_str_arg
 
+CSV = namedtuple("CSV", ["header", "index", "data"])
+
 
 class CelebA(VisionDataset):
     """`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.
@@ -61,7 +65,6 @@
             target_transform: Optional[Callable] = None,
             download: bool = False,
     ) -> None:
-        import pandas
         super(CelebA, self).__init__(root, transform=transform,
                                      target_transform=target_transform)
         self.split = split
@@ -88,23 +91,42 @@
         }
         split_ = split_map[verify_str_arg(split.lower(), "split",
                                           ("train", "valid", "test", "all"))]
+        splits = self._load_csv("list_eval_partition.txt")
+        identity = self._load_csv("identity_CelebA.txt")
+        bbox = self._load_csv("list_bbox_celeba.txt", header=1)
+        landmarks_align = self._load_csv("list_landmarks_align_celeba.txt", header=1)
+        attr = self._load_csv("list_attr_celeba.txt", header=1)
+
+        mask = slice(None) if split_ is None else (splits.data == split_).squeeze()
+
+        self.filename = splits.index
+        self.identity = identity.data[mask]
+        self.bbox = bbox.data[mask]
+        self.landmarks_align = landmarks_align.data[mask]
+        self.attr = attr.data[mask]
+        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}
+        self.attr_names = attr.header
+
+    def _load_csv(
+        self,
+        filename: str,
+        header: Optional[int] = None,
+    ) -> CSV:
+        data, indices, headers = [], [], []
 
         fn = partial(os.path.join, self.root, self.base_folder)
-        splits = pandas.read_csv(fn("list_eval_partition.txt"), delim_whitespace=True, header=None, index_col=0)
-        identity = pandas.read_csv(fn("identity_CelebA.txt"), delim_whitespace=True, header=None, index_col=0)
-        bbox = pandas.read_csv(fn("list_bbox_celeba.txt"), delim_whitespace=True, header=1, index_col=0)
-        landmarks_align = pandas.read_csv(fn("list_landmarks_align_celeba.txt"), delim_whitespace=True, header=1)
-        attr = pandas.read_csv(fn("list_attr_celeba.txt"), delim_whitespace=True, header=1)
-
-        mask = slice(None) if split_ is None else (splits[1] == split_)
-
-        self.filename = splits[mask].index.values
-        self.identity = torch.as_tensor(identity[mask].values)
-        self.bbox = torch.as_tensor(bbox[mask].values)
-        self.landmarks_align = torch.as_tensor(landmarks_align[mask].values)
-        self.attr = torch.as_tensor(attr[mask].values)
-        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}
-        self.attr_names = list(attr.columns)
+        with open(fn(filename)) as csv_file:
+            data = list(csv.reader(csv_file, delimiter=' ', skipinitialspace=True))
+
+        if header is not None:
+            headers = data[header]
+            data = data[header + 1:]
+
+        indices = [row[0] for row in data]
+        data = [row[1:] for row in data]
+        data_int = [list(map(int, i)) for i in data]
+
+        return CSV(headers, indices, torch.tensor(data_int))
 
     def _check_integrity(self) -> bool:
         for (_, md5, filename) in self.file_list:

{"golden_diff": "diff --git a/torchvision/datasets/celeba.py b/torchvision/datasets/celeba.py\n--- a/torchvision/datasets/celeba.py\n+++ b/torchvision/datasets/celeba.py\n@@ -1,3 +1,5 @@\n+from collections import namedtuple\n+import csv\n from functools import partial\n import torch\n import os\n@@ -6,6 +8,8 @@\n from .vision import VisionDataset\n from .utils import download_file_from_google_drive, check_integrity, verify_str_arg\n \n+CSV = namedtuple(\"CSV\", [\"header\", \"index\", \"data\"])\n+\n \n class CelebA(VisionDataset):\n     \"\"\"`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.\n@@ -61,7 +65,6 @@\n             target_transform: Optional[Callable] = None,\n             download: bool = False,\n     ) -> None:\n-        import pandas\n         super(CelebA, self).__init__(root, transform=transform,\n                                      target_transform=target_transform)\n         self.split = split\n@@ -88,23 +91,42 @@\n         }\n         split_ = split_map[verify_str_arg(split.lower(), \"split\",\n                                           (\"train\", \"valid\", \"test\", \"all\"))]\n+        splits = self._load_csv(\"list_eval_partition.txt\")\n+        identity = self._load_csv(\"identity_CelebA.txt\")\n+        bbox = self._load_csv(\"list_bbox_celeba.txt\", header=1)\n+        landmarks_align = self._load_csv(\"list_landmarks_align_celeba.txt\", header=1)\n+        attr = self._load_csv(\"list_attr_celeba.txt\", header=1)\n+\n+        mask = slice(None) if split_ is None else (splits.data == split_).squeeze()\n+\n+        self.filename = splits.index\n+        self.identity = identity.data[mask]\n+        self.bbox = bbox.data[mask]\n+        self.landmarks_align = landmarks_align.data[mask]\n+        self.attr = attr.data[mask]\n+        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}\n+        self.attr_names = attr.header\n+\n+    def _load_csv(\n+        self,\n+        filename: str,\n+        header: Optional[int] = None,\n+    ) -> CSV:\n+        data, indices, headers = [], [], []\n \n         fn = partial(os.path.join, self.root, self.base_folder)\n-        splits = pandas.read_csv(fn(\"list_eval_partition.txt\"), delim_whitespace=True, header=None, index_col=0)\n-        identity = pandas.read_csv(fn(\"identity_CelebA.txt\"), delim_whitespace=True, header=None, index_col=0)\n-        bbox = pandas.read_csv(fn(\"list_bbox_celeba.txt\"), delim_whitespace=True, header=1, index_col=0)\n-        landmarks_align = pandas.read_csv(fn(\"list_landmarks_align_celeba.txt\"), delim_whitespace=True, header=1)\n-        attr = pandas.read_csv(fn(\"list_attr_celeba.txt\"), delim_whitespace=True, header=1)\n-\n-        mask = slice(None) if split_ is None else (splits[1] == split_)\n-\n-        self.filename = splits[mask].index.values\n-        self.identity = torch.as_tensor(identity[mask].values)\n-        self.bbox = torch.as_tensor(bbox[mask].values)\n-        self.landmarks_align = torch.as_tensor(landmarks_align[mask].values)\n-        self.attr = torch.as_tensor(attr[mask].values)\n-        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}\n-        self.attr_names = list(attr.columns)\n+        with open(fn(filename)) as csv_file:\n+            data = list(csv.reader(csv_file, delimiter=' ', skipinitialspace=True))\n+\n+        if header is not None:\n+            headers = data[header]\n+            data = data[header + 1:]\n+\n+        indices = [row[0] for row in data]\n+        data = [row[1:] for row in data]\n+        data_int = [list(map(int, i)) for i in data]\n+\n+        return CSV(headers, indices, torch.tensor(data_int))\n \n     def _check_integrity(self) -> bool:\n         for (_, md5, filename) in self.file_list:\n", "issue": "Avoid pandas dependency for CelebA dataset\nThe CelebA dataset has a runtime dependency on `pandas`. Since all we need is `pandas.read_csv`, it would be interesting to see if we can replace `pandas.read_csv` by just the builtin `csv` module. The mergability of the PR would depend on how ugly / complex the code becomes... :)\n\ncc @pmeier\n", "before_files": [{"content": "from functools import partial\nimport torch\nimport os\nimport PIL\nfrom typing import Any, Callable, List, Optional, Union, Tuple\nfrom .vision import VisionDataset\nfrom .utils import download_file_from_google_drive, check_integrity, verify_str_arg\n\n\nclass CelebA(VisionDataset):\n    \"\"\"`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.\n\n    Args:\n        root (string): Root directory where images are downloaded to.\n        split (string): One of {'train', 'valid', 'test', 'all'}.\n            Accordingly dataset is selected.\n        target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``,\n            or ``landmarks``. Can also be a list to output a tuple with all specified target types.\n            The targets represent:\n\n                - ``attr`` (np.array shape=(40,) dtype=int): binary (0, 1) labels for attributes\n                - ``identity`` (int): label for each person (data points with the same identity are the same person)\n                - ``bbox`` (np.array shape=(4,) dtype=int): bounding box (x, y, width, height)\n                - ``landmarks`` (np.array shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x,\n                  righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y)\n\n            Defaults to ``attr``. If empty, ``None`` will be returned as target.\n\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.ToTensor``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        download (bool, optional): If true, downloads the dataset from the internet and\n            puts it in root directory. If dataset is already downloaded, it is not\n            downloaded again.\n    \"\"\"\n\n    base_folder = \"celeba\"\n    # There currently does not appear to be a easy way to extract 7z in python (without introducing additional\n    # dependencies). The \"in-the-wild\" (not aligned+cropped) images are only in 7z, so they are not available\n    # right now.\n    file_list = [\n        # File ID                                      MD5 Hash                            Filename\n        (\"0B7EVK8r0v71pZjFTYXZWM3FlRnM\", \"00d2c5bc6d35e252742224ab0c1e8fcb\", \"img_align_celeba.zip\"),\n        # (\"0B7EVK8r0v71pbWNEUjJKdDQ3dGc\",\"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_align_celeba_png.7z\"),\n        # (\"0B7EVK8r0v71peklHb0pGdDl6R28\", \"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_celeba.7z\"),\n        (\"0B7EVK8r0v71pblRyaVFSWGxPY0U\", \"75e246fa4810816ffd6ee81facbd244c\", \"list_attr_celeba.txt\"),\n        (\"1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS\", \"32bd1bd63d3c78cd57e08160ec5ed1e2\", \"identity_CelebA.txt\"),\n        (\"0B7EVK8r0v71pbThiMVRxWXZ4dU0\", \"00566efa6fedff7a56946cd1c10f1c16\", \"list_bbox_celeba.txt\"),\n        (\"0B7EVK8r0v71pd0FJY3Blby1HUTQ\", \"cc24ecafdb5b50baae59b03474781f8c\", \"list_landmarks_align_celeba.txt\"),\n        # (\"0B7EVK8r0v71pTzJIdlJWdHczRlU\", \"063ee6ddb681f96bc9ca28c6febb9d1a\", \"list_landmarks_celeba.txt\"),\n        (\"0B7EVK8r0v71pY0NSMzRuSXJEVkk\", \"d32c9cbf5e040fd4025c592c306e6668\", \"list_eval_partition.txt\"),\n    ]\n\n    def __init__(\n            self,\n            root: str,\n            split: str = \"train\",\n            target_type: Union[List[str], str] = \"attr\",\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            download: bool = False,\n    ) -> None:\n        import pandas\n        super(CelebA, self).__init__(root, transform=transform,\n                                     target_transform=target_transform)\n        self.split = split\n        if isinstance(target_type, list):\n            self.target_type = target_type\n        else:\n            self.target_type = [target_type]\n\n        if not self.target_type and self.target_transform is not None:\n            raise RuntimeError('target_transform is specified but target_type is empty')\n\n        if download:\n            self.download()\n\n        if not self._check_integrity():\n            raise RuntimeError('Dataset not found or corrupted.' +\n                               ' You can use download=True to download it')\n\n        split_map = {\n            \"train\": 0,\n            \"valid\": 1,\n            \"test\": 2,\n            \"all\": None,\n        }\n        split_ = split_map[verify_str_arg(split.lower(), \"split\",\n                                          (\"train\", \"valid\", \"test\", \"all\"))]\n\n        fn = partial(os.path.join, self.root, self.base_folder)\n        splits = pandas.read_csv(fn(\"list_eval_partition.txt\"), delim_whitespace=True, header=None, index_col=0)\n        identity = pandas.read_csv(fn(\"identity_CelebA.txt\"), delim_whitespace=True, header=None, index_col=0)\n        bbox = pandas.read_csv(fn(\"list_bbox_celeba.txt\"), delim_whitespace=True, header=1, index_col=0)\n        landmarks_align = pandas.read_csv(fn(\"list_landmarks_align_celeba.txt\"), delim_whitespace=True, header=1)\n        attr = pandas.read_csv(fn(\"list_attr_celeba.txt\"), delim_whitespace=True, header=1)\n\n        mask = slice(None) if split_ is None else (splits[1] == split_)\n\n        self.filename = splits[mask].index.values\n        self.identity = torch.as_tensor(identity[mask].values)\n        self.bbox = torch.as_tensor(bbox[mask].values)\n        self.landmarks_align = torch.as_tensor(landmarks_align[mask].values)\n        self.attr = torch.as_tensor(attr[mask].values)\n        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}\n        self.attr_names = list(attr.columns)\n\n    def _check_integrity(self) -> bool:\n        for (_, md5, filename) in self.file_list:\n            fpath = os.path.join(self.root, self.base_folder, filename)\n            _, ext = os.path.splitext(filename)\n            # Allow original archive to be deleted (zip and 7z)\n            # Only need the extracted images\n            if ext not in [\".zip\", \".7z\"] and not check_integrity(fpath, md5):\n                return False\n\n        # Should check a hash of the images\n        return os.path.isdir(os.path.join(self.root, self.base_folder, \"img_align_celeba\"))\n\n    def download(self) -> None:\n        import zipfile\n\n        if self._check_integrity():\n            print('Files already downloaded and verified')\n            return\n\n        for (file_id, md5, filename) in self.file_list:\n            download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5)\n\n        with zipfile.ZipFile(os.path.join(self.root, self.base_folder, \"img_align_celeba.zip\"), \"r\") as f:\n            f.extractall(os.path.join(self.root, self.base_folder))\n\n    def __getitem__(self, index: int) -> Tuple[Any, Any]:\n        X = PIL.Image.open(os.path.join(self.root, self.base_folder, \"img_align_celeba\", self.filename[index]))\n\n        target: Any = []\n        for t in self.target_type:\n            if t == \"attr\":\n                target.append(self.attr[index, :])\n            elif t == \"identity\":\n                target.append(self.identity[index, 0])\n            elif t == \"bbox\":\n                target.append(self.bbox[index, :])\n            elif t == \"landmarks\":\n                target.append(self.landmarks_align[index, :])\n            else:\n                # TODO: refactor with utils.verify_str_arg\n                raise ValueError(\"Target type \\\"{}\\\" is not recognized.\".format(t))\n\n        if self.transform is not None:\n            X = self.transform(X)\n\n        if target:\n            target = tuple(target) if len(target) > 1 else target[0]\n\n            if self.target_transform is not None:\n                target = self.target_transform(target)\n        else:\n            target = None\n\n        return X, target\n\n    def __len__(self) -> int:\n        return len(self.attr)\n\n    def extra_repr(self) -> str:\n        lines = [\"Target type: {target_type}\", \"Split: {split}\"]\n        return '\\n'.join(lines).format(**self.__dict__)\n", "path": "torchvision/datasets/celeba.py"}], "after_files": [{"content": "from collections import namedtuple\nimport csv\nfrom functools import partial\nimport torch\nimport os\nimport PIL\nfrom typing import Any, Callable, List, Optional, Union, Tuple\nfrom .vision import VisionDataset\nfrom .utils import download_file_from_google_drive, check_integrity, verify_str_arg\n\nCSV = namedtuple(\"CSV\", [\"header\", \"index\", \"data\"])\n\n\nclass CelebA(VisionDataset):\n    \"\"\"`Large-scale CelebFaces Attributes (CelebA) Dataset <http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html>`_ Dataset.\n\n    Args:\n        root (string): Root directory where images are downloaded to.\n        split (string): One of {'train', 'valid', 'test', 'all'}.\n            Accordingly dataset is selected.\n        target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``,\n            or ``landmarks``. Can also be a list to output a tuple with all specified target types.\n            The targets represent:\n\n                - ``attr`` (np.array shape=(40,) dtype=int): binary (0, 1) labels for attributes\n                - ``identity`` (int): label for each person (data points with the same identity are the same person)\n                - ``bbox`` (np.array shape=(4,) dtype=int): bounding box (x, y, width, height)\n                - ``landmarks`` (np.array shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x,\n                  righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y)\n\n            Defaults to ``attr``. If empty, ``None`` will be returned as target.\n\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.ToTensor``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        download (bool, optional): If true, downloads the dataset from the internet and\n            puts it in root directory. If dataset is already downloaded, it is not\n            downloaded again.\n    \"\"\"\n\n    base_folder = \"celeba\"\n    # There currently does not appear to be a easy way to extract 7z in python (without introducing additional\n    # dependencies). The \"in-the-wild\" (not aligned+cropped) images are only in 7z, so they are not available\n    # right now.\n    file_list = [\n        # File ID                                      MD5 Hash                            Filename\n        (\"0B7EVK8r0v71pZjFTYXZWM3FlRnM\", \"00d2c5bc6d35e252742224ab0c1e8fcb\", \"img_align_celeba.zip\"),\n        # (\"0B7EVK8r0v71pbWNEUjJKdDQ3dGc\",\"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_align_celeba_png.7z\"),\n        # (\"0B7EVK8r0v71peklHb0pGdDl6R28\", \"b6cd7e93bc7a96c2dc33f819aa3ac651\", \"img_celeba.7z\"),\n        (\"0B7EVK8r0v71pblRyaVFSWGxPY0U\", \"75e246fa4810816ffd6ee81facbd244c\", \"list_attr_celeba.txt\"),\n        (\"1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS\", \"32bd1bd63d3c78cd57e08160ec5ed1e2\", \"identity_CelebA.txt\"),\n        (\"0B7EVK8r0v71pbThiMVRxWXZ4dU0\", \"00566efa6fedff7a56946cd1c10f1c16\", \"list_bbox_celeba.txt\"),\n        (\"0B7EVK8r0v71pd0FJY3Blby1HUTQ\", \"cc24ecafdb5b50baae59b03474781f8c\", \"list_landmarks_align_celeba.txt\"),\n        # (\"0B7EVK8r0v71pTzJIdlJWdHczRlU\", \"063ee6ddb681f96bc9ca28c6febb9d1a\", \"list_landmarks_celeba.txt\"),\n        (\"0B7EVK8r0v71pY0NSMzRuSXJEVkk\", \"d32c9cbf5e040fd4025c592c306e6668\", \"list_eval_partition.txt\"),\n    ]\n\n    def __init__(\n            self,\n            root: str,\n            split: str = \"train\",\n            target_type: Union[List[str], str] = \"attr\",\n            transform: Optional[Callable] = None,\n            target_transform: Optional[Callable] = None,\n            download: bool = False,\n    ) -> None:\n        super(CelebA, self).__init__(root, transform=transform,\n                                     target_transform=target_transform)\n        self.split = split\n        if isinstance(target_type, list):\n            self.target_type = target_type\n        else:\n            self.target_type = [target_type]\n\n        if not self.target_type and self.target_transform is not None:\n            raise RuntimeError('target_transform is specified but target_type is empty')\n\n        if download:\n            self.download()\n\n        if not self._check_integrity():\n            raise RuntimeError('Dataset not found or corrupted.' +\n                               ' You can use download=True to download it')\n\n        split_map = {\n            \"train\": 0,\n            \"valid\": 1,\n            \"test\": 2,\n            \"all\": None,\n        }\n        split_ = split_map[verify_str_arg(split.lower(), \"split\",\n                                          (\"train\", \"valid\", \"test\", \"all\"))]\n        splits = self._load_csv(\"list_eval_partition.txt\")\n        identity = self._load_csv(\"identity_CelebA.txt\")\n        bbox = self._load_csv(\"list_bbox_celeba.txt\", header=1)\n        landmarks_align = self._load_csv(\"list_landmarks_align_celeba.txt\", header=1)\n        attr = self._load_csv(\"list_attr_celeba.txt\", header=1)\n\n        mask = slice(None) if split_ is None else (splits.data == split_).squeeze()\n\n        self.filename = splits.index\n        self.identity = identity.data[mask]\n        self.bbox = bbox.data[mask]\n        self.landmarks_align = landmarks_align.data[mask]\n        self.attr = attr.data[mask]\n        self.attr = (self.attr + 1) // 2  # map from {-1, 1} to {0, 1}\n        self.attr_names = attr.header\n\n    def _load_csv(\n        self,\n        filename: str,\n        header: Optional[int] = None,\n    ) -> CSV:\n        data, indices, headers = [], [], []\n\n        fn = partial(os.path.join, self.root, self.base_folder)\n        with open(fn(filename)) as csv_file:\n            data = list(csv.reader(csv_file, delimiter=' ', skipinitialspace=True))\n\n        if header is not None:\n            headers = data[header]\n            data = data[header + 1:]\n\n        indices = [row[0] for row in data]\n        data = [row[1:] for row in data]\n        data_int = [list(map(int, i)) for i in data]\n\n        return CSV(headers, indices, torch.tensor(data_int))\n\n    def _check_integrity(self) -> bool:\n        for (_, md5, filename) in self.file_list:\n            fpath = os.path.join(self.root, self.base_folder, filename)\n            _, ext = os.path.splitext(filename)\n            # Allow original archive to be deleted (zip and 7z)\n            # Only need the extracted images\n            if ext not in [\".zip\", \".7z\"] and not check_integrity(fpath, md5):\n                return False\n\n        # Should check a hash of the images\n        return os.path.isdir(os.path.join(self.root, self.base_folder, \"img_align_celeba\"))\n\n    def download(self) -> None:\n        import zipfile\n\n        if self._check_integrity():\n            print('Files already downloaded and verified')\n            return\n\n        for (file_id, md5, filename) in self.file_list:\n            download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5)\n\n        with zipfile.ZipFile(os.path.join(self.root, self.base_folder, \"img_align_celeba.zip\"), \"r\") as f:\n            f.extractall(os.path.join(self.root, self.base_folder))\n\n    def __getitem__(self, index: int) -> Tuple[Any, Any]:\n        X = PIL.Image.open(os.path.join(self.root, self.base_folder, \"img_align_celeba\", self.filename[index]))\n\n        target: Any = []\n        for t in self.target_type:\n            if t == \"attr\":\n                target.append(self.attr[index, :])\n            elif t == \"identity\":\n                target.append(self.identity[index, 0])\n            elif t == \"bbox\":\n                target.append(self.bbox[index, :])\n            elif t == \"landmarks\":\n                target.append(self.landmarks_align[index, :])\n            else:\n                # TODO: refactor with utils.verify_str_arg\n                raise ValueError(\"Target type \\\"{}\\\" is not recognized.\".format(t))\n\n        if self.transform is not None:\n            X = self.transform(X)\n\n        if target:\n            target = tuple(target) if len(target) > 1 else target[0]\n\n            if self.target_transform is not None:\n                target = self.target_transform(target)\n        else:\n            target = None\n\n        return X, target\n\n    def __len__(self) -> int:\n        return len(self.attr)\n\n    def extra_repr(self) -> str:\n        lines = [\"Target type: {target_type}\", \"Split: {split}\"]\n        return '\\n'.join(lines).format(**self.__dict__)\n", "path": "torchvision/datasets/celeba.py"}]}