megadetector 5.0.11__py3-none-any.whl → 5.0.13__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 (203) hide show
  1. megadetector/api/__init__.py +0 -0
  2. megadetector/api/batch_processing/__init__.py +0 -0
  3. megadetector/api/batch_processing/api_core/__init__.py +0 -0
  4. megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
  5. megadetector/api/batch_processing/api_core/batch_service/score.py +439 -0
  6. megadetector/api/batch_processing/api_core/server.py +294 -0
  7. megadetector/api/batch_processing/api_core/server_api_config.py +97 -0
  8. megadetector/api/batch_processing/api_core/server_app_config.py +55 -0
  9. megadetector/api/batch_processing/api_core/server_batch_job_manager.py +220 -0
  10. megadetector/api/batch_processing/api_core/server_job_status_table.py +149 -0
  11. megadetector/api/batch_processing/api_core/server_orchestration.py +360 -0
  12. megadetector/api/batch_processing/api_core/server_utils.py +88 -0
  13. megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
  14. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +46 -0
  15. megadetector/api/batch_processing/api_support/__init__.py +0 -0
  16. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +152 -0
  17. megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
  18. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  19. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  20. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  21. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +125 -0
  22. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  23. megadetector/api/synchronous/__init__.py +0 -0
  24. megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  25. megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +152 -0
  26. megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +263 -0
  27. megadetector/api/synchronous/api_core/animal_detection_api/config.py +35 -0
  28. megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
  29. megadetector/api/synchronous/api_core/tests/load_test.py +110 -0
  30. megadetector/classification/__init__.py +0 -0
  31. megadetector/classification/aggregate_classifier_probs.py +108 -0
  32. megadetector/classification/analyze_failed_images.py +227 -0
  33. megadetector/classification/cache_batchapi_outputs.py +198 -0
  34. megadetector/classification/create_classification_dataset.py +627 -0
  35. megadetector/classification/crop_detections.py +516 -0
  36. megadetector/classification/csv_to_json.py +226 -0
  37. megadetector/classification/detect_and_crop.py +855 -0
  38. megadetector/classification/efficientnet/__init__.py +9 -0
  39. megadetector/classification/efficientnet/model.py +415 -0
  40. megadetector/classification/efficientnet/utils.py +607 -0
  41. megadetector/classification/evaluate_model.py +520 -0
  42. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  43. megadetector/classification/json_to_azcopy_list.py +63 -0
  44. megadetector/classification/json_validator.py +699 -0
  45. megadetector/classification/map_classification_categories.py +276 -0
  46. megadetector/classification/merge_classification_detection_output.py +506 -0
  47. megadetector/classification/prepare_classification_script.py +194 -0
  48. megadetector/classification/prepare_classification_script_mc.py +228 -0
  49. megadetector/classification/run_classifier.py +287 -0
  50. megadetector/classification/save_mislabeled.py +110 -0
  51. megadetector/classification/train_classifier.py +827 -0
  52. megadetector/classification/train_classifier_tf.py +725 -0
  53. megadetector/classification/train_utils.py +323 -0
  54. megadetector/data_management/__init__.py +0 -0
  55. megadetector/data_management/annotations/__init__.py +0 -0
  56. megadetector/data_management/annotations/annotation_constants.py +34 -0
  57. megadetector/data_management/camtrap_dp_to_coco.py +237 -0
  58. megadetector/data_management/cct_json_utils.py +404 -0
  59. megadetector/data_management/cct_to_md.py +176 -0
  60. megadetector/data_management/cct_to_wi.py +289 -0
  61. megadetector/data_management/coco_to_labelme.py +283 -0
  62. megadetector/data_management/coco_to_yolo.py +662 -0
  63. megadetector/data_management/databases/__init__.py +0 -0
  64. megadetector/data_management/databases/add_width_and_height_to_db.py +33 -0
  65. megadetector/data_management/databases/combine_coco_camera_traps_files.py +206 -0
  66. megadetector/data_management/databases/integrity_check_json_db.py +493 -0
  67. megadetector/data_management/databases/subset_json_db.py +115 -0
  68. megadetector/data_management/generate_crops_from_cct.py +149 -0
  69. megadetector/data_management/get_image_sizes.py +189 -0
  70. megadetector/data_management/importers/add_nacti_sizes.py +52 -0
  71. megadetector/data_management/importers/add_timestamps_to_icct.py +79 -0
  72. megadetector/data_management/importers/animl_results_to_md_results.py +158 -0
  73. megadetector/data_management/importers/auckland_doc_test_to_json.py +373 -0
  74. megadetector/data_management/importers/auckland_doc_to_json.py +201 -0
  75. megadetector/data_management/importers/awc_to_json.py +191 -0
  76. megadetector/data_management/importers/bellevue_to_json.py +273 -0
  77. megadetector/data_management/importers/cacophony-thermal-importer.py +793 -0
  78. megadetector/data_management/importers/carrizo_shrubfree_2018.py +269 -0
  79. megadetector/data_management/importers/carrizo_trail_cam_2017.py +289 -0
  80. megadetector/data_management/importers/cct_field_adjustments.py +58 -0
  81. megadetector/data_management/importers/channel_islands_to_cct.py +913 -0
  82. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +180 -0
  83. megadetector/data_management/importers/eMammal/eMammal_helpers.py +249 -0
  84. megadetector/data_management/importers/eMammal/make_eMammal_json.py +223 -0
  85. megadetector/data_management/importers/ena24_to_json.py +276 -0
  86. megadetector/data_management/importers/filenames_to_json.py +386 -0
  87. megadetector/data_management/importers/helena_to_cct.py +283 -0
  88. megadetector/data_management/importers/idaho-camera-traps.py +1407 -0
  89. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +294 -0
  90. megadetector/data_management/importers/jb_csv_to_json.py +150 -0
  91. megadetector/data_management/importers/mcgill_to_json.py +250 -0
  92. megadetector/data_management/importers/missouri_to_json.py +490 -0
  93. megadetector/data_management/importers/nacti_fieldname_adjustments.py +79 -0
  94. megadetector/data_management/importers/noaa_seals_2019.py +181 -0
  95. megadetector/data_management/importers/pc_to_json.py +365 -0
  96. megadetector/data_management/importers/plot_wni_giraffes.py +123 -0
  97. megadetector/data_management/importers/prepare-noaa-fish-data-for-lila.py +359 -0
  98. megadetector/data_management/importers/prepare_zsl_imerit.py +131 -0
  99. megadetector/data_management/importers/rspb_to_json.py +356 -0
  100. megadetector/data_management/importers/save_the_elephants_survey_A.py +320 -0
  101. megadetector/data_management/importers/save_the_elephants_survey_B.py +329 -0
  102. megadetector/data_management/importers/snapshot_safari_importer.py +758 -0
  103. megadetector/data_management/importers/snapshot_safari_importer_reprise.py +665 -0
  104. megadetector/data_management/importers/snapshot_serengeti_lila.py +1067 -0
  105. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +150 -0
  106. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +153 -0
  107. megadetector/data_management/importers/sulross_get_exif.py +65 -0
  108. megadetector/data_management/importers/timelapse_csv_set_to_json.py +490 -0
  109. megadetector/data_management/importers/ubc_to_json.py +399 -0
  110. megadetector/data_management/importers/umn_to_json.py +507 -0
  111. megadetector/data_management/importers/wellington_to_json.py +263 -0
  112. megadetector/data_management/importers/wi_to_json.py +442 -0
  113. megadetector/data_management/importers/zamba_results_to_md_results.py +181 -0
  114. megadetector/data_management/labelme_to_coco.py +547 -0
  115. megadetector/data_management/labelme_to_yolo.py +272 -0
  116. megadetector/data_management/lila/__init__.py +0 -0
  117. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +97 -0
  118. megadetector/data_management/lila/add_locations_to_nacti.py +147 -0
  119. megadetector/data_management/lila/create_lila_blank_set.py +558 -0
  120. megadetector/data_management/lila/create_lila_test_set.py +152 -0
  121. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  122. megadetector/data_management/lila/download_lila_subset.py +178 -0
  123. megadetector/data_management/lila/generate_lila_per_image_labels.py +516 -0
  124. megadetector/data_management/lila/get_lila_annotation_counts.py +170 -0
  125. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  126. megadetector/data_management/lila/lila_common.py +300 -0
  127. megadetector/data_management/lila/test_lila_metadata_urls.py +132 -0
  128. megadetector/data_management/ocr_tools.py +870 -0
  129. megadetector/data_management/read_exif.py +809 -0
  130. megadetector/data_management/remap_coco_categories.py +84 -0
  131. megadetector/data_management/remove_exif.py +66 -0
  132. megadetector/data_management/rename_images.py +187 -0
  133. megadetector/data_management/resize_coco_dataset.py +189 -0
  134. megadetector/data_management/wi_download_csv_to_coco.py +247 -0
  135. megadetector/data_management/yolo_output_to_md_output.py +446 -0
  136. megadetector/data_management/yolo_to_coco.py +676 -0
  137. megadetector/detection/__init__.py +0 -0
  138. megadetector/detection/detector_training/__init__.py +0 -0
  139. megadetector/detection/detector_training/model_main_tf2.py +114 -0
  140. megadetector/detection/process_video.py +846 -0
  141. megadetector/detection/pytorch_detector.py +355 -0
  142. megadetector/detection/run_detector.py +779 -0
  143. megadetector/detection/run_detector_batch.py +1219 -0
  144. megadetector/detection/run_inference_with_yolov5_val.py +1087 -0
  145. megadetector/detection/run_tiled_inference.py +934 -0
  146. megadetector/detection/tf_detector.py +192 -0
  147. megadetector/detection/video_utils.py +698 -0
  148. megadetector/postprocessing/__init__.py +0 -0
  149. megadetector/postprocessing/add_max_conf.py +64 -0
  150. megadetector/postprocessing/categorize_detections_by_size.py +165 -0
  151. megadetector/postprocessing/classification_postprocessing.py +716 -0
  152. megadetector/postprocessing/combine_api_outputs.py +249 -0
  153. megadetector/postprocessing/compare_batch_results.py +966 -0
  154. megadetector/postprocessing/convert_output_format.py +396 -0
  155. megadetector/postprocessing/load_api_results.py +195 -0
  156. megadetector/postprocessing/md_to_coco.py +310 -0
  157. megadetector/postprocessing/md_to_labelme.py +330 -0
  158. megadetector/postprocessing/merge_detections.py +412 -0
  159. megadetector/postprocessing/postprocess_batch_results.py +1908 -0
  160. megadetector/postprocessing/remap_detection_categories.py +170 -0
  161. megadetector/postprocessing/render_detection_confusion_matrix.py +660 -0
  162. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +211 -0
  163. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +83 -0
  164. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1635 -0
  165. megadetector/postprocessing/separate_detections_into_folders.py +730 -0
  166. megadetector/postprocessing/subset_json_detector_output.py +700 -0
  167. megadetector/postprocessing/top_folders_to_bottom.py +223 -0
  168. megadetector/taxonomy_mapping/__init__.py +0 -0
  169. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  170. megadetector/taxonomy_mapping/map_new_lila_datasets.py +150 -0
  171. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +142 -0
  172. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +588 -0
  173. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  174. megadetector/taxonomy_mapping/simple_image_download.py +219 -0
  175. megadetector/taxonomy_mapping/species_lookup.py +834 -0
  176. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  177. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  178. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  179. megadetector/utils/__init__.py +0 -0
  180. megadetector/utils/azure_utils.py +178 -0
  181. megadetector/utils/ct_utils.py +613 -0
  182. megadetector/utils/directory_listing.py +246 -0
  183. megadetector/utils/md_tests.py +1164 -0
  184. megadetector/utils/path_utils.py +1045 -0
  185. megadetector/utils/process_utils.py +160 -0
  186. megadetector/utils/sas_blob_utils.py +509 -0
  187. megadetector/utils/split_locations_into_train_val.py +228 -0
  188. megadetector/utils/string_utils.py +92 -0
  189. megadetector/utils/url_utils.py +323 -0
  190. megadetector/utils/write_html_image_list.py +225 -0
  191. megadetector/visualization/__init__.py +0 -0
  192. megadetector/visualization/plot_utils.py +293 -0
  193. megadetector/visualization/render_images_with_thumbnails.py +275 -0
  194. megadetector/visualization/visualization_utils.py +1536 -0
  195. megadetector/visualization/visualize_db.py +552 -0
  196. megadetector/visualization/visualize_detector_output.py +405 -0
  197. {megadetector-5.0.11.dist-info → megadetector-5.0.13.dist-info}/LICENSE +0 -0
  198. {megadetector-5.0.11.dist-info → megadetector-5.0.13.dist-info}/METADATA +2 -2
  199. megadetector-5.0.13.dist-info/RECORD +201 -0
  200. megadetector-5.0.13.dist-info/top_level.txt +1 -0
  201. megadetector-5.0.11.dist-info/RECORD +0 -5
  202. megadetector-5.0.11.dist-info/top_level.txt +0 -1
  203. {megadetector-5.0.11.dist-info → megadetector-5.0.13.dist-info}/WHEEL +0 -0
@@ -0,0 +1,160 @@
1
+ """
2
+
3
+ process_utils.py
4
+
5
+ Run something at the command line and capture the output, based on:
6
+
7
+ https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running
8
+
9
+ Includes handy example code for doing this on multiple processes/threads.
10
+
11
+ """
12
+
13
+ #%% Constants, imports, and environment
14
+
15
+ import os
16
+ import subprocess
17
+
18
+ def execute(cmd,encoding=None,errors=None,env=None,verbose=False):
19
+ """
20
+ Run [cmd] (a single string) in a shell, yielding each line of output to the caller.
21
+
22
+ The "encoding", "errors", and "env" parameters are passed directly to subprocess.Popen().
23
+
24
+ "verbose" only impacts output about process management, it is not related to printing
25
+ output from the child process.
26
+
27
+ Args:
28
+ cmd (str): command to run
29
+ encoding (str, optional): stdout encoding, see Popen() documentation
30
+ errors (str, optional): error handling, see Popen() documentation
31
+ env (dict, optional): environment variables, see Popen() documentation
32
+ verbose (bool, optional): enable additional debug console output
33
+
34
+ Returns:
35
+ int: the command's return code, always zero, otherwise a CalledProcessError is raised
36
+ """
37
+
38
+ os.environ["PYTHONUNBUFFERED"] = "1"
39
+
40
+ if verbose:
41
+ if encoding is not None:
42
+ print('Launching child process with non-default encoding {}'.format(encoding))
43
+ if errors is not None:
44
+ print('Launching child process with non-default text error handling {}'.format(errors))
45
+ if env is not None:
46
+ print('Launching child process with non-default environment {}'.format(str(env)))
47
+
48
+ # https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running
49
+ popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
50
+ shell=True, universal_newlines=True, encoding=encoding,
51
+ errors=errors, env=env)
52
+ for stdout_line in iter(popen.stdout.readline, ""):
53
+ yield stdout_line
54
+ popen.stdout.close()
55
+ return_code = popen.wait()
56
+ if return_code:
57
+ raise subprocess.CalledProcessError(return_code, cmd)
58
+
59
+ return return_code
60
+
61
+
62
+ def execute_and_print(cmd,print_output=True,encoding=None,errors=None,
63
+ env=None,verbose=False,catch_exceptions=True):
64
+ """
65
+ Run [cmd] (a single string) in a shell, capturing and printing output. Returns
66
+ a dictionary with fields "status" and "output".
67
+
68
+ The "encoding", "errors", and "env" parameters are passed directly to subprocess.Popen().
69
+
70
+ "verbose" only impacts output about process management, it is not related to printing
71
+ output from the child process.
72
+
73
+ Args:
74
+ cmd (str): command to run
75
+ print_output (bool, optional): whether to print output from [cmd]
76
+ encoding (str, optional): stdout encoding, see Popen() documentation
77
+ errors (str, optional): error handling, see Popen() documentation
78
+ env (dict, optional): environment variables, see Popen() documentation
79
+ verbose (bool, optional): enable additional debug console output
80
+
81
+ Returns:
82
+ dict: a dictionary with fields "status" (the process return code) and "output"
83
+ (the content of stdout)
84
+ """
85
+
86
+ to_return = {'status':'unknown','output':''}
87
+ output = []
88
+ try:
89
+ for s in execute(cmd,encoding=encoding,errors=errors,env=env,verbose=verbose):
90
+ output.append(s)
91
+ if print_output:
92
+ print(s,end='',flush=True)
93
+ to_return['status'] = 0
94
+ except subprocess.CalledProcessError as cpe:
95
+ if not catch_exceptions:
96
+ raise
97
+ print('execute_and_print caught error: {} ({})'.format(cpe.output,str(cpe)))
98
+ to_return['status'] = cpe.returncode
99
+ to_return['output'] = output
100
+
101
+ return to_return
102
+
103
+
104
+ #%% Single-threaded test driver for execute_and_print
105
+
106
+ if False:
107
+
108
+ pass
109
+
110
+ #%%
111
+
112
+ if os.name == 'nt':
113
+ execute_and_print('echo hello && ping -n 5 127.0.0.1 && echo goodbye')
114
+ else:
115
+ execute_and_print('echo hello && sleep 1 && echo goodbye')
116
+
117
+
118
+ #%% Parallel test driver for execute_and_print
119
+
120
+ if False:
121
+
122
+ pass
123
+
124
+ #%%
125
+
126
+ from functools import partial
127
+ from multiprocessing.pool import ThreadPool as ThreadPool
128
+ from multiprocessing.pool import Pool as Pool
129
+
130
+ n_workers = 10
131
+
132
+ # Should we use threads (vs. processes) for parallelization?
133
+ use_threads = True
134
+
135
+ test_data = ['a','b','c','d']
136
+
137
+ def process_sample(s):
138
+ return execute_and_print('echo ' + s,True)
139
+
140
+ if n_workers == 1:
141
+
142
+ results = []
143
+ for i_sample,sample in enumerate(test_data):
144
+ results.append(process_sample(sample))
145
+
146
+ else:
147
+
148
+ n_threads = min(n_workers,len(test_data))
149
+
150
+ if use_threads:
151
+ print('Starting parallel thread pool with {} workers'.format(n_threads))
152
+ pool = ThreadPool(n_threads)
153
+ else:
154
+ print('Starting parallel process pool with {} workers'.format(n_threads))
155
+ pool = Pool(n_threads)
156
+
157
+ results = list(pool.map(partial(process_sample),test_data))
158
+
159
+ for r in results:
160
+ print(r)
@@ -0,0 +1,509 @@
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