utils.py 17 KB

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