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,516 @@
1
+ """
2
+
3
+ generate_lila_per_image_labels.py
4
+
5
+ Generate a .csv file with one row per annotation, containing full URLs to every
6
+ camera trap image on LILA, with taxonomically expanded labels.
7
+
8
+ Typically there will be one row per image, though images with multiple annotations
9
+ will have multiple rows.
10
+
11
+ Some images may not physically exist, particularly images that are labeled as "human".
12
+ This script does not validate image URLs.
13
+
14
+ Does not include bounding box annotations.
15
+
16
+ """
17
+
18
+ #%% Constants and imports
19
+
20
+ import os
21
+ import json
22
+ import pandas as pd
23
+ import numpy as np
24
+ import dateparser
25
+ import csv
26
+
27
+ from collections import defaultdict
28
+ from tqdm import tqdm
29
+
30
+ from megadetector.data_management.lila.lila_common import \
31
+ read_lila_metadata, \
32
+ read_metadata_file_for_dataset, \
33
+ read_lila_taxonomy_mapping
34
+
35
+ from megadetector.utils import write_html_image_list
36
+ from megadetector.utils.path_utils import zip_file
37
+ from megadetector.utils.path_utils import open_file
38
+
39
+ # We'll write images, metadata downloads, and temporary files here
40
+ lila_local_base = os.path.expanduser('~/lila')
41
+ preview_folder = os.path.join(lila_local_base,'csv_preview')
42
+
43
+ os.makedirs(lila_local_base,exist_ok=True)
44
+
45
+ metadata_dir = os.path.join(lila_local_base,'metadata')
46
+ os.makedirs(metadata_dir,exist_ok=True)
47
+
48
+ output_file = os.path.join(lila_local_base,'lila_image_urls_and_labels.csv')
49
+
50
+ # Some datasets don't have "sequence_level_annotation" fields populated, but we know their
51
+ # annotation level
52
+ ds_name_to_annotation_level = {}
53
+ ds_name_to_annotation_level['Caltech Camera Traps'] = 'image'
54
+ ds_name_to_annotation_level['ENA24'] = 'image'
55
+ ds_name_to_annotation_level['Island Conservation Camera Traps'] = 'image'
56
+ ds_name_to_annotation_level['Channel IslandsCamera Traps'] = 'image'
57
+ ds_name_to_annotation_level['WCS Camera Traps'] = 'sequence'
58
+ ds_name_to_annotation_level['Wellington Camera Traps'] = 'sequence'
59
+ ds_name_to_annotation_level['NACTI'] = 'unknown'
60
+
61
+ known_unmapped_labels = set(['WCS Camera Traps:#ref!'])
62
+
63
+ debug_max_images_per_dataset = -1
64
+ if debug_max_images_per_dataset > 0:
65
+ print('Running in debug mode')
66
+ output_file = output_file.replace('.csv','_debug.csv')
67
+
68
+
69
+ #%% Download and parse the metadata file
70
+
71
+ metadata_table = read_lila_metadata(metadata_dir)
72
+
73
+ # To select an individual data set for debugging
74
+ if False:
75
+ k = 'Idaho Camera Traps'
76
+ metadata_table = {k:metadata_table[k]}
77
+
78
+
79
+ #%% Download and extract metadata for each dataset
80
+
81
+ for ds_name in metadata_table.keys():
82
+ metadata_table[ds_name]['metadata_filename'] = read_metadata_file_for_dataset(ds_name=ds_name,
83
+ metadata_dir=metadata_dir,
84
+ metadata_table=metadata_table)
85
+
86
+ #%% Load taxonomy data
87
+
88
+ taxonomy_df = read_lila_taxonomy_mapping(metadata_dir)
89
+
90
+
91
+ #%% Build a dictionary that maps each [dataset,query] pair to the full taxonomic label set
92
+
93
+ ds_label_to_taxonomy = {}
94
+
95
+ # i_row = 0; row = taxonomy_df.iloc[i_row]
96
+ for i_row,row in taxonomy_df.iterrows():
97
+
98
+ ds_label = row['dataset_name'] + ':' + row['query']
99
+ assert ds_label.strip() == ds_label
100
+ assert ds_label not in ds_label_to_taxonomy
101
+ ds_label_to_taxonomy[ds_label] = row.to_dict()
102
+
103
+
104
+ #%% Process annotations for each dataset
105
+
106
+ # Takes several hours
107
+
108
+ # The order of these headers needs to match the order in which fields are added later in this cell;
109
+ # don't mess with this order.
110
+ header = ['dataset_name','url_gcp','url_aws','url_azure',
111
+ 'image_id','sequence_id','location_id','frame_num',
112
+ 'original_label','scientific_name','common_name','datetime','annotation_level']
113
+
114
+ taxonomy_levels_to_include = \
115
+ ['kingdom','phylum','subphylum','superclass','class','subclass','infraclass','superorder','order',
116
+ 'suborder','infraorder','superfamily','family','subfamily','tribe','genus','species','subspecies',
117
+ 'variety']
118
+
119
+ header.extend(taxonomy_levels_to_include)
120
+
121
+ missing_annotations = set()
122
+
123
+ def clearnan(v):
124
+ if isinstance(v,float):
125
+ assert np.isnan(v)
126
+ v = ''
127
+ assert isinstance(v,str)
128
+ return v
129
+
130
+ with open(output_file,'w',encoding='utf-8',newline='') as f:
131
+
132
+ csv_writer = csv.writer(f)
133
+ csv_writer.writerow(header)
134
+
135
+ # ds_name = list(metadata_table.keys())[0]
136
+ for ds_name in metadata_table.keys():
137
+
138
+ if 'bbox' in ds_name:
139
+ print('Skipping bbox dataset {}'.format(ds_name))
140
+ continue
141
+
142
+ print('Processing dataset {}'.format(ds_name))
143
+
144
+ json_filename = metadata_table[ds_name]['metadata_filename']
145
+ with open(json_filename, 'r') as f:
146
+ data = json.load(f)
147
+
148
+ categories = data['categories']
149
+ category_ids = [c['id'] for c in categories]
150
+ for c in categories:
151
+ category_id_to_name = {c['id']:c['name'] for c in categories}
152
+
153
+ annotations = data['annotations']
154
+ images = data['images']
155
+
156
+ image_id_to_annotations = defaultdict(list)
157
+
158
+ # Go through annotations, marking each image with the categories that are present
159
+ #
160
+ # ann = annotations[0]
161
+ for ann in annotations:
162
+ image_id_to_annotations[ann['image_id']].append(ann)
163
+
164
+ unannotated_images = []
165
+
166
+ found_date = False
167
+ found_location = False
168
+ found_annotation_level = False
169
+
170
+ if ds_name in ds_name_to_annotation_level:
171
+ expected_annotation_level = ds_name_to_annotation_level[ds_name]
172
+ else:
173
+ expected_annotation_level = None
174
+
175
+ # im = images[10]
176
+ for i_image,im in enumerate(images):
177
+
178
+ if (debug_max_images_per_dataset is not None) and (debug_max_images_per_dataset > 0) \
179
+ and (i_image >= debug_max_images_per_dataset):
180
+ break
181
+
182
+ file_name = im['file_name'].replace('\\','/')
183
+ base_url_gcp = metadata_table[ds_name]['image_base_url_gcp']
184
+ base_url_aws = metadata_table[ds_name]['image_base_url_aws']
185
+ base_url_azure = metadata_table[ds_name]['image_base_url_azure']
186
+ assert not base_url_gcp.endswith('/')
187
+ assert not base_url_aws.endswith('/')
188
+ assert not base_url_azure.endswith('/')
189
+
190
+ url_gcp = base_url_gcp + '/' + file_name
191
+ url_aws = base_url_aws + '/' + file_name
192
+ url_azure = base_url_azure + '/' + file_name
193
+
194
+ for k in im.keys():
195
+ if ('date' in k or 'time' in k) and (k not in ['datetime','date_captured']):
196
+ raise ValueError('Unrecognized datetime field')
197
+
198
+ # This field name was only used for Caltech Camera Traps
199
+ if 'date_captured' in im:
200
+ assert ds_name == 'Caltech Camera Traps'
201
+ im['datetime'] = im['date_captured']
202
+
203
+ def has_valid_datetime(im):
204
+ if 'datetime' not in im:
205
+ return False
206
+ v = im['datetime']
207
+ if v is None:
208
+ return False
209
+ if isinstance(v,str):
210
+ return len(v) > 0
211
+ else:
212
+ assert isinstance(v,float) and np.isnan(v)
213
+ return False
214
+
215
+ dt_string = ''
216
+ if (has_valid_datetime(im)):
217
+
218
+ dt = dateparser.parse(im['datetime'])
219
+
220
+ if dt is None or dt.year < 1990 or dt.year > 2025:
221
+
222
+ # raise ValueError('Suspicious date parsing result')
223
+
224
+ # Special case we don't want to print a warning about... this is
225
+ # in invalid date that very likely originates on the camera, not at
226
+ # some intermediate processing step.
227
+ #
228
+ # print('Suspicious date for image {}: {} ({})'.format(
229
+ # im['id'], im['datetime'], ds_name))
230
+ pass
231
+
232
+ else:
233
+
234
+ found_date = True
235
+ dt_string = dt.strftime("%m-%d-%Y %H:%M:%S")
236
+
237
+ # Location, sequence, and image IDs are only guaranteed to be unique within
238
+ # a dataset, so for the output .csv file, include both
239
+ if 'location' in im:
240
+ found_location = True
241
+ location_id = ds_name + ' : ' + str(im['location'])
242
+ else:
243
+ location_id = ds_name
244
+
245
+ image_id = ds_name + ' : ' + str(im['id'])
246
+
247
+ if 'seq_id' in im:
248
+ sequence_id = ds_name + ' : ' + str(im['seq_id'])
249
+ else:
250
+ sequence_id = ds_name + ' : ' + 'unknown'
251
+
252
+ if 'frame_num' in im:
253
+ frame_num = im['frame_num']
254
+ else:
255
+ frame_num = -1
256
+
257
+ annotations_this_image = image_id_to_annotations[im['id']]
258
+
259
+ categories_this_image = set()
260
+
261
+ annotation_level = 'unknown'
262
+
263
+ for ann in annotations_this_image:
264
+ assert ann['image_id'] == im['id']
265
+ categories_this_image.add(category_id_to_name[ann['category_id']])
266
+ if 'sequence_level_annotation' in ann:
267
+ found_annotation_level = True
268
+ if ann['sequence_level_annotation']:
269
+ annotation_level = 'sequence'
270
+ else:
271
+ annotation_level = 'image'
272
+ if expected_annotation_level is not None:
273
+ assert expected_annotation_level == annotation_level,\
274
+ 'Unexpected annotation level'
275
+ elif expected_annotation_level is not None:
276
+ annotation_level = expected_annotation_level
277
+
278
+ if len(categories_this_image) == 0:
279
+ unannotated_images.append(im)
280
+ continue
281
+
282
+ # category_name = list(categories_this_image)[0]
283
+ for category_name in categories_this_image:
284
+
285
+ ds_label = ds_name + ':' + category_name.lower()
286
+
287
+ if ds_label not in ds_label_to_taxonomy:
288
+
289
+ assert ds_label in known_unmapped_labels
290
+
291
+ # Only print a warning the first time we see an unmapped label
292
+ if ds_label not in missing_annotations:
293
+ print('Warning: {} not in taxonomy file'.format(ds_label))
294
+ missing_annotations.add(ds_label)
295
+ continue
296
+
297
+ taxonomy_labels = ds_label_to_taxonomy[ds_label]
298
+
299
+ """
300
+ header =
301
+ ['dataset_name','url','image_id','sequence_id','location_id',
302
+ 'frame_num','original_label','scientific_name','common_name',
303
+ 'datetime','annotation_level']
304
+ """
305
+
306
+ row = []
307
+ row.append(ds_name)
308
+ row.append(url_gcp)
309
+ row.append(url_aws)
310
+ row.append(url_azure)
311
+ row.append(image_id)
312
+ row.append(sequence_id)
313
+ row.append(location_id)
314
+ row.append(frame_num)
315
+ row.append(taxonomy_labels['query'])
316
+ row.append(clearnan(taxonomy_labels['scientific_name']))
317
+ row.append(clearnan(taxonomy_labels['common_name']))
318
+ row.append(dt_string)
319
+ row.append(annotation_level)
320
+
321
+ for s in taxonomy_levels_to_include:
322
+ row.append(clearnan(taxonomy_labels[s]))
323
+
324
+ assert len(row) == len(header)
325
+
326
+ csv_writer.writerow(row)
327
+
328
+ # ...for each category that was applied at least once to this image
329
+
330
+ # ...for each image in this dataset
331
+
332
+ if not found_date:
333
+ pass
334
+ # print('Warning: no date information available for this dataset')
335
+
336
+ if not found_location:
337
+ pass
338
+ # print('Warning: no location information available for this dataset')
339
+
340
+ if not found_annotation_level and (ds_name not in ds_name_to_annotation_level):
341
+ print('Warning: no annotation level information available for this dataset')
342
+
343
+ if len(unannotated_images) > 0:
344
+ print('Warning: {} of {} images are un-annotated\n'.\
345
+ format(len(unannotated_images),len(images)))
346
+
347
+ # ...for each dataset
348
+
349
+ # ...with open()
350
+
351
+ print('Processed {} datasets'.format(len(metadata_table)))
352
+
353
+
354
+ #%% Read the .csv back
355
+
356
+ df = pd.read_csv(output_file)
357
+ print('Read {} lines from {}'.format(len(df),output_file))
358
+
359
+
360
+ #%% Do some post-hoc integrity checking
361
+
362
+ # Takes ~10 minutes without using apply()
363
+
364
+ tqdm.pandas()
365
+
366
+ def isint(v):
367
+ return isinstance(v,int) or isinstance(v,np.int64)
368
+
369
+ valid_annotation_levels = set(['sequence','image','unknown'])
370
+
371
+ # Collect a list of locations within each dataset; we'll use this
372
+ # in the next cell to look for datasets that only have a single location
373
+ dataset_name_to_locations = defaultdict(set)
374
+
375
+ def check_row(row):
376
+
377
+ assert row['dataset_name'] in metadata_table.keys()
378
+ for url_column in ['url_gcp','url_aws','url_azure']:
379
+ assert row[url_column].startswith('https://') or row[url_column].startswith('http://')
380
+ assert ' : ' in row['image_id']
381
+ assert 'seq' not in row['location_id'].lower()
382
+ assert row['annotation_level'] in valid_annotation_levels
383
+
384
+ # frame_num should either be NaN or an integer
385
+ if isinstance(row['frame_num'],float):
386
+ assert np.isnan(row['frame_num'])
387
+ else:
388
+ # -1 is sometimes used for sequences of unknown length
389
+ assert isint(row['frame_num']) and row['frame_num'] >= -1
390
+
391
+ ds_name = row['dataset_name']
392
+ dataset_name_to_locations[ds_name].add(row['location_id'])
393
+
394
+ # Faster, but more annoying to debug
395
+ if False:
396
+
397
+ df.progress_apply(check_row, axis=1)
398
+
399
+ else:
400
+
401
+ # i_row = 0; row = df.iloc[i_row]
402
+ for i_row,row in tqdm(df.iterrows(),total=len(df)):
403
+ check_row(row)
404
+
405
+
406
+ #%% Check for datasets that have only one location string
407
+
408
+ # Expected: ENA24, Missouri Camera Traps
409
+
410
+ for ds_name in dataset_name_to_locations.keys():
411
+ if len(dataset_name_to_locations[ds_name]) == 1:
412
+ print('No location information for {}'.format(ds_name))
413
+
414
+
415
+ #%% Preview constants
416
+
417
+ n_empty_images_per_dataset = 3
418
+ n_non_empty_images_per_dataset = 10
419
+
420
+ os.makedirs(preview_folder,exist_ok=True)
421
+
422
+
423
+ #%% Choose images to download
424
+
425
+ np.random.seed(0)
426
+ images_to_download = []
427
+
428
+ # ds_name = list(metadata_table.keys())[2]
429
+ for ds_name in metadata_table.keys():
430
+
431
+ if 'bbox' in ds_name:
432
+ continue
433
+
434
+ # Find all rows for this dataset
435
+ ds_rows = df.loc[df['dataset_name'] == ds_name]
436
+
437
+ print('{} rows available for {}'.format(len(ds_rows),ds_name))
438
+ assert len(ds_rows) > 0
439
+
440
+ empty_rows = ds_rows[ds_rows['scientific_name'].isnull()]
441
+ non_empty_rows = ds_rows[~ds_rows['scientific_name'].isnull()]
442
+
443
+ if len(empty_rows) == 0:
444
+ print('No empty images available for {}'.format(ds_name))
445
+ elif len(empty_rows) > n_empty_images_per_dataset:
446
+ empty_rows = empty_rows.sample(n=n_empty_images_per_dataset)
447
+ images_to_download.extend(empty_rows.to_dict('records'))
448
+
449
+ if len(non_empty_rows) == 0:
450
+ print('No non-empty images available for {}'.format(ds_name))
451
+ elif len(non_empty_rows) > n_non_empty_images_per_dataset:
452
+ non_empty_rows = non_empty_rows.sample(n=n_non_empty_images_per_dataset)
453
+ images_to_download.extend(non_empty_rows.to_dict('records'))
454
+
455
+ # ...for each dataset
456
+
457
+ print('Selected {} total images'.format(len(images_to_download)))
458
+
459
+
460
+ #%% Download images (prep)
461
+
462
+ # Expect a few errors for images with human or vehicle labels (or things like "ignore" that *could* be humans)
463
+
464
+ preferred_cloud = 'aws'
465
+
466
+ url_to_target_file = {}
467
+
468
+ # i_image = 10; image = images_to_download[i_image]
469
+ for i_image,image in tqdm(enumerate(images_to_download),total=len(images_to_download)):
470
+
471
+ url = image['url_' + preferred_cloud]
472
+ ext = os.path.splitext(url)[1]
473
+ fn_relative = 'image_{}'.format(str(i_image).zfill(4)) + ext
474
+ fn_abs = os.path.join(preview_folder,fn_relative)
475
+ image['relative_file'] = fn_relative
476
+ image['url'] = url
477
+ url_to_target_file[url] = fn_abs
478
+
479
+
480
+ #%% Download images (execution)
481
+
482
+ from megadetector.utils.url_utils import parallel_download_urls
483
+ download_results = parallel_download_urls(url_to_target_file,verbose=False,overwrite=True,
484
+ n_workers=20,pool_type='thread')
485
+
486
+
487
+ #%% Write preview HTML
488
+
489
+ html_filename = os.path.join(preview_folder,'index.html')
490
+
491
+ html_images = []
492
+
493
+ # im = images_to_download[0]
494
+ for im in images_to_download:
495
+
496
+ if im['relative_file'] is None:
497
+ continue
498
+
499
+ output_im = {}
500
+ output_im['filename'] = im['relative_file']
501
+ output_im['linkTarget'] = im['url']
502
+ output_im['title'] = '<b>{}: {}</b><br/><br/>'.format(im['dataset_name'],im['original_label']) + str(im)
503
+ output_im['imageStyle'] = 'width:600px;'
504
+ output_im['textStyle'] = 'font-weight:normal;font-size:100%;'
505
+ html_images.append(output_im)
506
+
507
+ write_html_image_list.write_html_image_list(html_filename,html_images)
508
+
509
+ open_file(html_filename)
510
+
511
+
512
+ #%% Zip output file
513
+
514
+ zipped_output_file = zip_file(output_file,verbose=True)
515
+
516
+ print('Zipped {} to {}'.format(output_file,zipped_output_file))
@@ -0,0 +1,170 @@
1
+ """
2
+
3
+ get_lila_annotation_counts.py
4
+
5
+ Generates a .json-formatted dictionary mapping each LILA dataset to all categories
6
+ that exist for that dataset, with counts for the number of occurrences of each category
7
+ (the number of *annotations* for each category, not the number of *images*).
8
+
9
+ Also loads the taxonomy mapping file, to include scientific names for each category.
10
+
11
+ get_lila_image_counts.py counts the number of *images* for each category in each dataset.
12
+
13
+ """
14
+
15
+ #%% Constants and imports
16
+
17
+ import json
18
+ import os
19
+
20
+ from megadetector.data_management.lila.lila_common import \
21
+ read_lila_metadata, read_metadata_file_for_dataset, read_lila_taxonomy_mapping
22
+
23
+ # cloud provider to use for downloading images; options are 'gcp', 'azure', or 'aws'
24
+ preferred_cloud = 'gcp'
25
+
26
+ # array to fill for output
27
+ category_list = []
28
+
29
+ # We'll write images, metadata downloads, and temporary files here
30
+ lila_local_base = os.path.expanduser('~/lila')
31
+
32
+ output_dir = os.path.join(lila_local_base,'lila_categories_list')
33
+ os.makedirs(output_dir,exist_ok=True)
34
+
35
+ metadata_dir = os.path.join(lila_local_base,'metadata')
36
+ os.makedirs(metadata_dir,exist_ok=True)
37
+
38
+ output_file = os.path.join(output_dir,'lila_dataset_to_categories.json')
39
+
40
+
41
+ #%% Load category and taxonomy files
42
+
43
+ taxonomy_df = read_lila_taxonomy_mapping(metadata_dir)
44
+
45
+
46
+ #%% Map dataset names and category names to scientific names
47
+
48
+ ds_query_to_scientific_name = {}
49
+
50
+ unmapped_queries = set()
51
+
52
+ datasets_with_taxonomy_mapping = set()
53
+
54
+ # i_row = 1; row = taxonomy_df.iloc[i_row]; row
55
+ for i_row,row in taxonomy_df.iterrows():
56
+
57
+ datasets_with_taxonomy_mapping.add(row['dataset_name'])
58
+
59
+ ds_query = row['dataset_name'] + ':' + row['query']
60
+ ds_query = ds_query.lower()
61
+
62
+ if not isinstance(row['scientific_name'],str):
63
+ unmapped_queries.add(ds_query)
64
+ ds_query_to_scientific_name[ds_query] = 'unmapped'
65
+ continue
66
+
67
+ ds_query_to_scientific_name[ds_query] = row['scientific_name']
68
+
69
+ print('Loaded taxonomy mappings for {} datasets'.format(len(datasets_with_taxonomy_mapping)))
70
+
71
+
72
+ #%% Download and parse the metadata file
73
+
74
+ metadata_table = read_lila_metadata(metadata_dir)
75
+
76
+ print('Loaded metadata URLs for {} datasets'.format(len(metadata_table)))
77
+
78
+
79
+ #%% Download and extract metadata for each dataset
80
+
81
+ for ds_name in metadata_table.keys():
82
+ metadata_table[ds_name]['json_filename'] = read_metadata_file_for_dataset(ds_name=ds_name,
83
+ metadata_dir=metadata_dir,
84
+ metadata_table=metadata_table)
85
+
86
+
87
+ #%% Get category names and counts for each dataset
88
+
89
+ from collections import defaultdict
90
+
91
+ dataset_to_categories = {}
92
+
93
+ # ds_name = 'NACTI'
94
+ for ds_name in metadata_table.keys():
95
+
96
+ taxonomy_mapping_available = (ds_name in datasets_with_taxonomy_mapping)
97
+
98
+ if not taxonomy_mapping_available:
99
+ print('Warning: taxonomy mapping not available for {}'.format(ds_name))
100
+
101
+ print('Finding categories in {}'.format(ds_name))
102
+
103
+ json_filename = metadata_table[ds_name]['json_filename']
104
+ base_url = metadata_table[ds_name]['image_base_url_' + preferred_cloud]
105
+ assert not base_url.endswith('/')
106
+
107
+ # Open the metadata file
108
+ with open(json_filename, 'r') as f:
109
+ data = json.load(f)
110
+
111
+ # Collect list of categories and mappings to category name
112
+ categories = data['categories']
113
+
114
+ category_id_to_count = defaultdict(int)
115
+ annotations = data['annotations']
116
+
117
+ # ann = annotations[0]
118
+ for ann in annotations:
119
+ category_id_to_count[ann['category_id']] = category_id_to_count[ann['category_id']] + 1
120
+
121
+ # c = categories[0]
122
+ for c in categories:
123
+ count = category_id_to_count[c['id']]
124
+ if 'count' in c:
125
+ assert 'bbox' in ds_name or c['count'] == count
126
+ c['count'] = count
127
+
128
+ # Don't do taxonomy mapping for bbox data sets, which are sometimes just binary and are
129
+ # always redundant with the class-level data sets.
130
+ if 'bbox' in ds_name:
131
+ c['scientific_name_from_taxonomy_mapping'] = None
132
+ elif not taxonomy_mapping_available:
133
+ c['scientific_name_from_taxonomy_mapping'] = None
134
+ else:
135
+ taxonomy_query_string = ds_name.lower().strip() + ':' + c['name'].lower()
136
+ if taxonomy_query_string not in ds_query_to_scientific_name:
137
+ print('No match for query string {}'.format(taxonomy_query_string))
138
+ # As of right now, this is the only quirky case
139
+ assert '#ref!' in taxonomy_query_string and 'wcs' in ds_name.lower()
140
+ c['scientific_name_from_taxonomy_mapping'] = None
141
+ else:
142
+ sn = ds_query_to_scientific_name[taxonomy_query_string]
143
+ assert sn is not None and len(sn) > 0
144
+ c['scientific_name_from_taxonomy_mapping'] = sn
145
+
146
+ dataset_to_categories[ds_name] = categories
147
+
148
+ # ...for each dataset
149
+
150
+
151
+ #%% Print the results
152
+
153
+ # ds_name = list(dataset_to_categories.keys())[0]
154
+ for ds_name in dataset_to_categories:
155
+
156
+ print('\n** Category counts for {} **\n'.format(ds_name))
157
+
158
+ categories = dataset_to_categories[ds_name]
159
+ categories = sorted(categories, key=lambda x: x['count'], reverse=True)
160
+
161
+ for c in categories:
162
+ print('{} ({}): {}'.format(c['name'],c['scientific_name_from_taxonomy_mapping'],c['count']))
163
+
164
+ # ...for each dataset
165
+
166
+
167
+ #%% Save the results
168
+
169
+ with open(output_file, 'w') as f:
170
+ json.dump(dataset_to_categories,f,indent=1)