160 lines
8.1 KiB
Python
160 lines
8.1 KiB
Python
import json
|
||
from urllib.error import HTTPError, URLError
|
||
from urllib.request import Request, urlopen
|
||
|
||
from django.contrib import admin, messages
|
||
from django.core.exceptions import PermissionDenied
|
||
from django.http import HttpResponseNotAllowed
|
||
from django.shortcuts import get_object_or_404, redirect
|
||
from django.urls import path, reverse
|
||
from django.utils import timezone
|
||
from django.utils.html import format_html
|
||
from django.utils.translation import gettext as _, gettext_lazy, ngettext
|
||
|
||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||
from . import views as classifier_views
|
||
|
||
|
||
@admin.register(ClassificationRule)
|
||
class ClassificationRuleAdmin(admin.ModelAdmin):
|
||
list_display = ("value", "rule_type", "enabled")
|
||
list_filter = ("rule_type", "enabled")
|
||
search_fields = ("value",)
|
||
|
||
|
||
class ClassificationAdmin(admin.ModelAdmin):
|
||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||
list_filter = ("source_type", "visually_confirmed", "created_at")
|
||
search_fields = ("original_filename",)
|
||
readonly_fields = ("audio_file", "sensor", "h3_cell", "direction_display", "direction_accuracy_degrees", "original_filename", "created_at", "pretty_classifier_response")
|
||
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
|
||
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
|
||
|
||
@admin.display(description=gettext_lazy("Direction"))
|
||
def direction_display(self, obj):
|
||
return obj.direction_display
|
||
|
||
@admin.display(description=gettext_lazy("Classifier response"))
|
||
def pretty_classifier_response(self, obj):
|
||
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
|
||
|
||
|
||
@admin.register(PendingEvent)
|
||
class PendingEventAdmin(ClassificationAdmin):
|
||
actions = ("approve_selected", "deny_selected")
|
||
change_form_template = "admin/fireworks_detect/pending_change_form.html"
|
||
|
||
def get_urls(self):
|
||
custom_urls = [
|
||
path(
|
||
"<path:object_id>/classify/",
|
||
self.admin_site.admin_view(self.classify_record),
|
||
name="fireworks_detect_pendingevent_classify",
|
||
),
|
||
]
|
||
return custom_urls + super().get_urls()
|
||
|
||
def classify_record(self, request, object_id):
|
||
if request.method != "POST":
|
||
return HttpResponseNotAllowed(["POST"])
|
||
pending = get_object_or_404(PendingEvent, pk=object_id)
|
||
if not self.has_change_permission(request, pending):
|
||
raise PermissionDenied
|
||
change_url = reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk])
|
||
if not pending.audio_file:
|
||
self.message_user(request, _("This Pending event has no attached audio to classify."), messages.ERROR)
|
||
return redirect(change_url)
|
||
try:
|
||
if pending.audio_file.size > classifier_views.MAX_AUDIO_SIZE:
|
||
self.message_user(request, _("The attached audio exceeds the 25 MiB limit."), messages.ERROR)
|
||
return redirect(change_url)
|
||
with pending.audio_file.open("rb") as audio:
|
||
body, content_type = classifier_views._encode_audio_multipart(audio)
|
||
classifier_request = Request(
|
||
classifier_views.CLASSIFIER_URL,
|
||
data=body,
|
||
headers={"Content-Type": content_type, "Accept": "application/json"},
|
||
method="POST",
|
||
)
|
||
with urlopen(classifier_request, timeout=60) as response:
|
||
payload = json.loads(response.read().decode("utf-8"))
|
||
if not isinstance(payload, dict):
|
||
raise ValueError("Classifier response must be a JSON object")
|
||
except HTTPError as error:
|
||
self.message_user(request, _("The classifier returned HTTP %(code)s.") % {"code": error.code}, messages.ERROR)
|
||
return redirect(change_url)
|
||
except (URLError, TimeoutError, OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError):
|
||
self.message_user(request, _("The classifier could not be reached or returned invalid JSON."), messages.ERROR)
|
||
return redirect(change_url)
|
||
|
||
previous_response = pending.classifier_response if isinstance(pending.classifier_response, dict) else {}
|
||
pending.classifier_response = {**previous_response, **payload}
|
||
pending.save(update_fields=["classifier_response"])
|
||
self.message_user(request, _("Classification saved. This event remains Pending."), messages.SUCCESS)
|
||
return redirect(change_url)
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
@admin.action(description=gettext_lazy("Approve selected samples and move them to Events"))
|
||
def approve_selected(self, request, queryset):
|
||
approved = 0
|
||
for pending in queryset:
|
||
pending.approve()
|
||
approved += 1
|
||
self.message_user(request, ngettext("%(count)d sample approved and moved to Events.", "%(count)d samples approved and moved to Events.", approved) % {"count": approved}, messages.SUCCESS)
|
||
|
||
@admin.action(description=gettext_lazy("Deny selected samples and delete their uploaded audio"))
|
||
def deny_selected(self, request, queryset):
|
||
denied = 0
|
||
for pending in queryset:
|
||
pending.deny()
|
||
denied += 1
|
||
self.message_user(request, ngettext("%(count)d sample denied and removed.", "%(count)d samples denied and removed.", denied) % {"count": denied}, messages.WARNING)
|
||
|
||
|
||
@admin.register(Event)
|
||
class EventAdmin(ClassificationAdmin):
|
||
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
|
||
fields = ClassificationAdmin.fields + ("approved_at",)
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
|
||
@admin.register(Sensor)
|
||
class SensorAdmin(admin.ModelAdmin):
|
||
list_display = ("name", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix")
|
||
list_filter = ("is_active",)
|
||
search_fields = ("name", "token_prefix")
|
||
readonly_fields = ("token_prefix", "last_heartbeat", "last_submission", "created_at")
|
||
actions = ("issue_api_token",)
|
||
fieldsets = (
|
||
(gettext_lazy("Sensor"), {"fields": ("name", "is_active", "created_at")}),
|
||
(gettext_lazy("API token"), {"fields": ("token_prefix",), "description": gettext_lazy("Save the sensor first, select it in the list, then choose ‘Issue or rotate API token’. The complete token is shown once only; its salted hash is the only value stored.")}),
|
||
(gettext_lazy("Heartbeat"), {"fields": ("last_heartbeat", "last_submission"), "description": gettext_lazy("Devices should POST to /fireworks/heartbeat/ with Authorization: Bearer <token>. Green means seen within 5 minutes; amber within 15; red is older or never seen.")}),
|
||
)
|
||
|
||
@admin.display(description=gettext_lazy("Heartbeat"))
|
||
def heartbeat_light(self, obj):
|
||
if not obj.last_heartbeat:
|
||
colour, label = "#ef4444", _("Never seen")
|
||
else:
|
||
age = timezone.now() - obj.last_heartbeat
|
||
if age.total_seconds() <= 300:
|
||
colour, label = "#22c55e", _("Online")
|
||
elif age.total_seconds() <= 900:
|
||
colour, label = "#f59e0b", _("Delayed")
|
||
else:
|
||
colour, label = "#ef4444", _("Offline")
|
||
return format_html('<span style="display:inline-flex;align-items:center;gap:6px"><span style="width:10px;height:10px;border-radius:50%;background:{}"></span>{}</span>', colour, label)
|
||
|
||
@admin.action(description=gettext_lazy("Issue or rotate API token (shown once)"))
|
||
def issue_api_token(self, request, queryset):
|
||
if queryset.count() != 1:
|
||
self.message_user(request, _("Select exactly one sensor to issue a token."), messages.ERROR)
|
||
return
|
||
sensor = queryset.get()
|
||
token = sensor.issue_token()
|
||
self.message_user(request, format_html(_("Copy this token now; it is not stored and will not be shown again: <code>{}</code>"), token), messages.WARNING)
|