Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/utils/downloads.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Download utils3"""45import os6import platform7import subprocess8import time9import urllib10from pathlib import Path11from zipfile import ZipFile1213import requests14import torch151617def gsutil_getsize(url=''):18# gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du19s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')20return eval(s.split(' ')[0]) if len(s) else 0 # bytes212223def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):24# Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes25file = Path(file)26assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"27try: # url128print(f'Downloading {url} to {file}...')29torch.hub.download_url_to_file(url, str(file))30assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check31except Exception as e: # url232file.unlink(missing_ok=True) # remove partial downloads33print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')34os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail35finally:36if not file.exists() or file.stat().st_size < min_bytes: # check37file.unlink(missing_ok=True) # remove partial downloads38print(f"ERROR: {assert_msg}\n{error_msg}")39print('')404142def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download()43# Attempt file download if does not exist44file = Path(str(file).strip().replace("'", ''))4546if not file.exists():47# URL specified48name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.49if str(file).startswith(('http:/', 'https:/')): # download50url = str(file).replace(':/', '://') # Pathlib turns :// -> :/51file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...52if Path(file).is_file():53print(f'Found {url} locally at {file}') # file already exists54else:55safe_download(file=file, url=url, min_bytes=1E5)56return file5758# GitHub assets59file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)60try:61response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api62assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]63tag = response['tag_name'] # i.e. 'v1.0'64except: # fallback plan65assets = ['yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',66'yolov5n6.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']67try:68tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]69except:70tag = 'v6.0' # current release7172if name in assets:73safe_download(file,74url=f'https://github.com/{repo}/releases/download/{tag}/{name}',75# url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional)76min_bytes=1E5,77error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/')7879return str(file)808182def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):83# Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()84t = time.time()85file = Path(file)86cookie = Path('cookie') # gdrive cookie87print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')88file.unlink(missing_ok=True) # remove existing file89cookie.unlink(missing_ok=True) # remove existing cookie9091# Attempt file download92out = "NUL" if platform.system() == "Windows" else "/dev/null"93os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')94if os.path.exists('cookie'): # large file95s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'96else: # small file97s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'98r = os.system(s) # execute, capture return99cookie.unlink(missing_ok=True) # remove existing cookie100101# Error check102if r != 0:103file.unlink(missing_ok=True) # remove partial104print('Download error ') # raise Exception('Download error')105return r106107# Unzip if archive108if file.suffix == '.zip':109print('unzipping... ', end='')110ZipFile(file).extractall(path=file.parent) # unzip111file.unlink() # remove zip112113print(f'Done ({time.time() - t:.1f}s)')114return r115116117def get_token(cookie="./cookie"):118with open(cookie) as f:119for line in f:120if "download" in line:121return line.split()[-1]122return ""123124# Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------125#126#127# def upload_blob(bucket_name, source_file_name, destination_blob_name):128# # Uploads a file to a bucket129# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python130#131# storage_client = storage.Client()132# bucket = storage_client.get_bucket(bucket_name)133# blob = bucket.blob(destination_blob_name)134#135# blob.upload_from_filename(source_file_name)136#137# print('File {} uploaded to {}.'.format(138# source_file_name,139# destination_blob_name))140#141#142# def download_blob(bucket_name, source_blob_name, destination_file_name):143# # Uploads a blob from a bucket144# storage_client = storage.Client()145# bucket = storage_client.get_bucket(bucket_name)146# blob = bucket.blob(source_blob_name)147#148# blob.download_to_filename(destination_file_name)149#150# print('Blob {} downloaded to {}.'.format(151# source_blob_name,152# destination_file_name))153154155