Skip to content

Commit 8331104

Browse files
authored
GitHub API rate limit fix (ultralytics#1894)
1 parent 66648ae commit 8331104

File tree

1 file changed

+47
-45
lines changed

1 file changed

+47
-45
lines changed

utils/google_utils.py

Lines changed: 47 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -12,71 +12,73 @@
1212

1313
def gsutil_getsize(url=''):
1414
# gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15-
s = subprocess.check_output('gsutil du %s' % url, shell=True).decode('utf-8')
15+
s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
1616
return eval(s.split(' ')[0]) if len(s) else 0 # bytes
1717

1818

19-
def attempt_download(weights):
20-
# Attempt to download pretrained weights if not found locally
21-
weights = str(weights).strip().replace("'", '')
22-
file = Path(weights).name.lower()
23-
24-
msg = weights + ' missing, try downloading from https://github.com/ultralytics/yolov5/releases/'
25-
response = requests.get('https://api.github.com/repos/ultralytics/yolov5/releases/latest').json() # github api
26-
assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
27-
redundant = False # second download option
28-
29-
if file in assets and not os.path.isfile(weights):
30-
try: # GitHub
31-
tag = response['tag_name'] # i.e. 'v1.0'
32-
url = f'https://github.com/ultralytics/yolov5/releases/download/{tag}/{file}'
33-
print('Downloading %s to %s...' % (url, weights))
34-
torch.hub.download_url_to_file(url, weights)
35-
assert os.path.exists(weights) and os.path.getsize(weights) > 1E6 # check
36-
except Exception as e: # GCP
37-
print('Download error: %s' % e)
38-
assert redundant, 'No secondary mirror'
39-
url = 'https://storage.googleapis.com/ultralytics/yolov5/ckpt/' + file
40-
print('Downloading %s to %s...' % (url, weights))
41-
r = os.system('curl -L %s -o %s' % (url, weights)) # torch.hub.download_url_to_file(url, weights)
42-
finally:
43-
if not (os.path.exists(weights) and os.path.getsize(weights) > 1E6): # check
44-
os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
45-
print('ERROR: Download failure: %s' % msg)
46-
print('')
47-
return
48-
49-
50-
def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', name='tmp.zip'):
19+
def attempt_download(file):
20+
# Attempt file download if does not exist
21+
file = Path(str(file).strip().replace("'", '').lower())
22+
23+
if not file.exists():
24+
response = requests.get('https://api.github.com/repos/ultralytics/yolov5/releases/latest').json() # github api
25+
assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
26+
name = file.name
27+
28+
if name in assets:
29+
msg = f'{file} missing, try downloading from https://github.com/ultralytics/yolov5/releases/'
30+
redundant = False # second download option
31+
try: # GitHub
32+
tag = response['tag_name'] # i.e. 'v1.0'
33+
url = f'https://github.com/ultralytics/yolov5/releases/download/{tag}/{name}'
34+
print(f'Downloading {url} to {file}...')
35+
torch.hub.download_url_to_file(url, file)
36+
assert file.exists() and file.stat().st_size > 1E6 # check
37+
except Exception as e: # GCP
38+
print(f'Download error: {e}')
39+
assert redundant, 'No secondary mirror'
40+
url = f'https://storage.googleapis.com/ultralytics/yolov5/ckpt/{name}'
41+
print(f'Downloading {url} to {file}...')
42+
os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
43+
finally:
44+
if not file.exists() or file.stat().st_size < 1E6: # check
45+
file.unlink(missing_ok=True) # remove partial downloads
46+
print(f'ERROR: Download failure: {msg}')
47+
return
48+
49+
50+
def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
5151
# Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download()
5252
t = time.time()
53-
print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')
54-
os.remove(name) if os.path.exists(name) else None # remove existing
55-
os.remove('cookie') if os.path.exists('cookie') else None
53+
file = Path(file)
54+
cookie = Path('cookie') # gdrive cookie
55+
print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
56+
file.unlink(missing_ok=True) # remove existing file
57+
cookie.unlink(missing_ok=True) # remove existing cookie
5658

5759
# Attempt file download
5860
out = "NUL" if platform.system() == "Windows" else "/dev/null"
59-
os.system('curl -c ./cookie -s -L "drive.google.com/uc?export=download&id=%s" > %s ' % (id, out))
61+
os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
6062
if os.path.exists('cookie'): # large file
61-
s = 'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm=%s&id=%s" -o %s' % (get_token(), id, name)
63+
s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
6264
else: # small file
63-
s = 'curl -s -L -o %s "drive.google.com/uc?export=download&id=%s"' % (name, id)
65+
s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
6466
r = os.system(s) # execute, capture return
65-
os.remove('cookie') if os.path.exists('cookie') else None
67+
cookie.unlink(missing_ok=True) # remove existing cookie
6668

6769
# Error check
6870
if r != 0:
69-
os.remove(name) if os.path.exists(name) else None # remove partial
71+
file.unlink(missing_ok=True) # remove partial
7072
print('Download error ') # raise Exception('Download error')
7173
return r
7274

7375
# Unzip if archive
74-
if name.endswith('.zip'):
76+
if file.suffix == '.zip':
7577
print('unzipping... ', end='')
76-
os.system('unzip -q %s' % name) # unzip
77-
os.remove(name) # remove zip to free space
78+
os.system(f'unzip -q {file}') # unzip
79+
file.unlink() # remove zip to free space
7880

79-
print('Done (%.1fs)' % (time.time() - t))
81+
print(f'Done ({time.time() - t:.1f}s)')
8082
return r
8183

8284

0 commit comments

Comments
 (0)