256 lines
13 KiB
Python
256 lines
13 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.html import format_html, format_html_join
|
||
from django.utils.translation import gettext as _, gettext_lazy, ngettext
|
||
|
||
from .models import BrowserProcessingSettings, BurstCapture, BurstSession, ClassificationRule, Event, ManualReportRevision, 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",)
|
||
|
||
|
||
@admin.register(BrowserProcessingSettings)
|
||
class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
|
||
list_display = ("beta_status",)
|
||
readonly_fields = ("beta_status",)
|
||
fieldsets = (
|
||
(gettext_lazy("Browser-side media processing (Beta)"), {
|
||
"fields": ("beta_status", "browser_processing_beta_enabled"),
|
||
"description": gettext_lazy(
|
||
"Enables experimental client-side video audio extraction and YAMNet pre-classification. "
|
||
"Browser compatibility may vary. Disabling this restores the normal server-side submission flow."
|
||
),
|
||
}),
|
||
)
|
||
|
||
@admin.display(description=gettext_lazy("Beta status"))
|
||
def beta_status(self, obj):
|
||
if obj and obj.browser_processing_beta_enabled:
|
||
return format_html('<strong style="color:#166534">{}</strong>', _("Enabled"))
|
||
return format_html('<strong style="color:#991b1b">{}</strong>', _("Disabled — normal submission"))
|
||
|
||
def has_add_permission(self, request):
|
||
return super().has_add_permission(request) and not BrowserProcessingSettings.objects.exists()
|
||
|
||
def has_delete_permission(self, request, obj=None):
|
||
return False
|
||
|
||
|
||
class ClassificationAdmin(admin.ModelAdmin):
|
||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "event_kind", "observation_duration_minutes", "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", "observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate", "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")
|
||
list_display = ("original_filename", "source_type", "sensor", "sensor_owner", "captured_at", "created_at", "primary_label", "primary_score", "duration")
|
||
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata")
|
||
fields = ClassificationAdmin.fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures", "pretty_classifier_response")
|
||
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures")
|
||
|
||
@admin.display(description=gettext_lazy("Burst captures"))
|
||
def burst_captures(self, obj):
|
||
if not hasattr(obj, "burst_session"):
|
||
return "—"
|
||
parts = []
|
||
for capture in obj.burst_session.captures.all():
|
||
url = reverse("fireworks_detect:burst_capture_audio", args=[capture.pk])
|
||
parts.append(format_html('<details><summary>{} · {}s{}</summary><audio controls preload="none" src="{}"></audio></details>', capture.captured_at, f"{capture.duration_seconds:.1f}", " · primary" if capture.is_primary else "", url))
|
||
return format_html("<div>{}</div>", format_html_join("", "{}", ((part,) for part in parts)))
|
||
|
||
@admin.display(description=gettext_lazy("Sensor owner"))
|
||
def sensor_owner(self, obj):
|
||
return obj.sensor.owner if obj.sensor and obj.sensor.owner_id else "—"
|
||
|
||
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(actor=request.user)
|
||
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 + ("submitted_at", "approved_at")
|
||
fields = ClassificationAdmin.fields + ("submitted_at", "approved_at")
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
|
||
@admin.register(ManualReportRevision)
|
||
class ManualReportRevisionAdmin(admin.ModelAdmin):
|
||
list_display = ("original_pending_id", "previous_occurrences", "new_occurrences", "previous_duration_minutes", "new_duration_minutes", "changed_at")
|
||
readonly_fields = list_display
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
def has_change_permission(self, request, obj=None):
|
||
return False
|
||
|
||
def has_delete_permission(self, request, obj=None):
|
||
return False
|
||
|
||
|
||
@admin.register(Sensor)
|
||
class SensorAdmin(admin.ModelAdmin):
|
||
list_display = ("name", "owner", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix", "archived_at")
|
||
list_filter = ("is_active", "owner", "archived_at")
|
||
search_fields = ("name", "token_prefix", "owner__username", "owner__email")
|
||
readonly_fields = ("token_prefix", "last_heartbeat", "last_submission", "created_at", "archived_at")
|
||
actions = ("issue_api_token",)
|
||
fieldsets = (
|
||
(gettext_lazy("Sensor"), {"fields": ("name", "owner", "is_active", "created_at", "archived_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):
|
||
status, label = obj.heartbeat_status()
|
||
colour = {"online": "#22c55e", "delayed": "#f59e0b"}.get(status, "#ef4444")
|
||
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)
|
||
|
||
|
||
from .models import FieldNote, FieldNoteAssociation
|
||
|
||
|
||
@admin.register(FieldNote)
|
||
class FieldNoteAdmin(admin.ModelAdmin):
|
||
list_display = ("id", "author", "category", "source_type", "verification_status", "visibility", "created_at")
|
||
list_filter = ("visibility", "category", "source_type", "verification_status")
|
||
readonly_fields = tuple(f.name for f in FieldNote._meta.fields)
|
||
search_fields = ("content",)
|
||
|
||
def get_queryset(self, request):
|
||
return super().get_queryset(request).visible_to(request.user).select_related("author", "context")
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
def has_change_permission(self, request, obj=None):
|
||
return False
|
||
|
||
def has_delete_permission(self, request, obj=None):
|
||
return False
|
||
|
||
|
||
@admin.register(FieldNoteAssociation)
|
||
class FieldNoteAssociationAdmin(admin.ModelAdmin):
|
||
list_display = ("context", "actor", "reason", "created_at")
|
||
readonly_fields = tuple(f.name for f in FieldNoteAssociation._meta.fields)
|
||
|
||
def get_queryset(self, request):
|
||
qs = super().get_queryset(request)
|
||
if request.user.has_perm("fireworks_detect.view_all_fieldnotes"):
|
||
return qs
|
||
return qs.filter(context__author=request.user)
|
||
|
||
def has_add_permission(self, request):
|
||
return False
|
||
|
||
def has_change_permission(self, request, obj=None):
|
||
return False
|
||
|
||
def has_delete_permission(self, request, obj=None):
|
||
return False
|