Skip to content

afnio.utils.datasets.utils

afnio.utils.datasets.utils.calculate_md5(fpath, chunk_size=1024 * 1024)

Calculates the MD5 checksum of a file.

Parameters:

Name Type Description Default
fpath str | Path

Path to the file.

required
chunk_size int

Size of the chunks to read from the file.

1024 * 1024

Returns:

Type Description
str

MD5 checksum of the file.

Source code in afnio/utils/datasets/utils.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def calculate_md5(
    fpath: Union[str, pathlib.Path], chunk_size: int = 1024 * 1024
) -> str:
    """Calculates the MD5 checksum of a file.

    Args:
        fpath: Path to the file.
        chunk_size: Size of the chunks to read from the file.

    Returns:
        MD5 checksum of the file.
    """
    # Setting the `usedforsecurity` flag does not change anything about the
    # functionality, but indicates that we are not using the MD5 checksum for
    # cryptography. This enables its usage in restricted environments like FIPS.
    if sys.version_info >= (3, 9):
        md5 = hashlib.md5(usedforsecurity=False)
    else:
        md5 = hashlib.md5()
    with open(fpath, "rb") as f:
        while chunk := f.read(chunk_size):
            md5.update(chunk)
    return md5.hexdigest()

afnio.utils.datasets.utils.check_md5(fpath, md5, **kwargs)

Checks the MD5 checksum of a file.

Parameters:

Name Type Description Default
fpath str | Path

Path to the file.

required
md5 str

Expected MD5 checksum of the file.

required
**kwargs Any

Additional arguments to pass to calculate_md5.

{}

Returns:

Type Description
bool

True if the MD5 checksum matches, False otherwise.

Source code in afnio/utils/datasets/utils.py
79
80
81
82
83
84
85
86
87
88
89
90
def check_md5(fpath: Union[str, pathlib.Path], md5: str, **kwargs: Any) -> bool:
    """Checks the MD5 checksum of a file.

    Args:
        fpath: Path to the file.
        md5: Expected MD5 checksum of the file.
        **kwargs: Additional arguments to pass to [`calculate_md5`][..calculate_md5].

    Returns:
        True if the MD5 checksum matches, False otherwise.
    """
    return md5 == calculate_md5(fpath, **kwargs)

afnio.utils.datasets.utils.check_integrity(fpath, md5=None)

Checks the integrity of a file.

Parameters:

Name Type Description Default
fpath str | Path

Path to the file.

required
md5 str | None

Expected MD5 checksum of the file. If None, only checks if the file exists.

None

Returns:

Type Description
bool

True if the file exists and the MD5 checksum matches (if provided), False otherwise.

Source code in afnio/utils/datasets/utils.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def check_integrity(fpath: Union[str, pathlib.Path], md5: Optional[str] = None) -> bool:
    """Checks the integrity of a file.

    Args:
        fpath: Path to the file.
        md5: Expected MD5 checksum of the file. If None, only checks if the file exists.

    Returns:
        `True` if the file exists and the MD5 checksum matches (if provided), \
        `False` otherwise.
    """
    if not os.path.isfile(fpath):
        return False
    if md5 is None:
        return True
    return check_md5(fpath, md5)

afnio.utils.datasets.utils.download_url(url, root, filename=None, md5=None, max_redirect_hops=3)

Download a file from a url and place it in root.

Parameters:

Name Type Description Default
url str

URL to download file from.

required
root str | Path

Directory to place downloaded file in.

required
filename str | Path | None

Name to save the file under. If None, use the basename of the URL.

None
md5 str | None

MD5 checksum of the download. If None, do not check.

None
max_redirect_hops int

Maximum number of redirect hops allowed.

3
Source code in afnio/utils/datasets/utils.py
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
def download_url(
    url: str,
    root: Union[str, pathlib.Path],
    filename: Optional[Union[str, pathlib.Path]] = None,
    md5: Optional[str] = None,
    max_redirect_hops: int = 3,
) -> None:
    """Download a file from a url and place it in root.

    Args:
        url: URL to download file from.
        root: Directory to place downloaded file in.
        filename: Name to save the file under. If `None`, use the basename of the URL.
        md5: MD5 checksum of the download. If `None`, do not check.
        max_redirect_hops: Maximum number of redirect hops allowed.
    """
    root = os.path.expanduser(root)
    if not filename:
        filename = os.path.basename(url)
    fpath = os.fspath(os.path.join(root, filename))

    os.makedirs(root, exist_ok=True)

    # check if file is already present locally
    if check_integrity(fpath, md5):
        print(f"Using downloaded and verified file: {fpath}")
        return

    # download the file
    try:
        print(f"Downloading {url} to {fpath}")
        _urlretrieve(url, fpath)
    except (urllib.error.URLError, OSError) as e:
        if url[:5] == "https":
            url = url.replace("https:", "http:")
            print(
                f"Failed download. Trying https -> http instead. "
                f"Downloading {url} to {fpath}"
            )
            _urlretrieve(url, fpath)
        else:
            raise e

    # check integrity of downloaded file
    if not check_integrity(fpath, md5):
        raise RuntimeError("File not found or corrupted.")

afnio.utils.datasets.utils.download(url, download_root, extract_root=None, filename=None, md5=None, remove_finished=False)

Downloads a file from a URL and optionally extracts it.

Parameters:

Name Type Description Default
url str

URL to download file from.

required
download_root str | Path

Directory to place downloaded file in.

required
extract_root str | Path | None

Directory to extract the file to. If None, extract to download_root.

None
filename str | Path | None

Name to save the file under. If None, use the basename of the URL.

None
md5 str | None

MD5 checksum of the download. If None, do not check.

None
remove_finished bool

Whether to remove the downloaded file after extraction.

False
Source code in afnio/utils/datasets/utils.py
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
def download(
    url: str,
    download_root: Union[str, pathlib.Path],
    extract_root: Optional[Union[str, pathlib.Path]] = None,
    filename: Optional[Union[str, pathlib.Path]] = None,
    md5: Optional[str] = None,
    remove_finished: bool = False,
) -> None:
    """Downloads a file from a URL and optionally extracts it.

    Args:
        url: URL to download file from.
        download_root: Directory to place downloaded file in.
        extract_root: Directory to extract the file to.
            If `None`, extract to `download_root`.
        filename: Name to save the file under. If `None`, use the basename of the URL.
        md5: MD5 checksum of the download. If `None`, do not check.
        remove_finished: Whether to remove the downloaded file after extraction.
    """
    download_root = os.path.expanduser(download_root)
    if extract_root is None:
        extract_root = download_root
    if not filename:
        filename = os.path.basename(url)

    download_url(url, download_root, filename, md5)