megadetector 5.0.10__py3-none-any.whl → 5.0.11__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 (226) hide show
  1. {megadetector-5.0.10.dist-info → megadetector-5.0.11.dist-info}/LICENSE +0 -0
  2. {megadetector-5.0.10.dist-info → megadetector-5.0.11.dist-info}/METADATA +12 -11
  3. megadetector-5.0.11.dist-info/RECORD +5 -0
  4. megadetector-5.0.11.dist-info/top_level.txt +1 -0
  5. api/__init__.py +0 -0
  6. api/batch_processing/__init__.py +0 -0
  7. api/batch_processing/api_core/__init__.py +0 -0
  8. api/batch_processing/api_core/batch_service/__init__.py +0 -0
  9. api/batch_processing/api_core/batch_service/score.py +0 -439
  10. api/batch_processing/api_core/server.py +0 -294
  11. api/batch_processing/api_core/server_api_config.py +0 -98
  12. api/batch_processing/api_core/server_app_config.py +0 -55
  13. api/batch_processing/api_core/server_batch_job_manager.py +0 -220
  14. api/batch_processing/api_core/server_job_status_table.py +0 -152
  15. api/batch_processing/api_core/server_orchestration.py +0 -360
  16. api/batch_processing/api_core/server_utils.py +0 -92
  17. api/batch_processing/api_core_support/__init__.py +0 -0
  18. api/batch_processing/api_core_support/aggregate_results_manually.py +0 -46
  19. api/batch_processing/api_support/__init__.py +0 -0
  20. api/batch_processing/api_support/summarize_daily_activity.py +0 -152
  21. api/batch_processing/data_preparation/__init__.py +0 -0
  22. api/batch_processing/data_preparation/manage_local_batch.py +0 -2391
  23. api/batch_processing/data_preparation/manage_video_batch.py +0 -327
  24. api/batch_processing/integration/digiKam/setup.py +0 -6
  25. api/batch_processing/integration/digiKam/xmp_integration.py +0 -465
  26. api/batch_processing/integration/eMammal/test_scripts/config_template.py +0 -5
  27. api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +0 -126
  28. api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +0 -55
  29. api/batch_processing/postprocessing/__init__.py +0 -0
  30. api/batch_processing/postprocessing/add_max_conf.py +0 -64
  31. api/batch_processing/postprocessing/categorize_detections_by_size.py +0 -163
  32. api/batch_processing/postprocessing/combine_api_outputs.py +0 -249
  33. api/batch_processing/postprocessing/compare_batch_results.py +0 -958
  34. api/batch_processing/postprocessing/convert_output_format.py +0 -397
  35. api/batch_processing/postprocessing/load_api_results.py +0 -195
  36. api/batch_processing/postprocessing/md_to_coco.py +0 -310
  37. api/batch_processing/postprocessing/md_to_labelme.py +0 -330
  38. api/batch_processing/postprocessing/merge_detections.py +0 -401
  39. api/batch_processing/postprocessing/postprocess_batch_results.py +0 -1904
  40. api/batch_processing/postprocessing/remap_detection_categories.py +0 -170
  41. api/batch_processing/postprocessing/render_detection_confusion_matrix.py +0 -661
  42. api/batch_processing/postprocessing/repeat_detection_elimination/find_repeat_detections.py +0 -211
  43. api/batch_processing/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +0 -82
  44. api/batch_processing/postprocessing/repeat_detection_elimination/repeat_detections_core.py +0 -1631
  45. api/batch_processing/postprocessing/separate_detections_into_folders.py +0 -731
  46. api/batch_processing/postprocessing/subset_json_detector_output.py +0 -696
  47. api/batch_processing/postprocessing/top_folders_to_bottom.py +0 -223
  48. api/synchronous/__init__.py +0 -0
  49. api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  50. api/synchronous/api_core/animal_detection_api/api_backend.py +0 -152
  51. api/synchronous/api_core/animal_detection_api/api_frontend.py +0 -266
  52. api/synchronous/api_core/animal_detection_api/config.py +0 -35
  53. api/synchronous/api_core/animal_detection_api/data_management/annotations/annotation_constants.py +0 -47
  54. api/synchronous/api_core/animal_detection_api/detection/detector_training/copy_checkpoints.py +0 -43
  55. api/synchronous/api_core/animal_detection_api/detection/detector_training/model_main_tf2.py +0 -114
  56. api/synchronous/api_core/animal_detection_api/detection/process_video.py +0 -543
  57. api/synchronous/api_core/animal_detection_api/detection/pytorch_detector.py +0 -304
  58. api/synchronous/api_core/animal_detection_api/detection/run_detector.py +0 -627
  59. api/synchronous/api_core/animal_detection_api/detection/run_detector_batch.py +0 -1029
  60. api/synchronous/api_core/animal_detection_api/detection/run_inference_with_yolov5_val.py +0 -581
  61. api/synchronous/api_core/animal_detection_api/detection/run_tiled_inference.py +0 -754
  62. api/synchronous/api_core/animal_detection_api/detection/tf_detector.py +0 -165
  63. api/synchronous/api_core/animal_detection_api/detection/video_utils.py +0 -495
  64. api/synchronous/api_core/animal_detection_api/md_utils/azure_utils.py +0 -174
  65. api/synchronous/api_core/animal_detection_api/md_utils/ct_utils.py +0 -262
  66. api/synchronous/api_core/animal_detection_api/md_utils/directory_listing.py +0 -251
  67. api/synchronous/api_core/animal_detection_api/md_utils/matlab_porting_tools.py +0 -97
  68. api/synchronous/api_core/animal_detection_api/md_utils/path_utils.py +0 -416
  69. api/synchronous/api_core/animal_detection_api/md_utils/process_utils.py +0 -110
  70. api/synchronous/api_core/animal_detection_api/md_utils/sas_blob_utils.py +0 -509
  71. api/synchronous/api_core/animal_detection_api/md_utils/string_utils.py +0 -59
  72. api/synchronous/api_core/animal_detection_api/md_utils/url_utils.py +0 -144
  73. api/synchronous/api_core/animal_detection_api/md_utils/write_html_image_list.py +0 -226
  74. api/synchronous/api_core/animal_detection_api/md_visualization/visualization_utils.py +0 -841
  75. api/synchronous/api_core/tests/__init__.py +0 -0
  76. api/synchronous/api_core/tests/load_test.py +0 -110
  77. classification/__init__.py +0 -0
  78. classification/aggregate_classifier_probs.py +0 -108
  79. classification/analyze_failed_images.py +0 -227
  80. classification/cache_batchapi_outputs.py +0 -198
  81. classification/create_classification_dataset.py +0 -627
  82. classification/crop_detections.py +0 -516
  83. classification/csv_to_json.py +0 -226
  84. classification/detect_and_crop.py +0 -855
  85. classification/efficientnet/__init__.py +0 -9
  86. classification/efficientnet/model.py +0 -415
  87. classification/efficientnet/utils.py +0 -610
  88. classification/evaluate_model.py +0 -520
  89. classification/identify_mislabeled_candidates.py +0 -152
  90. classification/json_to_azcopy_list.py +0 -63
  91. classification/json_validator.py +0 -695
  92. classification/map_classification_categories.py +0 -276
  93. classification/merge_classification_detection_output.py +0 -506
  94. classification/prepare_classification_script.py +0 -194
  95. classification/prepare_classification_script_mc.py +0 -228
  96. classification/run_classifier.py +0 -286
  97. classification/save_mislabeled.py +0 -110
  98. classification/train_classifier.py +0 -825
  99. classification/train_classifier_tf.py +0 -724
  100. classification/train_utils.py +0 -322
  101. data_management/__init__.py +0 -0
  102. data_management/annotations/__init__.py +0 -0
  103. data_management/annotations/annotation_constants.py +0 -34
  104. data_management/camtrap_dp_to_coco.py +0 -238
  105. data_management/cct_json_utils.py +0 -395
  106. data_management/cct_to_md.py +0 -176
  107. data_management/cct_to_wi.py +0 -289
  108. data_management/coco_to_labelme.py +0 -272
  109. data_management/coco_to_yolo.py +0 -662
  110. data_management/databases/__init__.py +0 -0
  111. data_management/databases/add_width_and_height_to_db.py +0 -33
  112. data_management/databases/combine_coco_camera_traps_files.py +0 -206
  113. data_management/databases/integrity_check_json_db.py +0 -477
  114. data_management/databases/subset_json_db.py +0 -115
  115. data_management/generate_crops_from_cct.py +0 -149
  116. data_management/get_image_sizes.py +0 -188
  117. data_management/importers/add_nacti_sizes.py +0 -52
  118. data_management/importers/add_timestamps_to_icct.py +0 -79
  119. data_management/importers/animl_results_to_md_results.py +0 -158
  120. data_management/importers/auckland_doc_test_to_json.py +0 -372
  121. data_management/importers/auckland_doc_to_json.py +0 -200
  122. data_management/importers/awc_to_json.py +0 -189
  123. data_management/importers/bellevue_to_json.py +0 -273
  124. data_management/importers/cacophony-thermal-importer.py +0 -796
  125. data_management/importers/carrizo_shrubfree_2018.py +0 -268
  126. data_management/importers/carrizo_trail_cam_2017.py +0 -287
  127. data_management/importers/cct_field_adjustments.py +0 -57
  128. data_management/importers/channel_islands_to_cct.py +0 -913
  129. data_management/importers/eMammal/copy_and_unzip_emammal.py +0 -180
  130. data_management/importers/eMammal/eMammal_helpers.py +0 -249
  131. data_management/importers/eMammal/make_eMammal_json.py +0 -223
  132. data_management/importers/ena24_to_json.py +0 -275
  133. data_management/importers/filenames_to_json.py +0 -385
  134. data_management/importers/helena_to_cct.py +0 -282
  135. data_management/importers/idaho-camera-traps.py +0 -1407
  136. data_management/importers/idfg_iwildcam_lila_prep.py +0 -294
  137. data_management/importers/jb_csv_to_json.py +0 -150
  138. data_management/importers/mcgill_to_json.py +0 -250
  139. data_management/importers/missouri_to_json.py +0 -489
  140. data_management/importers/nacti_fieldname_adjustments.py +0 -79
  141. data_management/importers/noaa_seals_2019.py +0 -181
  142. data_management/importers/pc_to_json.py +0 -365
  143. data_management/importers/plot_wni_giraffes.py +0 -123
  144. data_management/importers/prepare-noaa-fish-data-for-lila.py +0 -359
  145. data_management/importers/prepare_zsl_imerit.py +0 -131
  146. data_management/importers/rspb_to_json.py +0 -356
  147. data_management/importers/save_the_elephants_survey_A.py +0 -320
  148. data_management/importers/save_the_elephants_survey_B.py +0 -332
  149. data_management/importers/snapshot_safari_importer.py +0 -758
  150. data_management/importers/snapshot_safari_importer_reprise.py +0 -665
  151. data_management/importers/snapshot_serengeti_lila.py +0 -1067
  152. data_management/importers/snapshotserengeti/make_full_SS_json.py +0 -150
  153. data_management/importers/snapshotserengeti/make_per_season_SS_json.py +0 -153
  154. data_management/importers/sulross_get_exif.py +0 -65
  155. data_management/importers/timelapse_csv_set_to_json.py +0 -490
  156. data_management/importers/ubc_to_json.py +0 -399
  157. data_management/importers/umn_to_json.py +0 -507
  158. data_management/importers/wellington_to_json.py +0 -263
  159. data_management/importers/wi_to_json.py +0 -441
  160. data_management/importers/zamba_results_to_md_results.py +0 -181
  161. data_management/labelme_to_coco.py +0 -548
  162. data_management/labelme_to_yolo.py +0 -272
  163. data_management/lila/__init__.py +0 -0
  164. data_management/lila/add_locations_to_island_camera_traps.py +0 -97
  165. data_management/lila/add_locations_to_nacti.py +0 -147
  166. data_management/lila/create_lila_blank_set.py +0 -557
  167. data_management/lila/create_lila_test_set.py +0 -151
  168. data_management/lila/create_links_to_md_results_files.py +0 -106
  169. data_management/lila/download_lila_subset.py +0 -177
  170. data_management/lila/generate_lila_per_image_labels.py +0 -515
  171. data_management/lila/get_lila_annotation_counts.py +0 -170
  172. data_management/lila/get_lila_image_counts.py +0 -111
  173. data_management/lila/lila_common.py +0 -300
  174. data_management/lila/test_lila_metadata_urls.py +0 -132
  175. data_management/ocr_tools.py +0 -874
  176. data_management/read_exif.py +0 -681
  177. data_management/remap_coco_categories.py +0 -84
  178. data_management/remove_exif.py +0 -66
  179. data_management/resize_coco_dataset.py +0 -189
  180. data_management/wi_download_csv_to_coco.py +0 -246
  181. data_management/yolo_output_to_md_output.py +0 -441
  182. data_management/yolo_to_coco.py +0 -676
  183. detection/__init__.py +0 -0
  184. detection/detector_training/__init__.py +0 -0
  185. detection/detector_training/model_main_tf2.py +0 -114
  186. detection/process_video.py +0 -703
  187. detection/pytorch_detector.py +0 -337
  188. detection/run_detector.py +0 -779
  189. detection/run_detector_batch.py +0 -1219
  190. detection/run_inference_with_yolov5_val.py +0 -917
  191. detection/run_tiled_inference.py +0 -935
  192. detection/tf_detector.py +0 -188
  193. detection/video_utils.py +0 -606
  194. docs/source/conf.py +0 -43
  195. md_utils/__init__.py +0 -0
  196. md_utils/azure_utils.py +0 -174
  197. md_utils/ct_utils.py +0 -612
  198. md_utils/directory_listing.py +0 -246
  199. md_utils/md_tests.py +0 -968
  200. md_utils/path_utils.py +0 -1044
  201. md_utils/process_utils.py +0 -157
  202. md_utils/sas_blob_utils.py +0 -509
  203. md_utils/split_locations_into_train_val.py +0 -228
  204. md_utils/string_utils.py +0 -92
  205. md_utils/url_utils.py +0 -323
  206. md_utils/write_html_image_list.py +0 -225
  207. md_visualization/__init__.py +0 -0
  208. md_visualization/plot_utils.py +0 -293
  209. md_visualization/render_images_with_thumbnails.py +0 -275
  210. md_visualization/visualization_utils.py +0 -1537
  211. md_visualization/visualize_db.py +0 -551
  212. md_visualization/visualize_detector_output.py +0 -406
  213. megadetector-5.0.10.dist-info/RECORD +0 -224
  214. megadetector-5.0.10.dist-info/top_level.txt +0 -8
  215. taxonomy_mapping/__init__.py +0 -0
  216. taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +0 -491
  217. taxonomy_mapping/map_new_lila_datasets.py +0 -154
  218. taxonomy_mapping/prepare_lila_taxonomy_release.py +0 -142
  219. taxonomy_mapping/preview_lila_taxonomy.py +0 -591
  220. taxonomy_mapping/retrieve_sample_image.py +0 -71
  221. taxonomy_mapping/simple_image_download.py +0 -218
  222. taxonomy_mapping/species_lookup.py +0 -834
  223. taxonomy_mapping/taxonomy_csv_checker.py +0 -159
  224. taxonomy_mapping/taxonomy_graph.py +0 -346
  225. taxonomy_mapping/validate_lila_category_mappings.py +0 -83
  226. {megadetector-5.0.10.dist-info → megadetector-5.0.11.dist-info}/WHEEL +0 -0
@@ -1,228 +0,0 @@
1
- """
2
-
3
- prepare_classification_script_mc.py
4
-
5
- Notebook-y script used to prepare a series of shell commands to run MegaClassifier
6
- on a MegaDetector result set.
7
-
8
- Differs from prepare_classification_script.py only in the final class mapping step.
9
-
10
- """
11
-
12
- #%% Job options
13
-
14
- import os
15
-
16
- organization_name = 'idfg'
17
- job_name = 'idfg-2022-01-27-EOE2021S_Group6'
18
- input_filename = 'idfg-2022-01-27-EOE2021S_Group6_detections.filtered_rde_0.60_0.85_30_0.20.json'
19
- image_base = '/datadrive/idfg/EOE2021S_Group6'
20
- crop_path = os.path.join(os.path.expanduser('~/crops'),job_name + '_crops')
21
- device_id = 0
22
-
23
- working_dir_base = os.path.join(os.path.expanduser('~/postprocessing'),
24
- organization_name,
25
- job_name)
26
-
27
- output_base = os.path.join(working_dir_base,'combined_api_outputs')
28
-
29
- assert os.path.isdir(working_dir_base)
30
- assert os.path.isdir(output_base)
31
-
32
- output_file = os.path.join(working_dir_base,'run_megaclassifier_' + job_name + '.sh')
33
-
34
- input_files = [
35
- os.path.join(
36
- os.path.expanduser('~/postprocessing'),
37
- organization_name,
38
- job_name,
39
- 'combined_api_outputs',
40
- input_filename
41
- )
42
- ]
43
-
44
- for fn in input_files:
45
- assert os.path.isfile(fn)
46
-
47
-
48
- #%% Constants
49
-
50
- classifier_base = os.path.expanduser('~/models/camera_traps/megaclassifier/v0.1/')
51
- assert os.path.isdir(classifier_base)
52
-
53
- checkpoint_path = os.path.join(classifier_base,'v0.1_efficientnet-b3_compiled.pt')
54
- assert os.path.isfile(checkpoint_path)
55
-
56
- classifier_categories_path = os.path.join(classifier_base,'v0.1_index_to_name.json')
57
- assert os.path.isfile(classifier_categories_path)
58
-
59
- target_mapping_path = os.path.join(classifier_base,'idfg_to_megaclassifier_labels.json')
60
- assert os.path.isfile(target_mapping_path)
61
-
62
- classifier_output_suffix = '_megaclassifier_output.csv.gz'
63
- final_output_suffix = '_megaclassifier.json'
64
-
65
- threshold_str = '0.65'
66
- n_threads_str = '50'
67
- image_size_str = '300'
68
- batch_size_str = '64'
69
- num_workers_str = '8'
70
- logdir = working_dir_base
71
-
72
- classification_threshold_str = '0.05'
73
-
74
- # This is just passed along to the metadata in the output file, it has no impact
75
- # on how the classification scripts run.
76
- typical_classification_threshold_str = '0.75'
77
-
78
- classifier_name = 'megaclassifier_v0.1_efficientnet-b3'
79
-
80
-
81
- #%% Set up environment
82
-
83
- commands = []
84
- # commands.append('cd MegaDetector/classification\n')
85
- # commands.append('conda activate cameratraps-classifier\n')
86
-
87
-
88
- #%% Crop images
89
-
90
- commands.append('\n### Cropping ###\n')
91
-
92
- # fn = input_files[0]
93
- for fn in input_files:
94
-
95
- input_file_path = fn
96
- crop_cmd = ''
97
-
98
- crop_comment = '\n# Cropping {}\n'.format(fn)
99
- crop_cmd += crop_comment
100
-
101
- crop_cmd += "python crop_detections.py \\\n" + \
102
- input_file_path + ' \\\n' + \
103
- crop_path + ' \\\n' + \
104
- '--images-dir "' + image_base + '"' + ' \\\n' + \
105
- '--threshold "' + threshold_str + '"' + ' \\\n' + \
106
- '--square-crops ' + ' \\\n' + \
107
- '--threads "' + n_threads_str + '"' + ' \\\n' + \
108
- '--logdir "' + logdir + '"' + ' \\\n' + \
109
- '\n'
110
- crop_cmd = '{}'.format(crop_cmd)
111
- commands.append(crop_cmd)
112
-
113
-
114
- #%% Run classifier
115
-
116
- commands.append('\n### Classifying ###\n')
117
-
118
- # fn = input_files[0]
119
- for fn in input_files:
120
-
121
- input_file_path = fn
122
- classifier_output_path = crop_path + classifier_output_suffix
123
-
124
- classify_cmd = ''
125
-
126
- classify_comment = '\n# Classifying {}\n'.format(fn)
127
- classify_cmd += classify_comment
128
-
129
- classify_cmd += "python run_classifier.py \\\n" + \
130
- checkpoint_path + ' \\\n' + \
131
- crop_path + ' \\\n' + \
132
- classifier_output_path + ' \\\n' + \
133
- '--detections-json "' + input_file_path + '"' + ' \\\n' + \
134
- '--classifier-categories "' + classifier_categories_path + '"' + ' \\\n' + \
135
- '--image-size "' + image_size_str + '"' + ' \\\n' + \
136
- '--batch-size "' + batch_size_str + '"' + ' \\\n' + \
137
- '--num-workers "' + num_workers_str + '"' + ' \\\n'
138
-
139
- if device_id is not None:
140
- classify_cmd += '--device {}'.format(device_id)
141
-
142
- classify_cmd += '\n\n'
143
- classify_cmd = '{}'.format(classify_cmd)
144
- commands.append(classify_cmd)
145
-
146
-
147
- #%% Remap classifier outputs
148
-
149
- commands.append('\n### Remapping ###\n')
150
-
151
- # fn = input_files[0]
152
- for fn in input_files:
153
-
154
- input_file_path = fn
155
- classifier_output_path = crop_path + classifier_output_suffix
156
- classifier_output_path_remapped = \
157
- classifier_output_path.replace(".csv.gz","_remapped.csv.gz")
158
- assert not (classifier_output_path == classifier_output_path_remapped)
159
-
160
- output_label_index = classifier_output_path_remapped.replace(
161
- "_remapped.csv.gz","_label_index_remapped.json")
162
-
163
- remap_cmd = ''
164
-
165
- remap_comment = '\n# Remapping {}\n'.format(fn)
166
- remap_cmd += remap_comment
167
-
168
- remap_cmd += "python aggregate_classifier_probs.py \\\n" + \
169
- classifier_output_path + ' \\\n' + \
170
- '--target-mapping "' + target_mapping_path + '"' + ' \\\n' + \
171
- '--output-csv "' + classifier_output_path_remapped + '"' + ' \\\n' + \
172
- '--output-label-index "' + output_label_index + '"' + ' \\\n' + \
173
- '\n'
174
-
175
- remap_cmd = '{}'.format(remap_cmd)
176
- commands.append(remap_cmd)
177
-
178
-
179
- #%% Merge classification and detection outputs
180
-
181
- commands.append('\n### Merging ###\n')
182
-
183
- # fn = input_files[0]
184
- for fn in input_files:
185
-
186
- input_file_path = fn
187
- classifier_output_path = crop_path + classifier_output_suffix
188
-
189
- classifier_output_path_remapped = \
190
- classifier_output_path.replace(".csv.gz","_remapped.csv.gz")
191
-
192
- output_label_index = classifier_output_path_remapped.replace(
193
- "_remapped.csv.gz","_label_index_remapped.json")
194
-
195
- final_output_path = os.path.join(output_base,
196
- os.path.basename(classifier_output_path)).\
197
- replace(classifier_output_suffix,
198
- final_output_suffix)
199
- final_output_path = final_output_path.replace('_detections','')
200
- final_output_path = final_output_path.replace('_crops','')
201
-
202
- merge_cmd = ''
203
-
204
- merge_comment = '\n# Merging {}\n'.format(fn)
205
- merge_cmd += merge_comment
206
-
207
- merge_cmd += "python merge_classification_detection_output.py \\\n" + \
208
- classifier_output_path_remapped + ' \\\n' + \
209
- output_label_index + ' \\\n' + \
210
- '--output-json "' + final_output_path + '"' + ' \\\n' + \
211
- '--detection-json "' + input_file_path + '"' + ' \\\n' + \
212
- '--classifier-name "' + classifier_name + '"' + ' \\\n' + \
213
- '--threshold "' + classification_threshold_str + '"' + ' \\\n' + \
214
- '--typical-confidence-threshold "' + typical_classification_threshold_str + '"' + ' \\\n' + \
215
- '\n'
216
- merge_cmd = '{}'.format(merge_cmd)
217
- commands.append(merge_cmd)
218
-
219
-
220
- #%% Write everything out
221
-
222
- with open(output_file,'w') as f:
223
- for s in commands:
224
- f.write('{}'.format(s))
225
-
226
- import stat
227
- st = os.stat(output_file)
228
- os.chmod(output_file, st.st_mode | stat.S_IEXEC)
@@ -1,286 +0,0 @@
1
- """
2
-
3
- run_classifier.py
4
-
5
- Run a species classifier.
6
-
7
- This script is the classifier counterpart to detection/run_tf_detector_batch.py.
8
- This script takes as input:
9
- 1) a detections JSON file, usually the output of run_tf_detector_batch.py or the
10
- output of the Batch API in the "Batch processing API output format"
11
- 2) a path to a directory containing crops of bounding boxes from the detections
12
- JSON file
13
- 3) a path to a PyTorch TorchScript compiled model file
14
- 4) (if the model is EfficientNet) an image size
15
-
16
- By default, this script overwrites the detections JSON file, adding in
17
- classification results. To output a new JSON file, use the --output argument.
18
-
19
- """
20
-
21
- #%% Imports
22
-
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import json
27
- import os
28
- from tqdm import tqdm
29
- from typing import Any
30
- from collections.abc import Callable, Sequence
31
-
32
- import pandas as pd
33
- import PIL
34
- import torch
35
- import torch.utils
36
- import torchvision as tv
37
- from torchvision.datasets.folder import default_loader
38
-
39
- from classification import train_classifier
40
-
41
-
42
- #%% Example usage
43
-
44
- """
45
- python run_classifier.py \
46
- detections.json \
47
- /path/to/crops \
48
- /path/to/model.pt \
49
- --image-size 224
50
- """
51
-
52
-
53
- #%% Classes
54
-
55
- class SimpleDataset(torch.utils.data.Dataset):
56
- """
57
- Very simple dataset.
58
- """
59
-
60
- def __init__(self, img_files: Sequence[str],
61
- images_dir: str | None = None,
62
- transform: Callable[[PIL.Image.Image], Any] | None = None):
63
- """Creates a SimpleDataset."""
64
- self.img_files = img_files
65
- self.images_dir = images_dir
66
- self.transform = transform
67
-
68
- def __getitem__(self, index: int) -> tuple[Any, str]:
69
- """
70
- Returns: tuple, (img, img_file)
71
- """
72
- img_file = self.img_files[index]
73
- if self.images_dir is not None:
74
- img_path = os.path.join(self.images_dir, img_file)
75
- else:
76
- img_path = img_file
77
- img = default_loader(img_path)
78
- if self.transform is not None:
79
- img = self.transform(img)
80
- return img, img_file
81
-
82
- def __len__(self) -> int:
83
- return len(self.img_files)
84
-
85
-
86
- #%% Support functions
87
-
88
- def create_loader(cropped_images_dir: str,
89
- detections_json_path: str | None,
90
- img_size: int,
91
- batch_size: int,
92
- num_workers: int
93
- ) -> torch.utils.data.DataLoader:
94
- """
95
- Creates a DataLoader.
96
-
97
- Args:
98
- cropped_images_dir: str, path to image crops
99
- detections_json_path: optional str, path to detections JSON
100
- img_size: int, resizes smallest side of image to img_size,
101
- then center-crops to (img_size, img_size)
102
- batch_size: int, batch size in dataloader
103
- num_workers: int, # of workers in dataloader
104
- """
105
-
106
- crop_files = []
107
-
108
- if detections_json_path is None:
109
- # recursively find all files in cropped_images_dir
110
- for subdir, _, files in os.walk(cropped_images_dir):
111
- for file_name in files:
112
- rel_dir = os.path.relpath(subdir, cropped_images_dir)
113
- rel_file = os.path.join(rel_dir, file_name)
114
- crop_files.append(rel_file)
115
-
116
- else:
117
- # only find crops of images from detections JSON
118
- print('Loading detections JSON')
119
- with open(detections_json_path, 'r') as f:
120
- js = json.load(f)
121
- detections = {img['file']: img for img in js['images']}
122
- detector_version = js['info']['detector']
123
-
124
- for img_file, info_dict in tqdm(detections.items()):
125
- if 'detections' not in info_dict or info_dict['detections'] is None:
126
- continue
127
- for i in range(len(info_dict['detections'])):
128
- crop_filename = img_file + f'___crop{i:02d}_{detector_version}.jpg'
129
- crop_path = os.path.join(cropped_images_dir, crop_filename)
130
- if os.path.exists(crop_path):
131
- crop_files.append(crop_filename)
132
-
133
- transform = tv.transforms.Compose([
134
- # resizes smaller edge to img_size
135
- tv.transforms.Resize(img_size, interpolation=PIL.Image.BICUBIC),
136
- tv.transforms.CenterCrop(img_size),
137
- tv.transforms.ToTensor(),
138
- tv.transforms.Normalize(mean=train_classifier.MEANS,
139
- std=train_classifier.STDS, inplace=True)
140
- ])
141
-
142
- dataset = SimpleDataset(img_files=crop_files, images_dir=cropped_images_dir,
143
- transform=transform)
144
- assert len(dataset) > 0
145
- loader = torch.utils.data.DataLoader(
146
- dataset, batch_size=batch_size, num_workers=num_workers,
147
- pin_memory=True)
148
- return loader
149
-
150
-
151
- #%% Main function
152
-
153
- def main(model_path: str,
154
- cropped_images_dir: str,
155
- output_csv_path: str,
156
- detections_json_path: str | None,
157
- classifier_categories_json_path: str | None,
158
- img_size: int,
159
- batch_size: int,
160
- num_workers: int,
161
- device_id: int | None = None) -> None:
162
-
163
- # Evaluating with accimage is much faster than Pillow or Pillow-SIMD, but accimage
164
- # is Linux-only.
165
- try:
166
- import accimage # noqa
167
- tv.set_image_backend('accimage')
168
- except:
169
- print('Warning: could not start accimage backend (ignore this if you\'re not using Linux)')
170
-
171
- # create dataset
172
- print('Creating data loader')
173
- loader = create_loader(
174
- cropped_images_dir, detections_json_path=detections_json_path,
175
- img_size=img_size, batch_size=batch_size, num_workers=num_workers)
176
-
177
- label_names = None
178
- if classifier_categories_json_path is not None:
179
- with open(classifier_categories_json_path, 'r') as f:
180
- categories = json.load(f)
181
- label_names = [categories[str(i)] for i in range(len(categories))]
182
-
183
- # create model
184
- print('Loading saved model')
185
- model = torch.jit.load(model_path)
186
- model, device = train_classifier.prep_device(model, device_id=device_id)
187
-
188
- test_epoch(model, loader, device=device, label_names=label_names,
189
- output_csv_path=output_csv_path)
190
-
191
-
192
- def test_epoch(model: torch.nn.Module,
193
- loader: torch.utils.data.DataLoader,
194
- device: torch.device,
195
- label_names: Sequence[str] | None,
196
- output_csv_path: str) -> None:
197
- """
198
- Runs for 1 epoch.
199
-
200
- Writes results to the output CSV in batches.
201
-
202
- Args:
203
- model: torch.nn.Module
204
- loader: torch.utils.data.DataLoader
205
- device: torch.device
206
- label_names: optional list of str, label names
207
- output_csv_path: str
208
- """
209
-
210
- # set dropout and BN layers to eval mode
211
- model.eval()
212
-
213
- header = True
214
- mode = 'w' # new file on first write
215
-
216
- with torch.no_grad():
217
- for inputs, img_files in tqdm(loader):
218
- inputs = inputs.to(device, non_blocking=True)
219
- outputs = model(inputs)
220
- probs = torch.nn.functional.softmax(outputs, dim=1).cpu().numpy()
221
-
222
- if label_names is None:
223
- label_names = [str(i) for i in range(probs.shape[1])]
224
-
225
- df = pd.DataFrame(data=probs, columns=label_names,
226
- index=pd.Index(img_files, name='path'))
227
- df.to_csv(output_csv_path, index=True, header=header, mode=mode)
228
-
229
- if header:
230
- header = False
231
- mode = 'a'
232
-
233
-
234
- #%% Command-line driver
235
-
236
- def _parse_args() -> argparse.Namespace:
237
-
238
- parser = argparse.ArgumentParser(
239
- formatter_class=argparse.ArgumentDefaultsHelpFormatter,
240
- description='Run classifier.')
241
- parser.add_argument(
242
- 'model',
243
- help='path to TorchScript compiled model')
244
- parser.add_argument(
245
- 'crops_dir',
246
- help='path to directory containing cropped images')
247
- parser.add_argument(
248
- 'output',
249
- help='path to save CSV file with classifier results (can use .csv.gz '
250
- 'extension for compression)')
251
- parser.add_argument(
252
- '-d', '--detections-json',
253
- help='path to detections JSON file, used to filter paths within '
254
- 'crops_dir')
255
- parser.add_argument(
256
- '-c', '--classifier-categories',
257
- help='path to JSON file for classifier categories. If not given, '
258
- 'classes are numbered "0", "1", "2", ...')
259
- parser.add_argument(
260
- '--image-size', type=int, default=224,
261
- help='size of input image to model, usually 224px, but may be larger '
262
- 'especially for EfficientNet models')
263
- parser.add_argument(
264
- '--batch-size', type=int, default=1,
265
- help='batch size for evaluating model')
266
- parser.add_argument(
267
- '--device', type=int, default=None,
268
- help='preferred CUDA device')
269
- parser.add_argument(
270
- '--num-workers', type=int, default=8,
271
- help='# of workers for data loading')
272
- return parser.parse_args()
273
-
274
-
275
- if __name__ == '__main__':
276
-
277
- args = _parse_args()
278
- main(model_path=args.model,
279
- cropped_images_dir=args.crops_dir,
280
- output_csv_path=args.output,
281
- detections_json_path=args.detections_json,
282
- classifier_categories_json_path=args.classifier_categories,
283
- img_size=args.image_size,
284
- batch_size=args.batch_size,
285
- num_workers=args.num_workers,
286
- device_id=args.device)
@@ -1,110 +0,0 @@
1
- """
2
-
3
- save_mislabeled.py
4
-
5
- Update the list of known mislabeled images in MegaDB.
6
-
7
- List of known mislabeled images is stored in Azure Blob Storage.
8
- * storage account: cameratrapsc
9
- * container: classifier-training
10
- * blob: megadb_mislabeled/{dataset}.csv, one file per dataset
11
-
12
- Each file megadb_mislabeled/{dataset}.csv has two columns:
13
-
14
- * 'file': str, blob name
15
-
16
- * 'correct_class': optional str, correct dataset class
17
-
18
- if empty, indicates that the existing class in MegaDB is inaccurate, but
19
- the correct class is unknown.
20
-
21
- This script assumes that the classifier-training container is mounted locally.
22
-
23
- Takes as input a CSV file (output from Timelapse) with the following columns:
24
-
25
- * 'File': str, <blob_basename>
26
- * 'RelativePath': str, <dataset>\<blob_dirname>
27
- * 'mislabeled': str, values in ['true', 'false']
28
- * 'correct_class': either empty or str
29
-
30
- """
31
-
32
- #%% Imports
33
-
34
- import argparse
35
- import os
36
- import pathlib
37
-
38
- import pandas as pd
39
-
40
-
41
- #%% Main function
42
-
43
- def update_mislabeled_images(container_path: str, input_csv_path: str) -> None:
44
-
45
- df = pd.read_csv(input_csv_path, index_col=False)
46
-
47
- # error checking
48
- assert df['mislabeled'].dtype == bool
49
-
50
- # any row with 'correct_class' should be marked 'mislabeled'
51
- tmp = (df['correct_class'].notna() & df['mislabeled']).sum()
52
- assert df['correct_class'].notna().sum() == tmp
53
-
54
- # filter to only the mislabeled rows
55
- df = df[df['mislabeled']].copy()
56
-
57
- # convert '\' to '/'
58
- df['RelativePath'] = df['RelativePath'].map(
59
- lambda p: pathlib.PureWindowsPath(p).as_posix())
60
- df[['dataset', 'blob_dirname']] = df['RelativePath'].str.split(
61
- '/', n=1, expand=True)
62
- df['file'] = df['blob_dirname'] + '/' + df['File']
63
-
64
- for ds, ds_df in df.groupby('dataset'):
65
-
66
- sr_path = os.path.join(container_path, 'megadb_mislabeled', f'{ds}.csv')
67
- if os.path.exists(sr_path):
68
- old_sr = pd.read_csv(sr_path, index_col='file', squeeze=True)
69
- else:
70
- old_sr = pd.Series(index=pd.Index([], name='file'),
71
- dtype='str', name='correct_class')
72
-
73
- ds_sr = ds_df.set_index('file', verify_integrity=True)['correct_class']
74
-
75
- # verify that overlapping indices are the same
76
- overlap_index = ds_sr.index.intersection(old_sr.index)
77
- assert ds_sr.loc[overlap_index].equals(old_sr.loc[overlap_index])
78
-
79
- # "add" any new mislabelings
80
- new_indices = ds_sr.index.difference(old_sr.index)
81
- new_sr = pd.concat([old_sr, ds_sr.loc[new_indices]],
82
- verify_integrity=True)
83
- new_sr.sort_index(inplace=True)
84
-
85
- # write out results
86
- new_sr.to_csv(sr_path, index=True)
87
-
88
-
89
- #%% Command-line driver
90
-
91
- def _parse_args() -> argparse.Namespace:
92
-
93
- parser = argparse.ArgumentParser(
94
- formatter_class=argparse.ArgumentDefaultsHelpFormatter,
95
- description='Merges classification results with Batch Detection API '
96
- 'outputs.')
97
- parser.add_argument(
98
- 'container_path',
99
- help='path to locally-mounted classifier-training container')
100
- parser.add_argument(
101
- 'input_csv',
102
- help='path to CSV file output by Timelapse')
103
- return parser.parse_args()
104
-
105
-
106
- if __name__ == '__main__':
107
-
108
- args = _parse_args()
109
- update_mislabeled_images(container_path=args.container_path,
110
- input_csv_path=args.input_csv)