You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 line
5.5KB

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