|
| 1 | +import bz2 |
| 2 | +import gzip |
| 3 | +import hashlib |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | +from tempfile import TemporaryDirectory |
| 7 | +from urllib.request import urlretrieve |
| 8 | + |
| 9 | +import h5py as h5 |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +from .datasources import MNIST_SOURCE, USPS_SOURCE |
| 13 | + |
| 14 | + |
| 15 | +class Downloader: |
| 16 | + """ |
| 17 | + Class to download and load the USPS dataset. |
| 18 | +
|
| 19 | + Methods |
| 20 | + ------- |
| 21 | + mnist(data_dir: Path) -> tuple[np.ndarray, np.ndarray] |
| 22 | + Download the MNIST dataset and save it as an HDF5 file to `data_dir`. |
| 23 | + svhn(data_dir: Path) -> tuple[np.ndarray, np.ndarray] |
| 24 | + Download the SVHN dataset and save it as an HDF5 file to `data_dir`. |
| 25 | + usps(data_dir: Path) -> tuple[np.ndarray, np.ndarray] |
| 26 | + Download the USPS dataset and save it as an HDF5 file to `data_dir`. |
| 27 | +
|
| 28 | + Raises |
| 29 | + ------ |
| 30 | + NotImplementedError |
| 31 | + If the download method is not implemented for the dataset. |
| 32 | +
|
| 33 | + Examples |
| 34 | + -------- |
| 35 | + >>> from pathlib import Path |
| 36 | + >>> from utils import Downloader |
| 37 | + >>> dir = Path('tmp') |
| 38 | + >>> dir.mkdir(exist_ok=True) |
| 39 | + >>> train, test = Downloader().usps(dir) |
| 40 | + """ |
| 41 | + |
| 42 | + def mnist(self, data_dir: Path) -> tuple[np.ndarray, np.ndarray]: |
| 43 | + def _chech_is_downloaded(path: Path) -> bool: |
| 44 | + path = path / "MNIST" |
| 45 | + if path.exists(): |
| 46 | + required_files = [MNIST_SOURCE[key][1] for key in MNIST_SOURCE.keys()] |
| 47 | + if all([(path / file).exists() for file in required_files]): |
| 48 | + print("MNIST Dataset already downloaded.") |
| 49 | + return True |
| 50 | + else: |
| 51 | + return False |
| 52 | + else: |
| 53 | + path.mkdir(parents=True, exist_ok=True) |
| 54 | + return False |
| 55 | + |
| 56 | + def _download_data(path: Path) -> None: |
| 57 | + urls = {key: MNIST_SOURCE[key][0] for key in MNIST_SOURCE.keys()} |
| 58 | + |
| 59 | + for name, url in urls.items(): |
| 60 | + file_path = os.path.join(path, url.split("/")[-1]) |
| 61 | + if not os.path.exists( |
| 62 | + file_path.replace(".gz", "") |
| 63 | + ): # Avoid re-downloading |
| 64 | + urlretrieve(url, file_path) |
| 65 | + with gzip.open(file_path, "rb") as f_in: |
| 66 | + with open(file_path.replace(".gz", ""), "wb") as f_out: |
| 67 | + f_out.write(f_in.read()) |
| 68 | + os.remove(file_path) # Remove compressed file |
| 69 | + |
| 70 | + def _get_labels(path: Path) -> np.ndarray: |
| 71 | + with open(path, "rb") as f: |
| 72 | + data = np.frombuffer(f.read(), dtype=np.uint8, offset=8) |
| 73 | + return data |
| 74 | + |
| 75 | + if not _chech_is_downloaded(data_dir): |
| 76 | + _download_data(data_dir) |
| 77 | + |
| 78 | + train_labels_path = data_dir / "MNIST" / MNIST_SOURCE["train_labels"][1] |
| 79 | + test_labels_path = data_dir / "MNIST" / MNIST_SOURCE["test_labels"][1] |
| 80 | + |
| 81 | + train_labels = _get_labels(train_labels_path) |
| 82 | + test_labels = _get_labels(test_labels_path) |
| 83 | + |
| 84 | + return train_labels, test_labels |
| 85 | + |
| 86 | + def svhn(self, data_dir: Path) -> tuple[np.ndarray, np.ndarray]: |
| 87 | + raise NotImplementedError("SVHN download not implemented yet") |
| 88 | + |
| 89 | + def usps(self, data_dir: Path) -> tuple[np.ndarray, np.ndarray]: |
| 90 | + """ |
| 91 | + Download the USPS dataset and save it as an HDF5 file to `data_dir/usps.h5`. |
| 92 | + """ |
| 93 | + |
| 94 | + def already_downloaded(path): |
| 95 | + if not path.exists() or not path.is_file(): |
| 96 | + return False |
| 97 | + |
| 98 | + with h5.File(path, "r") as f: |
| 99 | + return "train" in f and "test" in f |
| 100 | + |
| 101 | + filename = data_dir / "usps.h5" |
| 102 | + |
| 103 | + if already_downloaded(filename): |
| 104 | + with h5.File(filename, "r") as f: |
| 105 | + return f["train"]["target"][:], f["test"]["target"][:] |
| 106 | + |
| 107 | + url_train, _, train_md5 = USPS_SOURCE["train"] |
| 108 | + url_test, _, test_md5 = USPS_SOURCE["test"] |
| 109 | + |
| 110 | + # Using temporary directory ensures temporary files are deleted after use |
| 111 | + with TemporaryDirectory() as tmp_dir: |
| 112 | + train_path = Path(tmp_dir) / "train" |
| 113 | + test_path = Path(tmp_dir) / "test" |
| 114 | + |
| 115 | + # Download the dataset and report the progress |
| 116 | + urlretrieve(url_train, train_path, reporthook=self.__reporthook) |
| 117 | + self.__check_integrity(train_path, train_md5) |
| 118 | + train_targets = self.__extract_usps(train_path, filename, "train") |
| 119 | + |
| 120 | + urlretrieve(url_test, test_path, reporthook=self.__reporthook) |
| 121 | + self.__check_integrity(test_path, test_md5) |
| 122 | + test_targets = self.__extract_usps(test_path, filename, "test") |
| 123 | + |
| 124 | + return train_targets, test_targets |
| 125 | + |
| 126 | + def __extract_usps(self, src: Path, dest: Path, mode: str): |
| 127 | + # Load the dataset and save it as an HDF5 file |
| 128 | + with bz2.open(src) as fp: |
| 129 | + raw = [line.decode().split() for line in fp.readlines()] |
| 130 | + |
| 131 | + tmp = [[x.split(":")[-1] for x in data[1:]] for data in raw] |
| 132 | + |
| 133 | + imgs = np.asarray(tmp, dtype=np.float32) |
| 134 | + imgs = ((imgs + 1) / 2 * 255).astype(dtype=np.uint8) |
| 135 | + |
| 136 | + targets = [int(d[0]) - 1 for d in raw] |
| 137 | + |
| 138 | + with h5.File(dest, "a") as f: |
| 139 | + f.create_dataset(f"{mode}/data", data=imgs, dtype=np.float32) |
| 140 | + f.create_dataset(f"{mode}/target", data=targets, dtype=np.int32) |
| 141 | + |
| 142 | + return targets |
| 143 | + |
| 144 | + @staticmethod |
| 145 | + def __reporthook(blocknum, blocksize, totalsize): |
| 146 | + """ |
| 147 | + Use this function to report download progress |
| 148 | + for the urllib.request.urlretrieve function. |
| 149 | + """ |
| 150 | + |
| 151 | + denom = 1024 * 1024 |
| 152 | + readsofar = blocknum * blocksize |
| 153 | + |
| 154 | + if totalsize > 0: |
| 155 | + percent = readsofar * 1e2 / totalsize |
| 156 | + s = f"\r{int(percent):^3}% {readsofar / denom:.2f} of {totalsize / denom:.2f} MB" |
| 157 | + print(s, end="", flush=True) |
| 158 | + if readsofar >= totalsize: |
| 159 | + print() |
| 160 | + |
| 161 | + @staticmethod |
| 162 | + def __check_integrity(filepath, checksum): |
| 163 | + """Check the integrity of the USPS dataset file. |
| 164 | +
|
| 165 | + Args |
| 166 | + ---- |
| 167 | + filepath : pathlib.Path |
| 168 | + Path to the USPS dataset file. |
| 169 | + checksum : str |
| 170 | + MD5 checksum of the dataset file. |
| 171 | +
|
| 172 | + Returns |
| 173 | + ------- |
| 174 | + bool |
| 175 | + True if the checksum of the file matches the expected checksum, False otherwise |
| 176 | + """ |
| 177 | + |
| 178 | + file_hash = hashlib.md5(filepath.read_bytes()).hexdigest() |
| 179 | + |
| 180 | + if not checksum == file_hash: |
| 181 | + raise ValueError( |
| 182 | + f"File integrity check failed. Expected {checksum}, got {file_hash}" |
| 183 | + ) |
0 commit comments