142 lines
4.9 KiB
Python
142 lines
4.9 KiB
Python
import secrets
|
|
|
|
from django.contrib.auth.hashers import check_password, make_password
|
|
from django.core.files.storage import default_storage
|
|
from django.db import models, transaction
|
|
from django.utils import timezone
|
|
|
|
|
|
class Sensor(models.Model):
|
|
"""A physical recorder authorised to submit audio to the device API."""
|
|
|
|
name = models.CharField(max_length=100, unique=True, help_text="A recognisable device name, e.g. Garden ESP32.")
|
|
is_active = models.BooleanField(default=True)
|
|
token_prefix = models.CharField(max_length=15, blank=True, editable=False)
|
|
token_hash = models.CharField(max_length=256, blank=True, editable=False)
|
|
last_heartbeat = models.DateTimeField(null=True, blank=True, editable=False)
|
|
last_submission = models.DateTimeField(null=True, blank=True, editable=False)
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
class Meta:
|
|
ordering = ["name"]
|
|
|
|
def __str__(self):
|
|
return self.name
|
|
|
|
def issue_token(self):
|
|
"""Return a secret once; only a salted password hash is persisted."""
|
|
token = f"ss_{secrets.token_urlsafe(32)}"
|
|
self.token_prefix = token[:15]
|
|
self.token_hash = make_password(token)
|
|
self.save(update_fields=["token_prefix", "token_hash"])
|
|
return token
|
|
|
|
def token_matches(self, token):
|
|
return bool(self.token_hash) and check_password(token, self.token_hash)
|
|
|
|
def record_heartbeat(self, submission=False):
|
|
now = timezone.now()
|
|
self.last_heartbeat = now
|
|
fields = ["last_heartbeat"]
|
|
if submission:
|
|
self.last_submission = now
|
|
fields.append("last_submission")
|
|
self.save(update_fields=fields)
|
|
|
|
|
|
class ClassifiedAudio(models.Model):
|
|
"""Shared fields for a classifier response and its original audio upload."""
|
|
|
|
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d")
|
|
sensor = models.ForeignKey(Sensor, null=True, blank=True, on_delete=models.SET_NULL, related_name="%(class)s_records")
|
|
original_filename = models.CharField(max_length=255)
|
|
classifier_response = models.JSONField()
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
class Meta:
|
|
abstract = True
|
|
ordering = ["-created_at"]
|
|
|
|
def __str__(self):
|
|
return self.original_filename
|
|
|
|
@property
|
|
def predictions(self):
|
|
predictions = self.classifier_response.get("predictions", [])
|
|
return predictions if isinstance(predictions, list) else []
|
|
|
|
@property
|
|
def primary_prediction(self):
|
|
return self.predictions[0] if self.predictions else {}
|
|
|
|
@property
|
|
def primary_label(self):
|
|
return self.primary_prediction.get("class", "No prediction")
|
|
|
|
@property
|
|
def primary_score(self):
|
|
try:
|
|
return f"{float(self.primary_prediction.get('score', 0)) * 100:.1f}%"
|
|
except (TypeError, ValueError):
|
|
return "—"
|
|
|
|
@property
|
|
def duration(self):
|
|
return self.classifier_response.get("duration_seconds", "—")
|
|
|
|
|
|
def _preview_items(self, key):
|
|
preview = []
|
|
for item in self.classifier_response.get(key, []):
|
|
label = str(item.get("class", "Unknown"))
|
|
lowered = label.lower()
|
|
kind = "speech" if any(term in lowered for term in ("speech", "conversation", "narration", "monologue", "whisper")) else "firework" if any(term in lowered for term in ("firework", "firecracker", "explosion", "bang", "boom", "hiss", "crackle")) else "default"
|
|
preview.append({**item, "label": label, "kind": kind, "score_display": f"{float(item.get('score', 0)) * 100:.1f}%"})
|
|
return preview
|
|
|
|
@property
|
|
def admin_predictions(self):
|
|
return self._preview_items("predictions")
|
|
|
|
@property
|
|
def admin_peaks(self):
|
|
return self._preview_items("peak_predictions")
|
|
|
|
@property
|
|
def admin_audio_route(self):
|
|
return "fireworks_detect:pending_audio" if self._meta.model_name == "pendingevent" else "fireworks_detect:event_audio"
|
|
|
|
class PendingEvent(ClassifiedAudio):
|
|
"""A submitted classification awaiting a human review in Django admin."""
|
|
|
|
class Meta(ClassifiedAudio.Meta):
|
|
verbose_name = "Pending event"
|
|
verbose_name_plural = "Pending"
|
|
|
|
@transaction.atomic
|
|
def approve(self):
|
|
event = Event.objects.create(
|
|
audio_file=self.audio_file.name,
|
|
sensor=self.sensor,
|
|
original_filename=self.original_filename,
|
|
classifier_response=self.classifier_response,
|
|
)
|
|
self.delete()
|
|
return event
|
|
|
|
def deny(self):
|
|
file_name = self.audio_file.name
|
|
self.delete()
|
|
if file_name:
|
|
default_storage.delete(file_name)
|
|
|
|
|
|
class Event(ClassifiedAudio):
|
|
"""A reviewed classification that is safe to appear in the event feed."""
|
|
|
|
approved_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
class Meta(ClassifiedAudio.Meta):
|
|
verbose_name = "Event"
|
|
verbose_name_plural = "Events"
|