-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmodels.py
More file actions
4190 lines (3455 loc) · 155 KB
/
models.py
File metadata and controls
4190 lines (3455 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import datetime
import functools
import logging
import textwrap
import time
import typing
import urllib.parse
from io import BytesIO
from typing import Final, final # noqa: F401
import PIL.Image
import pydantic
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.db import IntegrityError, models, transaction
from django.db.models import Exists, OuterRef, Q
from django.db.models.fields.files import ImageFieldFile
from django.db.models.functions import Coalesce
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.template.defaultfilters import filesizeformat
from django.utils import timezone
from django_pydantic_field import SchemaField
from guardian.shortcuts import get_perms
from rest_framework.request import Request
import ami.tasks
import ami.utils
from ami.base.fields import DateStringField
from ami.base.models import BaseModel, BaseQuerySet
from ami.main import charts
from ami.main.models_future.filters import (
build_occurrence_default_filters_q,
build_occurrence_score_threshold_q,
build_taxa_recursive_filter_q,
)
from ami.main.models_future.projects import ProjectSettingsMixin
from ami.ml.schemas import BoundingBox
from ami.users.models import User
from ami.utils.media import calculate_file_checksum, extract_timestamp
from ami.utils.requests import get_apply_default_filters_flag, get_default_classification_threshold
from ami.utils.schemas import OrderedEnum
if typing.TYPE_CHECKING:
from ami.jobs.models import Job
from ami.ml.models import Pipeline, ProcessingService
logger = logging.getLogger(__name__)
# Constants
_POST_TITLE_MAX_LENGTH: Final = 80
class TaxonRank(OrderedEnum):
KINGDOM = "KINGDOM"
PHYLUM = "PHYLUM"
CLASS = "CLASS"
ORDER = "ORDER"
SUPERFAMILY = "SUPERFAMILY"
FAMILY = "FAMILY"
SUBFAMILY = "SUBFAMILY"
TRIBE = "TRIBE"
SUBTRIBE = "SUBTRIBE"
GENUS = "GENUS"
SPECIES = "SPECIES"
UNKNOWN = "UNKNOWN"
DEFAULT_RANKS = sorted(
[
TaxonRank.KINGDOM,
TaxonRank.PHYLUM,
TaxonRank.CLASS,
TaxonRank.ORDER,
TaxonRank.FAMILY,
TaxonRank.SUBFAMILY,
TaxonRank.TRIBE,
TaxonRank.GENUS,
TaxonRank.SPECIES,
]
)
def get_media_url(path: str) -> str:
"""
If path is a full URL, return it as-is.
Otherwise, join it with the MEDIA_URL setting.
"""
# @TODO use settings
# urllib.parse.urljoin(settings.MEDIA_URL, self.path)
if path.startswith("http"):
url = path
else:
# @TODO add a file field to the Detection model and use that to get the URL
url = default_storage.url(path.lstrip("/"))
return url
as_choices = lambda x: [(i, i) for i in x] # noqa: E731
def get_or_create_default_device(project: "Project") -> "Device":
"""Create a default device for a project."""
device, _created = Device.objects.get_or_create(name="Default Device", project=project)
logger.info(f"Created default device for project {project}")
return device
def get_or_create_default_research_site(project: "Project") -> "Site":
"""Create a default research site for a project."""
site, _created = Site.objects.get_or_create(name="Default Site", project=project)
logger.info(f"Created default research site for project {project}")
return site
def get_or_create_default_deployment(
project: "Project", site: "Site | None" = None, device: "Device | None" = None
) -> "Deployment":
"""Create a default deployment for a project."""
deployment, _created = Deployment.objects.get_or_create(
name="Default Station",
project=project,
research_site=site,
device=device,
latitude=0,
longitude=0,
)
logger.info(f"Created default deployment for project {project}")
return deployment
def get_or_create_default_collection(project: "Project") -> "SourceImageCollection":
"""
Create a default collection for a project for all images.
@TODO Consider ways to update this collection automatically. With a query-only collection
or a periodic task that runs the populate_collection method.
"""
collection, _created = SourceImageCollection.objects.get_or_create(
name="All Images",
project=project,
method="full",
)
logger.info(f"Created default collection for project {project}")
return collection
def get_or_create_default_project(user: User) -> "Project":
"""
Create a default project for a user.
Default related objects like devices and research sites will be created
when the project is saved for the first time.
If the project already exists, it will be returned without modification.
"""
project, _created = Project.objects.get_or_create(name="Scratch Project", owner=user, create_defaults=True)
logger.info(f"Created default project for user {user}")
return project
class ProjectQuerySet(BaseQuerySet):
def filter_by_user(self, user: User):
"""
Filters projects to include only those where the given user is a member.
"""
return self.filter(members=user)
class ProjectManager(models.Manager.from_queryset(ProjectQuerySet)):
pass
def create(self, create_defaults: bool = True, **kwargs) -> "Project":
"""
Create a new Project and related models with defaults.
Args:
create_defaults: Whether to create default related models
**kwargs: Model field values
Returns:
Created Project instance
"""
with transaction.atomic():
project_instance = super().create(**kwargs)
logger.info(f"Created project: {project_instance.name}")
if create_defaults:
self.create_related_defaults(project_instance)
return project_instance
def create_related_defaults(self, project: "Project"):
"""Create default device, and other related models for this project if they don't exist."""
device = get_or_create_default_device(project=project)
site = get_or_create_default_research_site(project=project)
if not project.deployments.exists():
get_or_create_default_deployment(project=project, site=site, device=device)
if not project.sourceimage_collections.exists():
get_or_create_default_collection(project=project)
if not project.processing_services.exists():
from ami.ml.models.processing_service import get_or_create_default_processing_service
get_or_create_default_processing_service(project=project)
class ProjectFeatureFlags(pydantic.BaseModel):
"""
Feature flags for the project.
"""
tags: bool = False # Whether the project supports tagging taxa
reprocess_existing_detections: bool = False # Whether to reprocess existing detections
default_filters: bool = False # Whether to show default filters form in UI
# Feature flag for jobs to reprocess all images in the project, even if already processed
reprocess_all_images: bool = False
async_pipeline_workers: bool = False # Whether to use async pipeline workers that pull tasks from a queue
def get_default_feature_flags() -> ProjectFeatureFlags:
return ProjectFeatureFlags()
@final
class Project(ProjectSettingsMixin, BaseModel):
""" """
name = models.CharField(max_length=_POST_TITLE_MAX_LENGTH)
description = models.TextField(blank=True)
image = models.ImageField(upload_to="projects", blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="projects")
members = models.ManyToManyField(
User,
through="UserProjectMembership",
related_name="user_projects",
blank=True,
)
draft = models.BooleanField(
default=False,
help_text="Indicates whether this project is in draft mode",
)
feature_flags = SchemaField(
ProjectFeatureFlags,
default=get_default_feature_flags,
null=False,
blank=True,
)
active = models.BooleanField(default=True)
priority = models.IntegerField(default=1)
# Backreferences for type hinting
captures: models.QuerySet["SourceImage"]
deployments: models.QuerySet["Deployment"]
events: models.QuerySet["Event"]
occurrences: models.QuerySet["Occurrence"]
taxa: models.QuerySet["Taxon"]
taxa_lists: models.QuerySet["TaxaList"]
devices: models.QuerySet["Device"]
sites: models.QuerySet["Site"]
jobs: models.QuerySet["Job"]
sourceimage_collections: models.QuerySet["SourceImageCollection"]
processing_services: models.QuerySet["ProcessingService"]
pipelines: models.QuerySet["Pipeline"]
tags: models.QuerySet["Tag"]
objects = ProjectManager()
def ensure_owner_membership(self):
"""Add owner to members if they are not already a member"""
if self.owner and not self.members.filter(id=self.owner.pk).exists():
self.members.add(self.owner)
def deployments_count(self) -> int:
return self.deployments.count()
def taxa_count(self):
return self.taxa.all().count()
def summary_data(self):
"""
Data prepared for rendering charts with plotly.js on the overview page.
"""
return [
{
"id": "captures",
"title": "Captures",
"plots": [
charts.captures_per_hour(project_pk=self.pk),
charts.captures_per_month(project_pk=self.pk),
],
},
{
"id": "occurrences",
"title": "Occurrences",
"plots": [
charts.detections_per_hour(project_pk=self.pk),
charts.average_occurrences_per_month(project_pk=self.pk),
],
},
{
"id": "taxa",
"title": "Taxa",
"plots": [
charts.project_top_taxa(project_pk=self.pk),
charts.unique_species_per_month(project_pk=self.pk),
],
},
]
def update_related_calculated_fields(self):
"""
Update calculated fields for all related events and deployments.
"""
# Update events
for event in self.events.all():
event.update_calculated_fields(save=True)
# Update deployments
for deployment in self.deployments.all():
deployment.update_calculated_fields(save=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
# Add owner to members
self.ensure_owner_membership()
def check_custom_permission(self, user, action: str) -> bool:
"""
Check custom permissions for actions like 'charts'.
Charts is treated as a read-only operation, so it follows the same
permission logic as 'retrieve'.
"""
from ami.users.roles import BasicMember, ProjectManager
if action == "charts":
# Same permission logic as retrieve action
if self.draft:
# Allow view permission for members and owners of draft projects
return BasicMember.has_role(user, self) or user == self.owner or user.is_superuser
return True
if action == "pipelines":
# Pipeline registration requires project management permissions
return ProjectManager.has_role(user, self) or user == self.owner or user.is_superuser
# Fall back to default permission checking for other actions
return super().check_custom_permission(user, action)
class Permissions:
"""CRUD Permission names follow the convention: `create_<model>`, `update_<model>`,
`delete_<model>`, `view_<model>`"""
# Project permissions
VIEW_PROJECT = "view_project"
UPDATE_PROJECT = "update_project"
DELETE_PROJECT = "delete_project"
CREATE_PROJECT = "create_project"
# Identification permissions
CREATE_IDENTIFICATION = "create_identification"
UPDATE_IDENTIFICATION = "update_identification"
DELETE_IDENTIFICATION = "delete_identification"
# Job permissions
CREATE_JOB = "create_job"
UPDATE_JOB = "update_job"
RUN_ML_JOB = "run_ml_job"
RUN_SINGLE_IMAGE_JOB = "run_single_image_ml_job"
RUN_POPULATE_CAPTURES_COLLECTION_JOB = "run_populate_captures_collection_job"
RUN_DATA_STORAGE_SYNC_JOB = "run_data_storage_sync_job"
RUN_DATA_EXPORT_JOB = "run_data_export_job"
RUN_POST_PROCESSING_JOB = "run_post_processing_job"
DELETE_JOB = "delete_job"
# Deployment permissions
CREATE_DEPLOYMENT = "create_deployment"
DELETE_DEPLOYMENT = "delete_deployment"
UPDATE_DEPLOYMENT = "update_deployment"
SYNC_DEPLOYMENT = "sync_deployment"
# Collection permissions
CREATE_COLLECTION = "create_sourceimagecollection"
UPDATE_COLLECTION = "update_sourceimagecollection"
DELETE_COLLECTION = "delete_sourceimagecollection"
POPULATE_COLLECTION = "populate_sourceimagecollection"
# Source Image permissions
CREATE_SOURCE_IMAGE = "create_sourceimage"
UPDATE_SOURCE_IMAGE = "update_sourceimage"
DELETE_SOURCE_IMAGE = "delete_sourceimage"
STAR_SOURCE_IMAGE = "star_sourceimage"
# SourceImageUpload permissions
CREATE_SOURCE_IMAGE_UPLOAD = "create_sourceimageupload"
UPDATE_SOURCE_IMAGE_UPLOAD = "update_sourceimageupload"
DELETE_SOURCE_IMAGE_UPLOAD = "delete_sourceimageupload"
# Storage permissions
CREATE_STORAGE = "create_s3storagesource"
DELETE_STORAGE = "delete_s3storagesource"
UPDATE_STORAGE = "update_s3storagesource"
TEST_STORAGE = "test_s3storagesource"
# Site permissions
CREATE_SITE = "create_site"
DELETE_SITE = "delete_site"
UPDATE_SITE = "update_site"
# Device permissions
CREATE_DEVICE = "create_device"
DELETE_DEVICE = "delete_device"
UPDATE_DEVICE = "update_device"
# User project membership permissions
VIEW_USER_PROJECT_MEMBERSHIP = "view_userprojectmembership"
CREATE_USER_PROJECT_MEMBERSHIP = "create_userprojectmembership"
UPDATE_USER_PROJECT_MEMBERSHIP = "update_userprojectmembership"
DELETE_USER_PROJECT_MEMBERSHIP = "delete_userprojectmembership"
# Data Export permissions
CREATE_DATA_EXPORT = "create_dataexport"
UPDATE_DATA_EXPORT = "update_dataexport"
DELETE_DATA_EXPORT = "delete_dataexport"
# Pipeline configuration permissions
CREATE_PROJECT_PIPELINE_CONFIG = "create_projectpipelineconfig"
UPDATE_PROJECT_PIPELINE_CONFIG = "update_projectpipelineconfig"
DELETE_PROJECT_PIPELINE_CONFIG = "delete_projectpipelineconfig"
# Other permissions
VIEW_PRIVATE_DATA = "view_private_data"
DELETE_OCCURRENCES = "delete_occurrences"
IMPORT_DATA = "import_data"
class Meta:
ordering = ["-priority", "created_at"]
permissions = [
# Identification permissions
("create_identification", "Can create identifications"),
("update_identification", "Can update identifications"),
("delete_identification", "Can delete identifications"),
# Job permissions
("create_job", "Can create a job"),
("update_job", "Can update a job"),
("run_ml_job", "Can run/retry/cancel ML jobs"),
("run_populate_captures_collection_job", "Can run/retry/cancel Populate Collection jobs"),
("run_data_storage_sync_job", "Can run/retry/cancel Data Storage Sync jobs"),
("run_data_export_job", "Can run/retry/cancel Data Export jobs"),
("run_single_image_ml_job", "Can process a single capture"),
("run_post_processing_job", "Can run/retry/cancel Post-Processing jobs"),
("delete_job", "Can delete a job"),
# Deployment permissions
("create_deployment", "Can create a deployment"),
("delete_deployment", "Can delete a deployment"),
("update_deployment", "Can update a deployment"),
("sync_deployment", "Can sync images to a deployment"),
# Collection permissions
("create_sourceimagecollection", "Can create a collection"),
("update_sourceimagecollection", "Can update a collection"),
("delete_sourceimagecollection", "Can delete a collection"),
("populate_sourceimagecollection", "Can populate a collection"),
# Source Image permissions
("create_sourceimage", "Can create a source image"),
("update_sourceimage", "Can update a source image"),
("delete_sourceimage", "Can delete a source image"),
("star_sourceimage", "Can star a source image"),
# SourceImageUpload permissions
("create_sourceimageupload", "Can create a source image upload"),
("update_sourceimageupload", "Can update a source image upload"),
("delete_sourceimageupload", "Can delete a source image upload"),
# Storage permissions
("create_s3storagesource", "Can create storage"),
("delete_s3storagesource", "Can delete storage"),
("update_s3storagesource", "Can update storage"),
("test_s3storagesource", "Can test storage connection"),
# Site permissions
("create_site", "Can create a site"),
("delete_site", "Can delete a site"),
("update_site", "Can update a site"),
# Device permissions
("create_device", "Can create a device"),
("delete_device", "Can delete a device"),
("update_device", "Can update a device"),
# User project membership permissions
("view_userprojectmembership", "Can view project members"),
("create_userprojectmembership", "Can add a user to the project"),
("update_userprojectmembership", "Can update a user's project membership and role in the project"),
("delete_userprojectmembership", "Can remove a user from the project"),
# Data Export permissions
("create_dataexport", "Can create a data export"),
("update_dataexport", "Can update a data export"),
("delete_dataexport", "Can delete a data export"),
# Pipeline configuration permissions
("create_projectpipelineconfig", "Can register pipelines for the project"),
("update_projectpipelineconfig", "Can update pipeline configurations"),
("delete_projectpipelineconfig", "Can remove pipelines from the project"),
# Other permissions
("view_private_data", "Can view private data"),
]
class UserProjectMembership(BaseModel):
"""
Through model connecting User <-> Project.
This model represents membership ONLY.
Role assignment is handled separately via permission groups.
"""
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="project_memberships",
)
project = models.ForeignKey(
"main.Project",
on_delete=models.CASCADE,
related_name="project_memberships",
)
def check_permission(self, user: AbstractUser | AnonymousUser, action: str) -> bool:
project = self.project
# Allow viewing membership details if the user has view permission on the project
if action == "retrieve":
return user.has_perm(Project.Permissions.VIEW_USER_PROJECT_MEMBERSHIP, project)
# Allow users to delete their own membership
if action == "destroy" and user == self.user:
return True
return super().check_permission(user, action)
def get_user_object_permissions(self, user) -> list[str]:
# Return delete permission if user is the same as the membership user
user_permissions = super().get_user_object_permissions(user)
if user == self.user:
if "delete" not in user_permissions:
user_permissions.append("delete")
return user_permissions
class Meta:
unique_together = ("user", "project")
@final
class Device(BaseModel):
"""
Configuration of hardware used to capture images.
If project is null then this is a public device that can be used by any project.
"""
name = models.CharField(max_length=_POST_TITLE_MAX_LENGTH)
description = models.TextField(blank=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, related_name="devices")
deployments: models.QuerySet["Deployment"]
class Meta:
verbose_name = "Device Configuration"
@final
class Site(BaseModel):
"""Research site with multiple deployments"""
name = models.CharField(max_length=_POST_TITLE_MAX_LENGTH)
description = models.TextField(blank=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, related_name="sites")
deployments: models.QuerySet["Deployment"]
def deployments_count(self) -> int:
return self.deployments.count()
# def boundary(self) -> Optional[models.GeometryField]:
# @TODO if/when we use GeoDjango
# return None
def boundary_rect(self) -> tuple[float, float, float, float] | None:
# Get the minumin and maximum latitude and longitude values of all deployments
# at this research site.
min_lat, max_lat, min_lon, max_lon = self.deployments.aggregate(
min_lat=models.Min("latitude"),
max_lat=models.Max("latitude"),
min_lon=models.Min("longitude"),
max_lon=models.Max("longitude"),
).values()
bounds = (min_lat, min_lon, max_lat, max_lon)
if None in bounds:
return None
else:
return bounds
class Meta:
verbose_name = "Research Site"
@final
class DeploymentManager(models.Manager.from_queryset(ProjectQuerySet)):
"""
Custom manager that adds counts of related objects to the default queryset.
"""
pass
def _create_source_image_for_sync(
deployment: "Deployment",
obj: ami.utils.s3.ObjectTypeDef,
) -> typing.Union["SourceImage", None]:
assert "Key" in obj, f"File in object store response has no Key: {obj}"
source_image = SourceImage(
deployment=deployment,
path=obj["Key"],
last_modified=obj.get("LastModified"),
size=obj.get("Size"),
checksum=obj.get("ETag", "").strip('"'),
checksum_algorithm=obj.get("ChecksumAlgorithm"),
)
logger.debug(f"Preparing to create or update SourceImage {source_image.path}")
source_image.update_calculated_fields()
return source_image
def _insert_or_update_batch_for_sync(
deployment: "Deployment",
source_images: list["SourceImage"],
total_files: int,
total_size: int,
sql_batch_size=500,
regroup_events_per_batch=False,
):
logger.info(f"Bulk inserting or updating batch of {len(source_images)} SourceImages")
try:
SourceImage.objects.bulk_create(
source_images,
batch_size=sql_batch_size,
update_conflicts=True,
unique_fields=["deployment", "path"], # type: ignore
update_fields=["last_modified", "size", "checksum", "checksum_algorithm"],
)
except IntegrityError as e:
logger.error(f"Error bulk inserting batch of SourceImages: {e}")
if total_files > (deployment.data_source_total_files or 0):
deployment.data_source_total_files = total_files
if total_size > (deployment.data_source_total_size or 0):
deployment.data_source_total_size = total_size
deployment.data_source_last_checked = datetime.datetime.now()
if regroup_events_per_batch:
group_images_into_events(deployment)
deployment.save(update_calculated_fields=False)
def _compare_totals_for_sync(deployment: "Deployment", total_files_found: int):
# @TODO compare total_files to the number of SourceImages for this deployment
existing_file_count = SourceImage.objects.filter(deployment=deployment).count()
delta = abs(existing_file_count - total_files_found)
if delta > 0:
logger.warning(
f"Deployment '{deployment}' has {existing_file_count} SourceImages "
f"but the data source has {total_files_found} files "
f"(+- {delta})"
)
@final
class Deployment(BaseModel):
"""
Class that describes a deployment of a device (camera & hardware) at a research site.
"""
name = models.CharField(max_length=_POST_TITLE_MAX_LENGTH)
description = models.TextField(blank=True)
latitude = models.FloatField(null=True, blank=True)
longitude = models.FloatField(null=True, blank=True)
image = models.ImageField(upload_to="deployments", blank=True, null=True)
project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, related_name="deployments")
# @TODO consider sharing only the "data source auth/config" then a one-to-one config for each deployment
# Or a pydantic model with nested attributes about each data source relationship
data_source = models.ForeignKey(
"S3StorageSource", on_delete=models.SET_NULL, null=True, blank=True, related_name="deployments"
)
# Pre-calculated values from the data source
data_source_total_files = models.IntegerField(blank=True, null=True)
data_source_total_size = models.BigIntegerField(blank=True, null=True)
data_source_subdir = models.CharField(max_length=255, blank=True, null=True)
data_source_regex = models.CharField(max_length=255, blank=True, null=True)
data_source_last_checked = models.DateTimeField(blank=True, null=True)
# data_source_start_date = models.DateTimeField(blank=True, null=True)
# data_source_end_date = models.DateTimeField(blank=True, null=True)
# data_source_last_check_duration = models.DurationField(blank=True, null=True)
# data_source_last_check_status = models.CharField(max_length=255, blank=True, null=True)
# data_source_last_check_notes = models.TextField(max_length=255, blank=True, null=True)
# Pre-calculated values
events_count = models.IntegerField(blank=True, null=True)
occurrences_count = models.IntegerField(blank=True, null=True)
captures_count = models.IntegerField(blank=True, null=True)
detections_count = models.IntegerField(blank=True, null=True)
taxa_count = models.IntegerField(blank=True, null=True)
first_capture_timestamp = models.DateTimeField(blank=True, null=True)
last_capture_timestamp = models.DateTimeField(blank=True, null=True)
research_site = models.ForeignKey(
Site,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="deployments",
)
device = models.ForeignKey(
Device,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="deployments",
)
events: models.QuerySet["Event"]
captures: models.QuerySet["SourceImage"]
occurrences: models.QuerySet["Occurrence"]
jobs: models.QuerySet["Job"]
objects = DeploymentManager()
class Meta:
ordering = ["name"]
def taxa(self) -> models.QuerySet["Taxon"]:
return Taxon.objects.filter(Q(occurrences__deployment=self)).distinct()
def first_capture(self) -> typing.Optional["SourceImage"]:
return SourceImage.objects.filter(deployment=self).order_by("timestamp").first()
def last_capture(self) -> typing.Optional["SourceImage"]:
return SourceImage.objects.filter(deployment=self).order_by("timestamp").last()
def get_first_and_last_timestamps(self) -> tuple[datetime.datetime, datetime.datetime]:
# Retrieve the timestamps of the first and last capture in a single query
first, last = (
SourceImage.objects.filter(deployment=self)
.aggregate(first=models.Min("timestamp"), last=models.Max("timestamp"))
.values()
)
return (first, last)
def first_date(self) -> datetime.date | None:
return self.first_capture_timestamp.date() if self.first_capture_timestamp else None
def last_date(self) -> datetime.date | None:
return self.last_capture_timestamp.date() if self.last_capture_timestamp else None
def data_source_uri(self) -> str | None:
if self.data_source:
uri = self.data_source.uri().rstrip("/")
if self.data_source_subdir:
uri = f"{uri}/{self.data_source_subdir.strip('/')}/"
if self.data_source_regex:
uri = f"{uri}?regex={self.data_source_regex}"
else:
uri = None
return uri
def data_source_total_size_display(self) -> str:
if self.data_source_total_size is None:
return filesizeformat(0)
else:
return filesizeformat(self.data_source_total_size)
def sync_captures(self, batch_size=1000, regroup_events_per_batch=False, job: "Job | None" = None) -> int:
"""Import images from the deployment's data source"""
deployment = self
assert deployment.data_source, f"Deployment {deployment.name} has no data source configured"
s3_config = deployment.data_source.config
total_size = 0
total_files = 0
source_images = []
django_batch_size = batch_size
sql_batch_size = 1000
if job:
job.logger.info(f"Syncing captures for deployment {deployment}")
job.update_progress()
job.save()
for obj, file_index in ami.utils.s3.list_files_paginated(
s3_config,
subdir=self.data_source_subdir,
regex_filter=self.data_source_regex,
):
logger.debug(f"Processing file {file_index}: {obj}")
if not obj:
continue
source_image = _create_source_image_for_sync(deployment, obj)
if source_image:
total_files += 1
total_size += obj.get("Size", 0)
source_images.append(source_image)
if len(source_images) >= django_batch_size:
_insert_or_update_batch_for_sync(
deployment, source_images, total_files, total_size, sql_batch_size, regroup_events_per_batch
)
source_images = []
if job:
job.logger.info(f"Processed {total_files} files")
job.progress.update_stage(job.job_type().key, total_files=total_files)
job.update_progress()
if source_images:
# Insert/update the last batch
_insert_or_update_batch_for_sync(
deployment, source_images, total_files, total_size, sql_batch_size, regroup_events_per_batch
)
if job:
job.logger.info(f"Processed {total_files} files")
job.progress.update_stage(job.job_type().key, total_files=total_files)
job.update_progress()
_compare_totals_for_sync(deployment, total_files)
# @TODO decide if we should delete SourceImages that are no longer in the data source
if job:
job.logger.info("Saving and recalculating sessions for deployment")
job.progress.update_stage(job.job_type().key, progress=1)
job.progress.add_stage("Update deployment cache")
job.update_progress()
# If new images were added, ensure the regroup happens now, not queued as an async task.
self.save(regroup_async=False)
if job:
job.progress.update_stage("Update deployment cache", progress=1)
job.update_progress()
return total_files
def audit_subdir_of_captures(self, ignore_deepest=False) -> dict[str, int]:
"""
Review the subdirs of all captures that belong to this deployment in an efficient query.
Group all captures by their subdir and count the number of captures in each group.
`ignore_deepest` will exclude the deepest subdir from the audit (usually the date folder)
"""
class SubdirExtractAll(models.Func):
function = "REGEXP_REPLACE"
template = "%(function)s(%(expressions)s, '/[^/]*$', '')"
class SubdirExtractParent(models.Func):
# Attempts failed to dynamically set the depth of the last directories to ignore.
# so this is a hardcoded version that ignores the last one directory.
# this is useful for ignoring the date folder in the path.
function = "REGEXP_REPLACE"
template = "%(function)s(%(expressions)s, '/[^/]*/[^/]*$', '')"
extract_func = SubdirExtractParent if ignore_deepest else SubdirExtractAll
subdirs_audit = (
self.captures.annotate(
subdir=models.Case(
models.When(path__contains="/", then=extract_func(models.F("path"))),
default=models.Value(""),
output_field=models.CharField(),
)
)
.values("subdir")
.annotate(count=models.Count("id"))
.exclude(subdir="")
.order_by("-count")
)
# Convert QuerySet to dictionary
return {item["subdir"]: item["count"] for item in subdirs_audit}
def update_subdir_of_captures(self, previous_subdir: str, new_subdir: str):
"""
Update the relative directory in the path of all captures that belong to this deployment in a single query.
This is useful when moving images to a new location in the data source. It is not run
automatically when the deployment's data source configuration is updated. But admins can
run it manually from the Django shell or a maintenance script.
Reminder: the public_base_url includes the path that precedes the subdir within the full file path.
Warning: this is essentially a find & replace operation on the path field of SourceImage objects.
"""
# Sanitize the subdir strings. Ensure that they end with a slash. This is are only protection against
# accidentally modifying the filename.
# Relative paths are stored without a leading slash.
previous_subdir = previous_subdir.strip("/") + "/"
new_subdir = new_subdir.strip("/") + "/"
# Update the path of all captures that belong to this deployment
captures = SourceImage.objects.filter(deployment=self, path__startswith=previous_subdir)
logger.info(f"Updating subdir of {captures.count()} captures from '{previous_subdir}' to '{new_subdir}'")
previous_count = captures.count()
captures.update(
path=models.functions.Replace(
models.F("path"),
models.Value(previous_subdir),
models.Value(new_subdir),
)
)
# Re-query the captures to ensure the path has been updated
unchanged_count = SourceImage.objects.filter(deployment=self, path__startswith=previous_subdir).count()
changed_count = SourceImage.objects.filter(deployment=self, path__startswith=new_subdir).count()
if unchanged_count:
raise ValueError(f"{unchanged_count} captures were not updated to new subdir: {new_subdir}")
if changed_count != previous_count:
raise ValueError(f"Only {changed_count} captures were updated to new subdir: {new_subdir}")
def update_children(self):
"""
Update all attribute on all child objects that should be equal to their deployment values.
e.g. Events, Occurrences, SourceImages must belong to same project as their deployment. But
they have their own copy of that attribute to reduce the number of joins required to query them.
"""
# All the child models that have a foreign key to project
child_models = [
"Event",
"Occurrence",
"SourceImage",
]
for model_name in child_models:
model = apps.get_model("main", model_name)
qs = model.objects.filter(deployment=self).exclude(project=self.project)
project_values = set(qs.values_list("project", flat=True).distinct())
if len(project_values):
logger.warning(
f"Deployment {self} has alternate projects set on {model_name} "
f"objects: {project_values}. Updating them!"
)
qs.update(project=self.project)
def update_calculated_fields(self, save=False):
"""Update calculated fields on the deployment."""
self.data_source_total_files = self.captures.count()
self.data_source_total_size = self.captures.aggregate(total_size=models.Sum("size")).get("total_size")
self.events_count = self.events.count()
self.captures_count = self.data_source_total_files or self.captures.count()
self.detections_count = Detection.objects.filter(Q(source_image__deployment=self)).count()
occ_qs = self.occurrences.filter(event__isnull=False).apply_default_filters( # type: ignore
project=self.project,
request=None,
) # type: ignore
self.occurrences_count = occ_qs.distinct().count()
self.taxa_count = occ_qs.values("determination_id").distinct().count()
self.first_capture_timestamp, self.last_capture_timestamp = self.get_first_and_last_timestamps()
if save:
self.save(update_calculated_fields=False)
def save(self, update_calculated_fields=True, regroup_async=True, *args, **kwargs):
super().save(*args, **kwargs)
if self.pk and update_calculated_fields:
if deployment_events_need_update(self):
logger.info(f"Deployment {self} has events that need to be regrouped")
if regroup_async:
ami.tasks.regroup_events.delay(self.pk)
else:
group_images_into_events(self)
self.update_calculated_fields(save=True)
if self.project:
self.update_children()
# @TODO this isn't working as a background task
# ami.tasks.model_task.delay("Project", self.project.pk, "update_children_project")
class EventQuerySet(BaseQuerySet):
def with_taxa_count(self, project: Project | None = None, request: Request | None = None):
"""
Annotate each event with the number of distinct taxa observed,
filtered by default filters (score threshold and taxa inclusion/exclusion).
"""