initial commit

This commit is contained in:
Joren de Graaf
2026-09-26 20:59:01 +02:00
parent e07f08c791
commit e572257f67
201 changed files with 36684 additions and 0 deletions
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+90
View File
@@ -0,0 +1,90 @@
import json
from django.contrib import admin, messages
from django.utils import timezone
from django.utils.html import format_html
from .models import Event, PendingEvent, Sensor
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "sensor", "primary_label", "primary_score", "duration", "created_at")
list_filter = ("created_at",)
search_fields = ("original_filename",)
readonly_fields = ("audio_file", "sensor", "original_filename", "created_at", "pretty_classifier_response")
fields = ("audio_file", "sensor", "original_filename", "created_at")
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
@admin.display(description="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")
def has_add_permission(self, request):
return False
@admin.action(description="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, f"{approved} sample(s) approved and moved to Events.", messages.SUCCESS)
@admin.action(description="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, f"{denied} sample(s) denied and removed.", 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 = (
("Sensor", {"fields": ("name", "is_active", "created_at")}),
("API token", {"fields": ("token_prefix",), "description": "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."}),
("Heartbeat", {"fields": ("last_heartbeat", "last_submission"), "description": "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="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="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)
+52
View File
@@ -0,0 +1,52 @@
import json
from django.contrib import admin, messages
from django.utils.html import format_html
from .models import Event, PendingEvent
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "primary_label", "primary_score", "duration", "created_at")
list_filter = ("created_at",)
search_fields = ("original_filename",)
readonly_fields = ("audio_file", "original_filename", "created_at", "pretty_classifier_response")
fields = ("audio_file", "original_filename", "created_at")
change_form_template = "admin/fireworks_detect/classification_change_form.html"
@admin.display(description="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")
def has_add_permission(self, request):
return False
@admin.action(description="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, f"{approved} sample(s) approved and moved to Events.", messages.SUCCESS)
@admin.action(description="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, f"{denied} sample(s) denied and removed.", 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
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class FireworksDetectConfig(AppConfig):
name = 'fireworks_detect'
@@ -0,0 +1,47 @@
# Generated by Django 6.1.1 on 2026-09-26 13:34
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('original_filename', models.CharField(max_length=255)),
('classifier_response', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('approved_at', models.DateTimeField(auto_now_add=True)),
],
options={
'verbose_name': 'Event',
'verbose_name_plural': 'Events',
'ordering': ['-created_at'],
'abstract': False,
},
),
migrations.CreateModel(
name='PendingEvent',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('original_filename', models.CharField(max_length=255)),
('classifier_response', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
],
options={
'verbose_name': 'Pending event',
'verbose_name_plural': 'Pending',
'ordering': ['-created_at'],
'abstract': False,
},
),
]
@@ -0,0 +1,40 @@
# Generated by Django 6.1.1 on 2026-09-26 14:16
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Sensor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='A recognisable device name, e.g. Garden ESP32.', max_length=100, unique=True)),
('is_active', models.BooleanField(default=True)),
('token_prefix', models.CharField(blank=True, editable=False, max_length=15)),
('token_hash', models.CharField(blank=True, editable=False, max_length=256)),
('last_heartbeat', models.DateTimeField(blank=True, editable=False, null=True)),
('last_submission', models.DateTimeField(blank=True, editable=False, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='event',
name='sensor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_records', to='fireworks_detect.sensor'),
),
migrations.AddField(
model_name='pendingevent',
name='sensor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_records', to='fireworks_detect.sensor'),
),
]
+141
View File
@@ -0,0 +1,141 @@
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"
+93
View File
@@ -0,0 +1,93 @@
from django.core.files.storage import default_storage
from django.db import models, transaction
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")
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")
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,
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"
@@ -0,0 +1,69 @@
{% if error %}
<section class="results-card error-card" role="alert">
<h2>Analysis unavailable</h2>
<p>{{ error }}</p>
</section>
{% else %}
<section class="results-card" tabindex="-1">
<div class="result-heading">
<div>
<h2>Analysis complete</h2>
<p>{{ result.filename|default:"Audio file" }}</p>
</div>
<span class="result-status">Ready</span>
</div>
<div class="meta">
<span>{{ result.duration_seconds|default:"—" }} seconds</span>
<span>{{ result.frames_analysed|default:"—" }} frames analysed</span>
<span>{{ result.yamnet_sample_rate|default:"—" }} Hz model rate</span>
</div>
<div class="legend" aria-label="Result legend">
{% if firework_count %}<span class="firework">✦ {{ firework_count }} firework-related signal{{ firework_count|pluralize }}</span>{% endif %}
{% if speech_count %}<span class="speech">● {{ speech_count }} speech/privacy signal{{ speech_count|pluralize }}</span>{% endif %}
</div>
<div class="result-grid">
<section class="result-group" aria-labelledby="top-predictions">
<h3 id="top-predictions">Top sound classes</h3>
{% if predictions %}
<ul class="prediction-list">
{% for prediction in predictions %}
<li class="prediction prediction--{{ prediction.kind }}" style="--score: {{ prediction.score_width }}">
<span class="prediction-label">{{ prediction.label }}</span>
<span class="prediction-score">{{ prediction.score_display }}</span>
<span class="score-bar" aria-hidden="true"><i></i></span>
</li>
{% endfor %}
</ul>
{% else %}<p class="empty">No overall predictions were returned.</p>{% endif %}
</section>
<section class="result-group" aria-labelledby="peak-predictions">
<h3 id="peak-predictions">Notable moments</h3>
{% if peak_predictions %}
<div class="peak-list">
{% for prediction in peak_predictions %}
<article class="peak-item">
<span class="peak-time">{{ prediction.time_seconds|default:"—" }}s · frame {{ prediction.frame|default:"—" }}</span>
<div class="prediction prediction--{{ prediction.kind }}" style="--score: {{ prediction.score_width }}">
<span class="prediction-label">{{ prediction.label }}</span>
<span class="prediction-score">{{ prediction.score_display }}</span>
<span class="score-bar" aria-hidden="true"><i></i></span>
</div>
</article>
{% endfor %}
</div>
{% else %}<p class="empty">No peak events were returned.</p>{% endif %}
</section>
</div>
{% if submission_token %}
<div class="review-submission" id="review-submission">
<input type="hidden" name="classification_token" value="{{ submission_token }}">
<div><strong>Submit this sample for review</strong><p>The audio and signed classifier response will be added to Pending.</p></div>
<button type="button" hx-post="{% url 'fireworks_detect:submit_pending' %}" hx-target="#review-submission" hx-swap="outerHTML" hx-encoding="multipart/form-data">Send to Pending →</button>
</div>
{% endif %}
</section>
{% endif %}
@@ -0,0 +1 @@
<h2>{{ event.original_filename }}</h2><p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · {{ result.duration_seconds|default:"—" }} seconds · {{ result.frames_analysed|default:"—" }} frames</p><h3>Top sound classes</h3>{% for prediction in predictions %}<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>{% empty %}<p class="empty">No predictions returned.</p>{% endfor %}<h3>Notable moments</h3>{% for prediction in peak_predictions %}<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>{% empty %}<p class="empty">No peak events returned.</p>{% endfor %}
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Events · Sound Signal</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script><style>:root{--i:#edf3ff;--m:#aab9d8;--l:#2b3d68}*{box-sizing:border-box}body{margin:0;min-height:100vh;padding:2rem;color:var(--i);font-family:system-ui;background:radial-gradient(circle at 8% 0,#263a76,transparent 31rem),#090e1d}.shell{width:min(100%,70rem);margin:auto}.top{display:flex;justify-content:space-between;gap:1rem;align-items:center;margin-bottom:3rem}.brand,a{color:inherit}.brand{text-decoration:none;font-weight:900;letter-spacing:.1em;text-transform:uppercase}.top a:not(.brand){padding:.6rem .8rem;border:1px solid var(--l);border-radius:.6rem;text-decoration:none}.eyebrow{color:#bcd4ff;font-size:.76rem;letter-spacing:.15em;text-transform:uppercase;font-weight:800}h1{font-size:clamp(2.5rem,6vw,4.5rem);letter-spacing:-.06em;margin:.4rem 0}.lede{color:var(--m);max-width:38rem;line-height:1.6}.grid{display:grid;grid-template-columns:minmax(0,.8fr) minmax(0,1.2fr);gap:1rem;margin-top:2rem}.panel{border:1px solid var(--l);border-radius:1rem;padding:1rem;background:#111a31d9}.event{width:100%;display:flex;justify-content:space-between;gap:.6rem;text-align:left;margin:.6rem 0;padding:.85rem;border:1px solid #374e7e;border-radius:.7rem;color:var(--i);background:#15223f;cursor:pointer}.event:hover{background:#20345f}.event small,.empty{color:var(--m)}.badge{color:#ffd08a}.detail h2{margin-top:0}.prediction{display:flex;justify-content:space-between;gap:1rem;padding:.65rem;margin:.45rem 0;border-left:3px solid #78a4f0;background:#111c34}.prediction--firework{border-color:#f5aa44}.prediction--speech{border-color:#fb7185}.meta{color:var(--m);font-size:.9rem}@media(max-width:42rem){body{padding:1rem}.grid{grid-template-columns:1fr}}</style></head><body><main class="shell"><header class="top"><a class="brand" href="{% url 'fireworks_detect:fireworks' %}">✦ Sound Signal</a><a href="{% url 'fireworks_detect:map' %}">Map</a></header><p class="eyebrow">Reviewed signal archive</p><h1>Approved events.</h1><p class="lede">This feed refreshes automatically every three seconds after a pending sample is approved in admin.</p><div class="grid"><section class="panel"><h2>Latest events</h2><div id="events-feed" hx-get="{% url 'fireworks_detect:events_list' %}" hx-trigger="load, every 3s" hx-swap="innerHTML"><p class="empty">Loading events…</p></div></section><section class="panel detail" id="event-detail"><h2>Select an event</h2><p class="empty">Choose an approved event to inspect its classification details.</p></section></div></main></body></html>
@@ -0,0 +1 @@
{% if events %}{% for event in events %}<button class="event" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML"><span><strong>{{ event.primary_label }}</strong><br><small>{{ event.original_filename }} · {{ event.duration }}s</small></span><span class="badge">{{ event.primary_score }} →</span></button>{% endfor %}{% else %}<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>{% endif %}
@@ -0,0 +1,571 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sound Signal · Fireworks detection</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
<style>
:root {
--ink: #eaf0ff;
--muted: #9caed1;
--surface: #111a31;
--surface-2: #17223e;
--line: #2a3a61;
--blue: #6aa8ff;
--violet: #a78bfa;
--fire: #ffb454;
--danger: #ff727c;
--success: #6ee7b7;
}
* {
box-sizing: border-box;
}
body {
min-width: 320px;
min-height: 100vh;
margin: 0;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: radial-gradient(circle at 10% 0%, #263a76 0, transparent 30rem), radial-gradient(circle at 90% 20%, #4d236c 0, transparent 28rem), #090e1d;
}
.shell {
width: min(100% - 2.5rem, 70rem);
margin: 0 auto;
padding: clamp(2rem, 6vw, 5rem) 0;
}
.brand {
display: flex;
align-items: center;
gap: .75rem;
/* margin-bottom: clamp(2.5rem, 6vw, 5rem); */
font-size: .9rem;
font-weight: 800;
letter-spacing: .11em;
text-transform: uppercase;
}
.brand-mark {
display: grid;
width: 2.25rem;
aspect-ratio: 1;
place-items: center;
border-radius: .75rem;
color: #141022;
background: linear-gradient(135deg, #fcd34d, #fb7185);
box-shadow: 0 .5rem 1.5rem #fb718550;
}
.intro {
max-width: 45rem;
}
.kicker {
margin: 0 0 .8rem;
color: #bfdbfe;
font-size: .78rem;
font-weight: 800;
letter-spacing: .15em;
text-transform: uppercase;
}
h1 {
max-width: 12ch;
margin: 0;
font-size: clamp(2.6rem, 7vw, 5.75rem);
line-height: .96;
letter-spacing: -.065em;
}
.lede {
max-width: 38rem;
margin: 1.5rem 0 2.5rem;
color: var(--muted);
font-size: clamp(1rem, 2vw, 1.18rem);
line-height: 1.65;
}
.upload-card,
.results-card {
border: 1px solid var(--line);
border-radius: 1.5rem;
background: linear-gradient(145deg, #162240d9, #0e162bdd);
box-shadow: 0 1.5rem 4rem #02061680;
backdrop-filter: blur(16px);
}
.upload-card {
padding: clamp(1rem, 3vw, 1.5rem);
}
.drop-zone {
display: grid;
min-height: 16rem;
place-items: center;
padding: 2rem;
border: 1.5px dashed #5d75aa;
border-radius: 1rem;
cursor: pointer;
text-align: center;
background: linear-gradient(135deg, #1b2a4e80, #291c4b66);
transition: .2s ease;
}
.drop-zone:hover,
.drop-zone.dragging {
border-color: var(--blue);
transform: translateY(-2px);
background: #203360a8;
}
.drop-zone:focus-within {
outline: 3px solid #6aa8ff66;
outline-offset: 3px;
}
.file-input {
width: .1px;
height: .1px;
position: absolute;
opacity: 0;
overflow: hidden;
}
.upload-icon {
display: grid;
width: 4rem;
aspect-ratio: 1;
place-items: center;
margin: 0 auto 1rem;
border-radius: 50%;
color: #dbeafe;
font-size: 1.8rem;
background: #4777c94d;
}
.drop-zone strong {
display: block;
font-size: 1.15rem;
}
.drop-zone span {
display: block;
margin-top: .4rem;
color: var(--muted);
font-size: .92rem;
}
.file-name {
min-height: 1.3rem;
margin: 1rem 0 0;
color: #c7d2fe;
font-size: .9rem;
overflow-wrap: anywhere;
}
.form-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: .9rem .25rem 0;
}
.file-note {
margin: 0;
color: var(--muted);
font-size: .8rem;
}
button,
.button {
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
gap: .6rem;
border: 0;
border-radius: .8rem;
padding: .85rem 1.15rem;
cursor: pointer;
color: #10172c;
font: inherit;
font-weight: 800;
background: linear-gradient(135deg, #93c5fd, #c4b5fd);
box-shadow: 0 .5rem 1.25rem #8b5cf640;
transition: transform .2s ease, filter .2s ease;
}
button:hover,
.button:hover {
transform: translateY(-1px);
filter: brightness(1.08);
}
button:disabled {
cursor: wait;
filter: saturate(.4);
transform: none;
}
.spinner {
width: 1rem;
height: 1rem;
border: 2px solid #263253;
border-top-color: currentColor;
border-radius: 50%;
animation: spin .75s linear infinite;
}
.htmx-indicator {
display: none;
}
.htmx-request.htmx-indicator {
display: inline-block;
}
.upload-form.htmx-request button {
pointer-events: none;
}
#upload-status {
min-height: 1.4rem;
margin: 1rem .25rem 0;
color: #c7d2fe;
font-size: .9rem;
}
.upload-form.htmx-request+#upload-status {
color: #fcd34d;
}
#classification-results {
margin-top: 1.5rem;
}
.results-card {
padding: clamp(1.25rem, 3vw, 2rem);
animation: reveal .35s ease-out;
}
.result-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.result-heading h2 {
margin: 0;
font-size: clamp(1.4rem, 3vw, 2rem);
letter-spacing: -.04em;
}
.result-heading p {
margin: .3rem 0 0;
color: var(--muted);
}
.result-status {
padding: .4rem .65rem;
border-radius: 999px;
color: #a7f3d0;
font-size: .75rem;
font-weight: 800;
white-space: nowrap;
background: #065f464d;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: .6rem;
margin: 1.5rem 0;
}
.meta span,
.legend span {
padding: .4rem .65rem;
border: 1px solid var(--line);
border-radius: 999px;
color: #bdc9e5;
font-size: .8rem;
background: #101a31;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: .5rem;
margin: 0 0 1.25rem;
}
.legend .firework {
color: #ffd18c;
border-color: #c7721e80;
}
.legend .speech {
color: #ffadb4;
border-color: #d5485880;
}
.topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:3.5rem; }.brand { display:flex; align-items:center; gap:.7rem; color:var(--ink); font-size:.9rem; font-weight:800; letter-spacing:.1em; text-decoration:none; text-transform:uppercase; }.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }.nav { display:flex; gap:.35rem; padding:.25rem; border:1px solid var(--line); border-radius:.75rem; background:#111a31a6; }.nav a { padding:.5rem .75rem; border-radius:.5rem; color:var(--muted); font-size:.86rem; font-weight:700; text-decoration:none; }.nav a[aria-current="page"] { color:var(--ink); background:#2a3b67; }
.result-grid {
display: grid;
grid-template-columns: minmax(0, 1.25fr) minmax(18rem, .75fr);
gap: 1.25rem;
}
.result-group {
padding: 1.1rem;
border: 1px solid var(--line);
border-radius: 1rem;
background: #0b1225a8;
}
.result-group h3 {
margin: 0 0 1rem;
font-size: 1rem;
}
.prediction-list {
display: grid;
gap: .75rem;
margin: 0;
padding: 0;
list-style: none;
}
.prediction {
--accent-color: #7799dd;
position: relative;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: .45rem .75rem;
align-items: center;
padding: .7rem .75rem;
overflow: hidden;
border: 1px solid #26365b;
border-left: 3px solid var(--accent-color);
border-radius: .7rem;
background: #121c34;
}
.prediction--firework {
--accent-color: var(--fire);
background: linear-gradient(90deg, #7a421d55, #121c34);
}
.prediction--speech {
--accent-color: var(--danger);
background: linear-gradient(90deg, #6c213055, #121c34);
}
.prediction-label {
min-width: 0;
font-weight: 700;
overflow-wrap: anywhere;
}
.prediction-score {
color: #c4d1ed;
font-size: .85rem;
font-variant-numeric: tabular-nums;
}
.score-bar {
grid-column: 1/-1;
height: .3rem;
overflow: hidden;
border-radius: 999px;
background: #263657;
}
.score-bar i {
display: block;
width: calc(var(--score) * 1%);
height: 100%;
border-radius: inherit;
background: var(--accent-color);
}
.peak-list {
display: grid;
gap: .7rem;
}
.peak-item {
padding-bottom: .7rem;
border-bottom: 1px solid #253453;
}
.peak-item:last-child {
padding-bottom: 0;
border-bottom: 0;
}
.peak-time {
color: #a9bce0;
font-size: .78rem;
}
.peak-item .prediction {
margin-top: .35rem;
}
.empty {
margin: 0;
color: var(--muted);
}
.error-card {
border-color: #a43d4d;
background: linear-gradient(135deg, #4b1724dd, #1a1427dd);
}
.error-card h2 {
color: #fecdd3;
}
.error-card p {
color: #fecdd3;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes reveal {
from {
opacity: 0;
transform: translateY(.75rem);
}
}
@media (max-width:42rem) {
.shell {
width: min(100% - 1.25rem, 70rem);
}
.form-footer,
.result-heading {
align-items: stretch;
flex-direction: column;
}
.form-footer button {
width: 100%;
}
.result-grid {
grid-template-columns: 1fr;
}
.result-status {
align-self: flex-start;
}
}
@media (prefers-reduced-motion:reduce) {
*,
::before,
::after {
scroll-behavior: auto !important;
animation-duration: .01ms !important;
transition-duration: .01ms !important;
}
}
</style>
</head>
<body>
<main class="shell">
<header class="topbar" style="display: flex">
<a class="brand" href="{% url 'fireworks_detect:fireworks' %}"><span class="brand-mark">✦</span> Sound
Signal</a>
<nav class="nav" aria-label="Fireworks navigation">
<a href="{% url 'fireworks_detect:fireworks' %}" aria-current="page">Analyse</a>
<a href="{% url 'fireworks_detect:map' %}" >Map</a>
</nav>
</header>
<section class="intro" aria-labelledby="page-title">
<p class="kicker">Audio event analysis</p>
<h1 id="page-title">See what your audio heard.</h1>
<p class="lede">Drop a recording to identify its most likely sounds. Firework-related signals are
highlighted in amber; speech-related signals are marked in red for future privacy filtering.</p>
<a href="https://pixabay.com/sound-effects/search/fireworks/" class="button" target="_blank">Here's some
samples to test with</a>
<br /><br />
</section>
<section class="upload-card" aria-label="Upload audio for classification">
<form class="upload-form" action="{% url 'fireworks_detect:classify_upload' %}" method="post"
enctype="multipart/form-data" hx-post="{% url 'fireworks_detect:classify_upload' %}"
hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data"
hx-indicator="#upload-indicator">
{% csrf_token %}
<label class="drop-zone" id="drop-zone">
<input class="file-input" id="audio-file" type="file" name="audio"
accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
<span>
<span class="upload-icon">↑</span>
<strong>Drop an audio file here</strong>
<span>or click to browse your device</span>
</span>
<span class="file-name" id="file-name">No file selected</span>
</label>
<div class="form-footer">
<p class="file-note">WAV, MP3, M4A, OGG and more · 25 MiB maximum</p>
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator"
aria-hidden="true"></span>Analyse audio</button>
</div>
<section id="classification-results" aria-live="polite" aria-label="Classification results"></section>
</form>
<p id="upload-status" role="status" aria-live="polite"></p>
</section>
</main>
<script>
const form = document.querySelector('.upload-form');
const dropZone = document.querySelector('#drop-zone');
const fileInput = document.querySelector('#audio-file');
const fileName = document.querySelector('#file-name');
const status = document.querySelector('#upload-status');
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
document.body.addEventListener('htmx:beforeSwap', (event) => {
if (event.detail.xhr.status >= 400) {
event.detail.shouldSwap = true;
event.detail.isError = false;
}
});
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
fileInput.value = '';
showFile();
status.textContent = '';
document.querySelector('#classification-results').replaceChildren();
}
});
</script>
</body>
</html>
@@ -0,0 +1,572 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sound Signal · Fireworks detection</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
<style>
:root {
--ink: #eaf0ff;
--muted: #9caed1;
--surface: #111a31;
--surface-2: #17223e;
--line: #2a3a61;
--blue: #6aa8ff;
--violet: #a78bfa;
--fire: #ffb454;
--danger: #ff727c;
--success: #6ee7b7;
}
* {
box-sizing: border-box;
}
body {
min-width: 320px;
min-height: 100vh;
margin: 0;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: radial-gradient(circle at 10% 0%, #263a76 0, transparent 30rem), radial-gradient(circle at 90% 20%, #4d236c 0, transparent 28rem), #090e1d;
}
.shell {
width: min(100% - 2.5rem, 70rem);
margin: 0 auto;
padding: clamp(2rem, 6vw, 5rem) 0;
}
.brand {
display: flex;
align-items: center;
gap: .75rem;
/* margin-bottom: clamp(2.5rem, 6vw, 5rem); */
font-size: .9rem;
font-weight: 800;
letter-spacing: .11em;
text-transform: uppercase;
}
.brand-mark {
display: grid;
width: 2.25rem;
aspect-ratio: 1;
place-items: center;
border-radius: .75rem;
color: #141022;
background: linear-gradient(135deg, #fcd34d, #fb7185);
box-shadow: 0 .5rem 1.5rem #fb718550;
}
.intro {
max-width: 45rem;
}
.kicker {
margin: 0 0 .8rem;
color: #bfdbfe;
font-size: .78rem;
font-weight: 800;
letter-spacing: .15em;
text-transform: uppercase;
}
h1 {
max-width: 12ch;
margin: 0;
font-size: clamp(2.6rem, 7vw, 5.75rem);
line-height: .96;
letter-spacing: -.065em;
}
.lede {
max-width: 38rem;
margin: 1.5rem 0 2.5rem;
color: var(--muted);
font-size: clamp(1rem, 2vw, 1.18rem);
line-height: 1.65;
}
.upload-card,
.results-card {
border: 1px solid var(--line);
border-radius: 1.5rem;
background: linear-gradient(145deg, #162240d9, #0e162bdd);
box-shadow: 0 1.5rem 4rem #02061680;
backdrop-filter: blur(16px);
}
.upload-card {
padding: clamp(1rem, 3vw, 1.5rem);
}
.drop-zone {
display: grid;
min-height: 16rem;
place-items: center;
padding: 2rem;
border: 1.5px dashed #5d75aa;
border-radius: 1rem;
cursor: pointer;
text-align: center;
background: linear-gradient(135deg, #1b2a4e80, #291c4b66);
transition: .2s ease;
}
.drop-zone:hover,
.drop-zone.dragging {
border-color: var(--blue);
transform: translateY(-2px);
background: #203360a8;
}
.drop-zone:focus-within {
outline: 3px solid #6aa8ff66;
outline-offset: 3px;
}
.file-input {
width: .1px;
height: .1px;
position: absolute;
opacity: 0;
overflow: hidden;
}
.upload-icon {
display: grid;
width: 4rem;
aspect-ratio: 1;
place-items: center;
margin: 0 auto 1rem;
border-radius: 50%;
color: #dbeafe;
font-size: 1.8rem;
background: #4777c94d;
}
.drop-zone strong {
display: block;
font-size: 1.15rem;
}
.drop-zone span {
display: block;
margin-top: .4rem;
color: var(--muted);
font-size: .92rem;
}
.file-name {
min-height: 1.3rem;
margin: 1rem 0 0;
color: #c7d2fe;
font-size: .9rem;
overflow-wrap: anywhere;
}
.form-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: .9rem .25rem 0;
}
.file-note {
margin: 0;
color: var(--muted);
font-size: .8rem;
}
button,
.button {
text-decoration: none;
display: inline-flex;
align-items: center;
justify-content: center;
gap: .6rem;
border: 0;
border-radius: .8rem;
padding: .85rem 1.15rem;
cursor: pointer;
color: #10172c;
font: inherit;
font-weight: 800;
background: linear-gradient(135deg, #93c5fd, #c4b5fd);
box-shadow: 0 .5rem 1.25rem #8b5cf640;
transition: transform .2s ease, filter .2s ease;
}
button:hover,
.button:hover {
transform: translateY(-1px);
filter: brightness(1.08);
}
button:disabled {
cursor: wait;
filter: saturate(.4);
transform: none;
}
.spinner {
width: 1rem;
height: 1rem;
border: 2px solid #263253;
border-top-color: currentColor;
border-radius: 50%;
animation: spin .75s linear infinite;
}
.htmx-indicator {
display: none;
}
.htmx-request.htmx-indicator {
display: inline-block;
}
.upload-form.htmx-request button {
pointer-events: none;
}
#upload-status {
min-height: 1.4rem;
margin: 1rem .25rem 0;
color: #c7d2fe;
font-size: .9rem;
}
.upload-form.htmx-request+#upload-status {
color: #fcd34d;
}
#classification-results {
margin-top: 1.5rem;
}
.results-card {
padding: clamp(1.25rem, 3vw, 2rem);
animation: reveal .35s ease-out;
}
.result-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.result-heading h2 {
margin: 0;
font-size: clamp(1.4rem, 3vw, 2rem);
letter-spacing: -.04em;
}
.result-heading p {
margin: .3rem 0 0;
color: var(--muted);
}
.result-status {
padding: .4rem .65rem;
border-radius: 999px;
color: #a7f3d0;
font-size: .75rem;
font-weight: 800;
white-space: nowrap;
background: #065f464d;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: .6rem;
margin: 1.5rem 0;
}
.meta span,
.legend span {
padding: .4rem .65rem;
border: 1px solid var(--line);
border-radius: 999px;
color: #bdc9e5;
font-size: .8rem;
background: #101a31;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: .5rem;
margin: 0 0 1.25rem;
}
.legend .firework {
color: #ffd18c;
border-color: #c7721e80;
}
.legend .speech {
color: #ffadb4;
border-color: #d5485880;
}
.topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:3.5rem; }.brand { display:flex; align-items:center; gap:.7rem; color:var(--ink); font-size:.9rem; font-weight:800; letter-spacing:.1em; text-decoration:none; text-transform:uppercase; }.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }.nav { display:flex; gap:.35rem; padding:.25rem; border:1px solid var(--line); border-radius:.75rem; background:#111a31a6; }.nav a { padding:.5rem .75rem; border-radius:.5rem; color:var(--muted); font-size:.86rem; font-weight:700; text-decoration:none; }.nav a[aria-current="page"] { color:var(--ink); background:#2a3b67; }
.result-grid {
display: grid;
grid-template-columns: minmax(0, 1.25fr) minmax(18rem, .75fr);
gap: 1.25rem;
}
.result-group {
padding: 1.1rem;
border: 1px solid var(--line);
border-radius: 1rem;
background: #0b1225a8;
}
.result-group h3 {
margin: 0 0 1rem;
font-size: 1rem;
}
.prediction-list {
display: grid;
gap: .75rem;
margin: 0;
padding: 0;
list-style: none;
}
.prediction {
--accent-color: #7799dd;
position: relative;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: .45rem .75rem;
align-items: center;
padding: .7rem .75rem;
overflow: hidden;
border: 1px solid #26365b;
border-left: 3px solid var(--accent-color);
border-radius: .7rem;
background: #121c34;
}
.prediction--firework {
--accent-color: var(--fire);
background: linear-gradient(90deg, #7a421d55, #121c34);
}
.prediction--speech {
--accent-color: var(--danger);
background: linear-gradient(90deg, #6c213055, #121c34);
}
.prediction-label {
min-width: 0;
font-weight: 700;
overflow-wrap: anywhere;
}
.prediction-score {
color: #c4d1ed;
font-size: .85rem;
font-variant-numeric: tabular-nums;
}
.score-bar {
grid-column: 1/-1;
height: .3rem;
overflow: hidden;
border-radius: 999px;
background: #263657;
}
.score-bar i {
display: block;
width: calc(var(--score) * 1%);
height: 100%;
border-radius: inherit;
background: var(--accent-color);
}
.peak-list {
display: grid;
gap: .7rem;
}
.peak-item {
padding-bottom: .7rem;
border-bottom: 1px solid #253453;
}
.peak-item:last-child {
padding-bottom: 0;
border-bottom: 0;
}
.peak-time {
color: #a9bce0;
font-size: .78rem;
}
.peak-item .prediction {
margin-top: .35rem;
}
.empty {
margin: 0;
color: var(--muted);
}
.error-card {
border-color: #a43d4d;
background: linear-gradient(135deg, #4b1724dd, #1a1427dd);
}
.error-card h2 {
color: #fecdd3;
}
.error-card p {
color: #fecdd3;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes reveal {
from {
opacity: 0;
transform: translateY(.75rem);
}
}
@media (max-width:42rem) {
.shell {
width: min(100% - 1.25rem, 70rem);
}
.form-footer,
.result-heading {
align-items: stretch;
flex-direction: column;
}
.form-footer button {
width: 100%;
}
.result-grid {
grid-template-columns: 1fr;
}
.result-status {
align-self: flex-start;
}
}
@media (prefers-reduced-motion:reduce) {
*,
::before,
::after {
scroll-behavior: auto !important;
animation-duration: .01ms !important;
transition-duration: .01ms !important;
}
}
</style>
</head>
<body>
<main class="shell">
<header class="topbar" style="display: flex">
<a class="brand" href="{% url 'fireworks_detect:fireworks' %}"><span class="brand-mark">✦</span> Sound
Signal</a>
<nav class="nav" aria-label="Fireworks navigation">
<a href="{% url 'fireworks_detect:fireworks' %}" aria-current="page">Analyse</a>
<a href="{% url 'fireworks_detect:map' %}" >Map</a>
</nav>
</header>
<section class="intro" aria-labelledby="page-title">
<p class="kicker">Audio event analysis</p>
<h1 id="page-title">See what your audio heard.</h1>
<p class="lede">Drop a recording to identify its most likely sounds. Firework-related signals are
highlighted in amber; speech-related signals are marked in red for future privacy filtering.</p>
<a href="https://pixabay.com/sound-effects/search/fireworks/" class="button" target="_blank">Here's some
samples to test with</a>
<br /><br />
</section>
<section class="upload-card" aria-label="Upload audio for classification">
<form class="upload-form" action="{% url 'fireworks_detect:classify' %}" method="post"
enctype="multipart/form-data" hx-post="{% url 'fireworks_detect:classify' %}"
hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data"
hx-indicator="#upload-indicator">
{% csrf_token %}
<label class="drop-zone" id="drop-zone">
<input class="file-input" id="audio-file" type="file" name="audio"
accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
<span>
<span class="upload-icon">↑</span>
<strong>Drop an audio file here</strong>
<span>or click to browse your device</span>
</span>
<span class="file-name" id="file-name">No file selected</span>
</label>
<div class="form-footer">
<p class="file-note">WAV, MP3, M4A, OGG and more · 25 MiB maximum</p>
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator"
aria-hidden="true"></span>Analyse audio</button>
</div>
</form>
<p id="upload-status" role="status" aria-live="polite"></p>
</section>
<section id="classification-results" aria-live="polite" aria-label="Classification results"></section>
</main>
<script>
const form = document.querySelector('.upload-form');
const dropZone = document.querySelector('#drop-zone');
const fileInput = document.querySelector('#audio-file');
const fileName = document.querySelector('#file-name');
const status = document.querySelector('#upload-status');
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
document.body.addEventListener('htmx:beforeSwap', (event) => {
if (event.detail.xhr.status >= 400) {
event.detail.shouldSwap = true;
event.detail.isError = false;
}
});
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
fileInput.value = '';
showFile();
status.textContent = '';
document.querySelector('#classification-results').replaceChildren();
}
});
</script>
</body>
</html>
@@ -0,0 +1,93 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signal map · Sound Signal</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
:root { --ink:#eef3ff; --muted:#a9b9d8; --surface:#111a31; --line:#2a3a61; --blue:#83b7ff; --violet:#b69cff; --amber:#ffbc61; --green:#6ee7b7; }
* { box-sizing:border-box; }
body { min-width:320px; min-height:100vh; margin:0; color:var(--ink); font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; background:radial-gradient(circle at 8% 0%,#263a76 0,transparent 32rem),radial-gradient(circle at 95% 0%,#492064 0,transparent 27rem),#090e1d; }
.shell {
width: min(100% - 2.5rem, 70rem);
margin: 0 auto;
padding: clamp(2rem, 6vw, 5rem) 0;
}
.topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:3.5rem; }.brand { display:flex; align-items:center; gap:.7rem; color:var(--ink); font-size:.9rem; font-weight:800; letter-spacing:.1em; text-decoration:none; text-transform:uppercase; }.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }.nav { display:flex; gap:.35rem; padding:.25rem; border:1px solid var(--line); border-radius:.75rem; background:#111a31a6; }.nav a { padding:.5rem .75rem; border-radius:.5rem; color:var(--muted); font-size:.86rem; font-weight:700; text-decoration:none; }.nav a[aria-current="page"] { color:var(--ink); background:#2a3b67; }
.kicker { margin:0 0 .65rem; color:#bfdbfe; font-size:.76rem; font-weight:800; letter-spacing:.14em; text-transform:uppercase; }.headline { display:flex; align-items:end; justify-content:space-between; gap:2rem; margin-bottom:2rem; }.headline h1 { margin:0; font-size:clamp(2.3rem,5vw,4.5rem); line-height:.98; letter-spacing:-.06em; }.headline p { max-width:30rem; margin:0; color:var(--muted); line-height:1.6; }
.filters { display:grid; grid-template-columns:1.3fr repeat(3,minmax(8rem,1fr)) auto; gap:.75rem; align-items:end; margin-bottom:1rem; padding:1rem; border:1px solid var(--line); border-radius:1.1rem; background:#121d37d9; box-shadow:0 1rem 3rem #03071466; }.filter { display:grid; gap:.35rem; }.filter label { color:#9fb1d5; font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }.filter select,.filter input { width:100%; min-height:2.65rem; border:1px solid #354a77; border-radius:.65rem; padding:0 .75rem; color:var(--ink); font:inherit; background:#0c1428; }.filter select:focus,.filter input:focus { outline:2px solid #82b5ff; outline-offset:2px; }.mock-tag { align-self:center; padding:.46rem .65rem; border:1px solid #4a5f8e; border-radius:999px; color:#c9d8f6; font-size:.75rem; font-weight:700; white-space:nowrap; background:#1d2b4e; }
.map-panel { overflow:hidden; border:1px solid var(--line); border-radius:1.25rem; background:var(--surface); box-shadow:0 1.5rem 4rem #0206168a; }.map-header { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.2rem; border-bottom:1px solid var(--line); }.map-header strong { font-size:.95rem; }.live { display:flex; align-items:center; gap:.45rem; color:#a7f3d0; font-size:.8rem; }.live i { width:.5rem; height:.5rem; border-radius:50%; background:var(--green); box-shadow:0 0 0 .25rem #34d3992e; }.map-wrap { position:relative; }.map { height:clamp(30rem,65vh,45rem); background:#dce4cf; }.legend { position:absolute; z-index:600; right:1rem; bottom:1rem; width:min(15rem,calc(100% - 2rem)); padding:.85rem; border:1px solid #344973; border-radius:.8rem; color:#dce7fe; font-size:.78rem; background:#101a31e8; box-shadow:0 .75rem 2rem #05091480; backdrop-filter:blur(10px); }.legend h2 { margin:0 0 .6rem; font-size:.82rem; }.legend div { display:flex; align-items:center; gap:.5rem; margin-top:.4rem; }.legend-dot { width:.7rem; height:.7rem; border:2px solid #f2c56b; border-radius:50%; background:#ed8e2e88; }.legend-ring { width:.85rem; height:.85rem; border:2px solid #a98af7; border-radius:50%; background:#8b5cf633; }.legend-line { width:1.1rem; border-top:2px dashed #644b9c; }.sensor-icon { display:grid; width:2.1rem; height:2.1rem; place-items:center; border:2px solid #e6edff; border-radius:50%; color:#14203b; font-size:.72rem; font-weight:900; background:linear-gradient(135deg,#a5c8ff,#c4b5fd); box-shadow:0 .2rem .8rem #18275080; }.source-icon { display:grid; width:2.45rem; height:2.45rem; place-items:center; border:2px solid #fff3d5; border-radius:50% 50% 50% 0; color:#452000; font-size:1.15rem; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; transform:rotate(-45deg); }.source-icon span { transform:rotate(45deg); }.direction-arrow { display:block; color:#5c408d; font-size:1.5rem; font-weight:900; line-height:1; text-shadow:0 .1rem .4rem #fff8; }
.leaflet-control-zoom a { color:#243456!important; }.leaflet-popup-content-wrapper,.leaflet-popup-tip { color:#e9f1ff; background:#14203a; }.leaflet-popup-content { margin:.75rem .9rem; font-family:inherit; }.popup-title { display:block; margin-bottom:.2rem; font-weight:800; }.popup-meta { color:#a9b9d8; font-size:.78rem; }
@media (max-width:52rem) { .shell { width:min(100% - 1.25rem,80rem); }.topbar { margin-bottom:2.5rem; }.headline { align-items:start; flex-direction:column; gap:1rem; }.filters { grid-template-columns:1fr 1fr; }.filters .filter:first-child { grid-column:1/-1; }.mock-tag { justify-self:start; }.map { height:32rem; } }
@media (max-width:30rem) { .nav a { padding:.5rem; }.filters { grid-template-columns:1fr; }.filters .filter:first-child { grid-column:auto; } }
</style>
</head>
<body>
<main class="shell">
<header class="topbar">
<a class="brand" href="{% url 'fireworks_detect:fireworks' %}"><span class="brand-mark">✦</span> Sound Signal</a>
<nav class="nav" aria-label="Fireworks navigation">
<a href="{% url 'fireworks_detect:fireworks' %}">Analyse</a>
<a href="{% url 'fireworks_detect:map' %}" aria-current="page">Map</a>
</nav>
</header>
<section class="headline" aria-labelledby="map-title">
<div><p class="kicker">Future event intelligence</p><h1 id="map-title">Sound activity map.</h1></div>
<p>A concept view of sensors triangulating a likely source. This uses entirely mock data for Heerenveen, ready for future incoming event records.</p>
</section>
<section class="filters" aria-label="Mock event filters">
<div class="filter"><label for="event-type">Event type</label><select id="event-type"><option>All sound events</option><option>Possible fireworks</option><option>Privacy-filtered speech</option></select></div>
<div class="filter"><label for="from-date">From</label><input id="from-date" type="date" value="2026-09-19"></div>
<div class="filter"><label for="range">Range</label><select id="range"><option>This week</option><option>Today</option><option>Last 30 days</option></select></div>
<div class="filter"><label for="confidence">Confidence</label><select id="confidence"><option>Any confidence</option><option>High confidence</option><option>Review needed</option></select></div>
<span class="mock-tag">Mock data</span>
</section>
<section class="map-panel" aria-label="Mock sound event map of Heerenveen">
<div class="map-header"><strong>Heerenveen, Netherlands</strong><span class="live"><i></i> 3 sensors simulated</span></div>
<div class="map-wrap"><div id="event-map" class="map" aria-label="Interactive map centered on Heerenveen"></div>
<aside class="legend" aria-label="Map legend"><h2>Triangulation estimate</h2><div><span class="legend-dot"></span> Higher-confidence source area</div><div><span class="legend-ring"></span> Broader possible area</div><div><span class="legend-line"></span> Simulated direction of arrival</div></aside>
</div>
</section>
</main>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
const map = L.map('event-map', { zoomControl: false, scrollWheelZoom: false }).setView([52.9512478, 5.943674], 14);
L.control.zoom({ position: 'bottomleft' }).addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '&copy; OpenStreetMap contributors',
}).addTo(map);
const estimatedSource = [52.9501, 5.9466];
const sensors = [
{ name: 'Sensor 1', position: [52.9570, 5.9335], confidence: '91% direction confidence' },
{ name: 'Sensor 2', position: [52.9586, 5.9508], confidence: '86% direction confidence' },
{ name: 'Sensor 3', position: [52.9458, 5.9370], confidence: '78% direction confidence' },
];
L.circle(estimatedSource, { radius: 1020, color: '#8b5cf6', weight: 1.5, fillColor: '#8b5cf6', fillOpacity: 0.10, dashArray: '5 8' }).addTo(map);
L.circle(estimatedSource, { radius: 370, color: '#f59e0b', weight: 2, fillColor: '#f59e0b', fillOpacity: 0.28 }).addTo(map);
const sourceIcon = L.divIcon({ className: '', html: '<div class="source-icon"><span>✦</span></div>', iconSize: [39, 39], iconAnchor: [20, 32] });
L.marker(estimatedSource, { icon: sourceIcon }).addTo(map).bindPopup('<span class="popup-title">Estimated sound source</span><span class="popup-meta">High-confidence area · mock event</span>');
function bearing(from, to) {
const lat = ((from[0] + to[0]) / 2) * Math.PI / 180;
return Math.atan2((to[1] - from[1]) * Math.cos(lat), to[0] - from[0]) * 180 / Math.PI;
}
sensors.forEach((sensor, index) => {
const line = L.polyline([sensor.position, estimatedSource], { color: '#60438f', weight: 2, opacity: 0.85, dashArray: '8 9' }).addTo(map);
line.bindTooltip('Direction of arrival', { sticky: true });
const arrowPosition = [sensor.position[0] + (estimatedSource[0] - sensor.position[0]) * 0.58, sensor.position[1] + (estimatedSource[1] - sensor.position[1]) * 0.58];
const arrowIcon = L.divIcon({ className: '', html: `<span class="direction-arrow" style="transform:rotate(${bearing(sensor.position, estimatedSource)}deg)">↑</span>`, iconSize: [22, 22], iconAnchor: [11, 11] });
L.marker(arrowPosition, { icon: arrowIcon, interactive: false }).addTo(map);
const sensorIcon = L.divIcon({ className: '', html: `<div class="sensor-icon">${index + 1}</div>`, iconSize: [34, 34], iconAnchor: [17, 17] });
L.marker(sensor.position, { icon: sensorIcon }).addTo(map).bindPopup(`<span class="popup-title">${sensor.name}</span><span class="popup-meta">${sensor.confidence}<br>Mock microphone node</span>`);
});
</script>
</body>
</html>
@@ -0,0 +1,3 @@
<div class="review-submission" id="review-submission" role="status">
{% if error %}<div><strong>Could not submit this sample</strong><p>{{ error }}</p></div>{% else %}<div><strong>Sent to Pending</strong><p>{{ pending.original_filename }} is ready for administrator review.</p></div><a href="{% url 'fireworks_detect:events' %}">View events</a>{% endif %}
</div>
+95
View File
@@ -0,0 +1,95 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sound Signal · Fireworks detection</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
<style>
:root { --ink:#eaf0ff; --muted:#9caed1; --surface:#111a31; --surface-2:#17223e; --line:#2a3a61; --blue:#6aa8ff; --violet:#a78bfa; --fire:#ffb454; --danger:#ff727c; --success:#6ee7b7; }
* { box-sizing:border-box; }
body { min-width:320px; min-height:100vh; margin:0; color:var(--ink); font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; background:radial-gradient(circle at 10% 0%,#263a76 0,transparent 30rem),radial-gradient(circle at 90% 20%,#4d236c 0,transparent 28rem),#090e1d; }
.shell { width:min(100% - 2.5rem,70rem); margin:0 auto; padding:clamp(2rem,6vw,5rem) 0; }
.brand { display:flex; align-items:center; gap:.75rem; margin-bottom:clamp(2.5rem,6vw,5rem); font-size:.9rem; font-weight:800; letter-spacing:.11em; text-transform:uppercase; }
.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }
.intro { max-width:45rem; }
.kicker { margin:0 0 .8rem; color:#bfdbfe; font-size:.78rem; font-weight:800; letter-spacing:.15em; text-transform:uppercase; }
h1 { max-width:12ch; margin:0; font-size:clamp(2.6rem,7vw,5.75rem); line-height:.96; letter-spacing:-.065em; }
.lede { max-width:38rem; margin:1.5rem 0 2.5rem; color:var(--muted); font-size:clamp(1rem,2vw,1.18rem); line-height:1.65; }
.upload-card,.results-card { border:1px solid var(--line); border-radius:1.5rem; background:linear-gradient(145deg,#162240d9,#0e162bdd); box-shadow:0 1.5rem 4rem #02061680; backdrop-filter:blur(16px); }
.upload-card { padding:clamp(1rem,3vw,1.5rem); }
.drop-zone { display:grid; min-height:16rem; place-items:center; padding:2rem; border:1.5px dashed #5d75aa; border-radius:1rem; cursor:pointer; text-align:center; background:linear-gradient(135deg,#1b2a4e80,#291c4b66); transition:.2s ease; }
.drop-zone:hover,.drop-zone.dragging { border-color:var(--blue); transform:translateY(-2px); background:#203360a8; }
.drop-zone:focus-within { outline:3px solid #6aa8ff66; outline-offset:3px; }
.file-input { width:.1px; height:.1px; position:absolute; opacity:0; overflow:hidden; }
.upload-icon { display:grid; width:4rem; aspect-ratio:1; place-items:center; margin:0 auto 1rem; border-radius:50%; color:#dbeafe; font-size:1.8rem; background:#4777c94d; }
.drop-zone strong { display:block; font-size:1.15rem; }
.drop-zone span { display:block; margin-top:.4rem; color:var(--muted); font-size:.92rem; }
.file-name { min-height:1.3rem; margin:1rem 0 0; color:#c7d2fe; font-size:.9rem; overflow-wrap:anywhere; }
.form-footer { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:.9rem .25rem 0; }
.file-note { margin:0; color:var(--muted); font-size:.8rem; }
button { display:inline-flex; align-items:center; justify-content:center; gap:.6rem; border:0; border-radius:.8rem; padding:.85rem 1.15rem; cursor:pointer; color:#10172c; font:inherit; font-weight:800; background:linear-gradient(135deg,#93c5fd,#c4b5fd); box-shadow:0 .5rem 1.25rem #8b5cf640; transition:transform .2s ease,filter .2s ease; }
button:hover { transform:translateY(-1px); filter:brightness(1.08); } button:disabled { cursor:wait; filter:saturate(.4); transform:none; }
.spinner { width:1rem; height:1rem; border:2px solid #263253; border-top-color:currentColor; border-radius:50%; animation:spin .75s linear infinite; }
.htmx-indicator { display:none; }.htmx-request.htmx-indicator { display:inline-block; }.upload-form.htmx-request button { pointer-events:none; }
#upload-status { min-height:1.4rem; margin:1rem .25rem 0; color:#c7d2fe; font-size:.9rem; } .upload-form.htmx-request + #upload-status { color:#fcd34d; }
#classification-results { margin-top:1.5rem; }
.results-card { padding:clamp(1.25rem,3vw,2rem); animation:reveal .35s ease-out; }
.result-heading { display:flex; align-items:flex-start; justify-content:space-between; gap:1rem; } .result-heading h2 { margin:0; font-size:clamp(1.4rem,3vw,2rem); letter-spacing:-.04em; }.result-heading p { margin:.3rem 0 0; color:var(--muted); }
.result-status { padding:.4rem .65rem; border-radius:999px; color:#a7f3d0; font-size:.75rem; font-weight:800; white-space:nowrap; background:#065f464d; }
.meta { display:flex; flex-wrap:wrap; gap:.6rem; margin:1.5rem 0; }.meta span,.legend span { padding:.4rem .65rem; border:1px solid var(--line); border-radius:999px; color:#bdc9e5; font-size:.8rem; background:#101a31; }.legend { display:flex; flex-wrap:wrap; gap:.5rem; margin:0 0 1.25rem; }.legend .firework { color:#ffd18c; border-color:#c7721e80; }.legend .speech { color:#ffadb4; border-color:#d5485880; }
.result-grid { display:grid; grid-template-columns:minmax(0,1.25fr) minmax(18rem,.75fr); gap:1.25rem; }.result-group { padding:1.1rem; border:1px solid var(--line); border-radius:1rem; background:#0b1225a8; }.result-group h3 { margin:0 0 1rem; font-size:1rem; }.prediction-list { display:grid; gap:.75rem; margin:0; padding:0; list-style:none; }.prediction { --accent-color:#7799dd; position:relative; display:grid; grid-template-columns:minmax(0,1fr) auto; gap:.45rem .75rem; align-items:center; padding:.7rem .75rem; overflow:hidden; border:1px solid #26365b; border-left:3px solid var(--accent-color); border-radius:.7rem; background:#121c34; }.prediction--firework { --accent-color:var(--fire); background:linear-gradient(90deg,#7a421d55,#121c34); }.prediction--speech { --accent-color:var(--danger); background:linear-gradient(90deg,#6c213055,#121c34); }.prediction-label { min-width:0; font-weight:700; overflow-wrap:anywhere; }.prediction-score { color:#c4d1ed; font-size:.85rem; font-variant-numeric:tabular-nums; }.score-bar { grid-column:1/-1; height:.3rem; overflow:hidden; border-radius:999px; background:#263657; }.score-bar i { display:block; width:calc(var(--score) * 1%); height:100%; border-radius:inherit; background:var(--accent-color); }.peak-list { display:grid; gap:.7rem; }.peak-item { padding-bottom:.7rem; border-bottom:1px solid #253453; }.peak-item:last-child { padding-bottom:0; border-bottom:0; }.peak-time { color:#a9bce0; font-size:.78rem; }.peak-item .prediction { margin-top:.35rem; }.empty { margin:0; color:var(--muted); }.error-card { border-color:#a43d4d; background:linear-gradient(135deg,#4b1724dd,#1a1427dd); }.error-card h2 { color:#fecdd3; }.error-card p { color:#fecdd3; }
@keyframes spin { to { transform:rotate(360deg); } } @keyframes reveal { from { opacity:0; transform:translateY(.75rem); } }
@media (max-width:42rem) { .shell { width:min(100% - 1.25rem,70rem); }.form-footer,.result-heading { align-items:stretch; flex-direction:column; }.form-footer button { width:100%; }.result-grid { grid-template-columns:1fr; }.result-status { align-self:flex-start; } }
@media (prefers-reduced-motion:reduce) { *,::before,::after { scroll-behavior:auto!important; animation-duration:.01ms!important; transition-duration:.01ms!important; } }
</style>
</head>
<body>
<main class="shell">
<div class="brand"><span class="brand-mark">✦</span> Sound Signal</div>
<section class="intro" aria-labelledby="page-title">
<p class="kicker">Audio event analysis</p>
<h1 id="page-title">See what your audio heard.</h1>
<p class="lede">Drop a recording to identify its most likely sounds. Firework-related signals are highlighted in amber; speech-related signals are marked in red for future privacy filtering.</p>
</section>
<section class="upload-card" aria-label="Upload audio for classification">
<form class="upload-form" action="{% url 'fireworks_detect:classify' %}" method="post" enctype="multipart/form-data" hx-post="{% url 'fireworks_detect:classify' %}" hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-indicator="#upload-indicator">
{% csrf_token %}
<label class="drop-zone" id="drop-zone">
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
<span>
<span class="upload-icon">↑</span>
<strong>Drop an audio file here</strong>
<span>or click to browse your device</span>
</span>
<span class="file-name" id="file-name">No file selected</span>
</label>
<div class="form-footer">
<p class="file-note">WAV, MP3, M4A, OGG and more · 25 MiB maximum</p>
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>Analyse audio</button>
</div>
</form>
<p id="upload-status" role="status" aria-live="polite"></p>
</section>
<section id="classification-results" aria-live="polite" aria-label="Classification results"></section>
</main>
<script>
const form = document.querySelector('.upload-form');
const dropZone = document.querySelector('#drop-zone');
const fileInput = document.querySelector('#audio-file');
const fileName = document.querySelector('#file-name');
const status = document.querySelector('#upload-status');
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
</script>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+31
View File
@@ -0,0 +1,31 @@
from django.urls import path
from .views import (
classify_audio,
classify_upload,
event_audio,
event_detail,
events_list,
events_view,
fireworks_map_view,
fireworks_view,
pending_audio,
submit_pending_event,
sensor_heartbeat,
)
app_name = "fireworks_detect"
urlpatterns = [
path("", fireworks_view, name="fireworks"),
path("map/", fireworks_map_view, name="map"),
path("classify/", classify_audio, name="classify"),
path("classify/upload/", classify_upload, name="classify_upload"),
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
path("submit-pending/", submit_pending_event, name="submit_pending"),
path("events/", events_view, name="events"),
path("events/list/", events_list, name="events_list"),
path("admin-audio/pending/<int:event_id>/", pending_audio, name="pending_audio"),
path("admin-audio/events/<int:event_id>/", event_audio, name="event_audio"),
path("events/<int:event_id>/", event_detail, name="event_detail"),
]
+25
View File
@@ -0,0 +1,25 @@
from django.urls import path
from .views import (
classify_audio,
event_audio,
event_detail,
events_list,
events_view,
fireworks_map_view,
fireworks_view,
pending_audio,
submit_pending_event,
)
app_name = "fireworks_detect"
urlpatterns = [
path("", fireworks_view, name="fireworks"),
path("map/", fireworks_map_view, name="map"),
path("classify/", classify_audio, name="classify"),
path("submit-pending/", submit_pending_event, name="submit_pending"),
path("events/", events_view, name="events"),
path("events/list/", events_list, name="events_list"),
path("events/<int:event_id>/", event_detail, name="event_detail"),
]
+266
View File
@@ -0,0 +1,266 @@
import json
import mimetypes
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.contrib.admin.views.decorators import staff_member_required
from django.http import FileResponse, Http404, JsonResponse
from django.core import signing
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .models import Event, PendingEvent, Sensor
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
MAX_AUDIO_SIZE = 25 * 1024 * 1024 # 25 MiB: enough for this demo, and avoids accidental large uploads.
FIREWORK_TERMS = (
"firework", "firecracker", "explosion", "explosive", "bang", "boom",
"hiss", "crackle", "burst", "gunshot", "artillery", "cannon", "rocket",
)
SPEECH_TERMS = (
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
"speaking", "speech synthesizer",
)
AUDIO_EXTENSIONS = {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".weba"}
@never_cache
def fireworks_view(request):
return render(request, "fireworks_detect/home.html")
@never_cache
def fireworks_map_view(request):
return render(request, "fireworks_detect/map.html")
@never_cache
def events_view(request):
return render(request, "fireworks_detect/events.html")
def _classification_context(payload):
predictions = _decorate_predictions(payload.get("predictions"))
peak_predictions = _decorate_predictions(payload.get("peak_predictions"))
return {
"result": payload,
"predictions": predictions,
"peak_predictions": peak_predictions,
"firework_count": sum(item["kind"] == "firework" for item in predictions + peak_predictions),
"speech_count": sum(item["kind"] == "speech" for item in predictions + peak_predictions),
}
def _label_kind(label):
lowered = label.lower()
if any(term in lowered for term in SPEECH_TERMS):
return "speech"
if any(term in lowered for term in FIREWORK_TERMS):
return "firework"
return "default"
def _score_details(score):
try:
percentage = max(0, min(float(score) * 100, 100))
except (TypeError, ValueError):
return "—", 0
return f"{percentage:.1f}%", round(percentage, 1)
def _decorate_predictions(predictions):
decorated = []
for prediction in predictions if isinstance(predictions, list) else []:
if not isinstance(prediction, dict):
continue
label = str(prediction.get("class", "Unknown"))
score, score_width = _score_details(prediction.get("score"))
decorated.append({
**prediction,
"label": label,
"kind": _label_kind(label),
"score_display": score,
"score_width": score_width,
})
return decorated
def _encode_audio_multipart(uploaded_file):
"""Build the multipart request expected by the classifier without a third-party HTTP client."""
boundary = f"----DjangoAudioUpload{uuid.uuid4().hex}"
filename = Path(uploaded_file.name).name.replace('"', "")
content_type = uploaded_file.content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
header = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
f"Content-Type: {content_type}\r\n\r\n"
).encode()
body = header + uploaded_file.read() + f"\r\n--{boundary}--\r\n".encode()
return body, f"multipart/form-data; boundary={boundary}"
def _render_error(request, message, status=400):
return render(request, "fireworks_detect/classification_result.html", {"error": message}, status=status)
@require_http_methods(["GET", "POST"])
@never_cache
def classify_upload(request):
# Opening this endpoint in a browser should return the upload screen rather
# than a 405 page. Only POST requests perform classification.
if request.method == "GET":
return redirect("fireworks_detect:fireworks")
uploaded_file = request.FILES.get("audio")
if not uploaded_file:
return _render_error(request, "Choose an audio file before starting the analysis.")
extension = Path(uploaded_file.name).suffix.lower()
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
return _render_error(request, "Please upload a supported audio file (such as WAV, MP3, M4A, or OGG).")
if uploaded_file.size > MAX_AUDIO_SIZE:
return _render_error(request, "This demo accepts audio files up to 25 MiB.")
body, content_type = _encode_audio_multipart(uploaded_file)
classifier_request = Request(
CLASSIFIER_URL,
data=body,
headers={"Content-Type": content_type, "Accept": "application/json"},
method="POST",
)
try:
with urlopen(classifier_request, timeout=60) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as error:
return _render_error(request, f"The classifier returned an error (HTTP {error.code}).", status=502)
except (URLError, TimeoutError):
return _render_error(request, "The classifier could not be reached. Please try again shortly.", status=502)
except json.JSONDecodeError:
return _render_error(request, "The classifier returned an unreadable response.", status=502)
if not isinstance(payload, dict):
return _render_error(request, "The classifier returned an unexpected response.", status=502)
# Keep the raw payload in this request flow; this is the future hand-off point
# for saving the upload and its classification to a database or queue.
context = _classification_context(payload)
context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification")
return render(request, "fireworks_detect/classification_result.html", context)
@require_http_methods(["POST"])
@never_cache
def submit_pending_event(request):
uploaded_file = request.FILES.get("audio")
token = request.POST.get("classification_token")
if not uploaded_file:
return render(request, "fireworks_detect/pending_submission.html", {"error": "Keep the analysed audio file selected before submitting it for review."}, status=400)
if not token:
return render(request, "fireworks_detect/pending_submission.html", {"error": "Analyse the file before submitting it for review."}, status=400)
try:
payload = signing.loads(token, salt="fireworks_detect.classification", max_age=60 * 60)
except signing.BadSignature:
return render(request, "fireworks_detect/pending_submission.html", {"error": "This analysis has expired. Please analyse the audio again."}, status=400)
if not isinstance(payload, dict):
return render(request, "fireworks_detect/pending_submission.html", {"error": "The saved analysis is not valid."}, status=400)
pending = PendingEvent.objects.create(
audio_file=uploaded_file,
original_filename=uploaded_file.name,
classifier_response=payload,
)
return render(request, "fireworks_detect/pending_submission.html", {"pending": pending})
@never_cache
def events_list(request):
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
@never_cache
def event_detail(request, event_id):
event = get_object_or_404(Event, pk=event_id)
context = _classification_context(event.classifier_response)
context["event"] = event
return render(request, "fireworks_detect/event_detail.html", context)
def _audio_response(record):
if not record.audio_file:
raise Http404("No audio is attached to this record.")
content_type = mimetypes.guess_type(record.audio_file.name)[0] or "application/octet-stream"
return FileResponse(record.audio_file.open("rb"), content_type=content_type)
@staff_member_required
def pending_audio(request, event_id):
return _audio_response(get_object_or_404(PendingEvent, pk=event_id))
@staff_member_required
def event_audio(request, event_id):
return _audio_response(get_object_or_404(Event, pk=event_id))
def _sensor_from_request(request):
authorization = request.headers.get("Authorization", "")
token = authorization.removeprefix("Bearer ").strip() if authorization.startswith("Bearer ") else request.headers.get("X-Sensor-Token", "").strip()
if not token:
return None
sensor = Sensor.objects.filter(is_active=True, token_prefix=token[:15]).first()
return sensor if sensor and sensor.token_matches(token) else None
def _sensor_error(message, status=400):
return JsonResponse({"detail": message}, status=status)
@csrf_exempt
@require_http_methods(["POST"])
def classify_audio(request):
"""Token-authenticated device API. Browser uploads use classify_upload instead."""
sensor = _sensor_from_request(request)
if not sensor:
return _sensor_error("A valid sensor API token is required.", 401)
uploaded_file = request.FILES.get("file") or request.FILES.get("audio")
if not uploaded_file:
return _sensor_error("Attach audio as multipart field 'file'.")
extension = Path(uploaded_file.name).suffix.lower()
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
return _sensor_error("Unsupported audio file.")
if uploaded_file.size > MAX_AUDIO_SIZE:
return _sensor_error("Audio exceeds the 25 MiB limit.")
body, content_type = _encode_audio_multipart(uploaded_file)
classifier_request = Request(CLASSIFIER_URL, data=body, headers={"Content-Type": content_type, "Accept": "application/json"}, method="POST")
try:
with urlopen(classifier_request, timeout=60) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as error:
return _sensor_error(f"Classifier returned HTTP {error.code}.", 502)
except (URLError, TimeoutError, json.JSONDecodeError):
return _sensor_error("Classifier is unavailable or returned invalid JSON.", 502)
if not isinstance(payload, dict):
return _sensor_error("Classifier returned an unexpected response.", 502)
uploaded_file.seek(0)
pending = PendingEvent.objects.create(audio_file=uploaded_file, sensor=sensor, original_filename=uploaded_file.name, classifier_response=payload)
sensor.record_heartbeat(submission=True)
return JsonResponse({**payload, "pending_event_id": pending.pk, "sensor": sensor.name}, status=201)
@csrf_exempt
@require_http_methods(["POST"])
def sensor_heartbeat(request):
sensor = _sensor_from_request(request)
if not sensor:
return _sensor_error("A valid sensor API token is required.", 401)
sensor.record_heartbeat()
return JsonResponse({"ok": True, "sensor": sensor.name, "heartbeat_at": sensor.last_heartbeat.isoformat()})
+193
View File
@@ -0,0 +1,193 @@
import json
import mimetypes
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.contrib.admin.views.decorators import staff_member_required
from django.http import FileResponse, Http404
from django.core import signing
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from .models import Event, PendingEvent
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
MAX_AUDIO_SIZE = 25 * 1024 * 1024 # 25 MiB: enough for this demo, and avoids accidental large uploads.
FIREWORK_TERMS = (
"firework", "firecracker", "explosion", "explosive", "bang", "boom",
"hiss", "crackle", "burst", "gunshot", "artillery", "cannon", "rocket",
)
SPEECH_TERMS = (
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
"speaking", "speech synthesizer",
)
AUDIO_EXTENSIONS = {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".weba"}
@never_cache
def fireworks_view(request):
return render(request, "fireworks_detect/home.html")
@never_cache
def fireworks_map_view(request):
return render(request, "fireworks_detect/map.html")
@never_cache
def events_view(request):
return render(request, "fireworks_detect/events.html")
def _classification_context(payload):
predictions = _decorate_predictions(payload.get("predictions"))
peak_predictions = _decorate_predictions(payload.get("peak_predictions"))
return {
"result": payload,
"predictions": predictions,
"peak_predictions": peak_predictions,
"firework_count": sum(item["kind"] == "firework" for item in predictions + peak_predictions),
"speech_count": sum(item["kind"] == "speech" for item in predictions + peak_predictions),
}
def _label_kind(label):
lowered = label.lower()
if any(term in lowered for term in SPEECH_TERMS):
return "speech"
if any(term in lowered for term in FIREWORK_TERMS):
return "firework"
return "default"
def _score_details(score):
try:
percentage = max(0, min(float(score) * 100, 100))
except (TypeError, ValueError):
return "—", 0
return f"{percentage:.1f}%", round(percentage, 1)
def _decorate_predictions(predictions):
decorated = []
for prediction in predictions if isinstance(predictions, list) else []:
if not isinstance(prediction, dict):
continue
label = str(prediction.get("class", "Unknown"))
score, score_width = _score_details(prediction.get("score"))
decorated.append({
**prediction,
"label": label,
"kind": _label_kind(label),
"score_display": score,
"score_width": score_width,
})
return decorated
def _encode_audio_multipart(uploaded_file):
"""Build the multipart request expected by the classifier without a third-party HTTP client."""
boundary = f"----DjangoAudioUpload{uuid.uuid4().hex}"
filename = Path(uploaded_file.name).name.replace('"', "")
content_type = uploaded_file.content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
header = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
f"Content-Type: {content_type}\r\n\r\n"
).encode()
body = header + uploaded_file.read() + f"\r\n--{boundary}--\r\n".encode()
return body, f"multipart/form-data; boundary={boundary}"
def _render_error(request, message, status=400):
return render(request, "fireworks_detect/classification_result.html", {"error": message}, status=status)
@require_http_methods(["GET", "POST"])
@never_cache
def classify_audio(request):
# Opening this endpoint in a browser should return the upload screen rather
# than a 405 page. Only POST requests perform classification.
if request.method == "GET":
return redirect("fireworks_detect:fireworks")
uploaded_file = request.FILES.get("audio")
if not uploaded_file:
return _render_error(request, "Choose an audio file before starting the analysis.")
extension = Path(uploaded_file.name).suffix.lower()
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
return _render_error(request, "Please upload a supported audio file (such as WAV, MP3, M4A, or OGG).")
if uploaded_file.size > MAX_AUDIO_SIZE:
return _render_error(request, "This demo accepts audio files up to 25 MiB.")
body, content_type = _encode_audio_multipart(uploaded_file)
classifier_request = Request(
CLASSIFIER_URL,
data=body,
headers={"Content-Type": content_type, "Accept": "application/json"},
method="POST",
)
try:
with urlopen(classifier_request, timeout=60) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as error:
return _render_error(request, f"The classifier returned an error (HTTP {error.code}).", status=502)
except (URLError, TimeoutError):
return _render_error(request, "The classifier could not be reached. Please try again shortly.", status=502)
except json.JSONDecodeError:
return _render_error(request, "The classifier returned an unreadable response.", status=502)
if not isinstance(payload, dict):
return _render_error(request, "The classifier returned an unexpected response.", status=502)
# Keep the raw payload in this request flow; this is the future hand-off point
# for saving the upload and its classification to a database or queue.
context = _classification_context(payload)
context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification")
return render(request, "fireworks_detect/classification_result.html", context)
@require_http_methods(["POST"])
@never_cache
def submit_pending_event(request):
uploaded_file = request.FILES.get("audio")
token = request.POST.get("classification_token")
if not uploaded_file:
return render(request, "fireworks_detect/pending_submission.html", {"error": "Keep the analysed audio file selected before submitting it for review."}, status=400)
if not token:
return render(request, "fireworks_detect/pending_submission.html", {"error": "Analyse the file before submitting it for review."}, status=400)
try:
payload = signing.loads(token, salt="fireworks_detect.classification", max_age=60 * 60)
except signing.BadSignature:
return render(request, "fireworks_detect/pending_submission.html", {"error": "This analysis has expired. Please analyse the audio again."}, status=400)
if not isinstance(payload, dict):
return render(request, "fireworks_detect/pending_submission.html", {"error": "The saved analysis is not valid."}, status=400)
pending = PendingEvent.objects.create(
audio_file=uploaded_file,
original_filename=uploaded_file.name,
classifier_response=payload,
)
return render(request, "fireworks_detect/pending_submission.html", {"pending": pending})
@never_cache
def events_list(request):
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
@never_cache
def event_detail(request, event_id):
event = get_object_or_404(Event, pk=event_id)
context = _classification_context(event.classifier_response)
context["event"] = event
return render(request, "fireworks_detect/event_detail.html", context)