downloads.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import contextlib
  3. import re
  4. import shutil
  5. import subprocess
  6. from itertools import repeat
  7. from multiprocessing.pool import ThreadPool
  8. from pathlib import Path
  9. from urllib import parse, request
  10. import requests
  11. import torch
  12. from ultralytics.utils import LOGGER, TQDM, checks, clean_url, emojis, is_online, url2file
  13. # Define Ultralytics GitHub assets maintained at https://github.com/ultralytics/assets
  14. GITHUB_ASSETS_REPO = "ultralytics/assets"
  15. GITHUB_ASSETS_NAMES = (
  16. [f"yolov8{k}{suffix}.pt" for k in "nsmlx" for suffix in ("", "-cls", "-seg", "-pose", "-obb")]
  17. + [f"yolov5{k}{resolution}u.pt" for k in "nsmlx" for resolution in ("", "6")]
  18. + [f"yolov3{k}u.pt" for k in ("", "-spp", "-tiny")]
  19. + [f"yolov8{k}-world.pt" for k in "smlx"]
  20. + [f"yolov8{k}-worldv2.pt" for k in "smlx"]
  21. + [f"yolov9{k}.pt" for k in "ce"]
  22. + [f"yolov10{k}.pt" for k in "nsmblx"]
  23. + [f"yolo_nas_{k}.pt" for k in "sml"]
  24. + [f"sam_{k}.pt" for k in "bl"]
  25. + [f"FastSAM-{k}.pt" for k in "sx"]
  26. + [f"rtdetr-{k}.pt" for k in "lx"]
  27. + ["mobile_sam.pt"]
  28. + ["calibration_image_sample_data_20x128x128x3_float32.npy.zip"]
  29. )
  30. GITHUB_ASSETS_STEMS = [Path(k).stem for k in GITHUB_ASSETS_NAMES]
  31. def is_url(url, check=False):
  32. """
  33. Validates if the given string is a URL and optionally checks if the URL exists online.
  34. Args:
  35. url (str): The string to be validated as a URL.
  36. check (bool, optional): If True, performs an additional check to see if the URL exists online.
  37. Defaults to True.
  38. Returns:
  39. (bool): Returns True for a valid URL. If 'check' is True, also returns True if the URL exists online.
  40. Returns False otherwise.
  41. Example:
  42. ```python
  43. valid = is_url("https://www.example.com")
  44. ```
  45. """
  46. with contextlib.suppress(Exception):
  47. url = str(url)
  48. result = parse.urlparse(url)
  49. assert all([result.scheme, result.netloc]) # check if is url
  50. if check:
  51. with request.urlopen(url) as response:
  52. return response.getcode() == 200 # check if exists online
  53. return True
  54. return False
  55. def delete_dsstore(path, files_to_delete=(".DS_Store", "__MACOSX")):
  56. """
  57. Deletes all ".DS_store" files under a specified directory.
  58. Args:
  59. path (str, optional): The directory path where the ".DS_store" files should be deleted.
  60. files_to_delete (tuple): The files to be deleted.
  61. Example:
  62. ```python
  63. from ultralytics.utils.downloads import delete_dsstore
  64. delete_dsstore('path/to/dir')
  65. ```
  66. Note:
  67. ".DS_store" files are created by the Apple operating system and contain metadata about folders and files. They
  68. are hidden system files and can cause issues when transferring files between different operating systems.
  69. """
  70. for file in files_to_delete:
  71. matches = list(Path(path).rglob(file))
  72. LOGGER.info(f"Deleting {file} files: {matches}")
  73. for f in matches:
  74. f.unlink()
  75. def zip_directory(directory, compress=True, exclude=(".DS_Store", "__MACOSX"), progress=True):
  76. """
  77. Zips the contents of a directory, excluding files containing strings in the exclude list. The resulting zip file is
  78. named after the directory and placed alongside it.
  79. Args:
  80. directory (str | Path): The path to the directory to be zipped.
  81. compress (bool): Whether to compress the files while zipping. Default is True.
  82. exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
  83. progress (bool, optional): Whether to display a progress bar. Defaults to True.
  84. Returns:
  85. (Path): The path to the resulting zip file.
  86. Example:
  87. ```python
  88. from ultralytics.utils.downloads import zip_directory
  89. file = zip_directory('path/to/dir')
  90. ```
  91. """
  92. from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
  93. delete_dsstore(directory)
  94. directory = Path(directory)
  95. if not directory.is_dir():
  96. raise FileNotFoundError(f"Directory '{directory}' does not exist.")
  97. # Unzip with progress bar
  98. files_to_zip = [f for f in directory.rglob("*") if f.is_file() and all(x not in f.name for x in exclude)]
  99. zip_file = directory.with_suffix(".zip")
  100. compression = ZIP_DEFLATED if compress else ZIP_STORED
  101. with ZipFile(zip_file, "w", compression) as f:
  102. for file in TQDM(files_to_zip, desc=f"Zipping {directory} to {zip_file}...", unit="file", disable=not progress):
  103. f.write(file, file.relative_to(directory))
  104. return zip_file # return path to zip file
  105. def unzip_file(file, path=None, exclude=(".DS_Store", "__MACOSX"), exist_ok=False, progress=True):
  106. """
  107. Unzips a *.zip file to the specified path, excluding files containing strings in the exclude list.
  108. If the zipfile does not contain a single top-level directory, the function will create a new
  109. directory with the same name as the zipfile (without the extension) to extract its contents.
  110. If a path is not provided, the function will use the parent directory of the zipfile as the default path.
  111. Args:
  112. file (str): The path to the zipfile to be extracted.
  113. path (str, optional): The path to extract the zipfile to. Defaults to None.
  114. exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').
  115. exist_ok (bool, optional): Whether to overwrite existing contents if they exist. Defaults to False.
  116. progress (bool, optional): Whether to display a progress bar. Defaults to True.
  117. Raises:
  118. BadZipFile: If the provided file does not exist or is not a valid zipfile.
  119. Returns:
  120. (Path): The path to the directory where the zipfile was extracted.
  121. Example:
  122. ```python
  123. from ultralytics.utils.downloads import unzip_file
  124. dir = unzip_file('path/to/file.zip')
  125. ```
  126. """
  127. from zipfile import BadZipFile, ZipFile, is_zipfile
  128. if not (Path(file).exists() and is_zipfile(file)):
  129. raise BadZipFile(f"File '{file}' does not exist or is a bad zip file.")
  130. if path is None:
  131. path = Path(file).parent # default path
  132. # Unzip the file contents
  133. with ZipFile(file) as zipObj:
  134. files = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]
  135. top_level_dirs = {Path(f).parts[0] for f in files}
  136. # Decide to unzip directly or unzip into a directory
  137. unzip_as_dir = len(top_level_dirs) == 1 # (len(files) > 1 and not files[0].endswith("/"))
  138. if unzip_as_dir:
  139. # Zip has 1 top-level directory
  140. extract_path = path # i.e. ../datasets
  141. path = Path(path) / list(top_level_dirs)[0] # i.e. extract coco8/ dir to ../datasets/
  142. else:
  143. # Zip has multiple files at top level
  144. path = extract_path = Path(path) / Path(file).stem # i.e. extract multiple files to ../datasets/coco8/
  145. # Check if destination directory already exists and contains files
  146. if path.exists() and any(path.iterdir()) and not exist_ok:
  147. # If it exists and is not empty, return the path without unzipping
  148. LOGGER.warning(f"WARNING ⚠️ Skipping {file} unzip as destination directory {path} is not empty.")
  149. return path
  150. for f in TQDM(files, desc=f"Unzipping {file} to {Path(path).resolve()}...", unit="file", disable=not progress):
  151. # Ensure the file is within the extract_path to avoid path traversal security vulnerability
  152. if ".." in Path(f).parts:
  153. LOGGER.warning(f"Potentially insecure file path: {f}, skipping extraction.")
  154. continue
  155. zipObj.extract(f, extract_path)
  156. return path # return unzip dir
  157. def check_disk_space(url="https://ultralytics.com/assets/coco128.zip", path=Path.cwd(), sf=1.5, hard=True):
  158. """
  159. Check if there is sufficient disk space to download and store a file.
  160. Args:
  161. url (str, optional): The URL to the file. Defaults to 'https://ultralytics.com/assets/coco128.zip'.
  162. path (str | Path, optional): The path or drive to check the available free space on.
  163. sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 2.0.
  164. hard (bool, optional): Whether to throw an error or not on insufficient disk space. Defaults to True.
  165. Returns:
  166. (bool): True if there is sufficient disk space, False otherwise.
  167. """
  168. try:
  169. r = requests.head(url) # response
  170. assert r.status_code < 400, f"URL error for {url}: {r.status_code} {r.reason}" # check response
  171. except Exception:
  172. return True # requests issue, default to True
  173. # Check file size
  174. gib = 1 << 30 # bytes per GiB
  175. data = int(r.headers.get("Content-Length", 0)) / gib # file size (GB)
  176. total, used, free = (x / gib for x in shutil.disk_usage(path)) # bytes
  177. if data * sf < free:
  178. return True # sufficient space
  179. # Insufficient space
  180. text = (
  181. f"WARNING ⚠️ Insufficient free disk space {free:.1f} GB < {data * sf:.3f} GB required, "
  182. f"Please free {data * sf - free:.1f} GB additional disk space and try again."
  183. )
  184. if hard:
  185. raise MemoryError(text)
  186. LOGGER.warning(text)
  187. return False
  188. def get_google_drive_file_info(link):
  189. """
  190. Retrieves the direct download link and filename for a shareable Google Drive file link.
  191. Args:
  192. link (str): The shareable link of the Google Drive file.
  193. Returns:
  194. (str): Direct download URL for the Google Drive file.
  195. (str): Original filename of the Google Drive file. If filename extraction fails, returns None.
  196. Example:
  197. ```python
  198. from ultralytics.utils.downloads import get_google_drive_file_info
  199. link = "https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link"
  200. url, filename = get_google_drive_file_info(link)
  201. ```
  202. """
  203. file_id = link.split("/d/")[1].split("/view")[0]
  204. drive_url = f"https://drive.google.com/uc?export=download&id={file_id}"
  205. filename = None
  206. # Start session
  207. with requests.Session() as session:
  208. response = session.get(drive_url, stream=True)
  209. if "quota exceeded" in str(response.content.lower()):
  210. raise ConnectionError(
  211. emojis(
  212. f"❌ Google Drive file download quota exceeded. "
  213. f"Please try again later or download this file manually at {link}."
  214. )
  215. )
  216. for k, v in response.cookies.items():
  217. if k.startswith("download_warning"):
  218. drive_url += f"&confirm={v}" # v is token
  219. cd = response.headers.get("content-disposition")
  220. if cd:
  221. filename = re.findall('filename="(.+)"', cd)[0]
  222. return drive_url, filename
  223. def safe_download(
  224. url,
  225. file=None,
  226. dir=None,
  227. unzip=True,
  228. delete=False,
  229. curl=False,
  230. retry=3,
  231. min_bytes=1e0,
  232. exist_ok=False,
  233. progress=True,
  234. ):
  235. """
  236. Downloads files from a URL, with options for retrying, unzipping, and deleting the downloaded file.
  237. Args:
  238. url (str): The URL of the file to be downloaded.
  239. file (str, optional): The filename of the downloaded file.
  240. If not provided, the file will be saved with the same name as the URL.
  241. dir (str, optional): The directory to save the downloaded file.
  242. If not provided, the file will be saved in the current working directory.
  243. unzip (bool, optional): Whether to unzip the downloaded file. Default: True.
  244. delete (bool, optional): Whether to delete the downloaded file after unzipping. Default: False.
  245. curl (bool, optional): Whether to use curl command line tool for downloading. Default: False.
  246. retry (int, optional): The number of times to retry the download in case of failure. Default: 3.
  247. min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered
  248. a successful download. Default: 1E0.
  249. exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.
  250. progress (bool, optional): Whether to display a progress bar during the download. Default: True.
  251. Example:
  252. ```python
  253. from ultralytics.utils.downloads import safe_download
  254. link = "https://ultralytics.com/assets/bus.jpg"
  255. path = safe_download(link)
  256. ```
  257. """
  258. gdrive = url.startswith("https://drive.google.com/") # check if the URL is a Google Drive link
  259. if gdrive:
  260. url, file = get_google_drive_file_info(url)
  261. f = Path(dir or ".") / (file or url2file(url)) # URL converted to filename
  262. if "://" not in str(url) and Path(url).is_file(): # URL exists ('://' check required in Windows Python<3.10)
  263. f = Path(url) # filename
  264. elif not f.is_file(): # URL and file do not exist
  265. desc = f"Downloading {url if gdrive else clean_url(url)} to '{f}'"
  266. LOGGER.info(f"{desc}...")
  267. f.parent.mkdir(parents=True, exist_ok=True) # make directory if missing
  268. check_disk_space(url, path=f.parent)
  269. for i in range(retry + 1):
  270. try:
  271. if curl or i > 0: # curl download with retry, continue
  272. s = "sS" * (not progress) # silent
  273. r = subprocess.run(["curl", "-#", f"-{s}L", url, "-o", f, "--retry", "3", "-C", "-"]).returncode
  274. assert r == 0, f"Curl return value {r}"
  275. else: # urllib download
  276. method = "torch"
  277. if method == "torch":
  278. torch.hub.download_url_to_file(url, f, progress=progress)
  279. else:
  280. with request.urlopen(url) as response, TQDM(
  281. total=int(response.getheader("Content-Length", 0)),
  282. desc=desc,
  283. disable=not progress,
  284. unit="B",
  285. unit_scale=True,
  286. unit_divisor=1024,
  287. ) as pbar:
  288. with open(f, "wb") as f_opened:
  289. for data in response:
  290. f_opened.write(data)
  291. pbar.update(len(data))
  292. if f.exists():
  293. if f.stat().st_size > min_bytes:
  294. break # success
  295. f.unlink() # remove partial downloads
  296. except Exception as e:
  297. if i == 0 and not is_online():
  298. raise ConnectionError(emojis(f"❌ Download failure for {url}. Environment is not online.")) from e
  299. elif i >= retry:
  300. raise ConnectionError(emojis(f"❌ Download failure for {url}. Retry limit reached.")) from e
  301. LOGGER.warning(f"⚠️ Download failure, retrying {i + 1}/{retry} {url}...")
  302. if unzip and f.exists() and f.suffix in {"", ".zip", ".tar", ".gz"}:
  303. from zipfile import is_zipfile
  304. unzip_dir = (dir or f.parent).resolve() # unzip to dir if provided else unzip in place
  305. if is_zipfile(f):
  306. unzip_dir = unzip_file(file=f, path=unzip_dir, exist_ok=exist_ok, progress=progress) # unzip
  307. elif f.suffix in {".tar", ".gz"}:
  308. LOGGER.info(f"Unzipping {f} to {unzip_dir}...")
  309. subprocess.run(["tar", "xf" if f.suffix == ".tar" else "xfz", f, "--directory", unzip_dir], check=True)
  310. if delete:
  311. f.unlink() # remove zip
  312. return unzip_dir
  313. def get_github_assets(repo="ultralytics/assets", version="latest", retry=False):
  314. """
  315. Retrieve the specified version's tag and assets from a GitHub repository. If the version is not specified, the
  316. function fetches the latest release assets.
  317. Args:
  318. repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
  319. version (str, optional): The release version to fetch assets from. Defaults to 'latest'.
  320. retry (bool, optional): Flag to retry the request in case of a failure. Defaults to False.
  321. Returns:
  322. (tuple): A tuple containing the release tag and a list of asset names.
  323. Example:
  324. ```python
  325. tag, assets = get_github_assets(repo='ultralytics/assets', version='latest')
  326. ```
  327. """
  328. if version != "latest":
  329. version = f"tags/{version}" # i.e. tags/v6.2
  330. url = f"https://api.github.com/repos/{repo}/releases/{version}"
  331. r = requests.get(url) # github api
  332. if r.status_code != 200 and r.reason != "rate limit exceeded" and retry: # failed and not 403 rate limit exceeded
  333. r = requests.get(url) # try again
  334. if r.status_code != 200:
  335. LOGGER.warning(f"⚠️ GitHub assets check failure for {url}: {r.status_code} {r.reason}")
  336. return "", []
  337. data = r.json()
  338. return data["tag_name"], [x["name"] for x in data["assets"]] # tag, assets i.e. ['yolov8n.pt', 'yolov8s.pt', ...]
  339. def attempt_download_asset(file, repo="ultralytics/assets", release="v8.2.0", **kwargs):
  340. """
  341. Attempt to download a file from GitHub release assets if it is not found locally. The function checks for the file
  342. locally first, then tries to download it from the specified GitHub repository release.
  343. Args:
  344. file (str | Path): The filename or file path to be downloaded.
  345. repo (str, optional): The GitHub repository in the format 'owner/repo'. Defaults to 'ultralytics/assets'.
  346. release (str, optional): The specific release version to be downloaded. Defaults to 'v8.2.0'.
  347. **kwargs (any): Additional keyword arguments for the download process.
  348. Returns:
  349. (str): The path to the downloaded file.
  350. Example:
  351. ```python
  352. file_path = attempt_download_asset('yolov8n.pt', repo='ultralytics/assets', release='latest')
  353. ```
  354. """
  355. from ultralytics.utils import SETTINGS # scoped for circular import
  356. # YOLOv3/5u updates
  357. file = str(file)
  358. file = checks.check_yolov5u_filename(file)
  359. file = Path(file.strip().replace("'", ""))
  360. if file.exists():
  361. return str(file)
  362. elif (SETTINGS["weights_dir"] / file).exists():
  363. return str(SETTINGS["weights_dir"] / file)
  364. else:
  365. # URL specified
  366. name = Path(parse.unquote(str(file))).name # decode '%2F' to '/' etc.
  367. download_url = f"https://github.com/{repo}/releases/download"
  368. if str(file).startswith(("http:/", "https:/")): # download
  369. url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
  370. file = url2file(name) # parse authentication https://url.com/file.txt?auth...
  371. if Path(file).is_file():
  372. LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
  373. else:
  374. safe_download(url=url, file=file, min_bytes=1e5, **kwargs)
  375. elif repo == GITHUB_ASSETS_REPO and name in GITHUB_ASSETS_NAMES:
  376. safe_download(url=f"{download_url}/{release}/{name}", file=file, min_bytes=1e5, **kwargs)
  377. else:
  378. tag, assets = get_github_assets(repo, release)
  379. if not assets:
  380. tag, assets = get_github_assets(repo) # latest release
  381. if name in assets:
  382. safe_download(url=f"{download_url}/{tag}/{name}", file=file, min_bytes=1e5, **kwargs)
  383. return str(file)
  384. def download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=1, retry=3, exist_ok=False):
  385. """
  386. Downloads files from specified URLs to a given directory. Supports concurrent downloads if multiple threads are
  387. specified.
  388. Args:
  389. url (str | list): The URL or list of URLs of the files to be downloaded.
  390. dir (Path, optional): The directory where the files will be saved. Defaults to the current working directory.
  391. unzip (bool, optional): Flag to unzip the files after downloading. Defaults to True.
  392. delete (bool, optional): Flag to delete the zip files after extraction. Defaults to False.
  393. curl (bool, optional): Flag to use curl for downloading. Defaults to False.
  394. threads (int, optional): Number of threads to use for concurrent downloads. Defaults to 1.
  395. retry (int, optional): Number of retries in case of download failure. Defaults to 3.
  396. exist_ok (bool, optional): Whether to overwrite existing contents during unzipping. Defaults to False.
  397. Example:
  398. ```python
  399. download('https://ultralytics.com/assets/example.zip', dir='path/to/dir', unzip=True)
  400. ```
  401. """
  402. dir = Path(dir)
  403. dir.mkdir(parents=True, exist_ok=True) # make directory
  404. if threads > 1:
  405. with ThreadPool(threads) as pool:
  406. pool.map(
  407. lambda x: safe_download(
  408. url=x[0],
  409. dir=x[1],
  410. unzip=unzip,
  411. delete=delete,
  412. curl=curl,
  413. retry=retry,
  414. exist_ok=exist_ok,
  415. progress=threads <= 1,
  416. ),
  417. zip(url, repeat(dir)),
  418. )
  419. pool.close()
  420. pool.join()
  421. else:
  422. for u in [url] if isinstance(url, (str, Path)) else url:
  423. safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry, exist_ok=exist_ok)