utils
Download, archive extraction, and hash verification helpers for disk-cached datasets.
Functions:
-
urltailnameβGet the name of the last segment of a URL.
-
urlsizeβGet the size of a URL.
-
check_terms_acceptedβConfirm the terms of use that gate a dataset's automatic download, asking on the terminal when not passed.
-
download_urlβDownload a file from a URL to a local path.
-
extract_zipβExtract a zip file to a directory.
-
extract_tarβExtract a tar file to a directory.
-
compute_hashβCompute the hash of a file.
-
check_cache_metaβValidate a processed cache against the parameters it was built with.
-
is_hash_validβCheck if the hash of a file matches the expected hash.
urltailname [source] ΒΆ
Get the name of the last segment of a URL.
Parameters:
-
url(str) βThe URL to get the basename from.
Returns:
-
strβThe (decoded) name of the last segment of the URL.
Examples:
urlsize [source] ΒΆ
urlsize(
url: str,
*,
timeout: Optional[float] = None,
cafile: Optional[str] = None,
capath: Optional[str] = None,
cadefault: bool = False,
context: Optional[SSLContext] = None,
) -> Optional[int]
Get the size of a URL.
Parameters:
-
url(str) βThe URL to get the size of.
-
timeout(Optional[float], default:None) βOptional timeout in seconds for the request.
-
cafile(Optional[str], default:None) βOptional path to a CA file.
-
capath(Optional[str], default:None) βOptional path to a directory with CA certificates.
-
cadefault(bool, default:False) βWhether to use the default CA store.
-
context(Optional[SSLContext], default:None) βOptional
SSLContextfor the request. Built fromcafile/capath/cadefaultwhen not provided.
Returns:
-
Optional[int]βThe size of the URL in bytes, or
Noneif the response has nocontent-lengthheader.
Examples:
check_terms_accepted [source] ΒΆ
Confirm the terms of use that gate a dataset's automatic download, asking on the terminal when not passed.
Parameters:
-
accept_terms(bool) βThe
accept_termsflag the dataset was built with. When false, the confirmation is asked interactively withinput; a non-interactive session (closed or captured stdin) counts as a refusal. -
name(str) βDataset class name, for the prompt and the error message.
-
terms_url(str) βWhere the terms of use are read and accepted.
Raises:
-
RuntimeErrorβIf the terms are not accepted.
download_url [source] ΒΆ
download_url(
url: str,
file_path: PathLike = "",
chunk_size: int = 1024 * 32,
description: str = "Downloading",
show_progress: bool = True,
overwrite: Union[bool, Literal["incomplete"]] = False,
timeout: float = 30.0,
headers: Optional[Dict[str, str]] = None,
) -> str
Download a file from a URL to a local path.
Parameters:
-
url(str) βThe URL to download the file from.
-
file_path(PathLike, default:'') βThe local path to save the file to (including the file name). If not provided, the file will be saved in the current working directory with the name taken from `Path
-
chunk_size(int, default:1024 * 32) βThe size of the chunks to download in bytes.
-
description(str, default:'Downloading') βThe description to display in the progress bar.
-
show_progress(bool, default:True) βWhether to display a progress bar.
-
overwrite(Union[bool, Literal['incomplete']], default:False) βWhether to overwrite the file if it already exists. If
True, the local file will be overwritten even if it already exists. If'incomplete', the local file will be overwritten if it already exists and its size does not match the expected size (when the remote size is unknown, the local file is kept). IfFalse, the local file will not be overwritten if it already exists. -
timeout(float, default:30.0) βTimeout in seconds passed to
urlopen, covering the connection and each blocking read, so a stalled server raises instead of hanging forever. -
headers(Optional[Dict[str, str]], default:None) βExtra request headers, such as
{"Authorization": "Bearer <token>"}for a gated file. They are sent tourlonly, not forwarded when the download is redirected, as to a content delivery network.
Returns:
-
strβThe local path to the downloaded file.
Examples:
extract_zip [source] ΒΆ
extract_zip(
zip_path: PathLike,
out_dir: PathLike,
relative_to: PathLike = "",
show_progress: bool = True,
) -> str
Extract a zip file to a directory.
Parameters:
-
zip_path(PathLike) βThe path to the zip file to extract.
-
out_dir(PathLike) βThe directory to extract the zip file to.
-
relative_to(PathLike, default:'') βIf provided, extract the zip file relative to this directory. This is useful when the zip file contains nested directories but you want to extract the files on a specific level (e.g. for a nested zip
A.zipcontaining files under directoryA, then you will getA/A/*.pngwhen extracting, but settingrelative_to="A"will extract the files toA/*.pngonly). -
show_progress(bool, default:True) βWhether to display a progress bar.
Returns:
-
strβThe path to the extracted directory.
Examples:
extract_tar [source] ΒΆ
extract_tar(
tar_path: PathLike,
dst_dir: PathLike,
/,
relative_to: PathLike = "",
show_progress: bool = True,
) -> str
Extract a tar file to a directory.
Parameters:
-
tar_path(PathLike) βThe path to the tar file to extract.
-
dst_dir(PathLike) βThe directory to extract the tar file to.
-
relative_to(PathLike, default:'') βIf provided, extract the tar file relative to this directory.
-
show_progress(bool, default:True) βWhether to display a progress bar.
compute_hash [source] ΒΆ
Compute the hash of a file.
Parameters:
-
file_path(PathLike) βThe path to the file to hash.
-
hash_type(HashType, default:'md5') βThe type of hash to compute.
Returns:
-
strβThe hex digest of the file's hash.
Examples:
check_cache_meta [source] ΒΆ
Validate a processed cache against the parameters it was built with.
Compares the JSON metadata stored next to a processed cache with the metadata the current constructor parameters would produce, and raises a RuntimeError on mismatch so a stale cache is never silently served. A missing metadata file (legacy cache) is accepted as-is.
Parameters:
-
meta_path(PathLike) βPath to the cache
meta.jsonfile. -
meta(Dict[str, Any]) βThe metadata the requested parameters would produce.
Examples:
is_hash_valid [source] ΒΆ
is_hash_valid(
file_path: PathLike,
expected_hash: Optional[str] = None,
hash_type: HashType = "md5",
) -> bool
Check if the hash of a file matches the expected hash.
Parameters:
-
file_path(PathLike) βThe path to the file to check the hash of.
-
expected_hash(Optional[str], default:None) βThe expected hash of the file. When
None, aUserWarningis emitted and the check passes without verifying the file. -
hash_type(HashType, default:'md5') βThe type of hash to use for the comparison. Prefer
sha256for new datasets.
Returns:
-
boolβTrue if the hash of the file matches the expected hash, False otherwise.
Examples: