megadetector 10.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 (147) hide show
  1. megadetector/__init__.py +0 -0
  2. megadetector/api/__init__.py +0 -0
  3. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  4. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  5. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  6. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +125 -0
  7. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  8. megadetector/classification/__init__.py +0 -0
  9. megadetector/classification/aggregate_classifier_probs.py +108 -0
  10. megadetector/classification/analyze_failed_images.py +227 -0
  11. megadetector/classification/cache_batchapi_outputs.py +198 -0
  12. megadetector/classification/create_classification_dataset.py +626 -0
  13. megadetector/classification/crop_detections.py +516 -0
  14. megadetector/classification/csv_to_json.py +226 -0
  15. megadetector/classification/detect_and_crop.py +853 -0
  16. megadetector/classification/efficientnet/__init__.py +9 -0
  17. megadetector/classification/efficientnet/model.py +415 -0
  18. megadetector/classification/efficientnet/utils.py +608 -0
  19. megadetector/classification/evaluate_model.py +520 -0
  20. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  21. megadetector/classification/json_to_azcopy_list.py +63 -0
  22. megadetector/classification/json_validator.py +696 -0
  23. megadetector/classification/map_classification_categories.py +276 -0
  24. megadetector/classification/merge_classification_detection_output.py +509 -0
  25. megadetector/classification/prepare_classification_script.py +194 -0
  26. megadetector/classification/prepare_classification_script_mc.py +228 -0
  27. megadetector/classification/run_classifier.py +287 -0
  28. megadetector/classification/save_mislabeled.py +110 -0
  29. megadetector/classification/train_classifier.py +827 -0
  30. megadetector/classification/train_classifier_tf.py +725 -0
  31. megadetector/classification/train_utils.py +323 -0
  32. megadetector/data_management/__init__.py +0 -0
  33. megadetector/data_management/animl_to_md.py +161 -0
  34. megadetector/data_management/annotations/__init__.py +0 -0
  35. megadetector/data_management/annotations/annotation_constants.py +33 -0
  36. megadetector/data_management/camtrap_dp_to_coco.py +270 -0
  37. megadetector/data_management/cct_json_utils.py +566 -0
  38. megadetector/data_management/cct_to_md.py +184 -0
  39. megadetector/data_management/cct_to_wi.py +293 -0
  40. megadetector/data_management/coco_to_labelme.py +284 -0
  41. megadetector/data_management/coco_to_yolo.py +702 -0
  42. megadetector/data_management/databases/__init__.py +0 -0
  43. megadetector/data_management/databases/add_width_and_height_to_db.py +107 -0
  44. megadetector/data_management/databases/combine_coco_camera_traps_files.py +210 -0
  45. megadetector/data_management/databases/integrity_check_json_db.py +528 -0
  46. megadetector/data_management/databases/subset_json_db.py +195 -0
  47. megadetector/data_management/generate_crops_from_cct.py +200 -0
  48. megadetector/data_management/get_image_sizes.py +164 -0
  49. megadetector/data_management/labelme_to_coco.py +559 -0
  50. megadetector/data_management/labelme_to_yolo.py +349 -0
  51. megadetector/data_management/lila/__init__.py +0 -0
  52. megadetector/data_management/lila/create_lila_blank_set.py +556 -0
  53. megadetector/data_management/lila/create_lila_test_set.py +187 -0
  54. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  55. megadetector/data_management/lila/download_lila_subset.py +182 -0
  56. megadetector/data_management/lila/generate_lila_per_image_labels.py +777 -0
  57. megadetector/data_management/lila/get_lila_annotation_counts.py +174 -0
  58. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  59. megadetector/data_management/lila/lila_common.py +319 -0
  60. megadetector/data_management/lila/test_lila_metadata_urls.py +164 -0
  61. megadetector/data_management/mewc_to_md.py +344 -0
  62. megadetector/data_management/ocr_tools.py +873 -0
  63. megadetector/data_management/read_exif.py +964 -0
  64. megadetector/data_management/remap_coco_categories.py +195 -0
  65. megadetector/data_management/remove_exif.py +156 -0
  66. megadetector/data_management/rename_images.py +194 -0
  67. megadetector/data_management/resize_coco_dataset.py +663 -0
  68. megadetector/data_management/speciesnet_to_md.py +41 -0
  69. megadetector/data_management/wi_download_csv_to_coco.py +247 -0
  70. megadetector/data_management/yolo_output_to_md_output.py +594 -0
  71. megadetector/data_management/yolo_to_coco.py +876 -0
  72. megadetector/data_management/zamba_to_md.py +188 -0
  73. megadetector/detection/__init__.py +0 -0
  74. megadetector/detection/change_detection.py +840 -0
  75. megadetector/detection/process_video.py +479 -0
  76. megadetector/detection/pytorch_detector.py +1451 -0
  77. megadetector/detection/run_detector.py +1267 -0
  78. megadetector/detection/run_detector_batch.py +2159 -0
  79. megadetector/detection/run_inference_with_yolov5_val.py +1314 -0
  80. megadetector/detection/run_md_and_speciesnet.py +1494 -0
  81. megadetector/detection/run_tiled_inference.py +1038 -0
  82. megadetector/detection/tf_detector.py +209 -0
  83. megadetector/detection/video_utils.py +1379 -0
  84. megadetector/postprocessing/__init__.py +0 -0
  85. megadetector/postprocessing/add_max_conf.py +72 -0
  86. megadetector/postprocessing/categorize_detections_by_size.py +166 -0
  87. megadetector/postprocessing/classification_postprocessing.py +1752 -0
  88. megadetector/postprocessing/combine_batch_outputs.py +249 -0
  89. megadetector/postprocessing/compare_batch_results.py +2110 -0
  90. megadetector/postprocessing/convert_output_format.py +403 -0
  91. megadetector/postprocessing/create_crop_folder.py +629 -0
  92. megadetector/postprocessing/detector_calibration.py +570 -0
  93. megadetector/postprocessing/generate_csv_report.py +522 -0
  94. megadetector/postprocessing/load_api_results.py +223 -0
  95. megadetector/postprocessing/md_to_coco.py +428 -0
  96. megadetector/postprocessing/md_to_labelme.py +351 -0
  97. megadetector/postprocessing/md_to_wi.py +41 -0
  98. megadetector/postprocessing/merge_detections.py +392 -0
  99. megadetector/postprocessing/postprocess_batch_results.py +2077 -0
  100. megadetector/postprocessing/remap_detection_categories.py +226 -0
  101. megadetector/postprocessing/render_detection_confusion_matrix.py +677 -0
  102. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +206 -0
  103. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +82 -0
  104. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1665 -0
  105. megadetector/postprocessing/separate_detections_into_folders.py +795 -0
  106. megadetector/postprocessing/subset_json_detector_output.py +964 -0
  107. megadetector/postprocessing/top_folders_to_bottom.py +238 -0
  108. megadetector/postprocessing/validate_batch_results.py +332 -0
  109. megadetector/taxonomy_mapping/__init__.py +0 -0
  110. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  111. megadetector/taxonomy_mapping/map_new_lila_datasets.py +213 -0
  112. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +165 -0
  113. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +543 -0
  114. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  115. megadetector/taxonomy_mapping/simple_image_download.py +224 -0
  116. megadetector/taxonomy_mapping/species_lookup.py +1008 -0
  117. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  118. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  119. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  120. megadetector/tests/__init__.py +0 -0
  121. megadetector/tests/test_nms_synthetic.py +335 -0
  122. megadetector/utils/__init__.py +0 -0
  123. megadetector/utils/ct_utils.py +1857 -0
  124. megadetector/utils/directory_listing.py +199 -0
  125. megadetector/utils/extract_frames_from_video.py +307 -0
  126. megadetector/utils/gpu_test.py +125 -0
  127. megadetector/utils/md_tests.py +2072 -0
  128. megadetector/utils/path_utils.py +2832 -0
  129. megadetector/utils/process_utils.py +172 -0
  130. megadetector/utils/split_locations_into_train_val.py +237 -0
  131. megadetector/utils/string_utils.py +234 -0
  132. megadetector/utils/url_utils.py +825 -0
  133. megadetector/utils/wi_platform_utils.py +968 -0
  134. megadetector/utils/wi_taxonomy_utils.py +1759 -0
  135. megadetector/utils/write_html_image_list.py +239 -0
  136. megadetector/visualization/__init__.py +0 -0
  137. megadetector/visualization/plot_utils.py +309 -0
  138. megadetector/visualization/render_images_with_thumbnails.py +243 -0
  139. megadetector/visualization/visualization_utils.py +1940 -0
  140. megadetector/visualization/visualize_db.py +630 -0
  141. megadetector/visualization/visualize_detector_output.py +479 -0
  142. megadetector/visualization/visualize_video_output.py +705 -0
  143. megadetector-10.0.13.dist-info/METADATA +134 -0
  144. megadetector-10.0.13.dist-info/RECORD +147 -0
  145. megadetector-10.0.13.dist-info/WHEEL +5 -0
  146. megadetector-10.0.13.dist-info/licenses/LICENSE +19 -0
  147. megadetector-10.0.13.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1759 @@
1
+ """
2
+
3
+ wi_taxonomy_utils.py
4
+
5
+ Functions related to working with the SpeciesNet / Wildlife Insights taxonomy.
6
+
7
+ """
8
+
9
+ #%% Imports and constants
10
+
11
+ import os
12
+ import json
13
+
14
+ import pandas as pd
15
+
16
+ from copy import deepcopy
17
+ from collections import defaultdict
18
+ from tqdm import tqdm
19
+
20
+ from megadetector.utils.path_utils import \
21
+ insert_before_extension, find_images
22
+
23
+ from megadetector.utils.ct_utils import (
24
+ split_list_into_n_chunks,
25
+ round_floats_in_nested_dict,
26
+ is_list_sorted,
27
+ invert_dictionary,
28
+ sort_list_of_dicts_by_key,
29
+ sort_dictionary_by_value,
30
+ )
31
+
32
+ from megadetector.postprocessing.validate_batch_results import \
33
+ validate_batch_results, ValidateBatchResultsOptions
34
+
35
+ from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP
36
+
37
+ md_category_id_to_name = DEFAULT_DETECTOR_LABEL_MAP
38
+ md_category_name_to_id = invert_dictionary(md_category_id_to_name)
39
+
40
+ blank_prediction_string = \
41
+ 'f1856211-cfb7-4a5b-9158-c0f72fd09ee6;;;;;;blank'
42
+ no_cv_result_prediction_string = \
43
+ 'f2efdae9-efb8-48fb-8a91-eccf79ab4ffb;no cv result;no cv result;no cv result;no cv result;no cv result;no cv result'
44
+ animal_prediction_string = \
45
+ '1f689929-883d-4dae-958c-3d57ab5b6c16;;;;;;animal'
46
+ human_prediction_string = \
47
+ '990ae9dd-7a59-4344-afcb-1b7b21368000;mammalia;primates;hominidae;homo;sapiens;human'
48
+ vehicle_prediction_string = \
49
+ 'e2895ed5-780b-48f6-8a11-9e27cb594511;;;;;;vehicle'
50
+
51
+ non_taxonomic_prediction_strings = [blank_prediction_string,
52
+ no_cv_result_prediction_string,
53
+ animal_prediction_string,
54
+ vehicle_prediction_string]
55
+
56
+ non_taxonomic_prediction_short_strings = [';'.join(s.split(';')[1:-1]) for s in \
57
+ non_taxonomic_prediction_strings]
58
+
59
+ # Ignore some files when generating instances.json from a folder
60
+ default_tokens_to_ignore = ['$RECYCLE.BIN']
61
+
62
+
63
+ #%% Miscellaneous taxonomy support functions
64
+
65
+ def is_valid_prediction_string(s):
66
+ """
67
+ Determine whether [s] is a valid WI prediction string. Prediction strings look like:
68
+
69
+ '90d950db-2106-4bd9-a4c1-777604c3eada;mammalia;rodentia;;;;rodent'
70
+
71
+ Args:
72
+ s (str): the string to be tested for validity
73
+
74
+ Returns:
75
+ bool: True if this looks more or less like a WI prediction string
76
+ """
77
+
78
+ # Note to self... don't get tempted to remove spaces here; spaces are used
79
+ # to indicate subspecies.
80
+ return isinstance(s,str) and (len(s.split(';')) == 7) and (s == s.lower())
81
+
82
+
83
+ def is_valid_taxonomy_string(s):
84
+ """
85
+ Determine whether [s] is a valid 5-token WI taxonomy string. Taxonomy strings
86
+ look like:
87
+
88
+ 'mammalia;rodentia;;;;rodent'
89
+ 'mammalia;chordata;canidae;canis;lupus dingo'
90
+
91
+ Args:
92
+ s (str): the string to be tested for validity
93
+
94
+ Returns:
95
+ bool: True if this looks more or less like a WI taxonomy string
96
+ """
97
+ return isinstance(s,str) and (len(s.split(';')) == 5) and (s == s.lower())
98
+
99
+
100
+ def clean_taxonomy_string(s):
101
+ """
102
+ If [s] is a seven-token prediction string, trim the GUID and common name to produce
103
+ a "clean" taxonomy string. Else if [s] is a five-token string, return it. Else error.
104
+
105
+ Args:
106
+ s (str): the seven- or five-token taxonomy/prediction string to clean
107
+
108
+ Returns:
109
+ str: the five-token taxonomy string
110
+ """
111
+
112
+ if is_valid_taxonomy_string(s):
113
+ return s
114
+ elif is_valid_prediction_string(s):
115
+ tokens = s.split(';')
116
+ assert len(tokens) == 7
117
+ return ';'.join(tokens[1:-1])
118
+ else:
119
+ raise ValueError('Invalid taxonomy string')
120
+
121
+
122
+ taxonomy_level_names = \
123
+ ['non-taxonomic','kingdom','phylum','class','order','family','genus','species','subspecies']
124
+
125
+
126
+ def taxonomy_level_to_string(k):
127
+ """
128
+ Maps taxonomy level indices (0 for kindgom, 1 for phylum, etc.) to strings.
129
+
130
+ Args:
131
+ k (int): taxonomy level index
132
+
133
+ Returns:
134
+ str: taxonomy level string
135
+ """
136
+
137
+ assert k >= 0 and k < len(taxonomy_level_names), \
138
+ 'Illegal taxonomy level index {}'.format(k)
139
+
140
+ return taxonomy_level_names[k]
141
+
142
+
143
+ def taxonomy_level_string_to_index(s):
144
+ """
145
+ Maps strings ('kingdom', 'species', etc.) to level indices.
146
+
147
+ Args:
148
+ s (str): taxonomy level string
149
+
150
+ Returns:
151
+ int: taxonomy level index
152
+ """
153
+
154
+ assert s in taxonomy_level_names, 'Unrecognized taxonomy level string {}'.format(s)
155
+ return taxonomy_level_names.index(s)
156
+
157
+
158
+ def taxonomy_level_index(s):
159
+ """
160
+ Returns the taxonomy level up to which [s] is defined (0 for non-taxnomic, 1 for kingdom,
161
+ 2 for phylum, etc. Empty strings and non-taxonomic strings are treated as level 0. 1 and 2
162
+ will never be returned; "animal" doesn't look like other taxonomic strings, so here we treat
163
+ it as non-taxonomic.
164
+
165
+ Args:
166
+ s (str): 5-token or 7-token taxonomy string
167
+
168
+ Returns:
169
+ int: taxonomy level
170
+ """
171
+
172
+ if s in non_taxonomic_prediction_strings or s in non_taxonomic_prediction_short_strings:
173
+ return 0
174
+
175
+ tokens = s.split(';')
176
+ assert len(tokens) in (5,7)
177
+
178
+ if len(tokens) == 7:
179
+ tokens = tokens[1:-1]
180
+
181
+ # Anything without a class is considered non-taxonomic
182
+ if len(tokens[0]) == 0:
183
+ return 0
184
+
185
+ # WI taxonomy strings start at class, so we'll never return 1 (kingdom) or 2 (phylum)
186
+ elif len(tokens[1]) == 0:
187
+ return 3
188
+ elif len(tokens[2]) == 0:
189
+ return 4
190
+ elif len(tokens[3]) == 0:
191
+ return 5
192
+ elif len(tokens[4]) == 0:
193
+ return 6
194
+ # Subspecies are delimited with a space
195
+ elif ' ' not in tokens[4]:
196
+ return 7
197
+ else:
198
+ return 8
199
+
200
+
201
+ def is_taxonomic_prediction_string(s):
202
+ """
203
+ Determines whether [s] is a classification string that has taxonomic properties; this
204
+ does not include, e.g., blanks/vehicles/no cv result. It also excludes "animal".
205
+
206
+ Args:
207
+ s (str): a five- or seven-token taxonomic string
208
+
209
+ Returns:
210
+ bool: whether [s] is a taxonomic category
211
+ """
212
+
213
+ return (taxonomy_level_index(s) > 0)
214
+
215
+
216
+
217
+ def get_kingdom(prediction_string):
218
+ """
219
+ Return the kingdom field from a WI prediction string
220
+
221
+ Args:
222
+ prediction_string (str): a string in the semicolon-delimited prediction string format
223
+
224
+ Returns:
225
+ str: the kingdom field from the input string
226
+ """
227
+ tokens = prediction_string.split(';')
228
+ assert is_valid_prediction_string(prediction_string)
229
+ return tokens[1]
230
+
231
+
232
+ def is_human_classification(prediction_string):
233
+ """
234
+ Determines whether the input string represents a human classification, which includes a variety
235
+ of common names (hiker, person, etc.)
236
+
237
+ Args:
238
+ prediction_string (str): a string in the semicolon-delimited prediction string format
239
+
240
+ Returns:
241
+ bool: whether this string corresponds to a human category
242
+ """
243
+ return prediction_string == human_prediction_string or 'homo;sapiens' in prediction_string
244
+
245
+
246
+ def is_vehicle_classification(prediction_string):
247
+ """
248
+ Determines whether the input string represents a vehicle classification.
249
+
250
+ Args:
251
+ prediction_string (str): a string in the semicolon-delimited prediction string format
252
+
253
+ Returns:
254
+ bool: whether this string corresponds to the vehicle category
255
+ """
256
+ return prediction_string == vehicle_prediction_string
257
+
258
+
259
+ def is_animal_classification(prediction_string):
260
+ """
261
+ Determines whether the input string represents an animal classification, which excludes, e.g.,
262
+ humans, blanks, vehicles, unknowns
263
+
264
+ Args:
265
+ prediction_string (str): a string in the semicolon-delimited prediction string format
266
+
267
+ Returns:
268
+ bool: whether this string corresponds to an animal category
269
+ """
270
+
271
+ if prediction_string == animal_prediction_string:
272
+ return True
273
+ if prediction_string == human_prediction_string or 'homo;sapiens' in prediction_string:
274
+ return False
275
+ if prediction_string == blank_prediction_string:
276
+ return False
277
+ if prediction_string == no_cv_result_prediction_string:
278
+ return False
279
+ if len(get_kingdom(prediction_string)) == 0:
280
+ return False
281
+ return True
282
+
283
+
284
+ def taxonomy_info_to_taxonomy_string(taxonomy_info, include_taxon_id_and_common_name=False):
285
+ """
286
+ Convert a taxonomy record in dict format to a five- or seven-token semicolon-delimited string
287
+
288
+ Args:
289
+ taxonomy_info (dict): dict in the format stored in, e.g., taxonomy_string_to_taxonomy_info
290
+ include_taxon_id_and_common_name (bool, optional): by default, this function returns a
291
+ five-token string of latin names; if this argument is True, it includes the leading
292
+ (GUID) and trailing (common name) tokens
293
+
294
+ Returns:
295
+ str: string in the format used as keys in, e.g., taxonomy_string_to_taxonomy_info
296
+ """
297
+ s = taxonomy_info['class'] + ';' + \
298
+ taxonomy_info['order'] + ';' + \
299
+ taxonomy_info['family'] + ';' + \
300
+ taxonomy_info['genus'] + ';' + \
301
+ taxonomy_info['species']
302
+
303
+ if include_taxon_id_and_common_name:
304
+ s = taxonomy_info['taxon_id'] + ';' + s + ';' + taxonomy_info['common_name']
305
+
306
+ return s
307
+
308
+
309
+ #%% Functions used to manipulate results files
310
+
311
+ def generate_whole_image_detections_for_classifications(classifications_json_file,
312
+ detections_json_file,
313
+ ensemble_json_file=None,
314
+ ignore_blank_classifications=True,
315
+ verbose=True):
316
+ """
317
+ Given a set of classification results in SpeciesNet format that were likely run on
318
+ already-cropped images, generate a file of [fake] detections in SpeciesNet format in which each
319
+ image is covered in a single whole-image detection.
320
+
321
+ Args:
322
+ classifications_json_file (str): SpeciesNet-formatted file containing classifications
323
+ detections_json_file (str): SpeciesNet-formatted file to write with detections
324
+ ensemble_json_file (str, optional): SpeciesNet-formatted file to write with detections
325
+ and classfications
326
+ ignore_blank_classifications (bool, optional): use non-top classifications when
327
+ the top classification is "blank" or "no CV result"
328
+ verbose (bool, optional): enable additional debug output
329
+
330
+ Returns:
331
+ dict: the contents of [detections_json_file]
332
+ """
333
+
334
+ with open(classifications_json_file,'r') as f:
335
+ classification_results = json.load(f)
336
+ predictions = classification_results['predictions']
337
+
338
+ output_predictions = []
339
+ ensemble_predictions = []
340
+
341
+ # i_prediction = 0; prediction = predictions[i_prediction]
342
+ for i_prediction,prediction in enumerate(predictions):
343
+
344
+ output_prediction = {}
345
+ output_prediction['filepath'] = prediction['filepath']
346
+ i_score = 0
347
+
348
+ if ignore_blank_classifications:
349
+
350
+ while (prediction['classifications']['classes'][i_score] in \
351
+ (blank_prediction_string,no_cv_result_prediction_string)):
352
+
353
+ i_score += 1
354
+ if (i_score >= len(prediction['classifications']['classes'])):
355
+
356
+ if verbose:
357
+
358
+ print('Ignoring blank classifications, but ' + \
359
+ 'image {} has no non-blank values'.format(
360
+ i_prediction))
361
+
362
+ # Just use the first one
363
+ i_score = 0
364
+ break
365
+
366
+ # ...if we passed the last prediction
367
+
368
+ # ...iterate over classes within this prediction
369
+
370
+ # ...if we're supposed to ignore blank classifications
371
+
372
+ top_classification = prediction['classifications']['classes'][i_score]
373
+ top_classification_score = prediction['classifications']['scores'][i_score]
374
+ if is_animal_classification(top_classification):
375
+ category_name = 'animal'
376
+ elif is_human_classification(top_classification):
377
+ category_name = 'human'
378
+ else:
379
+ category_name = 'vehicle'
380
+
381
+ if category_name == 'human':
382
+ md_category_name = 'person'
383
+ else:
384
+ md_category_name = category_name
385
+
386
+ output_detection = {}
387
+ output_detection['label'] = category_name
388
+ output_detection['category'] = md_category_name_to_id[md_category_name]
389
+ output_detection['conf'] = 1.0
390
+ output_detection['bbox'] = [0.0, 0.0, 1.0, 1.0]
391
+ output_prediction['detections'] = [output_detection]
392
+ output_predictions.append(output_prediction)
393
+
394
+ ensemble_prediction = {}
395
+ ensemble_prediction['filepath'] = prediction['filepath']
396
+ ensemble_prediction['detections'] = [output_detection]
397
+ ensemble_prediction['prediction'] = top_classification
398
+ ensemble_prediction['prediction_score'] = top_classification_score
399
+ ensemble_prediction['prediction_source'] = 'fake_ensemble_file_utility'
400
+ ensemble_prediction['classifications'] = prediction['classifications']
401
+ ensemble_predictions.append(ensemble_prediction)
402
+
403
+ # ...for each image
404
+
405
+ ## Write output
406
+
407
+ if ensemble_json_file is not None:
408
+
409
+ ensemble_output_data = {'predictions':ensemble_predictions}
410
+ with open(ensemble_json_file,'w') as f:
411
+ json.dump(ensemble_output_data,f,indent=1)
412
+ _ = validate_predictions_file(ensemble_json_file)
413
+
414
+ output_data = {'predictions':output_predictions}
415
+ with open(detections_json_file,'w') as f:
416
+ json.dump(output_data,f,indent=1)
417
+ return validate_predictions_file(detections_json_file)
418
+
419
+ # ...def generate_whole_image_detections_for_classifications(...)
420
+
421
+
422
+ def generate_md_results_from_predictions_json(predictions_json_file,
423
+ md_results_file=None,
424
+ base_folder=None,
425
+ max_decimals=5,
426
+ convert_human_to_person=True,
427
+ convert_homo_species_to_human=True,
428
+ verbose=False):
429
+ """
430
+ Generate an MD-formatted .json file from a predictions.json file, generated by the
431
+ SpeciesNet ensemble. Typically, MD results files use relative paths, and predictions.json
432
+ files use absolute paths, so this function optionally removes the leading string
433
+ [base_folder] from all file names.
434
+
435
+ Currently just applies the top classification category to every detection. If the top
436
+ classification is "blank", writes an empty detection list.
437
+
438
+ Uses the classification from the "prediction" field if it's available, otherwise
439
+ uses the "classifications" field.
440
+
441
+ When using the "prediction" field, records the top class in the "classifications" field to
442
+ a field in each image called "top_classification_common_name". This is often different
443
+ from the value of the "prediction" field.
444
+
445
+ speciesnet_to_md.py is a command-line driver for this function.
446
+
447
+ Args:
448
+ predictions_json_file (str): path to a predictions.json file, or a dict
449
+ md_results_file (str, optional): path to which we should write an MD-formatted .json file
450
+ base_folder (str, optional): leading string to remove from each path in the
451
+ predictions.json file
452
+ max_decimals (int, optional): number of decimal places to which we should round
453
+ all values
454
+ convert_human_to_person (bool, optional): WI predictions.json files sometimes use the
455
+ detection category "human"; MD files usually use "person". If True, switches "human"
456
+ to "person".
457
+ convert_homo_species_to_human (bool, optional): the ensemble often rolls human predictions
458
+ up to "homo species", which isn't wrong, but looks odd. This forces these back to
459
+ "homo sapiens".
460
+ verbose (bool, optional): enable additional debug output
461
+
462
+ Returns:
463
+ dict: results in MD format
464
+ """
465
+
466
+ # Read predictions file
467
+ if isinstance(predictions_json_file,str):
468
+ with open(predictions_json_file,'r') as f:
469
+ predictions = json.load(f)
470
+ else:
471
+ assert isinstance(predictions_json_file,dict)
472
+ predictions = predictions_json_file
473
+
474
+ # Round floating-point values (confidence scores, coordinates) to a
475
+ # reasonable number of decimal places
476
+ if (max_decimals is not None) and (max_decimals > 0):
477
+ round_floats_in_nested_dict(predictions, decimal_places=max_decimals)
478
+
479
+ predictions = predictions['predictions']
480
+ assert isinstance(predictions,list)
481
+
482
+ # Convert backslashes to forward slashes in both filenames and the base folder string
483
+ for im in predictions:
484
+ im['filepath'] = im['filepath'].replace('\\','/')
485
+ if base_folder is not None:
486
+ base_folder = base_folder.replace('\\','/')
487
+
488
+ detection_category_id_to_name = {}
489
+ classification_category_name_to_id = {}
490
+
491
+ # Keep track of detections that don't have an assigned detection category; these
492
+ # are fake detections we create for non-blank images with non-empty detection lists.
493
+ # We need to go back later and give them a legitimate detection category ID.
494
+ all_unknown_detections = []
495
+
496
+ # Create the output images list
497
+ images_out = []
498
+
499
+ base_folder_replacements = 0
500
+
501
+ # im_in = predictions[0]
502
+ for im_in in predictions:
503
+
504
+ im_out = {}
505
+
506
+ fn = im_in['filepath']
507
+ if base_folder is not None:
508
+ if fn.startswith(base_folder):
509
+ base_folder_replacements += 1
510
+ fn = fn.replace(base_folder,'',1)
511
+
512
+ im_out['file'] = fn
513
+
514
+ if 'failures' in im_in:
515
+
516
+ im_out['failure'] = str(im_in['failures'])
517
+ im_out['detections'] = None
518
+
519
+ else:
520
+
521
+ im_out['detections'] = []
522
+
523
+ if 'detections' in im_in:
524
+
525
+ if len(im_in['detections']) == 0:
526
+ im_out['detections'] = []
527
+ else:
528
+ # det_in = im_in['detections'][0]
529
+ for det_in in im_in['detections']:
530
+ det_out = {}
531
+ if det_in['category'] in detection_category_id_to_name:
532
+ assert detection_category_id_to_name[det_in['category']] == det_in['label']
533
+ else:
534
+ detection_category_id_to_name[det_in['category']] = det_in['label']
535
+ det_out = {}
536
+ for s in ['category','conf','bbox']:
537
+ det_out[s] = det_in[s]
538
+ im_out['detections'].append(det_out)
539
+
540
+ # ...if detections are present
541
+
542
+ class_to_assign = None
543
+ class_confidence = None
544
+ top_classification_common_name = None
545
+
546
+ if 'classifications' in im_in:
547
+
548
+ classifications = im_in['classifications']
549
+ assert len(classifications['scores']) == len(classifications['classes'])
550
+ assert is_list_sorted(classifications['scores'],reverse=True)
551
+ class_to_assign = classifications['classes'][0]
552
+ class_confidence = classifications['scores'][0]
553
+
554
+ tokens = class_to_assign.split(';')
555
+ assert len(tokens) == 7
556
+ top_classification_common_name = tokens[-1]
557
+ if len(top_classification_common_name) == 0:
558
+ top_classification_common_name = 'undefined'
559
+
560
+ if 'prediction' in im_in:
561
+
562
+ class_to_assign = None
563
+ im_out['top_classification_common_name'] = top_classification_common_name
564
+ class_to_assign = im_in['prediction']
565
+ if convert_homo_species_to_human and class_to_assign.endswith('homo species'):
566
+ class_to_assign = human_prediction_string
567
+ class_confidence = im_in['prediction_score']
568
+
569
+ if class_to_assign is not None:
570
+
571
+ if class_to_assign == blank_prediction_string:
572
+
573
+ # This is a scenario that's not captured well by the MD format: a blank prediction
574
+ # with detections present. But, for now, don't do anything special here, just making
575
+ # a note of this.
576
+ if len(im_out['detections']) > 0:
577
+ pass
578
+
579
+ else:
580
+
581
+ assert not class_to_assign.endswith('blank')
582
+
583
+ # This is a scenario that's not captured well by the MD format: no detections present,
584
+ # but a non-blank prediction. For now, create a fake detection to handle this prediction.
585
+ if len(im_out['detections']) == 0:
586
+
587
+ if verbose:
588
+ print('Warning: creating fake detection for non-blank whole-image classification' + \
589
+ ' in {}'.format(im_in['file']))
590
+ det_out = {}
591
+ all_unknown_detections.append(det_out)
592
+
593
+ # We will change this to a string-int later
594
+ det_out['category'] = 'unknown'
595
+ det_out['conf'] = class_confidence
596
+ det_out['bbox'] = [0,0,1,1]
597
+ im_out['detections'].append(det_out)
598
+
599
+ # ...if this is/isn't a blank classification
600
+
601
+ # Attach that classification to each detection
602
+
603
+ # Create a new category ID if necessary
604
+ if class_to_assign in classification_category_name_to_id:
605
+ classification_category_id = classification_category_name_to_id[class_to_assign]
606
+ else:
607
+ classification_category_id = str(len(classification_category_name_to_id))
608
+ classification_category_name_to_id[class_to_assign] = classification_category_id
609
+
610
+ for det in im_out['detections']:
611
+ det['classifications'] = []
612
+ det['classifications'].append([classification_category_id,class_confidence])
613
+
614
+ # ...if we have some type of classification for this image
615
+
616
+ # ...if this is/isn't a failure
617
+
618
+ images_out.append(im_out)
619
+
620
+ # ...for each image
621
+
622
+ if base_folder is not None:
623
+ if base_folder_replacements == 0:
624
+ print('Warning: you supplied {} as the base folder, but I made zero replacements'.format(
625
+ base_folder))
626
+
627
+ # Fix the 'unknown' category
628
+ if len(all_unknown_detections) > 0:
629
+
630
+ max_detection_category_id = max([int(x) for x in detection_category_id_to_name.keys()])
631
+ unknown_category_id = str(max_detection_category_id + 1)
632
+ detection_category_id_to_name[unknown_category_id] = 'unknown'
633
+
634
+ for det in all_unknown_detections:
635
+ assert det['category'] == 'unknown'
636
+ det['category'] = unknown_category_id
637
+
638
+
639
+ # Sort by filename
640
+
641
+ images_out = sort_list_of_dicts_by_key(images_out,'file')
642
+
643
+ # Prepare friendly classification names
644
+
645
+ classification_category_descriptions = \
646
+ invert_dictionary(classification_category_name_to_id)
647
+ classification_categories_out = {}
648
+ for category_id in classification_category_descriptions.keys():
649
+ category_name = classification_category_descriptions[category_id].split(';')[-1]
650
+ classification_categories_out[category_id] = category_name
651
+
652
+ # Prepare the output dict
653
+
654
+ detection_categories_out = detection_category_id_to_name
655
+ info = {}
656
+ info['format_version'] = 1.4
657
+ info['detector'] = 'converted_from_predictions_json'
658
+
659
+ if convert_human_to_person:
660
+ for k in detection_categories_out.keys():
661
+ if detection_categories_out[k] == 'human':
662
+ detection_categories_out[k] = 'person'
663
+
664
+ output_dict = {}
665
+ output_dict['info'] = info
666
+ output_dict['detection_categories'] = detection_categories_out
667
+ output_dict['classification_categories'] = classification_categories_out
668
+ output_dict['classification_category_descriptions'] = classification_category_descriptions
669
+ output_dict['images'] = images_out
670
+
671
+ if md_results_file is not None:
672
+ with open(md_results_file,'w') as f:
673
+ json.dump(output_dict,f,indent=1)
674
+
675
+ validation_options = ValidateBatchResultsOptions()
676
+ validation_options.raise_errors = True
677
+ _ = validate_batch_results(md_results_file, options=validation_options)
678
+
679
+ return output_dict
680
+
681
+ # ...def generate_md_results_from_predictions_json(...)
682
+
683
+
684
+ def generate_predictions_json_from_md_results(md_results_file,
685
+ predictions_json_file,
686
+ base_folder=None):
687
+ """
688
+ Generate a predictions.json file from the MD-formatted .json file [md_results_file]. Typically,
689
+ MD results files use relative paths, and predictions.json files use absolute paths, so
690
+ this function optionally prepends [base_folder]. Does not handle classification results in
691
+ MD format, since this is intended to prepare data for passing through the WI classifier.
692
+
693
+ md_to_wi.py is a command-line driver for this function.
694
+
695
+ Args:
696
+ md_results_file (str): path to an MD-formatted .json file
697
+ predictions_json_file (str): path to which we should write a predictions.json file
698
+ base_folder (str, optional): folder name to prepend to each path in md_results_file,
699
+ to convert relative paths to absolute paths.
700
+ """
701
+
702
+ # Validate the input file
703
+ validation_options = ValidateBatchResultsOptions()
704
+ validation_options.raise_errors = True
705
+ validation_options.return_data = True
706
+ md_results = validate_batch_results(md_results_file, options=validation_options)
707
+ category_id_to_name = md_results['detection_categories']
708
+
709
+ output_dict = {}
710
+ output_dict['predictions'] = []
711
+
712
+ # im = md_results['images'][0]
713
+ for im in md_results['images']:
714
+
715
+ prediction = {}
716
+ fn = im['file']
717
+ if base_folder is not None:
718
+ fn = os.path.join(base_folder,fn)
719
+ fn = fn.replace('\\','/')
720
+ prediction['filepath'] = fn
721
+ if 'failure' in im and im['failure'] is not None:
722
+ prediction['failures'] = ['DETECTOR']
723
+ else:
724
+ assert 'detections' in im and im['detections'] is not None
725
+ detections = []
726
+ for det in im['detections']:
727
+ output_det = deepcopy(det)
728
+ output_det['label'] = category_id_to_name[det['category']]
729
+ detections.append(output_det)
730
+
731
+ # detections *must* be sorted in descending order by confidence
732
+ detections = sort_list_of_dicts_by_key(detections,'conf', reverse=True)
733
+ prediction['detections'] = detections
734
+
735
+ assert len(prediction.keys()) >= 2
736
+ output_dict['predictions'].append(prediction)
737
+
738
+ # ...for each image
739
+
740
+ output_dir = os.path.dirname(predictions_json_file)
741
+ if len(output_dir) > 0:
742
+ os.makedirs(output_dir,exist_ok=True)
743
+ with open(predictions_json_file,'w') as f:
744
+ json.dump(output_dict,f,indent=1)
745
+
746
+ # ...def generate_predictions_json_from_md_results(...)
747
+
748
+
749
+ def generate_instances_json_from_folder(folder,
750
+ country=None,
751
+ admin1_region=None,
752
+ lat=None,
753
+ lon=None,
754
+ output_file=None,
755
+ filename_replacements=None,
756
+ tokens_to_ignore=default_tokens_to_ignore):
757
+ """
758
+ Generate an instances.json record that contains all images in [folder], optionally
759
+ including location information, in a format suitable for run_model.py. Optionally writes
760
+ the results to [output_file].
761
+
762
+ Args:
763
+ folder (str): the folder to recursively search for images
764
+ country (str, optional): a three-letter country code
765
+ admin1_region (str, optional): an administrative region code, typically a two-letter
766
+ US state code
767
+ lat (float, optional): latitude to associate with all images
768
+ lon (float, optional): longitude to associate with all images
769
+ output_file (str, optional): .json file to which we should write instance records
770
+ filename_replacements (dict, optional): str --> str dict indicating filename substrings
771
+ that should be replaced with other strings. Replacement occurs *after* converting
772
+ backslashes to forward slashes.
773
+ tokens_to_ignore (list, optional): ignore any images with these tokens in their
774
+ names, typically used to avoid $RECYCLE.BIN. Can be None.
775
+
776
+ Returns:
777
+ dict: dict with at least the field "instances"
778
+ """
779
+
780
+ assert os.path.isdir(folder)
781
+
782
+ print('Enumerating images in {}'.format(folder))
783
+ image_files_abs = find_images(folder,recursive=True,return_relative_paths=False)
784
+
785
+ if tokens_to_ignore is not None:
786
+ n_images_before_ignore_tokens = len(image_files_abs)
787
+ for token in tokens_to_ignore:
788
+ image_files_abs = [fn for fn in image_files_abs if token not in fn]
789
+ print('After ignoring {} tokens, kept {} of {} images'.format(
790
+ len(tokens_to_ignore),len(image_files_abs),n_images_before_ignore_tokens))
791
+
792
+ instances = []
793
+
794
+ # image_fn_abs = image_files_abs[0]
795
+ for image_fn_abs in image_files_abs:
796
+ instance = {}
797
+ instance['filepath'] = image_fn_abs.replace('\\','/')
798
+ if filename_replacements is not None:
799
+ for s in filename_replacements:
800
+ instance['filepath'] = instance['filepath'].replace(s,filename_replacements[s])
801
+ if country is not None:
802
+ instance['country'] = country
803
+ if admin1_region is not None:
804
+ instance['admin1_region'] = admin1_region
805
+ if lat is not None:
806
+ assert lon is not None, 'Latitude provided without longitude'
807
+ instance['latitude'] = lat
808
+ if lon is not None:
809
+ assert lat is not None, 'Longitude provided without latitude'
810
+ instance['longitude'] = lon
811
+ instances.append(instance)
812
+
813
+ to_return = {'instances':instances}
814
+
815
+ if output_file is not None:
816
+ output_dir = os.path.dirname(output_file)
817
+ if len(output_dir) > 0:
818
+ os.makedirs(output_dir,exist_ok=True)
819
+ with open(output_file,'w') as f:
820
+ json.dump(to_return,f,indent=1)
821
+
822
+ return to_return
823
+
824
+ # ...def generate_instances_json_from_folder(...)
825
+
826
+
827
+ def split_instances_into_n_batches(instances_json,n_batches,output_files=None):
828
+ """
829
+ Given an instances.json file, split it into batches of equal size.
830
+
831
+ Args:
832
+ instances_json (str): input .json file in
833
+ n_batches (int): number of new files to generate
834
+ output_files (list, optional): output .json files for each
835
+ batch. If supplied, should have length [n_batches]. If not
836
+ supplied, filenames will be generated based on [instances_json].
837
+
838
+ Returns:
839
+ list: list of output files that were written; identical to [output_files]
840
+ if it was supplied as input.
841
+ """
842
+
843
+ with open(instances_json,'r') as f:
844
+ instances = json.load(f)
845
+ assert isinstance(instances,dict) and 'instances' in instances
846
+ instances = instances['instances']
847
+
848
+ if output_files is not None:
849
+ assert len(output_files) == n_batches, \
850
+ 'Expected {} output files, received {}'.format(
851
+ n_batches,len(output_files))
852
+ else:
853
+ output_files = []
854
+ for i_batch in range(0,n_batches):
855
+ batch_string = 'batch_{}'.format(str(i_batch).zfill(3))
856
+ output_files.append(insert_before_extension(instances_json,batch_string))
857
+
858
+ batches = split_list_into_n_chunks(instances, n_batches)
859
+
860
+ for i_batch,batch in enumerate(batches):
861
+ batch_dict = {'instances':batch}
862
+ with open(output_files[i_batch],'w') as f:
863
+ json.dump(batch_dict,f,indent=1)
864
+
865
+ print('Wrote {} batches to file'.format(n_batches))
866
+
867
+ return output_files
868
+
869
+ # ...def split_instances_into_n_batches(...)
870
+
871
+
872
+ def merge_prediction_json_files(input_prediction_files,output_prediction_file):
873
+ """
874
+ Merge all predictions.json files in [files] into a single .json file.
875
+
876
+ Args:
877
+ input_prediction_files (list): list of predictions.json files to merge
878
+ output_prediction_file (str): output .json file
879
+ """
880
+
881
+ predictions = []
882
+ image_filenames_processed = set()
883
+
884
+ # input_json_fn = input_prediction_files[0]
885
+ for input_json_fn in tqdm(input_prediction_files):
886
+
887
+ assert os.path.isfile(input_json_fn), \
888
+ 'Could not find prediction file {}'.format(input_json_fn)
889
+ with open(input_json_fn,'r') as f:
890
+ results_this_file = json.load(f)
891
+ assert isinstance(results_this_file,dict)
892
+ predictions_this_file = results_this_file['predictions']
893
+ for prediction in predictions_this_file:
894
+ image_fn = prediction['filepath']
895
+ assert image_fn not in image_filenames_processed
896
+ predictions.extend(predictions_this_file)
897
+
898
+ output_dict = {'predictions':predictions}
899
+
900
+ output_dir = os.path.dirname(output_prediction_file)
901
+ if len(output_dir) > 0:
902
+ os.makedirs(output_dir,exist_ok=True)
903
+ with open(output_prediction_file,'w') as f:
904
+ json.dump(output_dict,f,indent=1)
905
+
906
+ # ...def merge_prediction_json_files(...)
907
+
908
+
909
+ def load_md_or_speciesnet_file(fn,verbose=True):
910
+ """
911
+ Load a .json file that may be in MD or SpeciesNet format. Typically used so
912
+ SpeciesNet files can be supplied to functions originally written to support MD
913
+ format.
914
+
915
+ Args:
916
+ fn (str): a .json file in predictions.json (MD or SpeciesNet) format
917
+ verbose (bool, optional): enable additional debug output
918
+
919
+ Returns:
920
+ dict: the contents of [fn], in MD format.
921
+ """
922
+
923
+ with open(fn,'r') as f:
924
+ detector_output = json.load(f)
925
+
926
+ # If this is a SpeicesNet file, convert to MD format
927
+ if 'predictions' in detector_output:
928
+
929
+ if verbose:
930
+ print('This appears to be a SpeciesNet output file, converting to MD format')
931
+ detector_output = generate_md_results_from_predictions_json(predictions_json_file=fn,
932
+ md_results_file=None,
933
+ base_folder=None)
934
+
935
+ # ...if this is a SpeciesNet file
936
+
937
+ assert 'images' in detector_output, \
938
+ 'Detector output file should be a json file with an "images" field.'
939
+
940
+ return detector_output
941
+
942
+ # ...def load_md_or_speciesnet_file(...)
943
+
944
+
945
+ def validate_predictions_file(fn,instances=None,verbose=True):
946
+ """
947
+ Validate the predictions.json file [fn].
948
+
949
+ Args:
950
+ fn (str): a .json file in predictions.json (SpeciesNet) format
951
+ instances (str or list, optional): a folder, instances.json file,
952
+ or dict loaded from an instances.json file. If supplied, this
953
+ function will verify that [fn] contains the same number of
954
+ images as [instances].
955
+ verbose (bool, optional): enable additional debug output
956
+
957
+ Returns:
958
+ dict: the contents of [fn]
959
+ """
960
+
961
+ with open(fn,'r') as f:
962
+ d = json.load(f)
963
+ predictions = d['predictions']
964
+
965
+ failures = []
966
+
967
+ for im in predictions:
968
+ if 'failures' in im:
969
+ failures.append(im)
970
+
971
+ if verbose:
972
+ print('Read predictions for {} images, with {} failure(s)'.format(
973
+ len(d['predictions']),len(failures)))
974
+
975
+ if instances is not None:
976
+
977
+ if isinstance(instances,str):
978
+ if os.path.isdir(instances):
979
+ instances = generate_instances_json_from_folder(folder=instances)
980
+ elif os.path.isfile(instances):
981
+ with open(instances,'r') as f:
982
+ instances = json.load(f)
983
+ else:
984
+ raise ValueError('Could not find instances file/folder {}'.format(
985
+ instances))
986
+ assert isinstance(instances,dict)
987
+ assert 'instances' in instances
988
+ instances = instances['instances']
989
+ if verbose:
990
+ print('Expected results for {} files'.format(len(instances)))
991
+ assert len(instances) == len(predictions), \
992
+ '{} instances expected, {} found'.format(
993
+ len(instances),len(predictions))
994
+
995
+ expected_files = set([instance['filepath'] for instance in instances])
996
+ found_files = set([prediction['filepath'] for prediction in predictions])
997
+ assert expected_files == found_files
998
+
999
+ # ...if a list of instances was supplied
1000
+
1001
+ return d
1002
+
1003
+ # ...def validate_predictions_file(...)
1004
+
1005
+
1006
+ #%% Functions related to geofencing
1007
+
1008
+ def find_geofence_adjustments(ensemble_json_file,use_latin_names=False):
1009
+ """
1010
+ Count the number of instances of each unique change made by the geofence.
1011
+
1012
+ Args:
1013
+ ensemble_json_file (str): SpeciesNet-formatted .json file produced
1014
+ by the full ensemble.
1015
+ use_latin_names (bool, optional): return a mapping using binomial names
1016
+ rather than common names.
1017
+
1018
+ Returns:
1019
+ dict: maps strings that look like "puma,felidae family" to integers,
1020
+ where that entry would indicate the number of times that "puma" was
1021
+ predicted, but mapped to family level by the geofence. Sorted in
1022
+ descending order by count.
1023
+ """
1024
+
1025
+ # Load and validate ensemble results
1026
+ ensemble_results = validate_predictions_file(ensemble_json_file)
1027
+
1028
+ assert isinstance(ensemble_results,dict)
1029
+ predictions = ensemble_results['predictions']
1030
+
1031
+ # Maps comma-separated pairs of common names (or binomial names) to
1032
+ # the number of times that transition (first --> second) happened
1033
+ rollup_pair_to_count = defaultdict(int)
1034
+
1035
+ # prediction = predictions[0]
1036
+ for prediction in tqdm(predictions):
1037
+
1038
+ if 'failures' in prediction and \
1039
+ prediction['failures'] is not None and \
1040
+ len(prediction['failures']) > 0:
1041
+ continue
1042
+
1043
+ assert 'prediction_source' in prediction, \
1044
+ 'Prediction present without [prediction_source] field, are you sure this ' + \
1045
+ 'is an ensemble output file?'
1046
+
1047
+ if 'geofence' in prediction['prediction_source']:
1048
+
1049
+ classification_taxonomy_string = \
1050
+ prediction['classifications']['classes'][0]
1051
+ prediction_taxonomy_string = prediction['prediction']
1052
+ assert is_valid_prediction_string(classification_taxonomy_string)
1053
+ assert is_valid_prediction_string(prediction_taxonomy_string)
1054
+
1055
+ # Typical examples:
1056
+ # '86f5b978-4f30-40cc-bd08-be9e3fba27a0;mammalia;rodentia;sciuridae;sciurus;carolinensis;eastern gray squirrel'
1057
+ # 'e4d1e892-0e4b-475a-a8ac-b5c3502e0d55;mammalia;rodentia;sciuridae;;;sciuridae family'
1058
+ classification_common_name = classification_taxonomy_string.split(';')[-1]
1059
+ prediction_common_name = prediction_taxonomy_string.split(';')[-1]
1060
+ classification_binomial_name = classification_taxonomy_string.split(';')[-2]
1061
+ prediction_binomial_name = prediction_taxonomy_string.split(';')[-2]
1062
+
1063
+ input_name = classification_binomial_name if use_latin_names else \
1064
+ classification_common_name
1065
+ output_name = prediction_binomial_name if use_latin_names else \
1066
+ prediction_common_name
1067
+
1068
+ rollup_pair = input_name.strip() + ',' + output_name.strip()
1069
+ rollup_pair_to_count[rollup_pair] += 1
1070
+
1071
+ # ...if we made a geofencing change
1072
+
1073
+ # ...for each prediction
1074
+
1075
+ rollup_pair_to_count = sort_dictionary_by_value(rollup_pair_to_count,reverse=True)
1076
+
1077
+ return rollup_pair_to_count
1078
+
1079
+ # ...def find_geofence_adjustments(...)
1080
+
1081
+
1082
+ def generate_geofence_adjustment_html_summary(rollup_pair_to_count,min_count=10):
1083
+ """
1084
+ Given a list of geofence rollups, likely generated by find_geofence_adjustments,
1085
+ generate an HTML summary of the changes made by geofencing. The resulting HTML
1086
+ is wrapped in <div>, but not, for example, in <html> or <body>.
1087
+
1088
+ Args:
1089
+ rollup_pair_to_count (dict): list of changes made by geofencing, see
1090
+ find_geofence_adjustments for details
1091
+ min_count (int, optional): minimum number of changes a pair needs in order
1092
+ to be included in the report.
1093
+ """
1094
+
1095
+ geofence_footer = ''
1096
+
1097
+ # Restrict to the list of taxa that were impacted by geofencing
1098
+ rollup_pair_to_count = \
1099
+ {key: value for key, value in rollup_pair_to_count.items() if value >= min_count}
1100
+
1101
+ # rollup_pair_to_count is sorted in descending order by count
1102
+ assert is_list_sorted(list(rollup_pair_to_count.values()),reverse=True)
1103
+
1104
+ if len(rollup_pair_to_count) > 0:
1105
+
1106
+ geofence_footer = \
1107
+ '<h3>Geofence changes that occurred more than {} times</h3>\n'.format(min_count)
1108
+ geofence_footer += '<div class="contentdiv">\n'
1109
+
1110
+ print('\nRollup changes with count > {}:'.format(min_count))
1111
+ for rollup_pair in rollup_pair_to_count.keys():
1112
+ count = rollup_pair_to_count[rollup_pair]
1113
+ rollup_pair_s = rollup_pair.replace(',',' --> ')
1114
+ print('{}: {}'.format(rollup_pair_s,count))
1115
+ rollup_pair_html = rollup_pair.replace(',',' &rarr; ')
1116
+ geofence_footer += '{} ({})<br/>\n'.format(rollup_pair_html,count)
1117
+
1118
+ geofence_footer += '</div>\n'
1119
+
1120
+ return geofence_footer
1121
+
1122
+ # ...def generate_geofence_adjustment_html_summary(...)
1123
+
1124
+
1125
+ #%% TaxonomyHandler class
1126
+
1127
+ class TaxonomyHandler:
1128
+ """
1129
+ Handler for taxonomy mapping and geofencing operations.
1130
+ """
1131
+
1132
+ def __init__(self, taxonomy_file, geofencing_file, country_code_file):
1133
+ """
1134
+ Initialize TaxonomyHandler with taxonomy information.
1135
+
1136
+ Args:
1137
+ taxonomy_file (str): .csv file containing the SpeciesNet (or WI) taxonomy,
1138
+ as seven-token taxonomic specifiers. Distributed with the SpeciesNet model.
1139
+ geofencing_file (str): .json file containing the SpeciesNet geofencing rules.
1140
+ Distributed with the SpeciesNet model.
1141
+ country_code_file: .csv file mapping country codes to names. Should include columns
1142
+ called "name" and "alpha-3". A compatible file is available at
1143
+ https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes
1144
+ """
1145
+
1146
+ #: Maps a taxonomy string (e.g. mammalia;cetartiodactyla;cervidae;odocoileus;virginianus) to
1147
+ #: a dict with keys taxon_id, common_name, kingdom, phylum, class, order, family, genus, species
1148
+ self.taxonomy_string_to_taxonomy_info = None
1149
+
1150
+ #: Maps a binomial name (one, two, or three ws-delimited tokens) to the same dict described above.
1151
+ self.binomial_name_to_taxonomy_info = None
1152
+
1153
+ #: Maps a common name to the same dict described above
1154
+ self.common_name_to_taxonomy_info = None
1155
+
1156
+ #: Dict mapping 5-token semicolon-delimited taxonomy strings to geofencing rules
1157
+ self.taxonomy_string_to_geofencing_rules = None
1158
+
1159
+ #: Maps lower-case country names to upper-case country codes
1160
+ self.country_to_country_code = None
1161
+
1162
+ #: Maps upper-case country codes to lower-case country names
1163
+ self.country_code_to_country = None
1164
+
1165
+ self._load_taxonomy_info(taxonomy_file=taxonomy_file)
1166
+ self._initialize_geofencing(geofencing_file=geofencing_file,
1167
+ country_code_file=country_code_file)
1168
+
1169
+
1170
+ def _load_taxonomy_info(self, taxonomy_file):
1171
+ """
1172
+ Load WI/SpeciesNet taxonomy information from a .csv file. Stores information in the
1173
+ instance dicts [taxonomy_string_to_taxonomy_info], [binomial_name_to_taxonomy_info],
1174
+ and [common_name_to_taxonomy_info].
1175
+
1176
+ Args:
1177
+ taxonomy_file (str): .csv file containing the SpeciesNet (or WI) taxonomy,
1178
+ as seven-token taxonomic specifiers. Distributed with the SpeciesNet model.
1179
+ """
1180
+
1181
+ """
1182
+ Taxonomy keys are five-token taxonomy strings, e.g.:
1183
+
1184
+ 'mammalia;cetartiodactyla;cervidae;odocoileus;virginianus'
1185
+
1186
+ Taxonomy values are seven-token strings w/Taxon IDs and common names, e.g.:
1187
+
1188
+ '5c7ce479-8a45-40b3-ae21-7c97dfae22f5;mammalia;cetartiodactyla;cervidae;odocoileus;virginianus;white-tailed deer'
1189
+ """
1190
+
1191
+ with open(taxonomy_file,'r') as f:
1192
+ taxonomy_lines = f.readlines()
1193
+ taxonomy_lines = [s.strip() for s in taxonomy_lines]
1194
+
1195
+ self.taxonomy_string_to_taxonomy_info = {}
1196
+ self.binomial_name_to_taxonomy_info = {}
1197
+ self.common_name_to_taxonomy_info = {}
1198
+
1199
+ five_token_string_to_seven_token_string = {}
1200
+
1201
+ for line in taxonomy_lines:
1202
+ tokens = line.split(';')
1203
+ assert len(tokens) == 7, 'Illegal line {} in taxonomy file {}'.format(
1204
+ line,taxonomy_file)
1205
+ five_token_string = ';'.join(tokens[1:-1])
1206
+ assert len(five_token_string.split(';')) == 5
1207
+ five_token_string_to_seven_token_string[five_token_string] = line
1208
+
1209
+ for taxonomy_string in five_token_string_to_seven_token_string.keys():
1210
+
1211
+ taxonomy_string = taxonomy_string.lower()
1212
+
1213
+ taxon_info = {}
1214
+ extended_string = five_token_string_to_seven_token_string[taxonomy_string]
1215
+ tokens = extended_string.split(';')
1216
+ assert len(tokens) == 7
1217
+ taxon_info['taxon_id'] = tokens[0]
1218
+ assert len(taxon_info['taxon_id']) == 36
1219
+ taxon_info['kingdom'] = 'animal'
1220
+ taxon_info['phylum'] = 'chordata'
1221
+ taxon_info['class'] = tokens[1]
1222
+ taxon_info['order'] = tokens[2]
1223
+ taxon_info['family'] = tokens[3]
1224
+ taxon_info['genus'] = tokens[4]
1225
+ taxon_info['species'] = tokens[5]
1226
+ taxon_info['common_name'] = tokens[6]
1227
+
1228
+ if taxon_info['common_name'] != '':
1229
+ self.common_name_to_taxonomy_info[taxon_info['common_name']] = taxon_info
1230
+
1231
+ self.taxonomy_string_to_taxonomy_info[taxonomy_string] = taxon_info
1232
+
1233
+ binomial_name = None
1234
+ if len(tokens[4]) > 0 and len(tokens[5]) > 0:
1235
+ # strip(), but don't remove spaces from the species name;
1236
+ # subspecies are separated with a space, e.g. canis;lupus dingo
1237
+ binomial_name = tokens[4].strip() + ' ' + tokens[5].strip()
1238
+ elif len(tokens[4]) > 0:
1239
+ binomial_name = tokens[4].strip()
1240
+ elif len(tokens[3]) > 0:
1241
+ binomial_name = tokens[3].strip()
1242
+ elif len(tokens[2]) > 0:
1243
+ binomial_name = tokens[2].strip()
1244
+ elif len(tokens[1]) > 0:
1245
+ binomial_name = tokens[1].strip()
1246
+ if binomial_name is None:
1247
+ # print('Warning: no binomial name for {}'.format(taxonomy_string))
1248
+ pass
1249
+ else:
1250
+ self.binomial_name_to_taxonomy_info[binomial_name] = taxon_info
1251
+
1252
+ taxon_info['binomial_name'] = binomial_name
1253
+
1254
+ # ...for each taxonomy string in the file
1255
+
1256
+ print('Created {} records in taxonomy_string_to_taxonomy_info'.format(len(self.taxonomy_string_to_taxonomy_info)))
1257
+ print('Created {} records in common_name_to_taxonomy_info'.format(len(self.common_name_to_taxonomy_info)))
1258
+
1259
+ # ...def _load_taxonomy_info(...)
1260
+
1261
+
1262
+ def _initialize_geofencing(self, geofencing_file, country_code_file):
1263
+ """
1264
+ Load geofencing information from a .json file, and country code mappings from
1265
+ a .csv file. Stores results in the instance tables [taxonomy_string_to_geofencing_rules],
1266
+ [country_to_country_code], and [country_code_to_country].
1267
+
1268
+ Args:
1269
+ geofencing_file (str): .json file with geofencing rules
1270
+ country_code_file (str): .csv file with country code mappings, in columns
1271
+ called "name" and "alpha-3", e.g. from
1272
+ https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.csv
1273
+ """
1274
+
1275
+ # Read country code information
1276
+ country_code_df = pd.read_csv(country_code_file)
1277
+ self.country_to_country_code = {}
1278
+ self.country_code_to_country = {}
1279
+ for i_row,row in country_code_df.iterrows():
1280
+ self.country_to_country_code[row['name'].lower()] = row['alpha-3'].upper()
1281
+ self.country_code_to_country[row['alpha-3'].upper()] = row['name'].lower()
1282
+
1283
+ # Read geofencing information
1284
+ with open(geofencing_file,'r',encoding='utf-8') as f:
1285
+ self.taxonomy_string_to_geofencing_rules = json.load(f)
1286
+
1287
+ """
1288
+ Geofencing keys are five-token taxonomy strings, e.g.:
1289
+
1290
+ 'mammalia;cetartiodactyla;cervidae;odocoileus;virginianus'
1291
+
1292
+ Geofencing values are tables mapping allow/block to country codes, optionally including region/state codes, e.g.:
1293
+
1294
+ {'allow': {
1295
+ 'ALA': [],
1296
+ 'ARG': [],
1297
+ ...
1298
+ 'SUR': [],
1299
+ 'TTO': [],
1300
+ 'USA': ['AL',
1301
+ 'AR',
1302
+ 'AZ',
1303
+ ...
1304
+ }
1305
+ """
1306
+
1307
+ # Validate
1308
+
1309
+ # species_string = next(iter(taxonomy_string_to_geofencing_rules.keys()))
1310
+ for species_string in self.taxonomy_string_to_geofencing_rules.keys():
1311
+
1312
+ species_rules = self.taxonomy_string_to_geofencing_rules[species_string]
1313
+
1314
+ if len(species_rules.keys()) > 1:
1315
+ print('Warning: taxon {} has both allow and block rules'.format(species_string))
1316
+
1317
+ for rule_type in species_rules.keys():
1318
+
1319
+ assert rule_type in ('allow','block')
1320
+ all_country_rules_this_species = species_rules[rule_type]
1321
+
1322
+ for country_code in all_country_rules_this_species.keys():
1323
+
1324
+ assert country_code in self.country_code_to_country
1325
+ region_rules = all_country_rules_this_species[country_code]
1326
+ # Right now we only have regional rules for the USA; these may be part of
1327
+ # allow or block rules.
1328
+ if len(region_rules) > 0:
1329
+ assert country_code == 'USA'
1330
+
1331
+ # ...for each country code in this rule set
1332
+
1333
+ # ...for each rule set for this species
1334
+
1335
+ # ...for each species
1336
+
1337
+ # ...def _initialize_geofencing(...)
1338
+
1339
+
1340
+ def _parse_region_code_list(self, codes):
1341
+ """
1342
+ Turn a list of country or state codes in string, delimited string, or list format
1343
+ into a list. Also does basic validity checking.
1344
+ """
1345
+
1346
+ if not isinstance(codes,list):
1347
+
1348
+ assert isinstance(codes,str)
1349
+
1350
+ codes = codes.strip()
1351
+
1352
+ # This is just a single codes
1353
+ if ',' not in codes:
1354
+ codes = [codes]
1355
+ else:
1356
+ codes = codes.split(',')
1357
+ codes = [c.strip() for c in codes]
1358
+
1359
+ assert isinstance(codes,list)
1360
+
1361
+ codes = [c.upper().strip() for c in codes]
1362
+
1363
+ for c in codes:
1364
+ assert len(c) in (2,3)
1365
+
1366
+ return codes
1367
+
1368
+ # ...def _parse_region_code_list(...)
1369
+
1370
+
1371
+ def generate_csv_rows_to_block_all_countries_except(self, species_string, block_except_list):
1372
+ """
1373
+ Generate rows in the format expected by geofence_fixes.csv, representing a list of
1374
+ allow and block rules to block all countries currently allowed for this species
1375
+ except [allow_countries], and add allow rules these countries.
1376
+
1377
+ Args:
1378
+ species_string (str): five-token taxonomy string
1379
+ block_except_list (list): list of country codes not to block
1380
+
1381
+ Returns:
1382
+ list of str: strings compatible with geofence_fixes.csv
1383
+ """
1384
+
1385
+ assert is_valid_taxonomy_string(species_string), \
1386
+ '{} is not a valid taxonomy string'.format(species_string)
1387
+
1388
+ assert self.taxonomy_string_to_geofencing_rules is not None, \
1389
+ 'Initialize geofencing prior to species lookup'
1390
+ assert self.taxonomy_string_to_taxonomy_info is not None, \
1391
+ 'Initialize taxonomy lookup prior to species lookup'
1392
+
1393
+ geofencing_rules_this_species = \
1394
+ self.taxonomy_string_to_geofencing_rules[species_string]
1395
+
1396
+ allowed_countries = []
1397
+ if 'allow' in geofencing_rules_this_species:
1398
+ allowed_countries.extend(geofencing_rules_this_species['allow'])
1399
+
1400
+ blocked_countries = []
1401
+ if 'block' in geofencing_rules_this_species:
1402
+ blocked_countries.extend(geofencing_rules_this_species['block'])
1403
+
1404
+ block_except_list = self._parse_region_code_list(block_except_list)
1405
+
1406
+ countries_to_block = []
1407
+ countries_to_allow = []
1408
+
1409
+ # country = allowed_countries[0]
1410
+ for country in allowed_countries:
1411
+ if country not in block_except_list and country not in blocked_countries:
1412
+ countries_to_block.append(country)
1413
+
1414
+ for country in block_except_list:
1415
+ if country in blocked_countries:
1416
+ raise ValueError("I can't allow a country that has already been blocked")
1417
+ if country not in allowed_countries:
1418
+ countries_to_allow.append(country)
1419
+
1420
+ rows = self.generate_csv_rows_for_species(species_string,
1421
+ allow_countries=countries_to_allow,
1422
+ block_countries=countries_to_block)
1423
+
1424
+ return rows
1425
+
1426
+ # ...def generate_csv_rows_to_block_all_countries_except(...)
1427
+
1428
+
1429
+ def generate_csv_rows_for_species(self, species_string,
1430
+ allow_countries=None,
1431
+ block_countries=None,
1432
+ allow_states=None,
1433
+ block_states=None):
1434
+ """
1435
+ Generate rows in the format expected by geofence_fixes.csv, representing a list of
1436
+ allow and/or block rules for the specified species and countries/states. Does not check
1437
+ that the rules make sense; e.g. nothing will stop you in this function from both allowing
1438
+ and blocking a country.
1439
+
1440
+ Args:
1441
+ species_string (str): five-token string in semicolon-delimited WI taxonomy format
1442
+ allow_countries (list or str, optional): three-letter country codes, list of
1443
+ country codes, or comma-separated list of country codes to allow
1444
+ block_countries (list or str, optional): three-letter country codes, list of
1445
+ country codes, or comma-separated list of country codes to block
1446
+ allow_states (list or str, optional): two-letter state codes, list of
1447
+ state codes, or comma-separated list of state codes to allow
1448
+ block_states (list or str, optional): two-letter state code, list of
1449
+ state codes, or comma-separated list of state codes to block
1450
+
1451
+ Returns:
1452
+ list of str: lines ready to be pasted into geofence_fixes.csv
1453
+ """
1454
+
1455
+ assert is_valid_taxonomy_string(species_string), \
1456
+ '{} is not a valid taxonomy string'.format(species_string)
1457
+
1458
+ lines = []
1459
+
1460
+ if allow_countries is not None:
1461
+ allow_countries = self._parse_region_code_list(allow_countries)
1462
+ for country in allow_countries:
1463
+ lines.append(species_string + ',allow,' + country + ',')
1464
+
1465
+ if block_countries is not None:
1466
+ block_countries = self._parse_region_code_list(block_countries)
1467
+ for country in block_countries:
1468
+ lines.append(species_string + ',block,' + country + ',')
1469
+
1470
+ if allow_states is not None:
1471
+ allow_states = self._parse_region_code_list(allow_states)
1472
+ for state in allow_states:
1473
+ lines.append(species_string + ',allow,USA,' + state)
1474
+
1475
+ if block_states is not None:
1476
+ block_states = self._parse_region_code_list(block_states)
1477
+ for state in block_states:
1478
+ lines.append(species_string + ',block,USA,' + state)
1479
+
1480
+ return lines
1481
+
1482
+ # ...def generate_csv_rows_for_species(...)
1483
+
1484
+
1485
+ def species_string_to_canonical_species_string(self, species):
1486
+ """
1487
+ Convert a string that may be a 5-token species string, a binomial name,
1488
+ or a common name into a 5-token species string, using taxonomic lookup.
1489
+
1490
+ Args:
1491
+ species (str): 5-token species string, binomial name, or common name
1492
+
1493
+ Returns:
1494
+ str: common name
1495
+
1496
+ Raises:
1497
+ ValueError: if [species] is not in our dictionary
1498
+ """
1499
+
1500
+ species = species.lower().strip()
1501
+
1502
+ # Turn "species" into a taxonomy string
1503
+
1504
+ # If this is already a taxonomy string...
1505
+ if len(species.split(';')) == 5:
1506
+ taxonomy_string = species
1507
+ # If this is a common name...
1508
+ elif species in self.common_name_to_taxonomy_info:
1509
+ taxonomy_info = self.common_name_to_taxonomy_info[species]
1510
+ taxonomy_string = taxonomy_info_to_taxonomy_string(taxonomy_info)
1511
+ # If this is a binomial name...
1512
+ elif (species in self.binomial_name_to_taxonomy_info):
1513
+ taxonomy_info = self.binomial_name_to_taxonomy_info[species]
1514
+ taxonomy_string = taxonomy_info_to_taxonomy_string(taxonomy_info)
1515
+ else:
1516
+ raise ValueError('Could not find taxonomic information for {}'.format(species))
1517
+
1518
+ return taxonomy_string
1519
+
1520
+ # ...def species_string_to_canonical_species_string(...)
1521
+
1522
+
1523
+ def species_string_to_taxonomy_info(self,species):
1524
+ """
1525
+ Convert a string that may be a 5-token species string, a binomial name,
1526
+ or a common name into a taxonomic info dictionary, using taxonomic lookup.
1527
+
1528
+ Args:
1529
+ species (str): 5-token species string, binomial name, or common name
1530
+
1531
+ Returns:
1532
+ dict: taxonomy information
1533
+
1534
+ Raises:
1535
+ ValueError: if [species] is not in our dictionary
1536
+ """
1537
+
1538
+ species = species.lower().strip()
1539
+ canonical_string = self.species_string_to_canonical_species_string(species)
1540
+ return self.taxonomy_string_to_taxonomy_info[canonical_string]
1541
+
1542
+
1543
+ def species_allowed_in_country(self, species, country, state=None, return_status=False):
1544
+ """
1545
+ Determines whether [species] is allowed in [country], according to
1546
+ already-initialized geofencing rules.
1547
+
1548
+ Args:
1549
+ species (str): can be a common name, a binomial name, or a species string
1550
+ country (str): country name or three-letter code
1551
+ state (str, optional): two-letter US state code
1552
+ return_status (bool, optional): by default, this function returns a bool;
1553
+ if you want to know *why* [species] is allowed/not allowed, settings
1554
+ return_status to True will return additional information.
1555
+
1556
+ Returns:
1557
+ bool or str: typically returns True if [species] is allowed in [country], else
1558
+ False. Returns a more detailed string if return_status is set.
1559
+ """
1560
+
1561
+ assert self.taxonomy_string_to_geofencing_rules is not None, \
1562
+ 'Initialize geofencing prior to species lookup'
1563
+ assert self.taxonomy_string_to_taxonomy_info is not None, \
1564
+ 'Initialize taxonomy lookup prior to species lookup'
1565
+
1566
+ taxonomy_string = self.species_string_to_canonical_species_string(species)
1567
+
1568
+ # Normalize [state]
1569
+
1570
+ if state is not None:
1571
+ state = state.upper()
1572
+ assert len(state) == 2
1573
+
1574
+ # Turn "country" into a country code
1575
+
1576
+ if len(country) == 3:
1577
+ assert country.upper() in self.country_code_to_country
1578
+ country = country.upper()
1579
+ else:
1580
+ assert country.lower() in self.country_to_country_code
1581
+ country = self.country_to_country_code[country.lower()]
1582
+
1583
+ country_code = country.upper()
1584
+
1585
+ # Species with no rules are allowed everywhere
1586
+ if taxonomy_string not in self.taxonomy_string_to_geofencing_rules:
1587
+ status = 'allow_by_default'
1588
+ if return_status:
1589
+ return status
1590
+ else:
1591
+ return True
1592
+
1593
+ geofencing_rules_this_species = self.taxonomy_string_to_geofencing_rules[taxonomy_string]
1594
+ allowed_countries = []
1595
+ blocked_countries = []
1596
+
1597
+ rule_types_this_species = list(geofencing_rules_this_species.keys())
1598
+ for rule_type in rule_types_this_species:
1599
+ assert rule_type in ('allow','block')
1600
+
1601
+ if 'block' in rule_types_this_species:
1602
+ blocked_countries = list(geofencing_rules_this_species['block'])
1603
+ if 'allow' in rule_types_this_species:
1604
+ allowed_countries = list(geofencing_rules_this_species['allow'])
1605
+
1606
+ status = None
1607
+
1608
+ # The convention is that block rules win over allow rules
1609
+ if country_code in blocked_countries:
1610
+ if country_code in allowed_countries:
1611
+ status = 'blocked_over_allow'
1612
+ else:
1613
+ status = 'blocked'
1614
+ elif country_code in allowed_countries:
1615
+ status = 'allowed'
1616
+ elif len(allowed_countries) > 0:
1617
+ # The convention is that if allow rules exist, any country not on that list
1618
+ # is blocked.
1619
+ status = 'block_not_on_country_allow_list'
1620
+ else:
1621
+ # Only block rules exist for this species, and they don't include this country
1622
+ assert len(blocked_countries) > 0
1623
+ status = 'allow_not_on_block_list'
1624
+
1625
+ # Now let's see whether we have to deal with any regional rules.
1626
+ #
1627
+ # Right now regional rules only exist for the US.
1628
+ if (country_code == 'USA') and ('USA' in geofencing_rules_this_species[rule_type]):
1629
+
1630
+ if state is None:
1631
+
1632
+ state_list = geofencing_rules_this_species[rule_type][country_code]
1633
+ if len(state_list) > 0:
1634
+ assert status.startswith('allow')
1635
+ status = 'allow_no_state'
1636
+
1637
+ else:
1638
+
1639
+ state_list = geofencing_rules_this_species[rule_type][country_code]
1640
+
1641
+ if state in state_list:
1642
+ # If the state is on the list, do what the list says
1643
+ if rule_type == 'allow':
1644
+ status = 'allow_on_state_allow_list'
1645
+ else:
1646
+ status = 'block_on_state_block_list'
1647
+ else:
1648
+ # If the state is not on the list, do the opposite of what the list says
1649
+ if rule_type == 'allow':
1650
+ status = 'block_not_on_state_allow_list'
1651
+ else:
1652
+ status = 'allow_not_on_state_block_list'
1653
+
1654
+ if return_status:
1655
+ return status
1656
+ else:
1657
+ if status.startswith('allow'):
1658
+ return True
1659
+ else:
1660
+ assert status.startswith('block')
1661
+ return False
1662
+
1663
+ # ...def species_allowed_in_country(...)
1664
+
1665
+
1666
+ def export_geofence_data_to_csv(self, csv_fn=None, include_common_names=True):
1667
+ """
1668
+ Converts the geofence .json representation into an equivalent .csv representation,
1669
+ with one taxon per row and one region per column. Empty values indicate non-allowed
1670
+ combinations, positive numbers indicate allowed combinations. Negative values
1671
+ are reserved for specific non-allowed combinations.
1672
+
1673
+ Args:
1674
+ csv_fn (str): output .csv file
1675
+ include_common_names (bool, optional): include a column for common names
1676
+
1677
+ Returns:
1678
+ dataframe: the pandas representation of the csv output file
1679
+ """
1680
+
1681
+ all_taxa = sorted(list(self.taxonomy_string_to_geofencing_rules.keys()))
1682
+ print('Preparing geofencing export for {} taxa'.format(len(all_taxa)))
1683
+
1684
+ all_regions = set()
1685
+
1686
+ # taxon = all_taxa[0]
1687
+ for taxon in all_taxa:
1688
+
1689
+ taxon_rules = self.taxonomy_string_to_geofencing_rules[taxon]
1690
+ for rule_type in taxon_rules.keys():
1691
+
1692
+ assert rule_type in ('allow','block')
1693
+ all_country_rules_this_species = taxon_rules[rule_type]
1694
+
1695
+ for country_code in all_country_rules_this_species.keys():
1696
+ all_regions.add(country_code)
1697
+ assert country_code in self.country_code_to_country
1698
+ assert len(country_code) == 3
1699
+ region_rules = all_country_rules_this_species[country_code]
1700
+ if len(region_rules) > 0:
1701
+ assert country_code == 'USA'
1702
+ for region_name in region_rules:
1703
+ assert len(region_name) == 2
1704
+ assert isinstance(region_name,str)
1705
+ all_regions.add(country_code + ':' + region_name)
1706
+
1707
+ all_regions = sorted(list(all_regions))
1708
+
1709
+ print('Found {} regions'.format(len(all_regions)))
1710
+
1711
+ n_allowed = 0
1712
+ df = pd.DataFrame(index=all_taxa,columns=all_regions)
1713
+ # df = df.fillna(np.nan)
1714
+
1715
+ for taxon in tqdm(all_taxa):
1716
+ for region in all_regions:
1717
+ tokens = region.split(':')
1718
+ country_code = tokens[0]
1719
+ state_code = None
1720
+ if len(tokens) > 1:
1721
+ state_code = tokens[1]
1722
+ allowed = self.species_allowed_in_country(species=taxon,
1723
+ country=country_code,
1724
+ state=state_code,
1725
+ return_status=False)
1726
+ if allowed:
1727
+ n_allowed += 1
1728
+ df.loc[taxon,region] = 1
1729
+
1730
+ # ...for each region
1731
+
1732
+ # ...for each taxon
1733
+
1734
+ print('Allowed {} of {} combinations'.format(n_allowed,len(all_taxa)*len(all_regions)))
1735
+
1736
+ # Before saving, convert columns with numeric values to integers
1737
+ for col in df.columns:
1738
+ # Check whether each column has any non-NaN values that could be integers
1739
+ if df[col].notna().any() and pd.to_numeric(df[col], errors='coerce').notna().any():
1740
+ # Convert column to Int64 type (pandas nullable integer type)
1741
+ df[col] = pd.to_numeric(df[col], errors='coerce').astype('Int64')
1742
+
1743
+ if include_common_names:
1744
+ df.insert(loc=0,column='common_name',value='')
1745
+ for taxon in all_taxa:
1746
+ if taxon in self.taxonomy_string_to_taxonomy_info:
1747
+ taxonomy_info = self.taxonomy_string_to_taxonomy_info[taxon]
1748
+ common_name = taxonomy_info['common_name']
1749
+ assert isinstance(common_name,str) and len(common_name) < 50
1750
+ df.loc[taxon,'common_name'] = common_name
1751
+
1752
+ if csv_fn is not None:
1753
+ df.to_csv(csv_fn,index=True,header=True)
1754
+
1755
+ return df
1756
+
1757
+ # ...def export_geofence_data_to_csv(...)
1758
+
1759
+ # ...class TaxonomyHandler