SudiptaKumar/object_detection
0
1# Google utils: https://cloud.google.com/storage/docs/reference/libraries2 3import os4import platform5import subprocess6import time7from pathlib import Path8 9import requests10import torch11 12 13def gsutil_getsize(url=''):14 # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du15 s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')16 return eval(s.split(' ')[0]) if len(s) else 0 # bytes17 18 19def attempt_download(file, repo='WongKinYiu/yolov7'):20 # Attempt file download if does not exist21 file = Path(str(file).strip().replace("'", '').lower())22 23 if not file.exists():24 try:25 response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api26 assets = [x['name'] for x in response['assets']] # release assets27 tag = response['tag_name'] # i.e. 'v1.0'28 except: # fallback plan29 assets = ['yolov7.pt', 'yolov7-tiny.pt', 'yolov7x.pt', 'yolov7-d6.pt', 'yolov7-e6.pt', 30 'yolov7-e6e.pt', 'yolov7-w6.pt']31 tag = subprocess.check_output('git tag', shell=True).decode().split()[-1]32 33 name = file.name34 if name in assets:35 msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'36 redundant = False # second download option37 try: # GitHub38 url = f'https://github.com/{repo}/releases/download/{tag}/{name}'39 print(f'Downloading {url} to {file}...')40 torch.hub.download_url_to_file(url, file)41 assert file.exists() and file.stat().st_size > 1E6 # check42 except Exception as e: # GCP43 print(f'Download error: {e}')44 assert redundant, 'No secondary mirror'45 url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'46 print(f'Downloading {url} to {file}...')47 os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)48 finally:49 if not file.exists() or file.stat().st_size < 1E6: # check50 file.unlink(missing_ok=True) # remove partial downloads51 print(f'ERROR: Download failure: {msg}')52 print('')53 return54 55 56def gdrive_download(id='', file='tmp.zip'):57 # Downloads a file from Google Drive. from yolov7.utils.google_utils import *; gdrive_download()58 t = time.time()59 file = Path(file)60 cookie = Path('cookie') # gdrive cookie61 print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')62 file.unlink(missing_ok=True) # remove existing file63 cookie.unlink(missing_ok=True) # remove existing cookie64 65 # Attempt file download66 out = "NUL" if platform.system() == "Windows" else "/dev/null"67 os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')68 if os.path.exists('cookie'): # large file69 s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'70 else: # small file71 s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'72 r = os.system(s) # execute, capture return73 cookie.unlink(missing_ok=True) # remove existing cookie74 75 # Error check76 if r != 0:77 file.unlink(missing_ok=True) # remove partial78 print('Download error ') # raise Exception('Download error')79 return r80 81 # Unzip if archive82 if file.suffix == '.zip':83 print('unzipping... ', end='')84 os.system(f'unzip -q {file}') # unzip85 file.unlink() # remove zip to free space86 87 print(f'Done ({time.time() - t:.1f}s)')88 return r89 90 91def get_token(cookie="./cookie"):92 with open(cookie) as f:93 for line in f:94 if "download" in line:95 return line.split()[-1]96 return ""97 98# def upload_blob(bucket_name, source_file_name, destination_blob_name):99# # Uploads a file to a bucket100# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python101#102# storage_client = storage.Client()103# bucket = storage_client.get_bucket(bucket_name)104# blob = bucket.blob(destination_blob_name)105#106# blob.upload_from_filename(source_file_name)107#108# print('File {} uploaded to {}.'.format(109# source_file_name,110# destination_blob_name))111#112#113# def download_blob(bucket_name, source_blob_name, destination_file_name):114# # Uploads a blob from a bucket115# storage_client = storage.Client()116# bucket = storage_client.get_bucket(bucket_name)117# blob = bucket.blob(source_blob_name)118#119# blob.download_to_filename(destination_file_name)120#121# print('Blob {} downloaded to {}.'.format(122# source_blob_name,123# destination_file_name))124 