utils.py 18 KB

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