基于Yolov7的路面病害检测代码
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

124 lines
4.8KB

  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 attempt_download(file, repo='WongKinYiu/yolov7'):
  14. # Attempt file download if does not exist
  15. file = Path(str(file).strip().replace("'", '').lower())
  16. if not file.exists():
  17. try:
  18. response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
  19. assets = [x['name'] for x in response['assets']] # release assets
  20. tag = response['tag_name'] # i.e. 'v1.0'
  21. except: # fallback plan
  22. assets = ['yolov7.pt', 'yolov7-tiny.pt', 'yolov7x.pt', 'yolov7-d6.pt', 'yolov7-e6.pt',
  23. 'yolov7-e6e.pt', 'yolov7-w6.pt']
  24. tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]
  25. name = file.name
  26. if name in assets:
  27. msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
  28. redundant = False # second download option
  29. try: # GitHub
  30. url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
  31. print(f'Downloading {url} to {file}...')
  32. torch.hub.download_url_to_file(url, file)
  33. assert file.exists() and file.stat().st_size > 1E6 # check
  34. except Exception as e: # GCP
  35. print(f'Download error: {e}')
  36. assert redundant, 'No secondary mirror'
  37. url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
  38. print(f'Downloading {url} to {file}...')
  39. os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
  40. finally:
  41. if not file.exists() or file.stat().st_size < 1E6: # check
  42. file.unlink(missing_ok=True) # remove partial downloads
  43. print(f'ERROR: Download failure: {msg}')
  44. print('')
  45. return
  46. def gdrive_download(id='', file='tmp.zip'):
  47. # Downloads a file from Google Drive. from yolov7.utils.google_utils import *; gdrive_download()
  48. t = time.time()
  49. file = Path(file)
  50. cookie = Path('cookie') # gdrive cookie
  51. print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
  52. file.unlink(missing_ok=True) # remove existing file
  53. cookie.unlink(missing_ok=True) # remove existing cookie
  54. # Attempt file download
  55. out = "NUL" if platform.system() == "Windows" else "/dev/null"
  56. os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
  57. if os.path.exists('cookie'): # large file
  58. s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
  59. else: # small file
  60. s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
  61. r = os.system(s) # execute, capture return
  62. cookie.unlink(missing_ok=True) # remove existing cookie
  63. # Error check
  64. if r != 0:
  65. file.unlink(missing_ok=True) # remove partial
  66. print('Download error ') # raise Exception('Download error')
  67. return r
  68. # Unzip if archive
  69. if file.suffix == '.zip':
  70. print('unzipping... ', end='')
  71. os.system(f'unzip -q {file}') # unzip
  72. file.unlink() # remove zip to free space
  73. print(f'Done ({time.time() - t:.1f}s)')
  74. return r
  75. def get_token(cookie="./cookie"):
  76. with open(cookie) as f:
  77. for line in f:
  78. if "download" in line:
  79. return line.split()[-1]
  80. return ""
  81. # def upload_blob(bucket_name, source_file_name, destination_blob_name):
  82. # # Uploads a file to a bucket
  83. # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
  84. #
  85. # storage_client = storage.Client()
  86. # bucket = storage_client.get_bucket(bucket_name)
  87. # blob = bucket.blob(destination_blob_name)
  88. #
  89. # blob.upload_from_filename(source_file_name)
  90. #
  91. # print('File {} uploaded to {}.'.format(
  92. # source_file_name,
  93. # destination_blob_name))
  94. #
  95. #
  96. # def download_blob(bucket_name, source_blob_name, destination_file_name):
  97. # # Uploads a blob from a bucket
  98. # storage_client = storage.Client()
  99. # bucket = storage_client.get_bucket(bucket_name)
  100. # blob = bucket.blob(source_blob_name)
  101. #
  102. # blob.download_to_filename(destination_file_name)
  103. #
  104. # print('Blob {} downloaded to {}.'.format(
  105. # source_blob_name,
  106. # destination_file_name))