utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import bz2
  2. import gzip
  3. import hashlib
  4. import lzma
  5. import os
  6. import os.path
  7. import pathlib
  8. import re
  9. import tarfile
  10. import urllib
  11. import urllib.error
  12. import urllib.request
  13. import zipfile
  14. from collections.abc import Iterable
  15. from typing import Any, Callable, IO, Optional, TypeVar, Union
  16. from urllib.parse import urlparse
  17. import numpy as np
  18. import torch
  19. from torch.utils.model_zoo import tqdm
  20. from .._internally_replaced_utils import _download_file_from_remote_location, _is_remote_location_available
  21. USER_AGENT = "pytorch/vision"
  22. def _urlretrieve(url: str, filename: Union[str, pathlib.Path], chunk_size: int = 1024 * 32) -> None:
  23. with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response:
  24. with open(filename, "wb") as fh, tqdm(total=response.length, unit="B", unit_scale=True) as pbar:
  25. while chunk := response.read(chunk_size):
  26. fh.write(chunk)
  27. pbar.update(len(chunk))
  28. def calculate_md5(fpath: Union[str, pathlib.Path], chunk_size: int = 1024 * 1024) -> str:
  29. # Setting the `usedforsecurity` flag does not change anything about the functionality, but indicates that we are
  30. # not using the MD5 checksum for cryptography. This enables its usage in restricted environments like FIPS. Without
  31. # it torchvision.datasets is unusable in these environments since we perform a MD5 check everywhere.
  32. md5 = hashlib.md5(usedforsecurity=False)
  33. with open(fpath, "rb") as f:
  34. while chunk := f.read(chunk_size):
  35. md5.update(chunk)
  36. return md5.hexdigest()
  37. def check_md5(fpath: Union[str, pathlib.Path], md5: str, **kwargs: Any) -> bool:
  38. return md5 == calculate_md5(fpath, **kwargs)
  39. def check_integrity(fpath: Union[str, pathlib.Path], md5: Optional[str] = None) -> bool:
  40. if not os.path.isfile(fpath):
  41. return False
  42. if md5 is None:
  43. return True
  44. return check_md5(fpath, md5)
  45. def _get_redirect_url(url: str, max_hops: int = 3) -> str:
  46. initial_url = url
  47. headers = {"Method": "HEAD", "User-Agent": USER_AGENT}
  48. for _ in range(max_hops + 1):
  49. with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as response:
  50. if response.url == url or response.url is None:
  51. return url
  52. url = response.url
  53. else:
  54. raise RecursionError(
  55. f"Request to {initial_url} exceeded {max_hops} redirects. The last redirect points to {url}."
  56. )
  57. def _get_google_drive_file_id(url: str) -> Optional[str]:
  58. parts = urlparse(url)
  59. if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None:
  60. return None
  61. match = re.match(r"/file/d/(?P<id>[^/]*)", parts.path)
  62. if match is None:
  63. return None
  64. return match.group("id")
  65. def download_url(
  66. url: str,
  67. root: Union[str, pathlib.Path],
  68. filename: Optional[Union[str, pathlib.Path]] = None,
  69. md5: Optional[str] = None,
  70. max_redirect_hops: int = 3,
  71. ) -> None:
  72. """Download a file from a url and place it in root.
  73. Args:
  74. url (str): URL to download file from
  75. root (str): Directory to place downloaded file in
  76. filename (str, optional): Name to save the file under. If None, use the basename of the URL
  77. md5 (str, optional): MD5 checksum of the download. If None, do not check
  78. max_redirect_hops (int, optional): Maximum number of redirect hops allowed
  79. """
  80. root = os.path.expanduser(root)
  81. if not filename:
  82. filename = os.path.basename(url)
  83. fpath = os.fspath(os.path.join(root, filename))
  84. os.makedirs(root, exist_ok=True)
  85. # check if file is already present locally
  86. if check_integrity(fpath, md5):
  87. return
  88. if _is_remote_location_available():
  89. _download_file_from_remote_location(fpath, url)
  90. else:
  91. # expand redirect chain if needed
  92. url = _get_redirect_url(url, max_hops=max_redirect_hops)
  93. # check if file is located on Google Drive
  94. file_id = _get_google_drive_file_id(url)
  95. if file_id is not None:
  96. return download_file_from_google_drive(file_id, root, filename, md5)
  97. # download the file
  98. try:
  99. _urlretrieve(url, fpath)
  100. except (urllib.error.URLError, OSError) as e: # type: ignore[attr-defined]
  101. if url[:5] == "https":
  102. url = url.replace("https:", "http:")
  103. _urlretrieve(url, fpath)
  104. else:
  105. raise e
  106. # check integrity of downloaded file
  107. if not check_integrity(fpath, md5):
  108. raise RuntimeError("File not found or corrupted.")
  109. def list_dir(root: Union[str, pathlib.Path], prefix: bool = False) -> list[str]:
  110. """List all directories at a given root
  111. Args:
  112. root (str): Path to directory whose folders need to be listed
  113. prefix (bool, optional): If true, prepends the path to each result, otherwise
  114. only returns the name of the directories found
  115. """
  116. root = os.path.expanduser(root)
  117. directories = [p for p in os.listdir(root) if os.path.isdir(os.path.join(root, p))]
  118. if prefix is True:
  119. directories = [os.path.join(root, d) for d in directories]
  120. return directories
  121. def list_files(root: Union[str, pathlib.Path], suffix: str, prefix: bool = False) -> list[str]:
  122. """List all files ending with a suffix at a given root
  123. Args:
  124. root (str): Path to directory whose folders need to be listed
  125. suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
  126. It uses the Python "str.endswith" method and is passed directly
  127. prefix (bool, optional): If true, prepends the path to each result, otherwise
  128. only returns the name of the files found
  129. """
  130. root = os.path.expanduser(root)
  131. files = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p)) and p.endswith(suffix)]
  132. if prefix is True:
  133. files = [os.path.join(root, d) for d in files]
  134. return files
  135. def download_file_from_google_drive(
  136. file_id: str,
  137. root: Union[str, pathlib.Path],
  138. filename: Optional[Union[str, pathlib.Path]] = None,
  139. md5: Optional[str] = None,
  140. ):
  141. """Download a Google Drive file from and place it in root.
  142. Args:
  143. file_id (str): id of file to be downloaded
  144. root (str): Directory to place downloaded file in
  145. filename (str, optional): Name to save the file under. If None, use the id of the file.
  146. md5 (str, optional): MD5 checksum of the download. If None, do not check
  147. """
  148. try:
  149. import gdown
  150. except ModuleNotFoundError:
  151. raise RuntimeError(
  152. "To download files from GDrive, 'gdown' is required. You can install it with 'pip install gdown'."
  153. )
  154. root = os.path.expanduser(root)
  155. if not filename:
  156. filename = file_id
  157. fpath = os.fspath(os.path.join(root, filename))
  158. os.makedirs(root, exist_ok=True)
  159. if check_integrity(fpath, md5):
  160. return
  161. gdown.download(id=file_id, output=fpath, quiet=False, user_agent=USER_AGENT)
  162. if not check_integrity(fpath, md5):
  163. raise RuntimeError("File not found or corrupted.")
  164. def _extract_tar(
  165. from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str]
  166. ) -> None:
  167. with tarfile.open(from_path, f"r:{compression[1:]}" if compression else "r") as tar:
  168. tar.extractall(to_path)
  169. _ZIP_COMPRESSION_MAP: dict[str, int] = {
  170. ".bz2": zipfile.ZIP_BZIP2,
  171. ".xz": zipfile.ZIP_LZMA,
  172. }
  173. def _extract_zip(
  174. from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str]
  175. ) -> None:
  176. with zipfile.ZipFile(
  177. from_path, "r", compression=_ZIP_COMPRESSION_MAP[compression] if compression else zipfile.ZIP_STORED
  178. ) as zip:
  179. zip.extractall(to_path)
  180. _ARCHIVE_EXTRACTORS: dict[str, Callable[[Union[str, pathlib.Path], Union[str, pathlib.Path], Optional[str]], None]] = {
  181. ".tar": _extract_tar,
  182. ".zip": _extract_zip,
  183. }
  184. _COMPRESSED_FILE_OPENERS: dict[str, Callable[..., IO]] = {
  185. ".bz2": bz2.open,
  186. ".gz": gzip.open,
  187. ".xz": lzma.open,
  188. }
  189. _FILE_TYPE_ALIASES: dict[str, tuple[Optional[str], Optional[str]]] = {
  190. ".tbz": (".tar", ".bz2"),
  191. ".tbz2": (".tar", ".bz2"),
  192. ".tgz": (".tar", ".gz"),
  193. }
  194. def _detect_file_type(file: Union[str, pathlib.Path]) -> tuple[str, Optional[str], Optional[str]]:
  195. """Detect the archive type and/or compression of a file.
  196. Args:
  197. file (str): the filename
  198. Returns:
  199. (tuple): tuple of suffix, archive type, and compression
  200. Raises:
  201. RuntimeError: if file has no suffix or suffix is not supported
  202. """
  203. suffixes = pathlib.Path(file).suffixes
  204. if not suffixes:
  205. raise RuntimeError(
  206. f"File '{file}' has no suffixes that could be used to detect the archive type and compression."
  207. )
  208. suffix = suffixes[-1]
  209. # check if the suffix is a known alias
  210. if suffix in _FILE_TYPE_ALIASES:
  211. return (suffix, *_FILE_TYPE_ALIASES[suffix])
  212. # check if the suffix is an archive type
  213. if suffix in _ARCHIVE_EXTRACTORS:
  214. return suffix, suffix, None
  215. # check if the suffix is a compression
  216. if suffix in _COMPRESSED_FILE_OPENERS:
  217. # check for suffix hierarchy
  218. if len(suffixes) > 1:
  219. suffix2 = suffixes[-2]
  220. # check if the suffix2 is an archive type
  221. if suffix2 in _ARCHIVE_EXTRACTORS:
  222. return suffix2 + suffix, suffix2, suffix
  223. return suffix, None, suffix
  224. valid_suffixes = sorted(set(_FILE_TYPE_ALIASES) | set(_ARCHIVE_EXTRACTORS) | set(_COMPRESSED_FILE_OPENERS))
  225. raise RuntimeError(f"Unknown compression or archive type: '{suffix}'.\nKnown suffixes are: '{valid_suffixes}'.")
  226. def _decompress(
  227. from_path: Union[str, pathlib.Path],
  228. to_path: Optional[Union[str, pathlib.Path]] = None,
  229. remove_finished: bool = False,
  230. ) -> pathlib.Path:
  231. r"""Decompress a file.
  232. The compression is automatically detected from the file name.
  233. Args:
  234. from_path (str): Path to the file to be decompressed.
  235. to_path (str): Path to the decompressed file. If omitted, ``from_path`` without compression extension is used.
  236. remove_finished (bool): If ``True``, remove the file after the extraction.
  237. Returns:
  238. (str): Path to the decompressed file.
  239. """
  240. suffix, archive_type, compression = _detect_file_type(from_path)
  241. if not compression:
  242. raise RuntimeError(f"Couldn't detect a compression from suffix {suffix}.")
  243. if to_path is None:
  244. to_path = pathlib.Path(os.fspath(from_path).replace(suffix, archive_type if archive_type is not None else ""))
  245. # We don't need to check for a missing key here, since this was already done in _detect_file_type()
  246. compressed_file_opener = _COMPRESSED_FILE_OPENERS[compression]
  247. with compressed_file_opener(from_path, "rb") as rfh, open(to_path, "wb") as wfh:
  248. wfh.write(rfh.read())
  249. if remove_finished:
  250. os.remove(from_path)
  251. return pathlib.Path(to_path)
  252. def extract_archive(
  253. from_path: Union[str, pathlib.Path],
  254. to_path: Optional[Union[str, pathlib.Path]] = None,
  255. remove_finished: bool = False,
  256. ) -> Union[str, pathlib.Path]:
  257. """Extract an archive.
  258. The archive type and a possible compression is automatically detected from the file name. If the file is compressed
  259. but not an archive the call is dispatched to :func:`decompress`.
  260. Args:
  261. from_path (str): Path to the file to be extracted.
  262. to_path (str): Path to the directory the file will be extracted to. If omitted, the directory of the file is
  263. used.
  264. remove_finished (bool): If ``True``, remove the file after the extraction.
  265. Returns:
  266. (str): Path to the directory the file was extracted to.
  267. """
  268. def path_or_str(ret_path: pathlib.Path) -> Union[str, pathlib.Path]:
  269. if isinstance(from_path, str):
  270. return os.fspath(ret_path)
  271. else:
  272. return ret_path
  273. if to_path is None:
  274. to_path = os.path.dirname(from_path)
  275. suffix, archive_type, compression = _detect_file_type(from_path)
  276. if not archive_type:
  277. ret_path = _decompress(
  278. from_path,
  279. os.path.join(to_path, os.path.basename(from_path).replace(suffix, "")),
  280. remove_finished=remove_finished,
  281. )
  282. return path_or_str(ret_path)
  283. # We don't need to check for a missing key here, since this was already done in _detect_file_type()
  284. extractor = _ARCHIVE_EXTRACTORS[archive_type]
  285. extractor(from_path, to_path, compression)
  286. if remove_finished:
  287. os.remove(from_path)
  288. return path_or_str(pathlib.Path(to_path))
  289. def download_and_extract_archive(
  290. url: str,
  291. download_root: Union[str, pathlib.Path],
  292. extract_root: Optional[Union[str, pathlib.Path]] = None,
  293. filename: Optional[Union[str, pathlib.Path]] = None,
  294. md5: Optional[str] = None,
  295. remove_finished: bool = False,
  296. ) -> None:
  297. download_root = os.path.expanduser(download_root)
  298. if extract_root is None:
  299. extract_root = download_root
  300. if not filename:
  301. filename = os.path.basename(url)
  302. download_url(url, download_root, filename, md5)
  303. archive = os.path.join(download_root, filename)
  304. extract_archive(archive, extract_root, remove_finished)
  305. def iterable_to_str(iterable: Iterable) -> str:
  306. return "'" + "', '".join([str(item) for item in iterable]) + "'"
  307. T = TypeVar("T", str, bytes)
  308. def verify_str_arg(
  309. value: T,
  310. arg: Optional[str] = None,
  311. valid_values: Optional[Iterable[T]] = None,
  312. custom_msg: Optional[str] = None,
  313. ) -> T:
  314. if not isinstance(value, str):
  315. if arg is None:
  316. msg = "Expected type str, but got type {type}."
  317. else:
  318. msg = "Expected type str for argument {arg}, but got type {type}."
  319. msg = msg.format(type=type(value), arg=arg)
  320. raise ValueError(msg)
  321. if valid_values is None:
  322. return value
  323. if value not in valid_values:
  324. if custom_msg is not None:
  325. msg = custom_msg
  326. else:
  327. msg = "Unknown value '{value}' for argument {arg}. Valid values are {{{valid_values}}}."
  328. msg = msg.format(value=value, arg=arg, valid_values=iterable_to_str(valid_values))
  329. raise ValueError(msg)
  330. return value
  331. def _read_pfm(file_name: Union[str, pathlib.Path], slice_channels: int = 2) -> np.ndarray:
  332. """Read file in .pfm format. Might contain either 1 or 3 channels of data.
  333. Args:
  334. file_name (str): Path to the file.
  335. slice_channels (int): Number of channels to slice out of the file.
  336. Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc.
  337. """
  338. with open(file_name, "rb") as f:
  339. header = f.readline().rstrip()
  340. if header not in [b"PF", b"Pf"]:
  341. raise ValueError("Invalid PFM file")
  342. dim_match = re.match(rb"^(\d+)\s(\d+)\s$", f.readline())
  343. if not dim_match:
  344. raise Exception("Malformed PFM header.")
  345. w, h = (int(dim) for dim in dim_match.groups())
  346. scale = float(f.readline().rstrip())
  347. if scale < 0: # little-endian
  348. endian = "<"
  349. scale = -scale
  350. else:
  351. endian = ">" # big-endian
  352. data = np.fromfile(f, dtype=endian + "f")
  353. pfm_channels = 3 if header == b"PF" else 1
  354. data = data.reshape(h, w, pfm_channels).transpose(2, 0, 1)
  355. data = np.flip(data, axis=1) # flip on h dimension
  356. data = data[:slice_channels, :, :]
  357. return data.astype(np.float32)
  358. def _flip_byte_order(t: torch.Tensor) -> torch.Tensor:
  359. return (
  360. t.contiguous().view(torch.uint8).view(*t.shape, t.element_size()).flip(-1).view(*t.shape[:-1], -1).view(t.dtype)
  361. )