megadetector 5.0.11__py3-none-any.whl → 5.0.12__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.
- megadetector/api/__init__.py +0 -0
- megadetector/api/batch_processing/__init__.py +0 -0
- megadetector/api/batch_processing/api_core/__init__.py +0 -0
- megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
- megadetector/api/batch_processing/api_core/batch_service/score.py +439 -0
- megadetector/api/batch_processing/api_core/server.py +294 -0
- megadetector/api/batch_processing/api_core/server_api_config.py +98 -0
- megadetector/api/batch_processing/api_core/server_app_config.py +55 -0
- megadetector/api/batch_processing/api_core/server_batch_job_manager.py +220 -0
- megadetector/api/batch_processing/api_core/server_job_status_table.py +152 -0
- megadetector/api/batch_processing/api_core/server_orchestration.py +360 -0
- megadetector/api/batch_processing/api_core/server_utils.py +92 -0
- megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
- megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +46 -0
- megadetector/api/batch_processing/api_support/__init__.py +0 -0
- megadetector/api/batch_processing/api_support/summarize_daily_activity.py +152 -0
- megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
- megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
- megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
- megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
- megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +126 -0
- megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
- megadetector/api/synchronous/__init__.py +0 -0
- megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
- megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +152 -0
- megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +266 -0
- megadetector/api/synchronous/api_core/animal_detection_api/config.py +35 -0
- megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
- megadetector/api/synchronous/api_core/tests/load_test.py +110 -0
- megadetector/classification/__init__.py +0 -0
- megadetector/classification/aggregate_classifier_probs.py +108 -0
- megadetector/classification/analyze_failed_images.py +227 -0
- megadetector/classification/cache_batchapi_outputs.py +198 -0
- megadetector/classification/create_classification_dataset.py +627 -0
- megadetector/classification/crop_detections.py +516 -0
- megadetector/classification/csv_to_json.py +226 -0
- megadetector/classification/detect_and_crop.py +855 -0
- megadetector/classification/efficientnet/__init__.py +9 -0
- megadetector/classification/efficientnet/model.py +415 -0
- megadetector/classification/efficientnet/utils.py +610 -0
- megadetector/classification/evaluate_model.py +520 -0
- megadetector/classification/identify_mislabeled_candidates.py +152 -0
- megadetector/classification/json_to_azcopy_list.py +63 -0
- megadetector/classification/json_validator.py +699 -0
- megadetector/classification/map_classification_categories.py +276 -0
- megadetector/classification/merge_classification_detection_output.py +506 -0
- megadetector/classification/prepare_classification_script.py +194 -0
- megadetector/classification/prepare_classification_script_mc.py +228 -0
- megadetector/classification/run_classifier.py +287 -0
- megadetector/classification/save_mislabeled.py +110 -0
- megadetector/classification/train_classifier.py +827 -0
- megadetector/classification/train_classifier_tf.py +725 -0
- megadetector/classification/train_utils.py +323 -0
- megadetector/data_management/__init__.py +0 -0
- megadetector/data_management/annotations/__init__.py +0 -0
- megadetector/data_management/annotations/annotation_constants.py +34 -0
- megadetector/data_management/camtrap_dp_to_coco.py +239 -0
- megadetector/data_management/cct_json_utils.py +395 -0
- megadetector/data_management/cct_to_md.py +176 -0
- megadetector/data_management/cct_to_wi.py +289 -0
- megadetector/data_management/coco_to_labelme.py +272 -0
- megadetector/data_management/coco_to_yolo.py +662 -0
- megadetector/data_management/databases/__init__.py +0 -0
- megadetector/data_management/databases/add_width_and_height_to_db.py +33 -0
- megadetector/data_management/databases/combine_coco_camera_traps_files.py +206 -0
- megadetector/data_management/databases/integrity_check_json_db.py +477 -0
- megadetector/data_management/databases/subset_json_db.py +115 -0
- megadetector/data_management/generate_crops_from_cct.py +149 -0
- megadetector/data_management/get_image_sizes.py +189 -0
- megadetector/data_management/importers/add_nacti_sizes.py +52 -0
- megadetector/data_management/importers/add_timestamps_to_icct.py +79 -0
- megadetector/data_management/importers/animl_results_to_md_results.py +158 -0
- megadetector/data_management/importers/auckland_doc_test_to_json.py +373 -0
- megadetector/data_management/importers/auckland_doc_to_json.py +201 -0
- megadetector/data_management/importers/awc_to_json.py +191 -0
- megadetector/data_management/importers/bellevue_to_json.py +273 -0
- megadetector/data_management/importers/cacophony-thermal-importer.py +796 -0
- megadetector/data_management/importers/carrizo_shrubfree_2018.py +269 -0
- megadetector/data_management/importers/carrizo_trail_cam_2017.py +289 -0
- megadetector/data_management/importers/cct_field_adjustments.py +58 -0
- megadetector/data_management/importers/channel_islands_to_cct.py +913 -0
- megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +180 -0
- megadetector/data_management/importers/eMammal/eMammal_helpers.py +249 -0
- megadetector/data_management/importers/eMammal/make_eMammal_json.py +223 -0
- megadetector/data_management/importers/ena24_to_json.py +276 -0
- megadetector/data_management/importers/filenames_to_json.py +386 -0
- megadetector/data_management/importers/helena_to_cct.py +283 -0
- megadetector/data_management/importers/idaho-camera-traps.py +1407 -0
- megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +294 -0
- megadetector/data_management/importers/jb_csv_to_json.py +150 -0
- megadetector/data_management/importers/mcgill_to_json.py +250 -0
- megadetector/data_management/importers/missouri_to_json.py +490 -0
- megadetector/data_management/importers/nacti_fieldname_adjustments.py +79 -0
- megadetector/data_management/importers/noaa_seals_2019.py +181 -0
- megadetector/data_management/importers/pc_to_json.py +365 -0
- megadetector/data_management/importers/plot_wni_giraffes.py +123 -0
- megadetector/data_management/importers/prepare-noaa-fish-data-for-lila.py +359 -0
- megadetector/data_management/importers/prepare_zsl_imerit.py +131 -0
- megadetector/data_management/importers/rspb_to_json.py +356 -0
- megadetector/data_management/importers/save_the_elephants_survey_A.py +320 -0
- megadetector/data_management/importers/save_the_elephants_survey_B.py +329 -0
- megadetector/data_management/importers/snapshot_safari_importer.py +758 -0
- megadetector/data_management/importers/snapshot_safari_importer_reprise.py +665 -0
- megadetector/data_management/importers/snapshot_serengeti_lila.py +1067 -0
- megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +150 -0
- megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +153 -0
- megadetector/data_management/importers/sulross_get_exif.py +65 -0
- megadetector/data_management/importers/timelapse_csv_set_to_json.py +490 -0
- megadetector/data_management/importers/ubc_to_json.py +399 -0
- megadetector/data_management/importers/umn_to_json.py +507 -0
- megadetector/data_management/importers/wellington_to_json.py +263 -0
- megadetector/data_management/importers/wi_to_json.py +442 -0
- megadetector/data_management/importers/zamba_results_to_md_results.py +181 -0
- megadetector/data_management/labelme_to_coco.py +547 -0
- megadetector/data_management/labelme_to_yolo.py +272 -0
- megadetector/data_management/lila/__init__.py +0 -0
- megadetector/data_management/lila/add_locations_to_island_camera_traps.py +97 -0
- megadetector/data_management/lila/add_locations_to_nacti.py +147 -0
- megadetector/data_management/lila/create_lila_blank_set.py +558 -0
- megadetector/data_management/lila/create_lila_test_set.py +152 -0
- megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
- megadetector/data_management/lila/download_lila_subset.py +178 -0
- megadetector/data_management/lila/generate_lila_per_image_labels.py +516 -0
- megadetector/data_management/lila/get_lila_annotation_counts.py +170 -0
- megadetector/data_management/lila/get_lila_image_counts.py +112 -0
- megadetector/data_management/lila/lila_common.py +300 -0
- megadetector/data_management/lila/test_lila_metadata_urls.py +132 -0
- megadetector/data_management/ocr_tools.py +874 -0
- megadetector/data_management/read_exif.py +681 -0
- megadetector/data_management/remap_coco_categories.py +84 -0
- megadetector/data_management/remove_exif.py +66 -0
- megadetector/data_management/resize_coco_dataset.py +189 -0
- megadetector/data_management/wi_download_csv_to_coco.py +246 -0
- megadetector/data_management/yolo_output_to_md_output.py +441 -0
- megadetector/data_management/yolo_to_coco.py +676 -0
- megadetector/detection/__init__.py +0 -0
- megadetector/detection/detector_training/__init__.py +0 -0
- megadetector/detection/detector_training/model_main_tf2.py +114 -0
- megadetector/detection/process_video.py +702 -0
- megadetector/detection/pytorch_detector.py +341 -0
- megadetector/detection/run_detector.py +779 -0
- megadetector/detection/run_detector_batch.py +1219 -0
- megadetector/detection/run_inference_with_yolov5_val.py +917 -0
- megadetector/detection/run_tiled_inference.py +934 -0
- megadetector/detection/tf_detector.py +189 -0
- megadetector/detection/video_utils.py +606 -0
- megadetector/postprocessing/__init__.py +0 -0
- megadetector/postprocessing/add_max_conf.py +64 -0
- megadetector/postprocessing/categorize_detections_by_size.py +163 -0
- megadetector/postprocessing/combine_api_outputs.py +249 -0
- megadetector/postprocessing/compare_batch_results.py +958 -0
- megadetector/postprocessing/convert_output_format.py +396 -0
- megadetector/postprocessing/load_api_results.py +195 -0
- megadetector/postprocessing/md_to_coco.py +310 -0
- megadetector/postprocessing/md_to_labelme.py +330 -0
- megadetector/postprocessing/merge_detections.py +401 -0
- megadetector/postprocessing/postprocess_batch_results.py +1902 -0
- megadetector/postprocessing/remap_detection_categories.py +170 -0
- megadetector/postprocessing/render_detection_confusion_matrix.py +660 -0
- megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +211 -0
- megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +83 -0
- megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1631 -0
- megadetector/postprocessing/separate_detections_into_folders.py +730 -0
- megadetector/postprocessing/subset_json_detector_output.py +696 -0
- megadetector/postprocessing/top_folders_to_bottom.py +223 -0
- megadetector/taxonomy_mapping/__init__.py +0 -0
- megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
- megadetector/taxonomy_mapping/map_new_lila_datasets.py +150 -0
- megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +142 -0
- megadetector/taxonomy_mapping/preview_lila_taxonomy.py +590 -0
- megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
- megadetector/taxonomy_mapping/simple_image_download.py +219 -0
- megadetector/taxonomy_mapping/species_lookup.py +834 -0
- megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
- megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
- megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
- megadetector/utils/__init__.py +0 -0
- megadetector/utils/azure_utils.py +178 -0
- megadetector/utils/ct_utils.py +612 -0
- megadetector/utils/directory_listing.py +246 -0
- megadetector/utils/md_tests.py +968 -0
- megadetector/utils/path_utils.py +1044 -0
- megadetector/utils/process_utils.py +157 -0
- megadetector/utils/sas_blob_utils.py +509 -0
- megadetector/utils/split_locations_into_train_val.py +228 -0
- megadetector/utils/string_utils.py +92 -0
- megadetector/utils/url_utils.py +323 -0
- megadetector/utils/write_html_image_list.py +225 -0
- megadetector/visualization/__init__.py +0 -0
- megadetector/visualization/plot_utils.py +293 -0
- megadetector/visualization/render_images_with_thumbnails.py +275 -0
- megadetector/visualization/visualization_utils.py +1536 -0
- megadetector/visualization/visualize_db.py +550 -0
- megadetector/visualization/visualize_detector_output.py +405 -0
- {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/METADATA +1 -1
- megadetector-5.0.12.dist-info/RECORD +199 -0
- megadetector-5.0.12.dist-info/top_level.txt +1 -0
- megadetector-5.0.11.dist-info/RECORD +0 -5
- megadetector-5.0.11.dist-info/top_level.txt +0 -1
- {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/LICENSE +0 -0
- {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
This script can be run in a separate process to monitor all instances of the batch API.
|
|
6
|
+
It sends a digest of submissions within the past day to a Teams channel webhook.
|
|
7
|
+
|
|
8
|
+
It requires the environment variables TEAMS_WEBHOOK, COSMOS_ENDPOINT and COSMOS_READ_KEY to be set.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
import os
|
|
13
|
+
import json
|
|
14
|
+
from datetime import datetime, timezone, timedelta
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
|
|
17
|
+
import requests
|
|
18
|
+
from azure.cosmos.cosmos_client import CosmosClient
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Cosmos DB `batch-api-jobs` table for job status
|
|
22
|
+
COSMOS_ENDPOINT = os.environ['COSMOS_ENDPOINT']
|
|
23
|
+
COSMOS_READ_KEY = os.environ['COSMOS_READ_KEY']
|
|
24
|
+
|
|
25
|
+
TEAMS_WEBHOOK = os.environ['TEAMS_WEBHOOK']
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def send_message():
|
|
29
|
+
cosmos_client = CosmosClient(COSMOS_ENDPOINT, credential=COSMOS_READ_KEY)
|
|
30
|
+
db_client = cosmos_client.get_database_client('camera-trap')
|
|
31
|
+
db_jobs_client = db_client.get_container_client('batch_api_jobs')
|
|
32
|
+
|
|
33
|
+
yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)
|
|
34
|
+
|
|
35
|
+
query = f'''
|
|
36
|
+
SELECT *
|
|
37
|
+
FROM job
|
|
38
|
+
WHERE job.job_submission_time >= "{yesterday.isoformat()}T00:00:00Z"
|
|
39
|
+
'''
|
|
40
|
+
|
|
41
|
+
result_iterable = db_jobs_client.query_items(query=query,
|
|
42
|
+
enable_cross_partition_query=True)
|
|
43
|
+
|
|
44
|
+
# aggregate the number of images, country and organization names info from each job
|
|
45
|
+
# submitted during yesterday (UTC time)
|
|
46
|
+
instance_num_images = defaultdict(lambda: defaultdict(int))
|
|
47
|
+
instance_countries = defaultdict(set)
|
|
48
|
+
instance_orgs = defaultdict(set)
|
|
49
|
+
|
|
50
|
+
total_images_received = 0
|
|
51
|
+
|
|
52
|
+
for job in result_iterable:
|
|
53
|
+
api_instance = job['api_instance']
|
|
54
|
+
status = job['status']
|
|
55
|
+
call_params = job['call_params']
|
|
56
|
+
|
|
57
|
+
if status['request_status'] == 'completed':
|
|
58
|
+
instance_num_images[api_instance]['num_images_completed'] += status.get('num_images', 0)
|
|
59
|
+
instance_num_images[api_instance]['num_images_total'] += status.get('num_images', 0)
|
|
60
|
+
total_images_received += status.get('num_images', 0)
|
|
61
|
+
|
|
62
|
+
instance_countries[api_instance].add(call_params.get('country', 'unknown'))
|
|
63
|
+
instance_orgs[api_instance].add(call_params.get('organization_name', 'unknown'))
|
|
64
|
+
|
|
65
|
+
print(f'send_message, number of images received yesterday: {total_images_received}')
|
|
66
|
+
|
|
67
|
+
if total_images_received < 1:
|
|
68
|
+
print('send_message, no images submitted yesterday, not sending a summary')
|
|
69
|
+
print('')
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
# create the card
|
|
73
|
+
sections = []
|
|
74
|
+
|
|
75
|
+
for instance_name, num_images in instance_num_images.items():
|
|
76
|
+
entry = {
|
|
77
|
+
'activityTitle': f'API instance: {instance_name}',
|
|
78
|
+
'facts': [
|
|
79
|
+
{
|
|
80
|
+
'name': 'Total images',
|
|
81
|
+
'value': '{:,}'.format(num_images['num_images_total'])
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
'name': 'Images completed',
|
|
85
|
+
'value': '{:,}'.format(num_images['num_images_completed'])
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
'name': 'Countries',
|
|
89
|
+
'value': ', '.join(sorted(list(instance_countries[instance_name])))
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
'name': 'Organizations',
|
|
93
|
+
'value': ', '.join(sorted(list(instance_orgs[instance_name])))
|
|
94
|
+
}
|
|
95
|
+
]
|
|
96
|
+
}
|
|
97
|
+
sections.append(entry)
|
|
98
|
+
|
|
99
|
+
card = {
|
|
100
|
+
'@type': 'MessageCard',
|
|
101
|
+
'@context': 'http://schema.org/extensions',
|
|
102
|
+
'themeColor': 'ffcdb2',
|
|
103
|
+
'summary': 'Digest of batch API activities over the past 24 hours',
|
|
104
|
+
'title': f'Camera traps batch API activities on {yesterday.strftime("%b %d, %Y")}',
|
|
105
|
+
'sections': sections,
|
|
106
|
+
'potentialAction': [
|
|
107
|
+
{
|
|
108
|
+
'@type': 'OpenUri',
|
|
109
|
+
'name': 'View Batch account in Azure Portal',
|
|
110
|
+
'targets': [
|
|
111
|
+
{
|
|
112
|
+
'os': 'default',
|
|
113
|
+
'uri': 'https://ms.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/74d91980-e5b4-4fd9-adb6-263b8f90ec5b/resourcegroups/camera_trap_api_rg/providers/Microsoft.Batch/batchAccounts/cameratrapssc/accountOverview'
|
|
114
|
+
}
|
|
115
|
+
]
|
|
116
|
+
}
|
|
117
|
+
]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
response = requests.post(TEAMS_WEBHOOK, data=json.dumps(card))
|
|
121
|
+
print(f'send_message, card to send:')
|
|
122
|
+
print(json.dumps(card, indent=4))
|
|
123
|
+
print(f'send_message, sent summary to webhook, response code: {response.status_code}')
|
|
124
|
+
print('')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main():
|
|
128
|
+
"""
|
|
129
|
+
Wake up at 5 minutes past midnight UTC to send a summary of yesterday's activities if there were any.
|
|
130
|
+
Then goes in a loop to wake up and send a summary every 24 hours.
|
|
131
|
+
"""
|
|
132
|
+
current = datetime.utcnow()
|
|
133
|
+
future = current.replace(day=current.day, hour=0, minute=5, second=0, microsecond=0) + timedelta(
|
|
134
|
+
days=1) # current has been modified
|
|
135
|
+
|
|
136
|
+
current = datetime.utcnow()
|
|
137
|
+
duration = future - current
|
|
138
|
+
|
|
139
|
+
duration_hours = duration.seconds / (60 * 60)
|
|
140
|
+
print(f'Current time: {current}')
|
|
141
|
+
print(f'Will wake up at {future}, in {duration_hours} hours')
|
|
142
|
+
print('')
|
|
143
|
+
|
|
144
|
+
time.sleep(duration.seconds)
|
|
145
|
+
|
|
146
|
+
while True:
|
|
147
|
+
print(f'Woke up at {datetime.utcnow()}')
|
|
148
|
+
send_message()
|
|
149
|
+
time.sleep(24 * 60 * 60)
|
|
150
|
+
|
|
151
|
+
if __name__ == '__main__':
|
|
152
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
#
|
|
2
|
+
# xmp_integration.py
|
|
3
|
+
#
|
|
4
|
+
# Tools for loading MegaDetector batch API results into XMP metadata, specifically
|
|
5
|
+
# for consumption in digiKam:
|
|
6
|
+
#
|
|
7
|
+
# https://cran.r-project.org/web/packages/camtrapR/vignettes/camtrapr2.html
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
#%% Imports and constants
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import tkinter
|
|
14
|
+
from tkinter import ttk, messagebox, filedialog
|
|
15
|
+
|
|
16
|
+
import inspect
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import json
|
|
20
|
+
import pyexiv2
|
|
21
|
+
import ntpath
|
|
22
|
+
import threading
|
|
23
|
+
import traceback
|
|
24
|
+
|
|
25
|
+
from tqdm import tqdm
|
|
26
|
+
from multiprocessing import Pool
|
|
27
|
+
from multiprocessing.pool import ThreadPool
|
|
28
|
+
from functools import partial
|
|
29
|
+
|
|
30
|
+
category_mapping = {'person': 'Human', 'animal': 'Animal', 'vehicle': 'Vehicle'}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
#%% Class definitions
|
|
34
|
+
|
|
35
|
+
class xmp_gui:
|
|
36
|
+
|
|
37
|
+
root = None
|
|
38
|
+
textarea_min_threshold = None
|
|
39
|
+
textarea_status = None
|
|
40
|
+
textarea_remove_path = None
|
|
41
|
+
textarea_rename_conf = None
|
|
42
|
+
textarea_rename_cats = None
|
|
43
|
+
num_threads = 1
|
|
44
|
+
|
|
45
|
+
class xmp_integration_options:
|
|
46
|
+
|
|
47
|
+
# Folder where images are stored
|
|
48
|
+
image_folder = None
|
|
49
|
+
|
|
50
|
+
# .json file containing MegaDetector output
|
|
51
|
+
input_file = None
|
|
52
|
+
|
|
53
|
+
# String to remove from all path names, typically representing a
|
|
54
|
+
# prefix that was added during MegaDetector processing
|
|
55
|
+
remove_path = None
|
|
56
|
+
|
|
57
|
+
# Optionally *rename* (not copy) all images that have no detections
|
|
58
|
+
# above [rename_conf] for the categories in rename_cats from x.jpg to
|
|
59
|
+
# x.check.jpg
|
|
60
|
+
rename_conf = None
|
|
61
|
+
|
|
62
|
+
# Comma-deleted list of category names (or "all") to apply the rename_conf
|
|
63
|
+
# behavior to.
|
|
64
|
+
rename_cats = None
|
|
65
|
+
|
|
66
|
+
# Minimum detection threshold (applies to all classes, defaults to None,
|
|
67
|
+
# i.e. 0.0
|
|
68
|
+
min_threshold = None
|
|
69
|
+
num_threads = 1
|
|
70
|
+
xmp_gui = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
#%% Functions
|
|
74
|
+
|
|
75
|
+
def write_status(options,s):
|
|
76
|
+
|
|
77
|
+
if options.xmp_gui is None:
|
|
78
|
+
return
|
|
79
|
+
options.xmp_gui.textarea_status.configure(state="normal")
|
|
80
|
+
options.xmp_gui.textarea_status.insert(tkinter.END, s + '\n')
|
|
81
|
+
options.xmp_gui.textarea_status.configure(state="disabled")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
n_images_processed = 0
|
|
85
|
+
|
|
86
|
+
def update_xmp_metadata(categories, options, rename_cats, n_images, image):
|
|
87
|
+
"""
|
|
88
|
+
Update the XMP metadata for a single image
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
# Relative image path
|
|
92
|
+
filename = ''
|
|
93
|
+
|
|
94
|
+
# Absolute image path
|
|
95
|
+
img_path = ''
|
|
96
|
+
|
|
97
|
+
global n_images_processed
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
|
|
101
|
+
filename = image['file']
|
|
102
|
+
if options.remove_path != None and len(options.remove_path) > 0:
|
|
103
|
+
filename = filename.replace(options.remove_path, '')
|
|
104
|
+
img_path = os.path.join(options.image_folder, filename)
|
|
105
|
+
assert os.path.isfile(img_path), 'Image {} not found'.format(img_path)
|
|
106
|
+
|
|
107
|
+
# List of categories to write to XMP metadata
|
|
108
|
+
image_categories = []
|
|
109
|
+
|
|
110
|
+
# Categories with above-threshold detections present for
|
|
111
|
+
# this image
|
|
112
|
+
original_image_cats = []
|
|
113
|
+
|
|
114
|
+
# Maximum confidence for each category
|
|
115
|
+
original_image_cats_conf = {}
|
|
116
|
+
|
|
117
|
+
for detection in image['detections']:
|
|
118
|
+
|
|
119
|
+
cat = category_mapping[categories[detection['category']]]
|
|
120
|
+
|
|
121
|
+
# Have we already added this to the list of categories to
|
|
122
|
+
# write out to this image?
|
|
123
|
+
if cat not in image_categories:
|
|
124
|
+
|
|
125
|
+
# If we're supposed to compare to a threshold...
|
|
126
|
+
if len(options.min_threshold) > 0 and \
|
|
127
|
+
options.min_threshold != None:
|
|
128
|
+
if float(detection['conf']) > float(options.min_threshold):
|
|
129
|
+
image_categories.append(cat)
|
|
130
|
+
original_image_cats.append(
|
|
131
|
+
categories[detection['category']])
|
|
132
|
+
|
|
133
|
+
# Else we treat *any* detection as valid...
|
|
134
|
+
else:
|
|
135
|
+
image_categories.append(cat)
|
|
136
|
+
original_image_cats.append(categories[detection['category']])
|
|
137
|
+
|
|
138
|
+
# Keep track of the highest-confidence detection for this class
|
|
139
|
+
if options.min_threshold != None and \
|
|
140
|
+
len(options.min_threshold) > 0 and \
|
|
141
|
+
detection['conf'] > \
|
|
142
|
+
original_image_cats_conf.get(
|
|
143
|
+
categories[detection['category']], 0):
|
|
144
|
+
|
|
145
|
+
original_image_cats_conf[categories[detection['category']]] = \
|
|
146
|
+
detection['conf']
|
|
147
|
+
|
|
148
|
+
img = pyexiv2.Image(r'{0}'.format(img_path))
|
|
149
|
+
img.modify_xmp({'Xmp.lr.hierarchicalSubject': image_categories})
|
|
150
|
+
|
|
151
|
+
# If we're doing the rename/.check behavior...
|
|
152
|
+
if not (options.rename_conf is None and options.rename_cats is None):
|
|
153
|
+
|
|
154
|
+
matching_cats = set(rename_cats).intersection(set(original_image_cats))
|
|
155
|
+
is_conf_low = False
|
|
156
|
+
if options.min_threshold != None and len(options.min_threshold) > 0:
|
|
157
|
+
for matching_cat in matching_cats:
|
|
158
|
+
if original_image_cats_conf[matching_cat] < float(options.rename_conf):
|
|
159
|
+
is_conf_low = True
|
|
160
|
+
if options.min_threshold != None and \
|
|
161
|
+
len(options.min_threshold) > 0 and \
|
|
162
|
+
len(image['detections']) == 0 or \
|
|
163
|
+
(len(options.rename_conf) > 0 and \
|
|
164
|
+
is_conf_low is True and \
|
|
165
|
+
len(matching_cats) > 0):
|
|
166
|
+
|
|
167
|
+
parent_folder = os.path.dirname(img_path)
|
|
168
|
+
file_name = ntpath.basename(img_path)
|
|
169
|
+
manual_file_name = file_name.split('.')[0]+'_check' + '.' + file_name.split('.')[1]
|
|
170
|
+
os.rename(img_path, os.path.join(parent_folder, manual_file_name))
|
|
171
|
+
|
|
172
|
+
if options.xmp_gui is not None:
|
|
173
|
+
|
|
174
|
+
n_images_processed += 1
|
|
175
|
+
percentage = round((n_images_processed)/n_images*100)
|
|
176
|
+
options.xmp_gui.progress_bar['value'] = percentage
|
|
177
|
+
options.xmp_gui.root.update_idletasks()
|
|
178
|
+
options.xmp_gui.style.configure('text.Horizontal.Tprogress_bar',
|
|
179
|
+
text='{:g} %'.format(percentage))
|
|
180
|
+
|
|
181
|
+
except Exception as e:
|
|
182
|
+
|
|
183
|
+
s = 'Error processing image {}: {}'.format(filename,str(e))
|
|
184
|
+
print(s)
|
|
185
|
+
traceback.print_exc()
|
|
186
|
+
write_status(options,s)
|
|
187
|
+
|
|
188
|
+
if False:
|
|
189
|
+
|
|
190
|
+
# Legacy code to rename files where XMP writing failed
|
|
191
|
+
parent_folder = os.path.dirname(img_path)
|
|
192
|
+
file_name = ntpath.basename(img_path)
|
|
193
|
+
failed_file_name = file_name.split('.')[0]+'_failed' + '.' + file_name.split('.')[1]
|
|
194
|
+
os.rename(img_path, os.path.join(
|
|
195
|
+
parent_folder, failed_file_name))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def process_input_data(options):
|
|
199
|
+
"""
|
|
200
|
+
Main function to loop over images and modify XMP data
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
if options.xmp_gui is not None:
|
|
204
|
+
|
|
205
|
+
if (options.image_folder is None) or (len(options.image_folder) == 0):
|
|
206
|
+
tkinter.messagebox.showerror(title='Error', message='Image folder is not selected')
|
|
207
|
+
sys.exit()
|
|
208
|
+
if (options.input_file is None) or (len(options.input_file) == 0):
|
|
209
|
+
tkinter.messagebox.showerror(
|
|
210
|
+
title='Error', message='No MegaDetector .json file selected')
|
|
211
|
+
sys.exit()
|
|
212
|
+
options.remove_path = options.xmp_gui.textarea_remove_path.get()
|
|
213
|
+
options.rename_conf = options.xmp_gui.textarea_rename_conf.get()
|
|
214
|
+
options.rename_cats = options.xmp_gui.textarea_rename_cats.get()
|
|
215
|
+
options.num_threads = options.xmp_gui.textarea_num_threads.get()
|
|
216
|
+
options.min_threshold = options.xmp_gui.textarea_min_threshold.get()
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
|
|
220
|
+
with open(options.input_file, 'r') as f:
|
|
221
|
+
data = f.read()
|
|
222
|
+
|
|
223
|
+
data = json.loads(data)
|
|
224
|
+
categories = data['detection_categories']
|
|
225
|
+
|
|
226
|
+
images = data['images']
|
|
227
|
+
n_images = len(images)
|
|
228
|
+
if not (options.rename_conf is None and options.rename_cats is None):
|
|
229
|
+
rename_cats = options.rename_cats.split(",")
|
|
230
|
+
if rename_cats[0] == 'all':
|
|
231
|
+
rename_cats = list(category_mapping.keys())
|
|
232
|
+
else:
|
|
233
|
+
rename_cats = []
|
|
234
|
+
if len(options.num_threads) > 0:
|
|
235
|
+
num_threads = int(options.num_threads)
|
|
236
|
+
else:
|
|
237
|
+
num_threads = 1
|
|
238
|
+
print(num_threads)
|
|
239
|
+
if options.xmp_gui is None:
|
|
240
|
+
func = partial(update_xmp_metadata, categories, options, rename_cats, n_images)
|
|
241
|
+
with Pool(num_threads) as p:
|
|
242
|
+
with tqdm(total=n_images) as pbar:
|
|
243
|
+
for i, _ in enumerate(p.imap_unordered(func, images)):
|
|
244
|
+
pbar.update()
|
|
245
|
+
else:
|
|
246
|
+
func = partial(update_xmp_metadata, categories, options, rename_cats, n_images)
|
|
247
|
+
with ThreadPool(num_threads) as p:
|
|
248
|
+
p.map(func, images)
|
|
249
|
+
s = 'Successfully processed {} images'.format(n_images)
|
|
250
|
+
print(s)
|
|
251
|
+
write_status(options,s)
|
|
252
|
+
|
|
253
|
+
except Exception as e:
|
|
254
|
+
|
|
255
|
+
print('Error processing input data: {}'.format(str(e)))
|
|
256
|
+
traceback.print_exc()
|
|
257
|
+
if options.xmp_gui is not None:
|
|
258
|
+
tkinter.messagebox.showerror(title='Error',
|
|
259
|
+
message='Make Sure you selected the proper image folder and JSON files')
|
|
260
|
+
sys.exit()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def start_input_processing(options):
|
|
264
|
+
|
|
265
|
+
t = threading.Thread(target=lambda: process_input_data(options))
|
|
266
|
+
t.start()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def browse_folder(options,folder_path_var):
|
|
270
|
+
|
|
271
|
+
filename = tkinter.filedialog.askdirectory()
|
|
272
|
+
options.image_folder = r'{0}'.format(filename)
|
|
273
|
+
folder_path_var.set(filename)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def browse_file(options,file_path_var):
|
|
277
|
+
|
|
278
|
+
filename = tkinter.filedialog.askopenfilename()
|
|
279
|
+
options.input_file = r'{0}'.format(filename)
|
|
280
|
+
file_path_var.set(filename)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def create_gui(options):
|
|
284
|
+
|
|
285
|
+
root = tkinter.Tk()
|
|
286
|
+
root.resizable(False, False)
|
|
287
|
+
root.configure(background='white')
|
|
288
|
+
root.title('DigiKam Integration')
|
|
289
|
+
|
|
290
|
+
group = tkinter.LabelFrame(root, padx=5, pady=5)
|
|
291
|
+
group.configure(background = 'white')
|
|
292
|
+
group.pack(padx=10, pady=10, fill='both', expand='yes')
|
|
293
|
+
|
|
294
|
+
canvas = tkinter.Canvas(group, width = 800, height = 150)
|
|
295
|
+
canvas.configure(background = 'white')
|
|
296
|
+
canvas.pack()
|
|
297
|
+
img1 = tkinter.PhotoImage(file='images/aiforearth.png')
|
|
298
|
+
canvas.create_image(0,0, anchor=tkinter.NW, image=img1)
|
|
299
|
+
img2 = tkinter.PhotoImage(file='images/bg.png')
|
|
300
|
+
canvas.create_image(0,20, anchor=tkinter.NW, image=img2)
|
|
301
|
+
|
|
302
|
+
frame = tkinter.Frame(root)
|
|
303
|
+
frame.configure(background='white')
|
|
304
|
+
frame.pack()
|
|
305
|
+
|
|
306
|
+
l1 = tkinter.Label(frame, text='Folder containing images')
|
|
307
|
+
l1.configure(background='white')
|
|
308
|
+
l1.grid(row=0, column=0)
|
|
309
|
+
|
|
310
|
+
folder_path_var = tkinter.StringVar()
|
|
311
|
+
|
|
312
|
+
e1 = tkinter.Entry(frame, width=50, textvariable=folder_path_var, highlightthickness=1)
|
|
313
|
+
e1.configure(highlightbackground='grey', highlightcolor='grey')
|
|
314
|
+
e1.grid(row=0, column=2)
|
|
315
|
+
|
|
316
|
+
b1 = tkinter.Button(frame, text='Browse', fg='blue', command=lambda: browse_folder(options,folder_path_var))
|
|
317
|
+
b1.grid(row=0, column=5, padx=10)
|
|
318
|
+
|
|
319
|
+
l2 = tkinter.Label(frame, text='Path to MegaDetector output .json file')
|
|
320
|
+
l2.configure(background='white')
|
|
321
|
+
l2.grid(row=1, column=0)
|
|
322
|
+
|
|
323
|
+
file_path_var = tkinter.StringVar()
|
|
324
|
+
|
|
325
|
+
e2 = tkinter.Entry(frame, width=50, textvariable=file_path_var, highlightthickness=1)
|
|
326
|
+
e2.configure(highlightbackground='grey', highlightcolor='grey')
|
|
327
|
+
e2.grid(row=1, column=2)
|
|
328
|
+
|
|
329
|
+
b2 = tkinter.Button(frame, text='Browse', fg='blue', command=lambda: browse_file(options,file_path_var))
|
|
330
|
+
b2.grid(row=1, column=5, padx=10)
|
|
331
|
+
|
|
332
|
+
l6 = tkinter.Label(frame, text='Minimum confidence to consider a category')
|
|
333
|
+
l6.configure(background='white')
|
|
334
|
+
l6.grid(row=2, column=0)
|
|
335
|
+
|
|
336
|
+
textarea_min_threshold = tkinter.Entry(frame, width=50, highlightthickness=1)
|
|
337
|
+
textarea_min_threshold.configure(highlightbackground='grey', highlightcolor='grey')
|
|
338
|
+
textarea_min_threshold.grid(row=2, column=2)
|
|
339
|
+
|
|
340
|
+
l3 = tkinter.Label(frame, text='Prefix to remove from image paths (optional)')
|
|
341
|
+
l3.configure(background='white')
|
|
342
|
+
l3.grid(row=3, column=0)
|
|
343
|
+
|
|
344
|
+
textarea_remove_path = tkinter.Entry(frame, width=50, highlightthickness=1)
|
|
345
|
+
textarea_remove_path.configure(highlightbackground='grey', highlightcolor='grey')
|
|
346
|
+
textarea_remove_path.grid(row=3, column=2)
|
|
347
|
+
|
|
348
|
+
l4 = tkinter.Label(frame, text='Confidence level to move images requires manual check (optional)')
|
|
349
|
+
l4.configure(background='white')
|
|
350
|
+
l4.grid(row=4, column=0)
|
|
351
|
+
|
|
352
|
+
textarea_rename_conf = tkinter.Entry(frame, width=50, highlightthickness=1)
|
|
353
|
+
textarea_rename_conf.configure(highlightbackground='grey', highlightcolor='grey')
|
|
354
|
+
textarea_rename_conf.grid(row=4, column=2)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
l5 = tkinter.Label(frame, text='Categories to check for the confidence (optional)')
|
|
358
|
+
l5.configure(background='white')
|
|
359
|
+
l5.grid(row=5, column=0)
|
|
360
|
+
|
|
361
|
+
textarea_rename_cats = tkinter.Entry(frame, width=50, highlightthickness=1)
|
|
362
|
+
textarea_rename_cats.configure(highlightbackground='grey', highlightcolor='grey')
|
|
363
|
+
textarea_rename_cats.grid(row=5, column=2)
|
|
364
|
+
|
|
365
|
+
l6 = tkinter.Label(frame, text='Number of threads to run (optional)')
|
|
366
|
+
l6.configure(background='white')
|
|
367
|
+
l6.grid(row=6, column=0)
|
|
368
|
+
|
|
369
|
+
textarea_num_threads = tkinter.Entry(frame, width=50, highlightthickness=1)
|
|
370
|
+
textarea_num_threads.configure(highlightbackground='grey', highlightcolor='grey')
|
|
371
|
+
textarea_num_threads.grid(row=6, column=2)
|
|
372
|
+
|
|
373
|
+
sb = tkinter.Button(frame, text='Submit', fg='black',
|
|
374
|
+
command=lambda: start_input_processing(options), padx=10)
|
|
375
|
+
sb.grid(row=7, column=2, padx=10, pady=10)
|
|
376
|
+
|
|
377
|
+
style = tkinter.ttk.Style(root)
|
|
378
|
+
style.layout('text.Horizontal.Tprogress_bar',
|
|
379
|
+
[('Horizontal.progress_bar.trough',
|
|
380
|
+
{'children': [('Horizontal.progress_bar.pbar',
|
|
381
|
+
{'side': 'left', 'sticky': 'ns'})],
|
|
382
|
+
'sticky': 'nswe'}),
|
|
383
|
+
('Horizontal.progress_bar.label', {'sticky': ''})])
|
|
384
|
+
style.configure('text.Horizontal.Tprogress_bar', text='0 %')
|
|
385
|
+
|
|
386
|
+
progress_bar = tkinter.ttk.Progressbar(root, style='text.Horizontal.Tprogress_bar', length=700,
|
|
387
|
+
maximum=100, value=0, mode='determinate')
|
|
388
|
+
progress_bar.pack(pady=10)
|
|
389
|
+
|
|
390
|
+
group2 = tkinter.LabelFrame(root, text='Status', padx=5, pady=5)
|
|
391
|
+
group2.pack(padx=10, pady=10, fill='both', expand='yes')
|
|
392
|
+
|
|
393
|
+
textarea_status = tkinter.Text(group2, height=10, width=100)
|
|
394
|
+
textarea_status.configure(state="disabled")
|
|
395
|
+
textarea_status.pack()
|
|
396
|
+
|
|
397
|
+
options.xmp_gui = xmp_gui()
|
|
398
|
+
options.xmp_gui.root = root
|
|
399
|
+
options.xmp_gui.textarea_min_threshold = textarea_min_threshold
|
|
400
|
+
options.xmp_gui.textarea_remove_path = textarea_remove_path
|
|
401
|
+
options.xmp_gui.textarea_rename_conf = textarea_rename_conf
|
|
402
|
+
options.xmp_gui.textarea_rename_cats = textarea_rename_cats
|
|
403
|
+
options.xmp_gui.textarea_num_threads = textarea_num_threads
|
|
404
|
+
options.xmp_gui.textarea_status = textarea_status
|
|
405
|
+
options.xmp_gui.progress_bar = progress_bar
|
|
406
|
+
options.xmp_gui.style = style
|
|
407
|
+
|
|
408
|
+
root.mainloop()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
#%% Interactive/test driver
|
|
412
|
+
|
|
413
|
+
if False:
|
|
414
|
+
|
|
415
|
+
#%%
|
|
416
|
+
|
|
417
|
+
options = xmp_integration_options()
|
|
418
|
+
options.input_file = r"C:\temp\demo_images\ssmini_xmp_test_orig\ssmini.mdv4.json"
|
|
419
|
+
options.image_folder = r"C:\temp\demo_images\ssmini_xmp_test"
|
|
420
|
+
options.remove_path = 'my_images/'
|
|
421
|
+
process_input_data(options)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
#%% Command-line driver
|
|
425
|
+
|
|
426
|
+
def args_to_object(args,obj):
|
|
427
|
+
"""
|
|
428
|
+
Copy all fields from the argparse table "args" to the object "obj"
|
|
429
|
+
"""
|
|
430
|
+
for n, v in inspect.getmembers(args):
|
|
431
|
+
if not n.startswith('_'):
|
|
432
|
+
setattr(obj, n, v)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def main():
|
|
436
|
+
|
|
437
|
+
parser = argparse.ArgumentParser()
|
|
438
|
+
parser.add_argument('--input_file', help = 'Path to the MegaDetector .json file', default=None)
|
|
439
|
+
parser.add_argument('--image_folder', help = 'Path to the folder containing images', default=None)
|
|
440
|
+
parser.add_argument('--min_threshold', help = 'Minimum detection confidence that will be treated as a detection event', default=None)
|
|
441
|
+
parser.add_argument('--remove_path', help = 'Prefix to remove from image paths in the .json file', default=None)
|
|
442
|
+
parser.add_argument('--rename_conf', help = 'Below this confidence level, images will be renamed for manual check', default=None)
|
|
443
|
+
parser.add_argument('--rename_cat', help = 'Category (or comma-delimited categories) to apply renaming behavior to', default=None)
|
|
444
|
+
parser.add_argument('--num_threads', help = 'Number of threads to use for image processing', default=1)
|
|
445
|
+
parser.add_argument('--gui', help = 'Run in GUI mode', action='store_true')
|
|
446
|
+
|
|
447
|
+
options = xmp_integration_options()
|
|
448
|
+
args = parser.parse_args()
|
|
449
|
+
args_to_object(args,options)
|
|
450
|
+
|
|
451
|
+
if options.gui:
|
|
452
|
+
assert options.input_file is None, 'Command-line argument specified in GUI mode'
|
|
453
|
+
assert options.image_folder is None, 'Command-line argument specified in GUI mode'
|
|
454
|
+
assert options.min_threshold is None, 'Command-line argument specified in GUI mode'
|
|
455
|
+
assert options.remove_path is None, 'Command-line argument specified in GUI mode'
|
|
456
|
+
assert options.rename_conf is None, 'Command-line argument specified in GUI mode'
|
|
457
|
+
assert options.rename_cat is None, 'Command-line argument specified in GUI mode'
|
|
458
|
+
assert options.num_threads == 1, 'Command-line argument specified in GUI mode'
|
|
459
|
+
create_gui(options)
|
|
460
|
+
else:
|
|
461
|
+
process_input_data(options)
|
|
462
|
+
|
|
463
|
+
if __name__ == '__main__':
|
|
464
|
+
|
|
465
|
+
main()
|