downloads.py 18 KB

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