CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/utils/downloads.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Download utils
4
"""
5
6
import os
7
import platform
8
import subprocess
9
import time
10
import urllib
11
from pathlib import Path
12
from zipfile import ZipFile
13
14
import requests
15
import torch
16
17
18
def gsutil_getsize(url=''):
19
# gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
20
s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
21
return eval(s.split(' ')[0]) if len(s) else 0 # bytes
22
23
24
def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
25
# Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
26
file = Path(file)
27
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
28
try: # url1
29
print(f'Downloading {url} to {file}...')
30
torch.hub.download_url_to_file(url, str(file))
31
assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
32
except Exception as e: # url2
33
file.unlink(missing_ok=True) # remove partial downloads
34
print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
35
os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
36
finally:
37
if not file.exists() or file.stat().st_size < min_bytes: # check
38
file.unlink(missing_ok=True) # remove partial downloads
39
print(f"ERROR: {assert_msg}\n{error_msg}")
40
print('')
41
42
43
def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download()
44
# Attempt file download if does not exist
45
file = Path(str(file).strip().replace("'", ''))
46
47
if not file.exists():
48
# URL specified
49
name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
50
if str(file).startswith(('http:/', 'https:/')): # download
51
url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
52
file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
53
if Path(file).is_file():
54
print(f'Found {url} locally at {file}') # file already exists
55
else:
56
safe_download(file=file, url=url, min_bytes=1E5)
57
return file
58
59
# GitHub assets
60
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
61
try:
62
response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
63
assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
64
tag = response['tag_name'] # i.e. 'v1.0'
65
except: # fallback plan
66
assets = ['yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
67
'yolov5n6.pt', 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
68
try:
69
tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
70
except:
71
tag = 'v6.0' # current release
72
73
if name in assets:
74
safe_download(file,
75
url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
76
# url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional)
77
min_bytes=1E5,
78
error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/')
79
80
return str(file)
81
82
83
def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
84
# Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
85
t = time.time()
86
file = Path(file)
87
cookie = Path('cookie') # gdrive cookie
88
print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
89
file.unlink(missing_ok=True) # remove existing file
90
cookie.unlink(missing_ok=True) # remove existing cookie
91
92
# Attempt file download
93
out = "NUL" if platform.system() == "Windows" else "/dev/null"
94
os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
95
if os.path.exists('cookie'): # large file
96
s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
97
else: # small file
98
s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
99
r = os.system(s) # execute, capture return
100
cookie.unlink(missing_ok=True) # remove existing cookie
101
102
# Error check
103
if r != 0:
104
file.unlink(missing_ok=True) # remove partial
105
print('Download error ') # raise Exception('Download error')
106
return r
107
108
# Unzip if archive
109
if file.suffix == '.zip':
110
print('unzipping... ', end='')
111
ZipFile(file).extractall(path=file.parent) # unzip
112
file.unlink() # remove zip
113
114
print(f'Done ({time.time() - t:.1f}s)')
115
return r
116
117
118
def get_token(cookie="./cookie"):
119
with open(cookie) as f:
120
for line in f:
121
if "download" in line:
122
return line.split()[-1]
123
return ""
124
125
# Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
126
#
127
#
128
# def upload_blob(bucket_name, source_file_name, destination_blob_name):
129
# # Uploads a file to a bucket
130
# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
131
#
132
# storage_client = storage.Client()
133
# bucket = storage_client.get_bucket(bucket_name)
134
# blob = bucket.blob(destination_blob_name)
135
#
136
# blob.upload_from_filename(source_file_name)
137
#
138
# print('File {} uploaded to {}.'.format(
139
# source_file_name,
140
# destination_blob_name))
141
#
142
#
143
# def download_blob(bucket_name, source_blob_name, destination_file_name):
144
# # Uploads a blob from a bucket
145
# storage_client = storage.Client()
146
# bucket = storage_client.get_bucket(bucket_name)
147
# blob = bucket.blob(source_blob_name)
148
#
149
# blob.download_to_filename(destination_file_name)
150
#
151
# print('Blob {} downloaded to {}.'.format(
152
# source_blob_name,
153
# destination_file_name))
154
155