|
| 1 | +import csv |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import tempfile |
| 5 | + |
| 6 | +from django.core.serializers.json import DjangoJSONEncoder |
| 7 | +from rest_framework import serializers |
| 8 | + |
| 9 | +from ami.exports.base import BaseExporter |
| 10 | +from ami.exports.utils import get_data_in_batches |
| 11 | +from ami.main.models import Occurrence |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def get_export_serializer(): |
| 17 | + from ami.main.api.serializers import OccurrenceSerializer |
| 18 | + |
| 19 | + class OccurrenceExportSerializer(OccurrenceSerializer): |
| 20 | + detection_images = serializers.SerializerMethodField() |
| 21 | + |
| 22 | + def get_detection_images(self, obj: Occurrence): |
| 23 | + """Convert the generator field to a list before serialization""" |
| 24 | + if hasattr(obj, "detection_images") and callable(obj.detection_images): |
| 25 | + return list(obj.detection_images()) # Convert generator to list |
| 26 | + return [] |
| 27 | + |
| 28 | + def get_permissions(self, instance_data): |
| 29 | + return instance_data |
| 30 | + |
| 31 | + def to_representation(self, instance): |
| 32 | + return serializers.HyperlinkedModelSerializer.to_representation(self, instance) |
| 33 | + |
| 34 | + return OccurrenceExportSerializer |
| 35 | + |
| 36 | + |
| 37 | +class JSONExporter(BaseExporter): |
| 38 | + """Handles JSON export of occurrences.""" |
| 39 | + |
| 40 | + file_format = "json" |
| 41 | + |
| 42 | + def get_serializer_class(self): |
| 43 | + return get_export_serializer() |
| 44 | + |
| 45 | + def get_queryset(self): |
| 46 | + return ( |
| 47 | + Occurrence.objects.filter(project=self.project) |
| 48 | + .select_related( |
| 49 | + "determination", |
| 50 | + "deployment", |
| 51 | + "event", |
| 52 | + ) |
| 53 | + .with_timestamps() # type: ignore[union-attr] Custom queryset method |
| 54 | + .with_detections_count() |
| 55 | + .with_identifications() |
| 56 | + ) |
| 57 | + |
| 58 | + def export(self): |
| 59 | + """Exports occurrences to JSON format.""" |
| 60 | + temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8") |
| 61 | + with open(temp_file.name, "w", encoding="utf-8") as f: |
| 62 | + first = True |
| 63 | + f.write("[") |
| 64 | + records_exported = 0 |
| 65 | + for i, batch in enumerate(get_data_in_batches(self.queryset, self.get_serializer_class())): |
| 66 | + json_data = json.dumps(batch, cls=DjangoJSONEncoder) |
| 67 | + json_data = json_data[1:-1] # remove [ and ] from json string |
| 68 | + f.write(",\n" if not first else "") |
| 69 | + f.write(json_data) |
| 70 | + first = False |
| 71 | + records_exported += len(batch) |
| 72 | + self.update_job_progress(records_exported) |
| 73 | + f.write("]") |
| 74 | + |
| 75 | + self.update_export_stats(file_temp_path=temp_file.name) |
| 76 | + return temp_file.name # Return file path |
| 77 | + |
| 78 | + |
| 79 | +class OccurrenceTabularSerializer(serializers.ModelSerializer): |
| 80 | + """Serializer to format occurrences for tabular data export.""" |
| 81 | + |
| 82 | + event_id = serializers.IntegerField(source="event.id", allow_null=True) |
| 83 | + event_name = serializers.CharField(source="event.name", allow_null=True) |
| 84 | + deployment_id = serializers.IntegerField(source="deployment.id", allow_null=True) |
| 85 | + deployment_name = serializers.CharField(source="deployment.name", allow_null=True) |
| 86 | + project_id = serializers.IntegerField(source="project.id", allow_null=True) |
| 87 | + project_name = serializers.CharField(source="project.name", allow_null=True) |
| 88 | + |
| 89 | + determination_id = serializers.IntegerField(source="determination.id", allow_null=True) |
| 90 | + determination_name = serializers.CharField(source="determination.name", allow_null=True) |
| 91 | + determination_score = serializers.FloatField(allow_null=True) |
| 92 | + verification_status = serializers.SerializerMethodField() |
| 93 | + |
| 94 | + class Meta: |
| 95 | + model = Occurrence |
| 96 | + fields = [ |
| 97 | + "id", |
| 98 | + "event_id", |
| 99 | + "event_name", |
| 100 | + "deployment_id", |
| 101 | + "deployment_name", |
| 102 | + "project_id", |
| 103 | + "project_name", |
| 104 | + "determination_id", |
| 105 | + "determination_name", |
| 106 | + "determination_score", |
| 107 | + "verification_status", |
| 108 | + "detections_count", |
| 109 | + "first_appearance_timestamp", |
| 110 | + "last_appearance_timestamp", |
| 111 | + "duration", |
| 112 | + ] |
| 113 | + |
| 114 | + def get_verification_status(self, obj): |
| 115 | + """ |
| 116 | + Returns 'Verified' if the occurrence has identifications, otherwise 'Not verified'. |
| 117 | + """ |
| 118 | + return "Verified" if obj.identifications.exists() else "Not verified" |
| 119 | + |
| 120 | + |
| 121 | +class CSVExporter(BaseExporter): |
| 122 | + """Handles CSV export of occurrences.""" |
| 123 | + |
| 124 | + file_format = "csv" |
| 125 | + |
| 126 | + serializer_class = OccurrenceTabularSerializer |
| 127 | + |
| 128 | + def get_queryset(self): |
| 129 | + return ( |
| 130 | + Occurrence.objects.filter(project=self.project) |
| 131 | + .select_related( |
| 132 | + "determination", |
| 133 | + "deployment", |
| 134 | + "event", |
| 135 | + ) |
| 136 | + .with_timestamps() # type: ignore[union-attr] Custom queryset method |
| 137 | + .with_detections_count() |
| 138 | + .with_identifications() |
| 139 | + ) |
| 140 | + |
| 141 | + def export(self): |
| 142 | + """Exports occurrences to CSV format.""" |
| 143 | + |
| 144 | + temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", newline="", encoding="utf-8") |
| 145 | + |
| 146 | + # Extract field names dynamically from the serializer |
| 147 | + serializer = self.serializer_class() |
| 148 | + field_names = list(serializer.fields.keys()) |
| 149 | + records_exported = 0 |
| 150 | + with open(temp_file.name, "w", newline="", encoding="utf-8") as csvfile: |
| 151 | + writer = csv.DictWriter(csvfile, fieldnames=field_names) |
| 152 | + writer.writeheader() |
| 153 | + |
| 154 | + for i, batch in enumerate(get_data_in_batches(self.queryset, self.serializer_class)): |
| 155 | + writer.writerows(batch) |
| 156 | + records_exported += len(batch) |
| 157 | + self.update_job_progress(records_exported) |
| 158 | + self.update_export_stats(file_temp_path=temp_file.name) |
| 159 | + return temp_file.name # Return the file path |
0 commit comments