-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodels.py
2955 lines (2405 loc) · 106 KB
/
models.py
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 hashlib
import logging
import textwrap
import time
import typing
import urllib.parse
from typing import Final, final # noqa: F401
import pydantic
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.db import IntegrityError, models
from django.db.models import Q
from django.db.models.fields.files import ImageFieldFile
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
import ami.tasks
import ami.utils
from ami.base.models import BaseModel
from ami.main import charts
from ami.users.models import User
from ami.utils.schemas import OrderedEnum
if typing.TYPE_CHECKING:
from ami.jobs.models import Job
logger = logging.getLogger(__name__)
# Constants
_POST_TITLE_MAX_LENGTH: Final = 80
class TaxonRank(OrderedEnum):
ORDER = "ORDER"
SUPERFAMILY = "SUPERFAMILY"
FAMILY = "FAMILY"
SUBFAMILY = "SUBFAMILY"
TRIBE = "TRIBE"
SUBTRIBE = "SUBTRIBE"
GENUS = "GENUS"
SPECIES = "SPECIES"
UNKNOWN = "UNKNOWN"
DEFAULT_RANKS = sorted(
[
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 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 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
@final
class Project(BaseModel):
""" """
name = models.CharField(max_length=_POST_TITLE_MAX_LENGTH)
description = models.TextField()
image = models.ImageField(upload_to="projects", blank=True, null=True)
# Backreferences for type hinting
deployments: models.QuerySet["Deployment"]
events: models.QuerySet["Event"]
occurrences: models.QuerySet["Occurrence"]
taxa: models.QuerySet["Taxon"]
taxa_lists: models.QuerySet["TaxaList"]
active = models.BooleanField(default=True)
priority = models.IntegerField(default=1)
devices: models.QuerySet["Device"]
sites: models.QuerySet["Site"]
jobs: models.QuerySet["Job"]
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.
"""
plots = []
plots.append(charts.captures_per_hour(project_pk=self.pk))
if self.occurrences.exists():
plots.append(charts.detections_per_hour(project_pk=self.pk))
plots.append(charts.occurrences_accumulated(project_pk=self.pk))
else:
plots.append(charts.events_per_month(project_pk=self.pk))
# plots.append(charts.captures_per_month(project_pk=self.pk))
return plots
def create_related_defaults(self):
"""Create default device, and other related models for this project if they don't exist."""
if not self.devices.exists():
create_default_device(project=self)
if not self.sites.exists():
create_default_research_site(project=self)
def save(self, *args, **kwargs):
new_project = bool(self._state.adding)
super().save(*args, **kwargs)
if new_project:
logger.info(f"Created new project {self}")
self.create_related_defaults()
class Meta:
ordering = ["-priority", "created_at"]
@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):
"""
Custom manager that adds counts of related objects to the default queryset.
"""
def get_queryset(self):
return (
super().get_queryset()
# Add any common annotations or optimizations here
)
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()
self.save()
self.update_calculated_fields(save=True)
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()
self.occurrences_count = (
self.occurrences.filter(
event__isnull=False,
)
.distinct()
.count()
)
self.taxa_count = (
Taxon.objects.filter(
occurrences__deployment=self,
occurrences__event__isnull=False,
)
.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, *args, **kwargs):
if self.pk:
events_last_updated = min(
[
self.events.aggregate(latest_updated_at=models.Max("updated_at")).get("latest_update_at")
or datetime.datetime.max,
self.updated_at,
]
)
else:
events_last_updated = datetime.datetime.min
super().save(*args, **kwargs)
if self.pk and update_calculated_fields:
# @TODO Use "dirty" flag strategy to only update when needed
new_or_updated_captures = self.captures.filter(updated_at__gte=events_last_updated).count()
deleted_captures = True if self.captures.count() < (self.captures_count or 0) else False
if new_or_updated_captures or deleted_captures:
ami.tasks.regroup_events.delay(self.pk)
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")
@final
class Event(BaseModel):
"""A monitoring session"""
group_by = models.CharField(
max_length=255,
db_index=True,
help_text=(
"A unique identifier for this event, used to group images into events. "
"This allows images to be prepended or appended to an existing event. "
"The default value is the day the event started, in the format YYYY-MM-DD. "
"However images could also be grouped by camera settings, image dimensions, hour of day, "
"or a random sample."
),
)
start = models.DateTimeField(db_index=True, help_text="The timestamp of the first image in the event.")
end = models.DateTimeField(null=True, blank=True, help_text="The timestamp of the last image in the event.")
project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, related_name="events")
deployment = models.ForeignKey(Deployment, on_delete=models.SET_NULL, null=True, related_name="events")
captures: models.QuerySet["SourceImage"]
occurrences: models.QuerySet["Occurrence"]
# Pre-calculated values
captures_count = models.IntegerField(blank=True, null=True)
detections_count = models.IntegerField(blank=True, null=True)
occurrences_count = models.IntegerField(blank=True, null=True)
calculated_fields_updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
ordering = ["start"]
indexes = [
models.Index(fields=["group_by"]),
models.Index(fields=["start"]),
]
constraints = [
models.UniqueConstraint(fields=["deployment", "group_by"], name="unique_event"),
]
def __str__(self) -> str:
return f"{self.start.strftime('%A')}, {self.date_label()}"
def name(self) -> str:
return str(self)
def day(self) -> datetime.date:
"""
Consider the start of the event to be the day it occurred on.
Most overnight monitoring sessions will start in the evening and end the next morning.
"""
return self.start.date()
def date_label(self) -> str:
"""
Format the date range for display.
If the start and end dates are different, display them as:
Jan 1-5, 2021
"""
if self.end and self.end.date() != self.start.date():
return f"{self.start.strftime('%b %-d')}-{self.end.strftime('%-d %Y')}"
else:
return f"{self.start.strftime('%b %-d %Y')}"
def duration(self):
"""Return the duration of the event.
If the event is still in progress, use the current time as the end time.
"""
now = datetime.datetime.now(tz=self.start.tzinfo)
if not self.end:
return now - self.start
return self.end - self.start
def duration_label(self) -> str:
"""
Format the duration for display.
If duration was populated by a query annotation, use that
otherwise call the duration() method to calculate it.
"""
duration = self.duration() if callable(self.duration) else self.duration
return ami.utils.dates.format_timedelta(duration)
def get_captures_count(self) -> int:
return self.captures.distinct().count()
def get_detections_count(self) -> int | None:
return Detection.objects.filter(Q(source_image__event=self)).count()
def get_occurrences_count(self, classification_threshold: float = 0) -> int:
return self.occurrences.distinct().filter(determination_score__gte=classification_threshold).count()
def stats(self) -> dict[str, int | None]:
return (
SourceImage.objects.filter(event=self)
.annotate(count=models.Count("detections"))
.aggregate(
detections_max_count=models.Max("count"),
detections_min_count=models.Min("count"),
# detections_avg_count=models.Avg("count"),
)
)
def taxa_count(self, classification_threshold: float = 0) -> int:
# Move this to a pre-calculated field or prefetch_related in the view
# return self.taxa(classification_threshold).count()
return 0
def taxa(self, classification_threshold: float = 0) -> models.QuerySet["Taxon"]:
return Taxon.objects.filter(
Q(occurrences__event=self),
occurrences__determination_score__gte=classification_threshold,
).distinct()
def first_capture(self):
return SourceImage.objects.filter(event=self).order_by("timestamp").first()
def summary_data(self):
"""
Data prepared for rendering charts with plotly.js
"""
plots = []
plots.append(charts.event_detections_per_hour(event_pk=self.pk))
plots.append(charts.event_top_taxa(event_pk=self.pk))
return plots
def update_calculated_fields(self, save=False, updated_timestamp: datetime.datetime | None = None):
"""
Important: if you update a new field, add it to the bulk_update call in update_calculated_fields_for_events
"""
event = self
if not event.group_by and event.start:
# If no group_by is set, use the start "day"
event.group_by = str(event.start.date())
if not event.project and event.deployment:
event.project = event.deployment.project
if event.pk is not None:
# Can only update start and end times if this is an update to an existing event
first = event.captures.order_by("timestamp").values("timestamp").first()
last = event.captures.order_by("-timestamp").values("timestamp").first()
if first:
event.start = first["timestamp"]
if last:
event.end = last["timestamp"]
event.captures_count = event.get_captures_count()
event.detections_count = event.get_detections_count()
event.occurrences_count = event.get_occurrences_count()
event.calculated_fields_updated_at = updated_timestamp or timezone.now()
if save:
event.save(update_calculated_fields=False)
def save(self, update_calculated_fields=True, *args, **kwargs):
super().save(*args, **kwargs)
if update_calculated_fields:
self.update_calculated_fields(save=True)
def update_calculated_fields_for_events(
qs: models.QuerySet[Event] | None = None,
pks: list[typing.Any] | None = None,
last_updated: datetime.datetime | None = None,
save=True,
):
"""
This function is called by a migration to update the calculated fields for all events.
@TODO this can likely be abstracted to a more generic function that can be used for any model
"""
to_update = []
qs = qs or Event.objects.all()
if pks:
qs = qs.filter(pk__in=pks)
if last_updated:
# query for None or before the last updated time
qs = qs.filter(
Q(calculated_fields_updated_at__isnull=True) | Q(calculated_fields_updated_at__lte=last_updated)
)
logging.info(f"Updating pre-calculated fields for {len(to_update)} events")
updated_timestamp = timezone.now()
for event in qs:
event.update_calculated_fields(save=False, updated_timestamp=updated_timestamp)
to_update.append(event)
if save:
updated_count = Event.objects.bulk_update(
to_update,
[
"group_by",
"start",
"end",
"project",
"captures_count",
"detections_count",
"occurrences_count",
"calculated_fields_updated_at",
],
)
if updated_count != len(to_update):
logging.error(f"Failed to update {len(to_update) - updated_count} events")
return to_update
def group_images_into_events(
deployment: Deployment, max_time_gap=datetime.timedelta(minutes=120), delete_empty=True
) -> list[Event]:
# Log a warning if multiple SourceImages have the same timestamp
dupes = (
SourceImage.objects.filter(deployment=deployment)
.values("timestamp")
.annotate(count=models.Count("id"))
.filter(count__gt=1)
.exclude(timestamp=None)
)
if dupes.count():
values = "\n".join(
[f'{d.strftime("%Y-%m-%d %H:%M:%S")} x{c}' for d, c in dupes.values_list("timestamp", "count")]
)
logger.warning(
f"Found {len(values)} images with the same timestamp in deployment '{deployment}'. "
f"Only one image will be used for each timestamp for each event."
)
image_timestamps = list(
SourceImage.objects.filter(deployment=deployment)
.exclude(timestamp=None)
.values_list("timestamp", flat=True)
.order_by("timestamp")
.distinct()
)
timestamp_groups = ami.utils.dates.group_datetimes_by_gap(image_timestamps, max_time_gap)
# @TODO this event grouping needs testing. Still getting events over 24 hours
# timestamp_groups = ami.utils.dates.group_datetimes_by_shifted_day(image_timestamps)
events = []
for group in timestamp_groups:
if not len(group):
continue
start_date = group[0]
end_date = group[-1]
# Print debugging info about groups
delta = end_date - start_date
hours = round(delta.seconds / 60 / 60, 1)
logger.debug(
f"Found session starting at {start_date} with {len(group)} images that ran for {hours} hours.\n"
f"From {start_date.strftime('%c')} to {end_date.strftime('%c')}."
)
# Creating events & assigning images
group_by = start_date.date()
event, _ = Event.objects.get_or_create(
deployment=deployment,
group_by=group_by,
defaults={"start": start_date, "end": end_date},
)
events.append(event)
SourceImage.objects.filter(deployment=deployment, timestamp__in=group).update(event=event)
event.save() # Update start and end times and other cached fields
logger.info(
f"Created/updated event {event} with {len(group)} images for deployment {deployment}. "
f"Duration: {event.duration_label()}"
)
logger.info(
f"Done grouping {len(image_timestamps)} captures into {len(events)} events " f"for deployment {deployment}"
)
if delete_empty:
logger.info("Deleting empty events for deployment")
delete_empty_events(deployment=deployment)
for event in events:
# Set the width and height of all images in each event based on the first image
logger.info(f"Setting image dimensions for event {event}")
set_dimensions_for_collection(event)
logger.info("Checking for unusual statistics of events")
events_over_24_hours = Event.objects.filter(
deployment=deployment, start__lt=models.F("end") - datetime.timedelta(days=1)
)
if events_over_24_hours.count():
logger.warning(f"Found {events_over_24_hours.count()} events over 24 hours in deployment {deployment}. ")
events_starting_before_noon = Event.objects.filter(
deployment=deployment, start__lt=models.F("start") + datetime.timedelta(hours=12)
)
if events_starting_before_noon.count():
logger.warning(
f"Found {events_starting_before_noon.count()} events starting before noon in deployment {deployment}. "
)
logger.info("Updating relevant cached fields on deployment")
deployment.events_count = len(events)
deployment.save(update_calculated_fields=False, update_fields=["events_count"])
return events
def delete_empty_events(deployment: Deployment, dry_run=False):
"""
Delete events that have no images, occurrences or other related records.
"""
# @TODO Search all models that have a foreign key to Event
# related_models = [
# f.related_model
# for f in Event._meta.get_fields()
# if f.one_to_many or f.one_to_one or (f.many_to_many and f.auto_created)
# ]
events = (
Event.objects.filter(deployment=deployment)
.annotate(
num_images=models.Count("captures"),
num_occurrences=models.Count("occurrences"),
)
.filter(num_images=0, num_occurrences=0)
)
if dry_run:
for event in events:
logger.debug(f"Would delete event {event} (dry run)")
else:
logger.info(f"Deleting {events.count()} empty events")
events.delete()
def sample_events(deployment: Deployment, day_interval: int = 3) -> typing.Generator[Event, None, None]:
"""
Return a sample of events from the deployment, evenly spaced apart by day_interval.
"""
last_event = None
for event in Event.objects.filter(deployment=deployment).order_by("start"):
if not last_event:
yield event
last_event = event
else:
delta = event.start - last_event.start
if delta.days >= day_interval:
yield event
last_event = event
@final
class S3StorageSource(BaseModel):
"""
Per-deployment configuration for an S3 bucket.
"""
name = models.CharField(max_length=255)
bucket = models.CharField(max_length=255)
prefix = models.CharField(max_length=255, blank=True)
access_key = models.TextField()
secret_key = models.TextField()
endpoint_url = models.CharField(max_length=255, blank=True, null=True)