Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#643 PPYolo-E

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-344-PP-Yolo-E-Training-Replicate-Recipe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
  1. import os
  2. import sys
  3. from io import StringIO, BytesIO
  4. from typing import List
  5. import botocore
  6. from super_gradients.common.aws_connection.aws_connector import AWSConnector
  7. from super_gradients.common.decorators.explicit_params_validator import explicit_params_validation
  8. from super_gradients.common.abstractions.abstract_logger import ILogger
  9. class KeyNotExistInBucketError(Exception):
  10. pass
  11. class S3Connector(ILogger):
  12. """
  13. S3Connector - S3 Connection Manager
  14. """
  15. def __init__(self, env: str, bucket_name: str):
  16. """
  17. :param s3_bucket:
  18. """
  19. super().__init__()
  20. self.env = env
  21. self.bucket_name = bucket_name
  22. self.s3_client = AWSConnector.get_aws_client_for_service_name(profile_name=env, service_name="s3")
  23. self.s3_resource = AWSConnector.get_aws_resource_for_service_name(profile_name=env, service_name="s3")
  24. @explicit_params_validation(validation_type="NoneOrEmpty")
  25. def check_key_exists(self, s3_key_to_check: str) -> bool:
  26. """
  27. check_key_exists - Checks if an S3 key exists
  28. :param s3_key_to_check:
  29. :return:
  30. """
  31. try:
  32. self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key_to_check)
  33. except botocore.exceptions.ClientError as ex:
  34. if ex.response["Error"]["Code"] == "404":
  35. return False
  36. else:
  37. self._logger.error("Failed to check key: " + str(s3_key_to_check) + " existence in bucket" + str(self.bucket_name))
  38. return None
  39. else:
  40. return True
  41. @explicit_params_validation(validation_type="NoneOrEmpty")
  42. def get_object_by_etag(self, bucket_relative_file_name: str, etag: str) -> object:
  43. """
  44. get_object_by_etag - Gets S3 object by it's ETag heder if it. exists
  45. :param bucket_relative_file_name: The name of the file in the bucket (relative)
  46. :param etag: The ETag of the object in S3
  47. :return:
  48. """
  49. try:
  50. etag = etag.strip('"')
  51. s3_object = self.s3_client.get_object(Bucket=self.bucket_name, Key=bucket_relative_file_name, IfMatch=etag)
  52. return s3_object
  53. except botocore.exceptions.ClientError as ex:
  54. if ex.response["Error"]["Code"] == "404":
  55. return False
  56. else:
  57. self._logger.error("Failed to check ETag: " + str(etag) + " existence in bucket " + str(self.bucket_name))
  58. return
  59. @explicit_params_validation(validation_type="NoneOrEmpty")
  60. def create_bucket(self) -> bool:
  61. """
  62. Creates a bucket with the initialized bucket name.
  63. :return: The new bucket response
  64. :raises ClientError: If the creation failed for any reason.
  65. """
  66. try:
  67. # TODO: Change bucket_owner_arn to the company's proper IAM Role
  68. self._logger.info("Creating Bucket: " + self.bucket_name)
  69. create_bucket_response = self.s3_client.create_bucket(ACL="private", Bucket=self.bucket_name)
  70. self._logger.info(f"Successfully created bucket: {create_bucket_response}")
  71. # Changing the bucket public access block to be private (disable public access)
  72. self._logger.debug("Disabling public access to the bucket...")
  73. self.s3_client.put_public_access_block(
  74. PublicAccessBlockConfiguration={"BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True},
  75. Bucket=self.bucket_name,
  76. )
  77. return create_bucket_response
  78. except botocore.exceptions.ClientError as err:
  79. self._logger.fatal(f'Failed to create bucket "{self.bucket_name}": {err}')
  80. raise
  81. @explicit_params_validation(validation_type="NoneOrEmpty")
  82. def delete_bucket(self):
  83. """
  84. Deletes a bucket with the initialized bucket name.
  85. :return: True if succeeded.
  86. :raises ClientError: If the creation failed for any reason.
  87. """
  88. try:
  89. self._logger.info("Deleting Bucket: " + self.bucket_name + " from S3")
  90. bucket = self.s3_resource.Bucket(self.bucket_name)
  91. bucket.objects.all().delete()
  92. bucket.delete()
  93. self._logger.debug("Successfully Deleted Bucket: " + self.bucket_name + " from S3")
  94. except botocore.exceptions.ClientError as ex:
  95. self._logger.fatal(f"Failed to delete bucket {self.bucket_name}: {ex}")
  96. raise ex
  97. return True
  98. @explicit_params_validation(validation_type="NoneOrEmpty")
  99. def get_object_metadata(self, s3_key: str):
  100. try:
  101. return self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key)
  102. except botocore.exceptions.ClientError as ex:
  103. if ex.response["Error"]["Code"] == "404":
  104. msg = "[" + sys._getframe().f_code.co_name + "] - Key does not exist in bucket)"
  105. self._logger.error(msg)
  106. raise KeyNotExistInBucketError(msg)
  107. raise ex
  108. @explicit_params_validation(validation_type="NoneOrEmpty")
  109. def delete_key(self, s3_key_to_delete: str) -> bool:
  110. """
  111. delete_key - Deletes a Key from an S3 Bucket
  112. :param s3_key_to_delete:
  113. :return: True/False if the operation succeeded/failed
  114. """
  115. try:
  116. self._logger.debug("Deleting Key: " + s3_key_to_delete + " from S3 bucket: " + self.bucket_name)
  117. obj_status = self.s3_client.head_object(Bucket=self.bucket_name, Key=s3_key_to_delete)
  118. except botocore.exceptions.ClientError as ex:
  119. if ex.response["Error"]["Code"] == "404":
  120. self._logger.error("[" + sys._getframe().f_code.co_name + "] - Key does not exist in bucket)")
  121. return False
  122. if obj_status["ContentLength"]:
  123. self._logger.debug("[" + sys._getframe().f_code.co_name + "] - Deleting file s3://" + self.bucket_name + s3_key_to_delete)
  124. self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_key_to_delete)
  125. return True
  126. @explicit_params_validation(validation_type="NoneOrEmpty")
  127. def upload_file_from_stream(self, file, key: str):
  128. """
  129. upload_file - Uploads a file to S3 via boto3 interface
  130. *Please Notice* - This method is for working with files, not objects
  131. :param key: The key (filename) to create in the S3 bucket
  132. :param filen: File to upload
  133. :return True/False if the operation succeeded/failed
  134. """
  135. try:
  136. self._logger.debug("Uploading Key: " + key + " to S3 bucket: " + self.bucket_name)
  137. buffer = BytesIO(file)
  138. self.upload_buffer(key, buffer)
  139. return True
  140. except Exception as ex:
  141. self._logger.critical("[" + sys._getframe().f_code.co_name + "] - Caught Exception while trying to upload file " + str(key) + "to S3" + str(ex))
  142. return False
  143. @explicit_params_validation(validation_type="NoneOrEmpty")
  144. def upload_file(self, filename_to_upload: str, key: str):
  145. """
  146. upload_file - Uploads a file to S3 via boto3 interface
  147. *Please Notice* - This method is for working with files, not objects
  148. :param key: The key (filename) to create in the S3 bucket
  149. :param filename_to_upload: Filename of the file to upload
  150. :return True/False if the operation succeeded/failed
  151. """
  152. try:
  153. self._logger.debug("Uploading Key: " + key + " to S3 bucket: " + self.bucket_name)
  154. self.s3_client.upload_file(Bucket=self.bucket_name, Filename=filename_to_upload, Key=key)
  155. return True
  156. except Exception as ex:
  157. self._logger.critical(f"[{sys._getframe().f_code.co_name}] - Caught Exception while trying to upload file {filename_to_upload} to S3 {ex}")
  158. return False
  159. @explicit_params_validation(validation_type="NoneOrEmpty")
  160. def download_key(self, target_path: str, key_to_download: str) -> bool:
  161. """
  162. download_file - Downloads a key from S3 using boto3 to the provided filename
  163. Please Notice* - This method is for working with files, not objects
  164. :param key_to_download: The key (filename) to download from the S3 bucket
  165. :param target_path: Filename of the file to download the content of the key to
  166. :return: True/False if the operation succeeded/failed
  167. """
  168. try:
  169. self._logger.debug("Uploading Key: " + key_to_download + " from S3 bucket: " + self.bucket_name)
  170. self.s3_client.download_file(Bucket=self.bucket_name, Filename=target_path, Key=key_to_download)
  171. except botocore.exceptions.ClientError as ex:
  172. if ex.response["Error"]["Code"] == "404":
  173. self._logger.error("[" + sys._getframe().f_code.co_name + "] - Key does exist in bucket)")
  174. else:
  175. self._logger.critical(f"[{sys._getframe().f_code.co_name}] - Caught Exception while trying to download key {key_to_download} from S3 {ex}")
  176. return False
  177. return True
  178. @explicit_params_validation(validation_type="NoneOrEmpty")
  179. def download_keys_by_prefix(self, s3_bucket_path_prefix: str, local_download_dir: str, s3_file_path_prefix: str = ""):
  180. """
  181. download_keys_by_prefix - Download all of the keys who match the provided in-bucket path prefix and file prefix
  182. :param s3_bucket_path_prefix: The S3 "folder" to download from
  183. :param local_download_dir: The local directory to download the files to
  184. :param s3_file_path_prefix: The specific prefix of the files we want to download
  185. :return:
  186. """
  187. if not os.path.isdir(local_download_dir):
  188. raise ValueError("[" + sys._getframe().f_code.co_name + "] - Provided directory does not exist")
  189. paginator = self.s3_client.get_paginator("list_objects")
  190. prefix = s3_bucket_path_prefix if not s3_file_path_prefix else s3_bucket_path_prefix + "/" + s3_file_path_prefix
  191. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=prefix)
  192. for item in page_iterator.search("Contents"):
  193. if item is not None:
  194. if item["Key"] == s3_bucket_path_prefix:
  195. continue
  196. key_to_download = item["Key"]
  197. local_filename = key_to_download.split("/")[-1]
  198. self.download_key(target_path=local_download_dir + "/" + local_filename, key_to_download=key_to_download)
  199. @explicit_params_validation(validation_type="NoneOrEmpty")
  200. def download_file_by_path(self, s3_file_path: str, local_download_dir: str):
  201. """
  202. :param s3_file_path: str - path ot s3 file e.g./ "s3://x/y.zip"
  203. :param local_download_dir: path to download
  204. :return:
  205. """
  206. if not os.path.isdir(local_download_dir):
  207. raise ValueError("[" + sys._getframe().f_code.co_name + "] - Provided directory does not exist")
  208. local_filename = s3_file_path.split("/")[-1]
  209. self.download_key(target_path=local_download_dir + "/" + local_filename, key_to_download=s3_file_path)
  210. return local_filename
  211. @explicit_params_validation(validation_type="NoneOrEmpty")
  212. def empty_folder_content_by_path_prefix(self, s3_bucket_path_prefix) -> list:
  213. """
  214. empty_folder_content_by_path_prefix - Deletes all of the files in the specified bucket path
  215. :param s3_bucket_path_prefix: The "folder" to empty
  216. :returns: Errors list
  217. """
  218. paginator = self.s3_client.get_paginator("list_objects")
  219. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=s3_bucket_path_prefix)
  220. files_dict_to_delete = dict(Objects=[])
  221. errors_list = []
  222. for item in page_iterator.search("Contents"):
  223. if item is not None:
  224. if item["Key"] == s3_bucket_path_prefix:
  225. continue
  226. files_dict_to_delete["Objects"].append(dict(Key=item["Key"]))
  227. # IF OBJECTS LIMIT HAS BEEN REACHED, FLUSH
  228. if len(files_dict_to_delete["Objects"]) >= 1000:
  229. self._delete_files_left_in_list(errors_list, files_dict_to_delete)
  230. files_dict_to_delete = dict(Objects=[])
  231. # DELETE THE FILES LEFT IN THE LIST
  232. if len(files_dict_to_delete["Objects"]):
  233. self._delete_files_left_in_list(errors_list, files_dict_to_delete)
  234. return errors_list
  235. def _delete_files_left_in_list(self, errors_list, files_dict_to_delete):
  236. try:
  237. s3_response = self.s3_client.delete_objects(Bucket=self.bucket_name, Delete=files_dict_to_delete)
  238. except Exception as ex:
  239. self._logger.critical("[" + sys._getframe().f_code.co_name + "] - Caught Exception while trying to delete keys " + "from S3 " + str(ex))
  240. if "Errors" in s3_response:
  241. errors_list.append(s3_response["Errors"])
  242. @explicit_params_validation(validation_type="NoneOrEmpty")
  243. def upload_buffer(self, new_key_name: str, buffer_to_write: StringIO):
  244. """
  245. Uploads a buffer into a file in S3 with the provided key name.
  246. :bucket: The name of the bucket
  247. :new_key_name: The name of the file to create in s3
  248. :buffer_to_write: A buffer that contains the file contents.
  249. """
  250. self.s3_resource.Object(self.bucket_name, new_key_name).put(Body=buffer_to_write.getvalue())
  251. @explicit_params_validation(validation_type="NoneOrEmpty")
  252. def list_bucket_objects(self, prefix: str = None) -> List[dict]:
  253. """
  254. Gets a list of dictionaries, representing files in the S3 bucket that is passed in the constructor (self.bucket).
  255. :param prefix: A prefix filter for the files names.
  256. :return: the objects, dict as received from botocore.
  257. """
  258. paginator = self.s3_client.get_paginator("list_objects")
  259. if prefix:
  260. page_iterator = paginator.paginate(Bucket=self.bucket_name, Prefix=prefix)
  261. else:
  262. page_iterator = paginator.paginate(Bucket=self.bucket_name)
  263. bucket_objects = []
  264. for item in page_iterator.search("Contents"):
  265. if not item or item["Key"] == self.bucket_name:
  266. continue
  267. bucket_objects.append(item)
  268. return bucket_objects
  269. @explicit_params_validation(validation_type="NoneOrEmpty")
  270. def create_presigned_upload_url(self, object_name: str, fields=None, conditions=None, expiration=3600):
  271. """Generate a presigned URL S3 POST request to upload a file
  272. :param bucket_name: string
  273. :param object_name: string
  274. :param fields: Dictionary of prefilled form fields
  275. :param conditions: List of conditions to include in the policy
  276. :param expiration: Time in seconds for the presigned URL to remain valid
  277. :return: Dictionary with the following keys:
  278. url: URL to post to
  279. fields: Dictionary of form fields and values to submit with the POST request
  280. """
  281. # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html#generating-a-presigned-url-to-upload-a-file
  282. file_already_exist = self.check_key_exists(object_name)
  283. if file_already_exist:
  284. raise FileExistsError(f"The key {object_name} already exists in bucket {self.bucket_name}")
  285. response = self.s3_client.generate_presigned_post(self.bucket_name, object_name, Fields=fields, Conditions=conditions, ExpiresIn=expiration)
  286. return response
  287. @explicit_params_validation(validation_type="NoneOrEmpty")
  288. def create_presigned_download_url(self, bucket_name: str, object_name: str, expiration=3600):
  289. """Generate a presigned URL S3 Get request to download a file
  290. :param bucket_name: string
  291. :param object_name: string
  292. :param expiration: Time in seconds for the presigned URL to remain valid
  293. :return: URL encoded with the credentials in the query, to be fetched using any HTTP client.
  294. """
  295. # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html
  296. response = self.s3_client.generate_presigned_url("get_object", Params={"Bucket": bucket_name, "Key": object_name}, ExpiresIn=expiration)
  297. return response
  298. @staticmethod
  299. def convert_content_length_to_mb(content_length):
  300. return round(float(f"{content_length / (1e+6):2f}"), 2)
  301. @explicit_params_validation(validation_type="NoneOrEmpty")
  302. def copy_key(self, destination_bucket_name: str, source_key: str, destination_key: str):
  303. self._logger.info(f"Copying the bucket object {self.bucket_name}:{source_key} to {destination_bucket_name}/{destination_key}")
  304. copy_source = {"Bucket": self.bucket_name, "Key": source_key}
  305. # Copying the key
  306. bucket = self.s3_resource.Bucket(destination_bucket_name)
  307. bucket.copy(copy_source, destination_key)
  308. return True
  309. # @explicit_params_validation(validation_type='NoneOrEmpty')
  310. # def list_common_prefixes(self) -> List[str]:
  311. # """
  312. # Gets a list of dictionaries, representing directories in the S3 bucket that is passed in the constructor (self.bucket).
  313. # :return: The names of the directories in the bucket.
  314. # """
  315. # paginator = self.s3_client.get_paginator('list_objects_v2')
  316. # page_iterator = paginator.paginate(Bucket=self.bucket_name)
  317. # prefixes = set()
  318. # for item in page_iterator.search('Contents'):
  319. # if not item:
  320. # continue
  321. #
  322. # if len(item.split('/') == 1):
  323. # prefixes.append(item)
  324. # return prefixes
Discard
Tip!

Press p or to see the previous file or, n or to see the next file