Sa-m commited on
Commit
cdbfa77
1 Parent(s): 4c7f4ca

Upload google_utils.py

Browse files
Files changed (1) hide show
  1. utils/google_utils.py +123 -0
utils/google_utils.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2
+
3
+ import os
4
+ import platform
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import requests
10
+ import torch
11
+
12
+
13
+ def gsutil_getsize(url=''):
14
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17
+
18
+
19
+ def attempt_download(file, repo='WongKinYiu/yolov7'):
20
+ # Attempt file download if does not exist
21
+ 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 api
26
+ assets = [x['name'] for x in response['assets']] # release assets
27
+ tag = response['tag_name'] # i.e. 'v1.0'
28
+ except: # fallback plan
29
+ 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.name
34
+ if name in assets:
35
+ msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
36
+ redundant = False # second download option
37
+ try: # GitHub
38
+ 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 # check
42
+ except Exception as e: # GCP
43
+ 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: # check
50
+ file.unlink(missing_ok=True) # remove partial downloads
51
+ print(f'ERROR: Download failure: {msg}')
52
+ print('')
53
+ return
54
+
55
+
56
+ def 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 cookie
61
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
62
+ file.unlink(missing_ok=True) # remove existing file
63
+ cookie.unlink(missing_ok=True) # remove existing cookie
64
+
65
+ # Attempt file download
66
+ 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 file
69
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
70
+ else: # small file
71
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
72
+ r = os.system(s) # execute, capture return
73
+ cookie.unlink(missing_ok=True) # remove existing cookie
74
+
75
+ # Error check
76
+ if r != 0:
77
+ file.unlink(missing_ok=True) # remove partial
78
+ print('Download error ') # raise Exception('Download error')
79
+ return r
80
+
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
+
87
+ print(f'Done ({time.time() - t:.1f}s)')
88
+ return r
89
+
90
+
91
+ def 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 bucket
100
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
101
+ #
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 bucket
115
+ # 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))