megadetector 5.0.28__py3-none-any.whl → 10.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of megadetector might be problematic. Click here for more details.

Files changed (197) hide show
  1. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +2 -2
  2. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +1 -1
  3. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +1 -1
  4. megadetector/classification/aggregate_classifier_probs.py +3 -3
  5. megadetector/classification/analyze_failed_images.py +5 -5
  6. megadetector/classification/cache_batchapi_outputs.py +5 -5
  7. megadetector/classification/create_classification_dataset.py +11 -12
  8. megadetector/classification/crop_detections.py +10 -10
  9. megadetector/classification/csv_to_json.py +8 -8
  10. megadetector/classification/detect_and_crop.py +13 -15
  11. megadetector/classification/efficientnet/model.py +8 -8
  12. megadetector/classification/efficientnet/utils.py +6 -5
  13. megadetector/classification/evaluate_model.py +7 -7
  14. megadetector/classification/identify_mislabeled_candidates.py +6 -6
  15. megadetector/classification/json_to_azcopy_list.py +1 -1
  16. megadetector/classification/json_validator.py +29 -32
  17. megadetector/classification/map_classification_categories.py +9 -9
  18. megadetector/classification/merge_classification_detection_output.py +12 -9
  19. megadetector/classification/prepare_classification_script.py +19 -19
  20. megadetector/classification/prepare_classification_script_mc.py +26 -26
  21. megadetector/classification/run_classifier.py +4 -4
  22. megadetector/classification/save_mislabeled.py +6 -6
  23. megadetector/classification/train_classifier.py +1 -1
  24. megadetector/classification/train_classifier_tf.py +9 -9
  25. megadetector/classification/train_utils.py +10 -10
  26. megadetector/data_management/annotations/annotation_constants.py +1 -2
  27. megadetector/data_management/camtrap_dp_to_coco.py +79 -46
  28. megadetector/data_management/cct_json_utils.py +103 -103
  29. megadetector/data_management/cct_to_md.py +49 -49
  30. megadetector/data_management/cct_to_wi.py +33 -33
  31. megadetector/data_management/coco_to_labelme.py +75 -75
  32. megadetector/data_management/coco_to_yolo.py +210 -193
  33. megadetector/data_management/databases/add_width_and_height_to_db.py +86 -12
  34. megadetector/data_management/databases/combine_coco_camera_traps_files.py +40 -40
  35. megadetector/data_management/databases/integrity_check_json_db.py +228 -200
  36. megadetector/data_management/databases/subset_json_db.py +33 -33
  37. megadetector/data_management/generate_crops_from_cct.py +88 -39
  38. megadetector/data_management/get_image_sizes.py +54 -49
  39. megadetector/data_management/labelme_to_coco.py +133 -125
  40. megadetector/data_management/labelme_to_yolo.py +159 -73
  41. megadetector/data_management/lila/create_lila_blank_set.py +81 -83
  42. megadetector/data_management/lila/create_lila_test_set.py +32 -31
  43. megadetector/data_management/lila/create_links_to_md_results_files.py +18 -18
  44. megadetector/data_management/lila/download_lila_subset.py +21 -24
  45. megadetector/data_management/lila/generate_lila_per_image_labels.py +365 -107
  46. megadetector/data_management/lila/get_lila_annotation_counts.py +35 -33
  47. megadetector/data_management/lila/get_lila_image_counts.py +22 -22
  48. megadetector/data_management/lila/lila_common.py +73 -70
  49. megadetector/data_management/lila/test_lila_metadata_urls.py +28 -19
  50. megadetector/data_management/mewc_to_md.py +344 -340
  51. megadetector/data_management/ocr_tools.py +262 -255
  52. megadetector/data_management/read_exif.py +249 -227
  53. megadetector/data_management/remap_coco_categories.py +90 -28
  54. megadetector/data_management/remove_exif.py +81 -21
  55. megadetector/data_management/rename_images.py +187 -187
  56. megadetector/data_management/resize_coco_dataset.py +588 -120
  57. megadetector/data_management/speciesnet_to_md.py +41 -41
  58. megadetector/data_management/wi_download_csv_to_coco.py +55 -55
  59. megadetector/data_management/yolo_output_to_md_output.py +248 -122
  60. megadetector/data_management/yolo_to_coco.py +333 -191
  61. megadetector/detection/change_detection.py +832 -0
  62. megadetector/detection/process_video.py +340 -337
  63. megadetector/detection/pytorch_detector.py +358 -278
  64. megadetector/detection/run_detector.py +399 -186
  65. megadetector/detection/run_detector_batch.py +404 -377
  66. megadetector/detection/run_inference_with_yolov5_val.py +340 -327
  67. megadetector/detection/run_tiled_inference.py +257 -249
  68. megadetector/detection/tf_detector.py +24 -24
  69. megadetector/detection/video_utils.py +332 -295
  70. megadetector/postprocessing/add_max_conf.py +19 -11
  71. megadetector/postprocessing/categorize_detections_by_size.py +45 -45
  72. megadetector/postprocessing/classification_postprocessing.py +468 -433
  73. megadetector/postprocessing/combine_batch_outputs.py +23 -23
  74. megadetector/postprocessing/compare_batch_results.py +590 -525
  75. megadetector/postprocessing/convert_output_format.py +106 -102
  76. megadetector/postprocessing/create_crop_folder.py +347 -147
  77. megadetector/postprocessing/detector_calibration.py +173 -168
  78. megadetector/postprocessing/generate_csv_report.py +508 -499
  79. megadetector/postprocessing/load_api_results.py +48 -27
  80. megadetector/postprocessing/md_to_coco.py +133 -102
  81. megadetector/postprocessing/md_to_labelme.py +107 -90
  82. megadetector/postprocessing/md_to_wi.py +40 -40
  83. megadetector/postprocessing/merge_detections.py +92 -114
  84. megadetector/postprocessing/postprocess_batch_results.py +319 -301
  85. megadetector/postprocessing/remap_detection_categories.py +91 -38
  86. megadetector/postprocessing/render_detection_confusion_matrix.py +214 -205
  87. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +57 -57
  88. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +27 -28
  89. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +704 -679
  90. megadetector/postprocessing/separate_detections_into_folders.py +226 -211
  91. megadetector/postprocessing/subset_json_detector_output.py +265 -262
  92. megadetector/postprocessing/top_folders_to_bottom.py +45 -45
  93. megadetector/postprocessing/validate_batch_results.py +70 -70
  94. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +52 -52
  95. megadetector/taxonomy_mapping/map_new_lila_datasets.py +18 -19
  96. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +54 -33
  97. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +67 -67
  98. megadetector/taxonomy_mapping/retrieve_sample_image.py +16 -16
  99. megadetector/taxonomy_mapping/simple_image_download.py +8 -8
  100. megadetector/taxonomy_mapping/species_lookup.py +156 -74
  101. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +14 -14
  102. megadetector/taxonomy_mapping/taxonomy_graph.py +10 -10
  103. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +13 -13
  104. megadetector/utils/ct_utils.py +1049 -211
  105. megadetector/utils/directory_listing.py +21 -77
  106. megadetector/utils/gpu_test.py +22 -22
  107. megadetector/utils/md_tests.py +632 -529
  108. megadetector/utils/path_utils.py +1520 -431
  109. megadetector/utils/process_utils.py +41 -41
  110. megadetector/utils/split_locations_into_train_val.py +62 -62
  111. megadetector/utils/string_utils.py +148 -27
  112. megadetector/utils/url_utils.py +489 -176
  113. megadetector/utils/wi_utils.py +2658 -2526
  114. megadetector/utils/write_html_image_list.py +137 -137
  115. megadetector/visualization/plot_utils.py +34 -30
  116. megadetector/visualization/render_images_with_thumbnails.py +39 -74
  117. megadetector/visualization/visualization_utils.py +487 -435
  118. megadetector/visualization/visualize_db.py +232 -198
  119. megadetector/visualization/visualize_detector_output.py +82 -76
  120. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/METADATA +5 -2
  121. megadetector-10.0.0.dist-info/RECORD +139 -0
  122. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/WHEEL +1 -1
  123. megadetector/api/batch_processing/api_core/__init__.py +0 -0
  124. megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
  125. megadetector/api/batch_processing/api_core/batch_service/score.py +0 -439
  126. megadetector/api/batch_processing/api_core/server.py +0 -294
  127. megadetector/api/batch_processing/api_core/server_api_config.py +0 -97
  128. megadetector/api/batch_processing/api_core/server_app_config.py +0 -55
  129. megadetector/api/batch_processing/api_core/server_batch_job_manager.py +0 -220
  130. megadetector/api/batch_processing/api_core/server_job_status_table.py +0 -149
  131. megadetector/api/batch_processing/api_core/server_orchestration.py +0 -360
  132. megadetector/api/batch_processing/api_core/server_utils.py +0 -88
  133. megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
  134. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +0 -46
  135. megadetector/api/batch_processing/api_support/__init__.py +0 -0
  136. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +0 -152
  137. megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
  138. megadetector/api/synchronous/__init__.py +0 -0
  139. megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  140. megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +0 -151
  141. megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +0 -263
  142. megadetector/api/synchronous/api_core/animal_detection_api/config.py +0 -35
  143. megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
  144. megadetector/api/synchronous/api_core/tests/load_test.py +0 -110
  145. megadetector/data_management/importers/add_nacti_sizes.py +0 -52
  146. megadetector/data_management/importers/add_timestamps_to_icct.py +0 -79
  147. megadetector/data_management/importers/animl_results_to_md_results.py +0 -158
  148. megadetector/data_management/importers/auckland_doc_test_to_json.py +0 -373
  149. megadetector/data_management/importers/auckland_doc_to_json.py +0 -201
  150. megadetector/data_management/importers/awc_to_json.py +0 -191
  151. megadetector/data_management/importers/bellevue_to_json.py +0 -272
  152. megadetector/data_management/importers/cacophony-thermal-importer.py +0 -793
  153. megadetector/data_management/importers/carrizo_shrubfree_2018.py +0 -269
  154. megadetector/data_management/importers/carrizo_trail_cam_2017.py +0 -289
  155. megadetector/data_management/importers/cct_field_adjustments.py +0 -58
  156. megadetector/data_management/importers/channel_islands_to_cct.py +0 -913
  157. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +0 -180
  158. megadetector/data_management/importers/eMammal/eMammal_helpers.py +0 -249
  159. megadetector/data_management/importers/eMammal/make_eMammal_json.py +0 -223
  160. megadetector/data_management/importers/ena24_to_json.py +0 -276
  161. megadetector/data_management/importers/filenames_to_json.py +0 -386
  162. megadetector/data_management/importers/helena_to_cct.py +0 -283
  163. megadetector/data_management/importers/idaho-camera-traps.py +0 -1407
  164. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +0 -294
  165. megadetector/data_management/importers/import_desert_lion_conservation_camera_traps.py +0 -387
  166. megadetector/data_management/importers/jb_csv_to_json.py +0 -150
  167. megadetector/data_management/importers/mcgill_to_json.py +0 -250
  168. megadetector/data_management/importers/missouri_to_json.py +0 -490
  169. megadetector/data_management/importers/nacti_fieldname_adjustments.py +0 -79
  170. megadetector/data_management/importers/noaa_seals_2019.py +0 -181
  171. megadetector/data_management/importers/osu-small-animals-to-json.py +0 -364
  172. megadetector/data_management/importers/pc_to_json.py +0 -365
  173. megadetector/data_management/importers/plot_wni_giraffes.py +0 -123
  174. megadetector/data_management/importers/prepare_zsl_imerit.py +0 -131
  175. megadetector/data_management/importers/raic_csv_to_md_results.py +0 -416
  176. megadetector/data_management/importers/rspb_to_json.py +0 -356
  177. megadetector/data_management/importers/save_the_elephants_survey_A.py +0 -320
  178. megadetector/data_management/importers/save_the_elephants_survey_B.py +0 -329
  179. megadetector/data_management/importers/snapshot_safari_importer.py +0 -758
  180. megadetector/data_management/importers/snapshot_serengeti_lila.py +0 -1067
  181. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +0 -150
  182. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +0 -153
  183. megadetector/data_management/importers/sulross_get_exif.py +0 -65
  184. megadetector/data_management/importers/timelapse_csv_set_to_json.py +0 -490
  185. megadetector/data_management/importers/ubc_to_json.py +0 -399
  186. megadetector/data_management/importers/umn_to_json.py +0 -507
  187. megadetector/data_management/importers/wellington_to_json.py +0 -263
  188. megadetector/data_management/importers/wi_to_json.py +0 -442
  189. megadetector/data_management/importers/zamba_results_to_md_results.py +0 -180
  190. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +0 -101
  191. megadetector/data_management/lila/add_locations_to_nacti.py +0 -151
  192. megadetector/utils/azure_utils.py +0 -178
  193. megadetector/utils/sas_blob_utils.py +0 -509
  194. megadetector-5.0.28.dist-info/RECORD +0 -209
  195. /megadetector/{api/batch_processing/__init__.py → __init__.py} +0 -0
  196. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/licenses/LICENSE +0 -0
  197. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/top_level.txt +0 -0
@@ -1,509 +0,0 @@
1
- """
2
-
3
- sas_blob_utils.py
4
-
5
- This module contains helper functions for dealing with Shared Access Signatures
6
- (SAS) tokens for Azure Blob Storage.
7
-
8
- The default Azure Storage SAS URI format is:
9
-
10
- https://<account>.blob.core.windows.net/<container>/<blob>?<sas_token>
11
-
12
- This module assumes azure-storage-blob version 12.5.
13
-
14
- Documentation for Azure Blob Storage:
15
- docs.microsoft.com/en-us/azure/developer/python/sdk/storage/storage-blob-readme
16
-
17
- Documentation for SAS:
18
- docs.microsoft.com/en-us/azure/storage/common/storage-sas-overview
19
-
20
- """
21
-
22
- #%% Imports
23
-
24
- from datetime import datetime, timedelta
25
- import io
26
- import re
27
- from typing import (Any, AnyStr, Dict, IO, Iterable, List, Optional, Set, Tuple, Union)
28
- from urllib import parse
29
- import uuid
30
-
31
- from tqdm import tqdm
32
-
33
- from azure.storage.blob import (
34
- BlobClient,
35
- BlobProperties,
36
- ContainerClient,
37
- ContainerSasPermissions,
38
- generate_container_sas)
39
-
40
-
41
- #%% URI management
42
-
43
- def build_azure_storage_uri(
44
- account: str,
45
- container: Optional[str] = None,
46
- blob: Optional[str] = None,
47
- sas_token: Optional[str] = None,
48
- account_url_template: str = 'https://{account}.blob.core.windows.net'
49
- ) -> str:
50
- """
51
- Args:
52
- account: str, name of Azure Storage account
53
- container: optional str, name of Azure Blob Storage container
54
- blob: optional str, name of blob, not URL-escaped
55
- if blob is given, must also specify container
56
- sas_token: optional str, Shared Access Signature (SAS). Leading ?
57
- is removed if present.
58
- account_url_template: str, Python 3 string formatting template,
59
- contains '{account}' placeholder, defaults to default Azure
60
- Storage URL format. Set this value if using Azurite Azure Storage
61
- emulator.
62
-
63
- Returns: str, Azure storage URI
64
- """
65
-
66
- uri = account_url_template.format(account=account)
67
- if container is not None:
68
- uri = f'{uri}/{container}'
69
- if blob is not None:
70
- assert container is not None
71
- blob = parse.quote(blob)
72
- uri = f'{uri}/{blob}'
73
- if sas_token is not None:
74
- if sas_token[0] == '?':
75
- sas_token = sas_token[1:]
76
- uri = f'{uri}?{sas_token}'
77
- return uri
78
-
79
-
80
- def _get_resource_reference(prefix: str) -> str:
81
- return '{}{}'.format(prefix, str(uuid.uuid4()).replace('-', ''))
82
-
83
-
84
- def get_client_from_uri(container_uri: str) -> ContainerClient:
85
- """
86
- Gets a ContainerClient for the given container URI.
87
- """
88
-
89
- return ContainerClient.from_container_url(container_uri)
90
-
91
-
92
- def get_account_from_uri(sas_uri: str) -> str:
93
- """
94
- Assumes that sas_uri points to Azure Blob Storage account hosted at
95
- a default Azure URI. Does not work for locally-emulated Azure Storage
96
- or Azure Storage hosted at custom endpoints.
97
- """
98
-
99
- url_parts = parse.urlsplit(sas_uri)
100
- loc = url_parts.netloc # "<account>.blob.core.windows.net"
101
- return loc.split('.')[0]
102
-
103
-
104
- def is_container_uri(sas_uri: str) -> bool:
105
- """
106
- Returns True if the signed resource field in the URI "sr" is a container "c"
107
- or a directory "d"
108
- """
109
-
110
- data = get_all_query_parts(sas_uri)
111
- if 'sr' not in data:
112
- return False
113
-
114
- if 'c' in data['sr'] or 'd' in data['sr']:
115
- return True
116
- else:
117
- return False
118
-
119
- def is_blob_uri(sas_uri: str) -> bool:
120
- """
121
- Returns True if the signed resource field in the URI "sr" is a blob "b".
122
- """
123
-
124
- data = get_all_query_parts(sas_uri)
125
- if 'sr' not in data:
126
- return False
127
-
128
- if 'b' in data['sr']:
129
- return True
130
- else:
131
- return False
132
-
133
-
134
- def get_container_from_uri(sas_uri: str, unquote: bool = True) -> str:
135
- """
136
- Gets the container name from a Azure Blob Storage URI.
137
-
138
- Assumes that sas_uri points to Azure Blob Storage account hosted at
139
- a default Azure URI. Does not work for locally-emulated Azure Storage
140
- or Azure Storage hosted at custom endpoints.
141
-
142
- Args:
143
- sas_uri: str, Azure blob storage URI, may include SAS token
144
- unquote: bool, whether to replace any %xx escapes by their
145
- single-character equivalent, default True
146
-
147
- Returns: str, container name
148
-
149
- Raises: ValueError, if sas_uri does not include a container
150
- """
151
-
152
- url_parts = parse.urlsplit(sas_uri)
153
- raw_path = url_parts.path.lstrip('/') # remove leading "/" from path
154
- container = raw_path.split('/')[0]
155
- if container == '':
156
- raise ValueError('Given sas_uri does not include a container.')
157
- if unquote:
158
- container = parse.unquote(container)
159
- return container
160
-
161
-
162
- def get_blob_from_uri(sas_uri: str, unquote: bool = True) -> str:
163
- """
164
- Return the path to the blob from the root container if this sas_uri
165
- is for an individual blob; otherwise returns None.
166
-
167
- Args:
168
- sas_uri: str, Azure blob storage URI, may include SAS token
169
- unquote: bool, whether to replace any %xx escapes by their
170
- single-character equivalent, default True
171
-
172
- Returns: str, blob name (path to the blob from the root container)
173
-
174
- Raises: ValueError, if sas_uri does not include a blob name
175
- """
176
-
177
- # Get the entire path with all slashes after the container
178
- url_parts = parse.urlsplit(sas_uri)
179
- raw_path = url_parts.path.lstrip('/') # remove leading "/" from path
180
- parts = raw_path.split('/', maxsplit=1)
181
- if len(parts) < 2 or parts[1] == '':
182
- raise ValueError('Given sas_uri does not include a blob name')
183
-
184
- blob = parts[1] # first item is an empty string
185
- if unquote:
186
- blob = parse.unquote(blob)
187
- return blob
188
-
189
-
190
- def get_sas_token_from_uri(sas_uri: str) -> Optional[str]:
191
- """
192
- Get the query part of the SAS token that contains permissions, access
193
- times and signature.
194
-
195
- Args:
196
- sas_uri: str, Azure blob storage SAS token
197
-
198
- Returns: str, query part of the SAS token (without leading '?'),
199
- or None if URI has no token.
200
- """
201
-
202
- url_parts = parse.urlsplit(sas_uri)
203
- sas_token = url_parts.query or None # None if query is empty string
204
- return sas_token
205
-
206
-
207
- def get_resource_type_from_uri(sas_uri: str) -> Optional[str]:
208
- """
209
- Get the resource type pointed to by this SAS token.
210
-
211
- Args:
212
- sas_uri: str, Azure blob storage URI with SAS token
213
-
214
- Returns: A string (either 'blob' or 'container') or None.
215
- """
216
-
217
- url_parts = parse.urlsplit(sas_uri)
218
- data = parse.parse_qs(url_parts.query)
219
- if 'sr' in data:
220
- types = data['sr']
221
- if 'b' in types:
222
- return 'blob'
223
- elif 'c' in types:
224
- return 'container'
225
- return None
226
-
227
-
228
- def get_endpoint_suffix(sas_uri):
229
- """
230
- Gets the endpoint at which the blob storage account is served.
231
- Args:
232
- sas_uri: str, Azure blob storage URI with SAS token
233
-
234
- Returns: A string, usually 'core.windows.net' or 'core.chinacloudapi.cn', to
235
- use for the `endpoint` argument in various blob storage SDK functions.
236
- """
237
-
238
- url_parts = parse.urlsplit(sas_uri)
239
- suffix = url_parts.netloc.split('.blob.')[1].split('/')[0]
240
- return suffix
241
-
242
-
243
- def get_permissions_from_uri(sas_uri: str) -> Set[str]:
244
- """
245
- Get the permissions given by this SAS token.
246
-
247
- Args:
248
- sas_uri: str, Azure blob storage URI with SAS token
249
-
250
- Returns: A set containing some of 'read', 'write', 'delete' and 'list'.
251
- Empty set returned if no permission specified in sas_uri.
252
- """
253
-
254
- data = get_all_query_parts(sas_uri)
255
- permissions_set = set()
256
- if 'sp' in data:
257
- permissions = data['sp'][0]
258
- if 'r' in permissions:
259
- permissions_set.add('read')
260
- if 'w' in permissions:
261
- permissions_set.add('write')
262
- if 'd' in permissions:
263
- permissions_set.add('delete')
264
- if 'l' in permissions:
265
- permissions_set.add('list')
266
- return permissions_set
267
-
268
-
269
- def get_all_query_parts(sas_uri: str) -> Dict[str, Any]:
270
- """
271
- Gets the SAS token parameters.
272
- """
273
-
274
- url_parts = parse.urlsplit(sas_uri)
275
- return parse.parse_qs(url_parts.query)
276
-
277
-
278
- #%% Blob
279
-
280
- def check_blob_exists(sas_uri: str, blob_name: Optional[str] = None) -> bool:
281
- """
282
- Checks whether a given URI points to an actual blob.
283
-
284
- Assumes that sas_uri points to Azure Blob Storage account hosted at
285
- a default Azure URI. Does not work for locally-emulated Azure Storage
286
- or Azure Storage hosted at custom endpoints. In these cases, create a
287
- BlobClient using the default constructor, instead of from_blob_url(),
288
- and use the BlobClient.exists() method directly.
289
-
290
- Args:
291
- sas_uri: str, URI to a container or a blob
292
- if blob_name is given, sas_uri is treated as a container URI
293
- otherwise, sas_uri is treated as a blob URI
294
- blob_name: optional str, name of blob, not URL-escaped
295
- must be given if sas_uri is a URI to a container
296
-
297
- Returns: bool, whether the sas_uri given points to an existing blob
298
- """
299
-
300
- if blob_name is not None:
301
- sas_uri = build_blob_uri(
302
- container_uri=sas_uri, blob_name=blob_name)
303
-
304
- with BlobClient.from_blob_url(sas_uri) as blob_client:
305
- return blob_client.exists()
306
-
307
-
308
- def upload_blob(container_uri: str, blob_name: str,
309
- data: Union[Iterable[AnyStr], IO[AnyStr]],
310
- overwrite: bool = False) -> str:
311
- """
312
- Creates a new blob of the given name from an IO stream.
313
-
314
- Args:
315
- container_uri: str, URI to a container, may include SAS token
316
- blob_name: str, name of blob to upload
317
- data: str, bytes, or IO stream
318
- if str, assumes utf-8 encoding
319
- overwrite: bool, whether to overwrite existing blob (if any)
320
-
321
- Returns: str, URL to blob, includes SAS token if container_uri has SAS token
322
- """
323
-
324
- account_url, container, sas_token = split_container_uri(container_uri)
325
- with BlobClient(account_url=account_url, container_name=container,
326
- blob_name=blob_name, credential=sas_token) as blob_client:
327
- blob_client.upload_blob(data, overwrite=overwrite)
328
- return blob_client.url
329
-
330
-
331
- def download_blob_to_stream(sas_uri: str) -> Tuple[io.BytesIO, BlobProperties]:
332
- """
333
- Downloads a blob to an IO stream.
334
-
335
- Args:
336
- sas_uri: str, URI to a blob
337
-
338
- Returns:
339
- output_stream: io.BytesIO, remember to close it when finished using
340
- blob_properties: BlobProperties
341
-
342
- Raises: azure.core.exceptions.ResourceNotFoundError, if sas_uri points
343
- to a non-existent blob
344
- """
345
-
346
- with BlobClient.from_blob_url(sas_uri) as blob_client:
347
- output_stream = io.BytesIO()
348
- blob_client.download_blob().readinto(output_stream)
349
- output_stream.seek(0)
350
- blob_properties = blob_client.get_blob_properties()
351
- return output_stream, blob_properties
352
-
353
-
354
- def build_blob_uri(container_uri: str, blob_name: str) -> str:
355
- """
356
- Args:
357
- container_uri: str, URI to blob storage container
358
- <account_url>/<container>?<sas_token>
359
- blob_name: str, name of blob, not URL-escaped
360
-
361
- Returns: str, blob URI <account_url>/<container>/<blob_name>?<sas_token>,
362
- <blob_name> is URL-escaped
363
- """
364
-
365
- account_url, container, sas_token = split_container_uri(container_uri)
366
-
367
- blob_name = parse.quote(blob_name)
368
- blob_uri = f'{account_url}/{container}/{blob_name}'
369
- if sas_token is not None:
370
- blob_uri += f'?{sas_token}'
371
- return blob_uri
372
-
373
-
374
- #%% Container
375
-
376
- def list_blobs_in_container(
377
- container_uri: str,
378
- blob_prefix: Optional[str] = None,
379
- blob_suffix: Optional[Union[str, Tuple[str]]] = None,
380
- rsearch: Optional[str] = None,
381
- limit: Optional[int] = None,
382
- verbose: Optional[bool] = True
383
- ) -> List[str]:
384
- """
385
- Get a sorted list of blob names in this container.
386
-
387
- Args:
388
- container_uri: str, URI to a container, may include SAS token
389
- blob_prefix: optional str, returned results will only contain blob names
390
- to with this prefix
391
- blob_suffix: optional str or tuple of str, returned results will only
392
- contain blob names with this/these suffix(es). The blob names will
393
- be lowercased first before comparing with the suffix(es).
394
- rsearch: optional str, returned results will only contain blob names
395
- that match this regex. Can also be a list of regexes, in which case
396
- blobs matching *any* of the regex's will be returned.
397
- limit: int, maximum # of blob names to list
398
- if None, then returns all blob names
399
-
400
- Returns:
401
- sorted list of blob names, of length limit or shorter.
402
- """
403
-
404
- if verbose:
405
- print('Listing blobs')
406
-
407
- if (get_sas_token_from_uri(container_uri) is not None
408
- and get_resource_type_from_uri(container_uri) != 'container'):
409
- raise ValueError('The SAS token provided is not for a container.')
410
-
411
- if blob_prefix is not None and not isinstance(blob_prefix, str):
412
- raise ValueError('blob_prefix must be a str.')
413
-
414
- if (blob_suffix is not None
415
- and not isinstance(blob_suffix, str)
416
- and not isinstance(blob_suffix, tuple)):
417
- raise ValueError('blob_suffix must be a str or a tuple of strings')
418
-
419
- list_blobs = []
420
- with get_client_from_uri(container_uri) as container_client:
421
- generator = container_client.list_blobs(
422
- name_starts_with=blob_prefix)
423
-
424
- if blob_suffix is None and rsearch is None:
425
- list_blobs = [blob.name for blob in tqdm(generator,disable=(not verbose))]
426
- i = len(list_blobs)
427
- else:
428
- i = 0
429
- for blob in tqdm(generator,disable=(not verbose)):
430
- i += 1
431
- suffix_ok = (blob_suffix is None
432
- or blob.name.lower().endswith(blob_suffix))
433
- regex_ok = False
434
- if rsearch is None:
435
- regex_ok = True
436
- else:
437
- if not isinstance(rsearch, list):
438
- rsearch = [rsearch]
439
- # Check whether this blob name matches *any* of our regex's
440
- for expr in rsearch:
441
- if re.search(expr, blob.name) is not None:
442
- regex_ok = True
443
- break
444
- if suffix_ok and regex_ok:
445
- list_blobs.append(blob.name)
446
- if limit is not None and len(list_blobs) == limit:
447
- break
448
-
449
- if verbose:
450
- print(f'Enumerated {len(list_blobs)} matching blobs out of {i} total')
451
-
452
- return sorted(list_blobs) # sort for determinism
453
-
454
-
455
- def generate_writable_container_sas(account_name: str,
456
- account_key: str,
457
- container_name: str,
458
- access_duration_hrs: float,
459
- account_url: Optional[str] = None
460
- ) -> str:
461
- """
462
- Creates a container and returns a SAS URI with read/write/list
463
- permissions.
464
-
465
- Args:
466
- account_name: str, name of blob storage account
467
- account_key: str, account SAS token or account shared access key
468
- container_name: str, name of container to create, must not match an
469
- existing container in the given storage account
470
- access_duration_hrs: float
471
- account_url: str, optional, defaults to default Azure Storage URL
472
-
473
- Returns: str, URL to newly created container
474
-
475
- Raises: azure.core.exceptions.ResourceExistsError, if container already
476
- exists
477
- """
478
-
479
- if account_url is None:
480
- account_url = build_azure_storage_uri(account=account_name)
481
- with ContainerClient(account_url=account_url,
482
- container_name=container_name,
483
- credential=account_key) as container_client:
484
- container_client.create_container()
485
-
486
- permissions = ContainerSasPermissions(read=True, write=True, list=True)
487
- container_sas_token = generate_container_sas(
488
- account_name=account_name,
489
- container_name=container_name,
490
- account_key=account_key,
491
- permission=permissions,
492
- expiry=datetime.utcnow() + timedelta(hours=access_duration_hrs))
493
-
494
- return f'{account_url}/{container_name}?{container_sas_token}'
495
-
496
-
497
- def split_container_uri(container_uri: str) -> Tuple[str, str, Optional[str]]:
498
- """
499
- Args:
500
- container_uri: str, URI to blob storage container
501
- <account_url>/<container>?<sas_token>
502
-
503
- Returns: account_url, container_name, sas_token
504
- """
505
-
506
- account_container = container_uri.split('?', maxsplit=1)[0]
507
- account_url, container_name = account_container.rsplit('/', maxsplit=1)
508
- sas_token = get_sas_token_from_uri(container_uri)
509
- return account_url, container_name, sas_token