Compare commits

24 Commits
Author SHA1 Message Date
Joren de Graaf 2a0603f463 redesign clock card on manual submission 2026-10-07 09:46:19 +02:00
Joren de Graaf f5da668179 manual submission redesign phase H - finetuning mobile 2026-10-06 20:27:54 +02:00
Joren de Graaf 31169e89d4 manual submission redesign phase H - finetuning 2026-10-06 20:19:58 +02:00
Joren de Graaf 10ddaada15 manual submission redesign phase G 2026-10-06 20:04:21 +02:00
Joren de Graaf faa466dd69 manual submission redesign phase F 2026-10-06 19:57:14 +02:00
Joren de Graaf 21bf9c72a7 manual submission redesign phase E 2026-10-06 19:54:08 +02:00
Joren de Graaf d11b9da8e7 manual submission redesign phase D - compiled 2026-10-06 19:51:27 +02:00
Joren de Graaf dda5cd9c84 manual submission redesign phase D 2026-10-06 19:50:52 +02:00
Joren de Graaf e555023587 manual submission redesign phase C 2026-10-06 19:47:10 +02:00
Joren de Graaf 165a156bbf manual submission redesign phase B 2026-10-06 19:44:24 +02:00
Joren de Graaf 3884073241 manual submission redesign phase A 2026-10-06 19:39:57 +02:00
Joren de Graaf d86c7c9250 latest changes before manual submissions redesign 2026-10-06 19:31:30 +02:00
Joren de Graaf d427d73b8d browser audio detection phase 4 2026-10-02 21:45:24 +02:00
Joren de Graaf 9ff8bf8c26 browser audio detection phase 3 2026-10-02 21:34:38 +02:00
Joren de Graaf ff0d78ccba browser audio detection phase 2 2026-10-02 16:57:12 +02:00
Joren de Graaf df837c240f browser audio processing phase 1 2026-10-02 16:44:15 +02:00
Joren de Graaf e85fb408d4 sensors added to settings 2026-10-02 15:38:18 +02:00
Joren de Graaf ddcce61868 mobile menu added 2026-10-02 13:13:38 +02:00
Joren de Graaf 3b864f001d added translations 2026-10-01 22:43:45 +02:00
Joren de Graaf 2e36f26089 add dashboard to home 2026-10-01 17:29:29 +02:00
Joren de Graaf 278c5cd58c added light/dark mode toggle v1, unified menu 2026-10-01 17:14:19 +02:00
Joren de Graaf ac1b9bff0c added compass direction finding 2026-10-01 16:38:13 +02:00
Joren de Graaf 7ab01d3a77 latest changes 2026-09-29 12:12:46 +02:00
Joren de Graaf a4f3542e67 initial commit 2026-09-26 20:59:01 +02:00
686 changed files with 71993 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# Frontend development server
VITE_HOST=127.0.0.1
VITE_PORT=5173
VITE_DEV_SERVER_URL=http://127.0.0.1:5173/
# Development-only Vite base; keep this aligned with VITE_DEV_SERVER_URL.
VITE_DEV_BASE_URL=/
VITE_USE_DEV_SERVER=true
# Django development process (override the whole command for uv, docker, etc.)
DJANGO_HOST=127.0.0.1
DJANGO_PORT=8000
# DJANGO_DEV_COMMAND=python manage.py runserver 127.0.0.1:8000
# Vite discovers every .js file beneath VITE_ENTRY_DIR by default.
VITE_ENTRY_DIR=frontend/src/entries
# Production build output and Django static namespace
VITE_OUT_DIR=vite_integration/static/vite
VITE_STATIC_PREFIX=vite
# Must match Django STATIC_URL plus VITE_STATIC_PREFIX (for example, /static/vite/).
VITE_BASE_URL=/static/vite/
+3
View File
@@ -0,0 +1,3 @@
vite_integration/static/vite/*
!vite_integration/static/vite/.gitkeep
node_modules/
+245
View File
@@ -0,0 +1,245 @@
# Ntfy blueprint for a Django tasks and health tracker
This is a portable version of this project's `/settings` integration. It gives each user a topic URL, a test button, an enable switch, and one function that task or health code can call. Replace `accounts` with the app that owns your user preferences. The examples assume an authenticated `/settings/` page and Django's standard CSRF and messages middleware.
## 1. Store preferences
In `accounts/models.py` (merge these fields into an existing per-user settings model if you have one):
```python
from django.conf import settings
from django.db import models
class NotificationSettings(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ntfy_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
```
Run `python manage.py makemigrations accounts` and `python manage.py migrate`.
## 2. Add the sender
Create `notifications/services.py` (and an empty `notifications/__init__.py` if needed):
```python
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
class NotificationError(Exception):
"""A delivery error safe to display to a user."""
def send_ntfy_notification(url, title, message, timeout=10):
request = Request(
url,
data=message.encode("utf-8"),
headers={"Content-Type": "text/plain; charset=utf-8", "Title": title},
method="POST",
)
try:
with urlopen(request, timeout=timeout) as response:
status = response.getcode()
except HTTPError as error:
raise NotificationError(f"ntfy server responded with HTTP {error.code}.") from error
except (TimeoutError, socket.timeout):
raise NotificationError("Connection to the ntfy server timed out.") from None
except URLError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
except OSError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
if not 200 <= status < 300:
raise NotificationError(f"ntfy server responded with HTTP {status}.")
def send_notification(user, title, message):
from accounts.models import NotificationSettings
preferences = NotificationSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
return True
```
The URL is a destination and may contain a private topic name. Keep it out of logs and error messages. A user supplied server URL also lets the server make outbound requests; restrict destinations or allow only your trusted ntfy host if your deployment needs that boundary. Add authentication headers if your ntfy server requires them; this example uses a topic URL only.
## 3. Form, views, and routes
In `accounts/forms.py`:
```python
from django import forms
from .models import NotificationSettings
class NotificationSettingsForm(forms.ModelForm):
class Meta:
model = NotificationSettings
fields = ["ntfy_url", "ntfy_enabled"]
widgets = {"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"})}
def clean_ntfy_url(self):
return self.cleaned_data["ntfy_url"].strip()
def clean(self):
data = super().clean()
if data.get("ntfy_enabled") and not data.get("ntfy_url"):
self.add_error("ntfy_url", "Enter a topic URL before enabling notifications.")
return data
```
In `accounts/views.py`:
```python
from hashlib import sha256
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.decorators.http import require_POST
from notifications.services import NotificationError, send_ntfy_notification
from .forms import NotificationSettingsForm
from .models import NotificationSettings
def test_key(user):
return f"ntfy_tested_url_fingerprint:{user.pk}"
def fingerprint(url):
return sha256(url.encode("utf-8")).hexdigest()
@login_required
def settings_page(request):
preferences, _ = NotificationSettings.objects.get_or_create(user=request.user)
old_url = preferences.ntfy_url
form = NotificationSettingsForm(request.POST or None, instance=preferences)
if request.method == "POST" and form.is_valid():
url = form.cleaned_data["ntfy_url"]
just_tested = bool(url) and request.session.get(test_key(request.user)) == fingerprint(url)
previously_tested = url == old_url and preferences.ntfy_last_tested_at is not None
if form.cleaned_data["ntfy_enabled"] and not (just_tested or previously_tested):
form.add_error("ntfy_url", "Test this URL successfully before enabling notifications.")
else:
preferences = form.save(commit=False)
if not url:
preferences.ntfy_enabled = False
preferences.ntfy_last_tested_at = None
elif just_tested:
preferences.ntfy_last_tested_at = timezone.now()
elif url != old_url:
preferences.ntfy_last_tested_at = None
preferences.save()
request.session.pop(test_key(request.user), None)
messages.success(request, "Notification settings saved.")
return redirect("settings_page")
return render(request, "accounts/settings.html", {"form": form})
@login_required
@require_POST
def test_ntfy(request):
url = request.POST.get("ntfy_url", "").strip()
try:
URLValidator(schemes=["http", "https"])(url)
except ValidationError:
return render(request, "accounts/ntfy_test_result.html", {"error": "Enter a valid HTTP or HTTPS topic URL."}, status=400)
try:
send_ntfy_notification(url, "Tasks & Health", "Test notification sent successfully.")
except NotificationError as error:
return render(request, "accounts/ntfy_test_result.html", {"error": str(error)}, status=502)
request.session[test_key(request.user)] = fingerprint(url)
return render(request, "accounts/ntfy_test_result.html", {"success": True})
```
In `accounts/urls.py`, include these routes under `/settings/` in the project URLconf:
```python
from django.urls import path
from . import views
urlpatterns = [
path("", views.settings_page, name="settings_page"),
path("notifications/ntfy/test/", views.test_ntfy, name="ntfy_test"),
]
```
## 4. Settings UI
Put this section inside your existing `/settings/` template. It uses htmx for the inline test response; load htmx once in the page layout (or replace `hx-post` with a small `fetch` handler). Keep the CSRF input inside the form.
```html
<form method="post" action="{% url 'settings_page' %}">
{% csrf_token %}
<section aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Use a topic URL from your ntfy server. Test it before enabling notifications.</p>
<label for="ntfy-url">Topic URL</label>
{{ form.ntfy_url }} {{ form.ntfy_url.errors }}
<div class="check">
{{ form.ntfy_enabled }}
<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label>
</div>
<button type="button" hx-post="{% url 'ntfy_test' %}"
hx-include="#ntfy-url, [name='csrfmiddlewaretoken']"
hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
<div id="ntfy-test-result" aria-live="polite"></div>
</section>
<button type="submit">Save settings</button>
</form>
<script>
document.querySelector("#ntfy-url").addEventListener("input", () => {
document.querySelector("#ntfy-test-result").replaceChildren();
});
</script>
```
`accounts/ntfy_test_result.html`:
```html
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>
{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
```
Suggested CSS, scoped to your existing settings styles:
```css
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
.check { display: flex; gap: .6rem; align-items: center; }
.check label { margin: 0; }
.alert { margin-top: 1rem; padding: .75rem; border-radius: .55rem; }
.alert--success { color: #d1fae5; background: #14532d; }
.alert--error { color: #fee2e2; background: #7f1d1d; }
```
## 5. Trigger from tasks or health events
Call the provider agnostic `send_notification` after a meaningful state change. Put delivery on a background worker for normal operation, since the HTTP call can take up to ten seconds. Queue the job after the database commit so it cannot announce a rolled back change.
```python
from django.db import transaction
# After saving a task completion, missed deadline, check-in, or health alert:
user_id = task.user_id
task_id = task.pk
transaction.on_commit(lambda: enqueue_task_event_notification(user_id, task_id))
```
`enqueue_task_event_notification` is your existing Celery, RQ, or job queue entry point. In its worker, reload the user and task, confirm that the event still qualifies, then call `send_notification(user, "Task due", "Your task is due today.")`. Catch `NotificationError`, log a safe error without the topic URL, and retry according to your queue policy. Use an event ID or unique job key if duplicate delivery matters. If you have no worker yet, a management command run by cron can drain a small notification outbox instead.
Typical mapping for this app:
| App event | Suggested message | Trigger location |
| --- | --- | --- |
| Task due | “Your task is due today.” | Scheduled due-date job |
| Task completed | “Task completed.” | Completion service, after commit |
| Check-in missed | “Your daily check-in is still open.” | Scheduled reminder job |
| Health threshold crossed | “A tracked value crossed your chosen threshold.” | Threshold evaluator, after commit |
Avoid including sensitive health measurements in the notification unless the user explicitly opts in. Define the event's recipient and idempotency rule in the app service, rather than in the ntfy sender.
## 6. Minimum verification
Test an invalid URL, a failed test, a successful test followed by save, a changed URL requiring a new test, and disabled settings suppressing sends. Mock `urlopen` or `send_ntfy_notification`; do not send real notifications in tests. Check one actual device delivery manually with a private topic before enabling event triggers.
Source implementation in this repo: `members/views.py`, `members/forms.py`, `members/models.py`, `members/templates/members/user_settings.html`, `notifications/services.py`, and `fireworks_detect/signals.py`. The source app groups Pending events by minute with `PendingNotificationBatch` and a scheduled command; use that pattern if your tracker needs digest notifications.
+152
View File
@@ -0,0 +1,152 @@
# Portable Django + Vite integration
This repository originally used only Django native static files. The Vite integration below is now wired into the rendered public pages and custom Admin pages: shared assets live in `frontend/src/`, while Django still owns template rendering and its native static files.
## What is included
- `vite_integration/`: reusable Django app and `{% vite_asset %}` tag
- `frontend/src/entries/`: one Vite entry module per rendered page, with shared `styles/` and `scripts/` modules
- `vite.config.mjs`: Vite output, manifest, host, port, and entry configuration
- `package.json`: `dev`, `django`, `vite`, and `build` scripts
- `scripts/dev-django.mjs`: configurable backend process for `concurrently`
- `.env.vite.example`: documented development and production variables
Vite builds into `vite_integration/static/vite/`. Because this is a Django app static directory, Django's staticfiles finders and `collectstatic` discover the manifest and built assets automatically.
## Prerequisites
- Python and the Django environment for the project
- Node.js 20+ and npm
- A configured Django `STATIC_URL` and `STATIC_ROOT` for production
## Install in this repository
```sh
cp .env.vite.example .env.vite
npm install
set -a; . ./.env.vite; set +a
npm run dev
```
`npm run dev` starts Django and Vite together using `concurrently`. It runs `python manage.py runserver 127.0.0.1:8000` and Vite on `127.0.0.1:5173` by default. Change the variables before starting it, or set `DJANGO_DEV_COMMAND` to replace the backend command completely.
## Add an entry point to a template
Choose an entry point and include it once in the relevant base template:
```django
{% load vite %}
{% vite_asset "frontend/src/entries/site.js" %}
```
The tag renders Vite's HMR client and the entry point when `VITE_USE_DEV_SERVER=true`. Otherwise it reads Vite's manifest and renders the fingerprinted CSS and JavaScript under Django's static URL. See `vite_integration/templates/vite_integration/example_assets.html` for the same snippet.
## Production
```sh
set -a; . ./.env.vite; set +a
VITE_USE_DEV_SERVER=false npm run build
VITE_USE_DEV_SERVER=false python manage.py collectstatic --noinput
```
Build before `collectstatic`. The generated `vite/.vite/manifest.json` and `vite/assets/*` are collected with all other Django static files. Do not use the Vite development server in production.
## Reuse in a fresh Django project
Copy these files and directories:
```text
vite_integration/
frontend/src/
scripts/dev-django.mjs
vite.config.mjs
package.json
.env.vite.example
```
Create `frontend/src/entries/site.js` (or another entry beneath `VITE_ENTRY_DIR`) that imports the page CSS and JavaScript. Then add `vite_integration` to `INSTALLED_APPS`, add the template tag to a base template, configure `STATIC_URL`/`STATIC_ROOT`, install npm packages, and use the development or production commands above. The integration contains no application names, routes, or backend URLs.
## Configuration values to customize
| Variable/setting | Default | Purpose |
| --- | --- | --- |
| `DJANGO_DEV_COMMAND` | `python manage.py runserver <host>:<port>` | Complete backend development command |
| `DJANGO_HOST`, `DJANGO_PORT` | `127.0.0.1`, `8000` | Default backend bind address |
| `VITE_HOST`, `VITE_PORT` | `127.0.0.1`, `5173` | Vite bind address and port |
| `VITE_DEV_SERVER_URL` | `http://127.0.0.1:5173/` | URL Django templates use for HMR |
| `VITE_DEV_BASE_URL` | `/` | Development-only Vite base path |
| `VITE_USE_DEV_SERVER` | `false` | Enables HMR tags; set only for development |
| `VITE_ENTRY_DIR` | `frontend/src/entries` | Directory Vite scans for page entry points |
| `VITE_ENTRY` | unset | Optional comma-separated explicit entry point list |
| `VITE_OUT_DIR` | `vite_integration/static/vite` | Build output relative to project root |
| `VITE_STATIC_PREFIX` | `vite` | Django static namespace for built files |
| `VITE_BASE_URL` | `/static/vite/` | Public base URL emitted by Vite |
| `VITE_MANIFEST_PATH` | staticfiles finder | Optional explicit manifest location |
Django settings override environment variables with the same names. `VITE_BASE_URL` must equal the public `STATIC_URL` followed by `VITE_STATIC_PREFIX` (for example, `/static/vite/`). A `.env.vite` file is not automatically read by Django; export/source it in the process manager, shell, container, or deployment configuration.
## Troubleshooting
- **Vite manifest not found:** run `npm run build` before `collectstatic`; check that `VITE_OUT_DIR` ends below a Django app `static/` directory and that its final segment matches `VITE_STATIC_PREFIX`.
- **Browser cannot reach HMR:** set `VITE_DEV_SERVER_URL` to the browser-reachable Vite address, and use matching `VITE_HOST`/`VITE_PORT`. For containers or remote browsers this is often `0.0.0.0` for the host plus a public hostname for the URL.
- **A page fails in development:** set `VITE_USE_DEV_SERVER=true` only while `npm run vite` or `npm run dev` is running.
- **Assets return 404 after deployment:** rerun both the build and `collectstatic`; ensure the web server serves `STATIC_ROOT` at `STATIC_URL`.
## Interface translations
English text in templates and Python is the source language. Dutch translations live in `locale/nl/LC_MESSAGES/django.po`; the compiled `django.mo` is used at runtime. Logged-in users choose their language at `/settings/`. Visitors use the language switcher in the public navigation, which saves Django's standard language cookie. URLs and stored status or source codes do not change with the language.
Update translations after changing user-facing source text:
```bash
python manage.py makemessages -l nl --ignore=node_modules --ignore=staticfiles --ignore='*.orig'
# Edit locale/nl/LC_MESSAGES/django.po
python manage.py compilemessages
```
The small amount of JavaScript UI text is translated by Django in `templates/js_translations.html` and read from `window.BOOMCAST_I18N`. After changing JavaScript, run `npm run build` and `python manage.py collectstatic --noinput` for production. Classifier class names, API keys, sensor tokens, H3 values and stored source/status values remain language-neutral.
## Browser Processing Beta
The administrator setting `browser_processing_beta_enabled` is off by default.
When enabled, the upload form shows **Process recording in this browser (Beta)**,
which also starts off. With the user toggle off, ordinary audio uses the
existing server upload and classifier. With it on, selected audio is checked
locally and selected video is converted to 16 kHz mono WAV before the local
check. Files the user submits still run through the server classifier.
Switching back to server mode cancels browser work and clears the local gate.
The server upload endpoint currently accepts audio, so a video selected in
server mode requires an audio file or browser mode.
Browser assets are loaded only after the user enables the toggle and selects a
file. Regenerate the self-hosted model using [the YAMNet build guide](scripts/BROWSER_YAMNET.md),
then run `npm run build` and `python manage.py collectstatic --noinput`.
# Pending event notifications
Users can test and enable an ntfy topic in Settings. New Pending events are
counted by source (manual or sensor) in one-minute batches per enabled user.
Run `python manage.py send_pending_notifications` once per minute with the
application's Python environment and working directory. For example, a cron
entry can use `* * * * * cd /path/to/django && /path/to/python manage.py send_pending_notifications`.
It sends completed minute batches,
then removes them; failed deliveries remain queued for the next run.
For a systemd user timer on the laptop, install the units in
[`deploy/systemd/`](deploy/systemd/) and start the timer:
```sh
cd /home/jorenmartijn/python/django
/usr/bin/python3 -m venv /home/jorenmartijn/python/.venv-notifications
/home/jorenmartijn/python/.venv-notifications/bin/python -m pip install -r requirements.txt
/home/jorenmartijn/python/.venv-notifications/bin/python manage.py check
mkdir -p ~/.config/systemd/user
cp deploy/systemd/send-pending-notifications.service deploy/systemd/send-pending-notifications.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now send-pending-notifications.timer
systemctl --user list-timers send-pending-notifications.timer
```
The service runs `/home/jorenmartijn/python/.venv-notifications/bin/python` with this
project as its working directory. To keep the user timer running after logout,
run `sudo loginctl enable-linger jorenmartijn` once on the laptop. Check a run
with `journalctl --user -u send-pending-notifications.service -n 30`.
BIN
View File
Binary file not shown.
@@ -0,0 +1,7 @@
[Unit]
Description=Send batched Pending event ntfy notifications
[Service]
Type=oneshot
WorkingDirectory=/home/jorenmartijn/python/django
ExecStart=/home/jorenmartijn/python/.venv-notifications/bin/python /home/jorenmartijn/python/django/manage.py send_pending_notifications
@@ -0,0 +1,11 @@
[Unit]
Description=Send Pending event ntfy summaries every minute
[Timer]
OnCalendar=*-*-* *:*:00
AccuracySec=1s
Persistent=true
Unit=send-pending-notifications.service
[Install]
WantedBy=timers.target
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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+177
View File
@@ -0,0 +1,177 @@
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
from django.utils.translation import gettext as _, gettext_lazy, ngettext
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
from . import views as classifier_views
@admin.register(ClassificationRule)
class ClassificationRuleAdmin(admin.ModelAdmin):
list_display = ("value", "rule_type", "enabled")
list_filter = ("rule_type", "enabled")
search_fields = ("value",)
@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", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
list_filter = ("source_type", "visually_confirmed", "created_at")
search_fields = ("original_filename",)
readonly_fields = ("audio_file", "sensor", "h3_cell", "direction_display", "direction_accuracy_degrees", "original_filename", "created_at", "pretty_classifier_response")
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
@admin.display(description=gettext_lazy("Direction"))
def direction_display(self, obj):
return obj.direction_display
@admin.display(description=gettext_lazy("Classifier response"))
def pretty_classifier_response(self, obj):
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
@admin.register(PendingEvent)
class PendingEventAdmin(ClassificationAdmin):
actions = ("approve_selected", "deny_selected")
change_form_template = "admin/fireworks_detect/pending_change_form.html"
def get_urls(self):
custom_urls = [
path(
"<path:object_id>/classify/",
self.admin_site.admin_view(self.classify_record),
name="fireworks_detect_pendingevent_classify",
),
]
return custom_urls + super().get_urls()
def classify_record(self, request, object_id):
if request.method != "POST":
return HttpResponseNotAllowed(["POST"])
pending = get_object_or_404(PendingEvent, pk=object_id)
if not self.has_change_permission(request, pending):
raise PermissionDenied
change_url = reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk])
if not pending.audio_file:
self.message_user(request, _("This Pending event has no attached audio to classify."), messages.ERROR)
return redirect(change_url)
try:
if pending.audio_file.size > classifier_views.MAX_AUDIO_SIZE:
self.message_user(request, _("The attached audio exceeds the 25 MiB limit."), messages.ERROR)
return redirect(change_url)
with pending.audio_file.open("rb") as audio:
body, content_type = classifier_views._encode_audio_multipart(audio)
classifier_request = Request(
classifier_views.CLASSIFIER_URL,
data=body,
headers={"Content-Type": content_type, "Accept": "application/json"},
method="POST",
)
with urlopen(classifier_request, timeout=60) as response:
payload = json.loads(response.read().decode("utf-8"))
if not isinstance(payload, dict):
raise ValueError("Classifier response must be a JSON object")
except HTTPError as error:
self.message_user(request, _("The classifier returned HTTP %(code)s.") % {"code": error.code}, messages.ERROR)
return redirect(change_url)
except (URLError, TimeoutError, OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError):
self.message_user(request, _("The classifier could not be reached or returned invalid JSON."), messages.ERROR)
return redirect(change_url)
previous_response = pending.classifier_response if isinstance(pending.classifier_response, dict) else {}
pending.classifier_response = {**previous_response, **payload}
pending.save(update_fields=["classifier_response"])
self.message_user(request, _("Classification saved. This event remains Pending."), messages.SUCCESS)
return redirect(change_url)
def has_add_permission(self, request):
return False
@admin.action(description=gettext_lazy("Approve selected samples and move them to Events"))
def approve_selected(self, request, queryset):
approved = 0
for pending in queryset:
pending.approve()
approved += 1
self.message_user(request, ngettext("%(count)d sample approved and moved to Events.", "%(count)d samples approved and moved to Events.", approved) % {"count": approved}, messages.SUCCESS)
@admin.action(description=gettext_lazy("Deny selected samples and delete their uploaded audio"))
def deny_selected(self, request, queryset):
denied = 0
for pending in queryset:
pending.deny()
denied += 1
self.message_user(request, ngettext("%(count)d sample denied and removed.", "%(count)d samples denied and removed.", denied) % {"count": denied}, messages.WARNING)
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
fields = ClassificationAdmin.fields + ("approved_at",)
def has_add_permission(self, request):
return False
@admin.register(Sensor)
class SensorAdmin(admin.ModelAdmin):
list_display = ("name", "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)
+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
+8
View File
@@ -0,0 +1,8 @@
from django.apps import AppConfig
class FireworksDetectConfig(AppConfig):
name = 'fireworks_detect'
def ready(self):
from . import signals # noqa: F401
+84
View File
@@ -0,0 +1,84 @@
"""Public, advisory configuration for the optional browser processing beta."""
import json
from pathlib import Path
from django.templatetags.static import static
from django.urls import reverse
from .models import BrowserProcessingSettings, ClassificationRule
POLICY_VERSION = 1
SPEECH_LABEL_TERMS = (
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
"speaking", "speech synthesizer",
)
GATE_RESULTS = {"whitelist_match", "speech_only", "no_match", "unavailable", "error"}
RELEVANCE_THRESHOLD = 0.5
SPEECH_THRESHOLD = 0.5
MODEL_VERSION = "google-yamnet-1"
def browser_config():
"""Keep template configuration in one small, non-secret object."""
return {
"browserProcessingBeta": BrowserProcessingSettings.enabled(),
"policyUrl": reverse("fireworks_detect:browser_policy"),
"policyVersion": POLICY_VERSION,
}
def browser_policy():
enabled = BrowserProcessingSettings.enabled()
policy = {
"version": POLICY_VERSION,
"browser_processing_beta_enabled": enabled,
"whitelist": [],
"privacy_sensitive_speech": [],
"thresholds": {},
"model_version": MODEL_VERSION,
"model_url": "",
"class_map_url": "",
}
if not enabled:
return policy
rules = ClassificationRule.objects.filter(enabled=True).order_by("value")
policy["whitelist"] = list(rules.filter(rule_type=ClassificationRule.RuleType.WHITELIST).values_list("value", flat=True))
class_map_path = Path(__file__).parent / "static/browser-yamnet/yamnet_class_map.json"
class_names = json.loads(class_map_path.read_text(encoding="utf-8"))
speech_classes = {name for name in class_names if any(term in name.lower() for term in SPEECH_LABEL_TERMS)}
speech_classes.update(value for value in rules.filter(rule_type=ClassificationRule.RuleType.BLACKLIST).values_list("value", flat=True)
if any(term in value.lower() for term in SPEECH_LABEL_TERMS))
policy["privacy_sensitive_speech"] = sorted(speech_classes)
policy["thresholds"] = {"relevance": RELEVANCE_THRESHOLD, "speech": SPEECH_THRESHOLD}
policy["model_url"] = static("browser-yamnet/model.json")
policy["class_map_url"] = static("browser-yamnet/yamnet_class_map.json")
return policy
def advisory_browser_metadata(post_data):
"""Parse bounded diagnostics; never use this to authorize or classify audio."""
raw = post_data.get("browser_processing_metadata", "")
if not raw or len(raw) > 1024:
return {}
try:
submitted = json.loads(raw)
except (TypeError, ValueError):
return {}
if not isinstance(submitted, dict):
return {}
metadata = {}
for key in ("browser_processing_used", "browser_override"):
if type(submitted.get(key)) is bool:
metadata[key] = submitted[key]
version = submitted.get("browser_processing_version")
if type(version) is int and 0 < version <= POLICY_VERSION:
metadata["browser_processing_version"] = version
gate_result = submitted.get("browser_gate_result")
if isinstance(gate_result, str) and gate_result in GATE_RESULTS:
metadata["browser_gate_result"] = gate_result
speech = submitted.get("browser_speech_detected")
if type(speech) is bool:
metadata["browser_speech_detected"] = speech
return metadata
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from .views import classification_blacklist, classification_whitelist
app_name = "classification_rules"
urlpatterns = [
path("whitelist/", classification_whitelist, name="whitelist"),
path("blacklist/", classification_blacklist, name="blacklist"),
]
+42
View File
@@ -0,0 +1,42 @@
import h3
from django.conf import settings
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
def h3_resolution():
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
return resolution
def cell_from_coordinates(latitude, longitude):
if latitude is None or longitude is None:
return None
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
def cell_boundary(cell):
try:
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
except (ValueError, h3.H3Error):
return None
def cell_center(cell):
"""Return the centre of an H3 cell without exposing its source coordinate."""
try:
latitude, longitude = h3.cell_to_latlng(cell)
return [latitude, longitude]
except (ValueError, h3.H3Error):
return None
def cell_disk(cell, distance=1):
try:
return sorted(h3.grid_disk(cell, distance))
except (ValueError, h3.H3Error):
return []
+33
View File
@@ -0,0 +1,33 @@
import h3
from django.conf import settings
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
def h3_resolution():
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
return resolution
def cell_from_coordinates(latitude, longitude):
if latitude is None or longitude is None:
return None
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
def cell_boundary(cell):
try:
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
except (ValueError, h3.H3Error):
return None
def cell_disk(cell, distance=1):
try:
return sorted(h3.grid_disk(cell, distance))
except (ValueError, h3.H3Error):
return []
+1
View File
@@ -0,0 +1 @@
"""Management commands for fireworks detection."""
@@ -0,0 +1 @@
"""Fireworks detection management commands."""
@@ -0,0 +1,25 @@
from django.core.management.base import BaseCommand
from fireworks_detect.h3_utils import cell_from_coordinates, h3_resolution
from fireworks_detect.models import Event, PendingEvent
class Command(BaseCommand):
help = "Populate H3 cells for coordinate-bearing Pending and approved events."
def handle(self, *args, **options):
updated = 0
for model in (PendingEvent, Event):
for record in model.objects.exclude(latitude__isnull=True).exclude(longitude__isnull=True):
h3_cell = cell_from_coordinates(record.latitude, record.longitude)
if record.h3_cell == h3_cell:
continue
record.h3_cell = h3_cell
record.save(update_fields=["h3_cell"])
updated += 1
self.stdout.write(
self.style.SUCCESS(
f"Updated {updated} record(s) at H3 resolution {h3_resolution()}."
)
)
@@ -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'),
),
]
@@ -0,0 +1,35 @@
# Generated by Django 6.1.1 on 2026-09-29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0002_sensor_event_sensor_pendingevent_sensor"),
]
operations = [
migrations.CreateModel(
name="ClassificationRule",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("value", models.CharField(max_length=255)),
(
"rule_type",
models.CharField(
choices=[("whitelist", "Whitelist"), ("blacklist", "Blacklist")],
max_length=10,
),
),
("enabled", models.BooleanField(default=True)),
],
options={
"ordering": ["value"],
},
),
migrations.AddConstraint(
model_name="classificationrule",
constraint=models.UniqueConstraint(fields=("value", "rule_type"), name="unique_classification_rule"),
),
]
@@ -0,0 +1,63 @@
# Generated by Django 6.1.1 on 2026-09-29 20:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0003_classificationrule'),
]
operations = [
migrations.AddField(
model_name='event',
name='location',
field=models.CharField(blank=True, max_length=255),
),
migrations.AddField(
model_name='event',
name='occurrences',
field=models.PositiveIntegerField(default=1),
),
migrations.AddField(
model_name='event',
name='source_type',
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
),
migrations.AddField(
model_name='event',
name='visually_confirmed',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pendingevent',
name='location',
field=models.CharField(blank=True, max_length=255),
),
migrations.AddField(
model_name='pendingevent',
name='occurrences',
field=models.PositiveIntegerField(default=1),
),
migrations.AddField(
model_name='pendingevent',
name='source_type',
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
),
migrations.AddField(
model_name='pendingevent',
name='visually_confirmed',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='event',
name='audio_file',
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
),
migrations.AlterField(
model_name='pendingevent',
name='audio_file',
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
),
]
@@ -0,0 +1,33 @@
# Generated by Django 6.1.1 on 2026-09-29 21:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0004_event_location_event_occurrences_event_source_type_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='latitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='event',
name='longitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='latitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='longitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
]
@@ -0,0 +1,23 @@
# Generated by Django 6.1.1 on 2026-09-29 21:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0005_event_latitude_event_longitude_pendingevent_latitude_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='h3_cell',
field=models.CharField(blank=True, db_index=True, max_length=20),
),
migrations.AddField(
model_name='pendingevent',
name='h3_cell',
field=models.CharField(blank=True, db_index=True, max_length=20),
),
]
@@ -0,0 +1,43 @@
# Generated by Django 6.1.1 on 2026-09-30 07:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0006_event_h3_cell_pendingevent_h3_cell'),
]
operations = [
migrations.AddField(
model_name='event',
name='direction_accuracy_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='direction_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='direction_source',
field=models.CharField(blank=True, max_length=32),
),
migrations.AddField(
model_name='pendingevent',
name='direction_accuracy_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='direction_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='direction_source',
field=models.CharField(blank=True, max_length=32),
),
]
@@ -0,0 +1,23 @@
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0007_event_direction_accuracy_degrees_and_more"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name="sensor",
name="owner",
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="sensors", to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name="sensor",
name="archived_at",
field=models.DateTimeField(blank=True, editable=False, null=True),
),
]
@@ -0,0 +1,24 @@
# Generated by Django 6.1.1 on 2026-10-02 14:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0008_sensor_owner_sensor_archived_at'),
]
operations = [
migrations.CreateModel(
name='BrowserProcessingSettings',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('browser_processing_beta_enabled', models.BooleanField(default=False)),
],
options={
'verbose_name': 'Browser-side media processing (Beta)',
'verbose_name_plural': 'Browser-side media processing (Beta)',
},
),
]
@@ -0,0 +1,16 @@
from django.db import migrations
def create_disabled_settings(apps, schema_editor):
Settings = apps.get_model("fireworks_detect", "BrowserProcessingSettings")
Settings.objects.get_or_create(pk=1, defaults={"browser_processing_beta_enabled": False})
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0009_browserprocessingsettings"),
]
operations = [
migrations.RunPython(create_disabled_settings, migrations.RunPython.noop),
]
+260
View File
@@ -0,0 +1,260 @@
import math
import secrets
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.db import models, transaction
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
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."))
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name="sensors")
is_active = models.BooleanField(default=True)
archived_at = models.DateTimeField(null=True, blank=True, editable=False)
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 heartbeat_status(self):
if not self.last_heartbeat:
return "never", _("Never seen")
age = (timezone.now() - self.last_heartbeat).total_seconds()
if age <= 300:
return "online", _("Online")
if age <= 900:
return "delayed", _("Delayed")
return "offline", _("Offline")
def archive(self):
self.archived_at = timezone.now()
self.is_active = False
self.token_hash = ""
self.token_prefix = ""
self.save(update_fields=["archived_at", "is_active", "token_hash", "token_prefix"])
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 ClassificationRule(models.Model):
"""A configurable inclusion or exclusion rule for a classification label."""
class RuleType(models.TextChoices):
WHITELIST = "whitelist", _("Whitelist")
BLACKLIST = "blacklist", _("Blacklist")
value = models.CharField(max_length=255)
rule_type = models.CharField(max_length=10, choices=RuleType.choices)
enabled = models.BooleanField(default=True)
class Meta:
ordering = ["value"]
constraints = [
models.UniqueConstraint(fields=["value", "rule_type"], name="unique_classification_rule"),
]
def __str__(self):
return f"{self.value} ({self.get_rule_type_display()})"
class BrowserProcessingSettings(models.Model):
"""Single site-wide switch for experimental browser processing."""
browser_processing_beta_enabled = models.BooleanField(default=False)
class Meta:
verbose_name = _("Browser-side media processing (Beta)")
verbose_name_plural = _("Browser-side media processing (Beta)")
def save(self, *args, **kwargs):
self.pk = 1
return super().save(*args, **kwargs)
@classmethod
def enabled(cls):
return bool(cls.objects.filter(pk=1).values_list("browser_processing_beta_enabled", flat=True).first())
def __str__(self):
return str(_("Browser-side media processing (Beta)"))
class ClassifiedAudio(models.Model):
"""Shared fields for a classifier response and its original audio upload."""
class SourceType(models.TextChoices):
SENSOR = "sensor", _("Sensor")
MANUAL = "manual", _("Manual report")
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d", blank=True)
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()
source_type = models.CharField(max_length=10, choices=SourceType.choices, default=SourceType.SENSOR)
occurrences = models.PositiveIntegerField(default=1)
location = models.CharField(max_length=255, blank=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
h3_cell = models.CharField(max_length=20, blank=True, db_index=True)
visually_confirmed = models.BooleanField(default=False)
direction_degrees = models.FloatField(null=True, blank=True)
direction_accuracy_degrees = models.FloatField(null=True, blank=True)
direction_source = models.CharField(max_length=32, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
ordering = ["-created_at"]
def __str__(self):
return self.original_filename
def clean(self):
super().clean()
errors = {}
if self.direction_degrees is not None and (
not math.isfinite(self.direction_degrees) or not 0 <= self.direction_degrees < 360
):
errors["direction_degrees"] = _("Direction must be a finite value from 0 up to, but not including, 360 degrees.")
if self.direction_accuracy_degrees is not None and (
not math.isfinite(self.direction_accuracy_degrees) or self.direction_accuracy_degrees < 0
):
errors["direction_accuracy_degrees"] = _("Compass accuracy must be a finite, non-negative value.")
if errors:
raise ValidationError(errors)
@property
def direction_cardinal(self):
if self.direction_degrees is None:
return None
directions = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
return directions[int((self.direction_degrees + 22.5) % 360 // 45)]
@property
def direction_display(self):
if self.direction_degrees is None:
return "—"
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
@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,
source_type=self.source_type,
occurrences=self.occurrences,
location=self.location,
latitude=self.latitude,
longitude=self.longitude,
h3_cell=self.h3_cell,
visually_confirmed=self.visually_confirmed,
direction_degrees=self.direction_degrees,
direction_accuracy_degrees=self.direction_accuracy_degrees,
direction_source=self.direction_source,
)
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"
+19
View File
@@ -0,0 +1,19 @@
from django.db.models import F
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from members.models import PendingNotificationBatch, UserSettings
from .models import PendingEvent
@receiver(post_save, sender=PendingEvent)
def count_new_pending_event(sender, instance, created, **kwargs):
if not created:
return
minute = timezone.now().replace(second=0, microsecond=0)
field = "manual_count" if instance.source_type == PendingEvent.SourceType.MANUAL else "sensor_count"
for user_id in UserSettings.objects.filter(ntfy_enabled=True).exclude(ntfy_url="").values_list("user_id", flat=True):
batch, _ = PendingNotificationBatch.objects.get_or_create(user_id=user_id, minute=minute)
PendingNotificationBatch.objects.filter(pk=batch.pk).update(**{field: F(field) + 1})
@@ -0,0 +1,3 @@
google-yamnet-1
source_revision=c651073789719ff39dcf51406733bbcaaafb43f2
tensorflow=2.21.0
File diff suppressed because one or more lines are too long
@@ -0,0 +1,522 @@
index,mid,display_name
0,/m/09x0r,Speech
1,/m/0ytgt,"Child speech, kid speaking"
2,/m/01h8n0,Conversation
3,/m/02qldy,"Narration, monologue"
4,/m/0261r1,Babbling
5,/m/0brhx,Speech synthesizer
6,/m/07p6fty,Shout
7,/m/07q4ntr,Bellow
8,/m/07rwj3x,Whoop
9,/m/07sr1lc,Yell
10,/t/dd00135,Children shouting
11,/m/03qc9zr,Screaming
12,/m/02rtxlg,Whispering
13,/m/01j3sz,Laughter
14,/t/dd00001,Baby laughter
15,/m/07r660_,Giggle
16,/m/07s04w4,Snicker
17,/m/07sq110,Belly laugh
18,/m/07rgt08,"Chuckle, chortle"
19,/m/0463cq4,"Crying, sobbing"
20,/t/dd00002,"Baby cry, infant cry"
21,/m/07qz6j3,Whimper
22,/m/07qw_06,"Wail, moan"
23,/m/07plz5l,Sigh
24,/m/015lz1,Singing
25,/m/0l14jd,Choir
26,/m/01swy6,Yodeling
27,/m/02bk07,Chant
28,/m/01c194,Mantra
29,/t/dd00005,Child singing
30,/t/dd00006,Synthetic singing
31,/m/06bxc,Rapping
32,/m/02fxyj,Humming
33,/m/07s2xch,Groan
34,/m/07r4k75,Grunt
35,/m/01w250,Whistling
36,/m/0lyf6,Breathing
37,/m/07mzm6,Wheeze
38,/m/01d3sd,Snoring
39,/m/07s0dtb,Gasp
40,/m/07pyy8b,Pant
41,/m/07q0yl5,Snort
42,/m/01b_21,Cough
43,/m/0dl9sf8,Throat clearing
44,/m/01hsr_,Sneeze
45,/m/07ppn3j,Sniff
46,/m/06h7j,Run
47,/m/07qv_x_,Shuffle
48,/m/07pbtc8,"Walk, footsteps"
49,/m/03cczk,"Chewing, mastication"
50,/m/07pdhp0,Biting
51,/m/0939n_,Gargling
52,/m/01g90h,Stomach rumble
53,/m/03q5_w,"Burping, eructation"
54,/m/02p3nc,Hiccup
55,/m/02_nn,Fart
56,/m/0k65p,Hands
57,/m/025_jnm,Finger snapping
58,/m/0l15bq,Clapping
59,/m/01jg02,"Heart sounds, heartbeat"
60,/m/01jg1z,Heart murmur
61,/m/053hz1,Cheering
62,/m/028ght,Applause
63,/m/07rkbfh,Chatter
64,/m/03qtwd,Crowd
65,/m/07qfr4h,"Hubbub, speech noise, speech babble"
66,/t/dd00013,Children playing
67,/m/0jbk,Animal
68,/m/068hy,"Domestic animals, pets"
69,/m/0bt9lr,Dog
70,/m/05tny_,Bark
71,/m/07r_k2n,Yip
72,/m/07qf0zm,Howl
73,/m/07rc7d9,Bow-wow
74,/m/0ghcn6,Growling
75,/t/dd00136,Whimper (dog)
76,/m/01yrx,Cat
77,/m/02yds9,Purr
78,/m/07qrkrw,Meow
79,/m/07rjwbb,Hiss
80,/m/07r81j2,Caterwaul
81,/m/0ch8v,"Livestock, farm animals, working animals"
82,/m/03k3r,Horse
83,/m/07rv9rh,Clip-clop
84,/m/07q5rw0,"Neigh, whinny"
85,/m/01xq0k1,"Cattle, bovinae"
86,/m/07rpkh9,Moo
87,/m/0239kh,Cowbell
88,/m/068zj,Pig
89,/t/dd00018,Oink
90,/m/03fwl,Goat
91,/m/07q0h5t,Bleat
92,/m/07bgp,Sheep
93,/m/025rv6n,Fowl
94,/m/09b5t,"Chicken, rooster"
95,/m/07st89h,Cluck
96,/m/07qn5dc,"Crowing, cock-a-doodle-doo"
97,/m/01rd7k,Turkey
98,/m/07svc2k,Gobble
99,/m/09ddx,Duck
100,/m/07qdb04,Quack
101,/m/0dbvp,Goose
102,/m/07qwf61,Honk
103,/m/01280g,Wild animals
104,/m/0cdnk,"Roaring cats (lions, tigers)"
105,/m/04cvmfc,Roar
106,/m/015p6,Bird
107,/m/020bb7,"Bird vocalization, bird call, bird song"
108,/m/07pggtn,"Chirp, tweet"
109,/m/07sx8x_,Squawk
110,/m/0h0rv,"Pigeon, dove"
111,/m/07r_25d,Coo
112,/m/04s8yn,Crow
113,/m/07r5c2p,Caw
114,/m/09d5_,Owl
115,/m/07r_80w,Hoot
116,/m/05_wcq,"Bird flight, flapping wings"
117,/m/01z5f,"Canidae, dogs, wolves"
118,/m/06hps,"Rodents, rats, mice"
119,/m/04rmv,Mouse
120,/m/07r4gkf,Patter
121,/m/03vt0,Insect
122,/m/09xqv,Cricket
123,/m/09f96,Mosquito
124,/m/0h2mp,"Fly, housefly"
125,/m/07pjwq1,Buzz
126,/m/01h3n,"Bee, wasp, etc."
127,/m/09ld4,Frog
128,/m/07st88b,Croak
129,/m/078jl,Snake
130,/m/07qn4z3,Rattle
131,/m/032n05,Whale vocalization
132,/m/04rlf,Music
133,/m/04szw,Musical instrument
134,/m/0fx80y,Plucked string instrument
135,/m/0342h,Guitar
136,/m/02sgy,Electric guitar
137,/m/018vs,Bass guitar
138,/m/042v_gx,Acoustic guitar
139,/m/06w87,"Steel guitar, slide guitar"
140,/m/01glhc,Tapping (guitar technique)
141,/m/07s0s5r,Strum
142,/m/018j2,Banjo
143,/m/0jtg0,Sitar
144,/m/04rzd,Mandolin
145,/m/01bns_,Zither
146,/m/07xzm,Ukulele
147,/m/05148p4,Keyboard (musical)
148,/m/05r5c,Piano
149,/m/01s0ps,Electric piano
150,/m/013y1f,Organ
151,/m/03xq_f,Electronic organ
152,/m/03gvt,Hammond organ
153,/m/0l14qv,Synthesizer
154,/m/01v1d8,Sampler
155,/m/03q5t,Harpsichord
156,/m/0l14md,Percussion
157,/m/02hnl,Drum kit
158,/m/0cfdd,Drum machine
159,/m/026t6,Drum
160,/m/06rvn,Snare drum
161,/m/03t3fj,Rimshot
162,/m/02k_mr,Drum roll
163,/m/0bm02,Bass drum
164,/m/011k_j,Timpani
165,/m/01p970,Tabla
166,/m/01qbl,Cymbal
167,/m/03qtq,Hi-hat
168,/m/01sm1g,Wood block
169,/m/07brj,Tambourine
170,/m/05r5wn,Rattle (instrument)
171,/m/0xzly,Maraca
172,/m/0mbct,Gong
173,/m/016622,Tubular bells
174,/m/0j45pbj,Mallet percussion
175,/m/0dwsp,"Marimba, xylophone"
176,/m/0dwtp,Glockenspiel
177,/m/0dwt5,Vibraphone
178,/m/0l156b,Steelpan
179,/m/05pd6,Orchestra
180,/m/01kcd,Brass instrument
181,/m/0319l,French horn
182,/m/07gql,Trumpet
183,/m/07c6l,Trombone
184,/m/0l14_3,Bowed string instrument
185,/m/02qmj0d,String section
186,/m/07y_7,"Violin, fiddle"
187,/m/0d8_n,Pizzicato
188,/m/01xqw,Cello
189,/m/02fsn,Double bass
190,/m/085jw,"Wind instrument, woodwind instrument"
191,/m/0l14j_,Flute
192,/m/06ncr,Saxophone
193,/m/01wy6,Clarinet
194,/m/03m5k,Harp
195,/m/0395lw,Bell
196,/m/03w41f,Church bell
197,/m/027m70_,Jingle bell
198,/m/0gy1t2s,Bicycle bell
199,/m/07n_g,Tuning fork
200,/m/0f8s22,Chime
201,/m/026fgl,Wind chime
202,/m/0150b9,Change ringing (campanology)
203,/m/03qjg,Harmonica
204,/m/0mkg,Accordion
205,/m/0192l,Bagpipes
206,/m/02bxd,Didgeridoo
207,/m/0l14l2,Shofar
208,/m/07kc_,Theremin
209,/m/0l14t7,Singing bowl
210,/m/01hgjl,Scratching (performance technique)
211,/m/064t9,Pop music
212,/m/0glt670,Hip hop music
213,/m/02cz_7,Beatboxing
214,/m/06by7,Rock music
215,/m/03lty,Heavy metal
216,/m/05r6t,Punk rock
217,/m/0dls3,Grunge
218,/m/0dl5d,Progressive rock
219,/m/07sbbz2,Rock and roll
220,/m/05w3f,Psychedelic rock
221,/m/06j6l,Rhythm and blues
222,/m/0gywn,Soul music
223,/m/06cqb,Reggae
224,/m/01lyv,Country
225,/m/015y_n,Swing music
226,/m/0gg8l,Bluegrass
227,/m/02x8m,Funk
228,/m/02w4v,Folk music
229,/m/06j64v,Middle Eastern music
230,/m/03_d0,Jazz
231,/m/026z9,Disco
232,/m/0ggq0m,Classical music
233,/m/05lls,Opera
234,/m/02lkt,Electronic music
235,/m/03mb9,House music
236,/m/07gxw,Techno
237,/m/07s72n,Dubstep
238,/m/0283d,Drum and bass
239,/m/0m0jc,Electronica
240,/m/08cyft,Electronic dance music
241,/m/0fd3y,Ambient music
242,/m/07lnk,Trance music
243,/m/0g293,Music of Latin America
244,/m/0ln16,Salsa music
245,/m/0326g,Flamenco
246,/m/0155w,Blues
247,/m/05fw6t,Music for children
248,/m/02v2lh,New-age music
249,/m/0y4f8,Vocal music
250,/m/0z9c,A capella
251,/m/0164x2,Music of Africa
252,/m/0145m,Afrobeat
253,/m/02mscn,Christian music
254,/m/016cjb,Gospel music
255,/m/028sqc,Music of Asia
256,/m/015vgc,Carnatic music
257,/m/0dq0md,Music of Bollywood
258,/m/06rqw,Ska
259,/m/02p0sh1,Traditional music
260,/m/05rwpb,Independent music
261,/m/074ft,Song
262,/m/025td0t,Background music
263,/m/02cjck,Theme music
264,/m/03r5q_,Jingle (music)
265,/m/0l14gg,Soundtrack music
266,/m/07pkxdp,Lullaby
267,/m/01z7dr,Video game music
268,/m/0140xf,Christmas music
269,/m/0ggx5q,Dance music
270,/m/04wptg,Wedding music
271,/t/dd00031,Happy music
272,/t/dd00033,Sad music
273,/t/dd00034,Tender music
274,/t/dd00035,Exciting music
275,/t/dd00036,Angry music
276,/t/dd00037,Scary music
277,/m/03m9d0z,Wind
278,/m/09t49,Rustling leaves
279,/t/dd00092,Wind noise (microphone)
280,/m/0jb2l,Thunderstorm
281,/m/0ngt1,Thunder
282,/m/0838f,Water
283,/m/06mb1,Rain
284,/m/07r10fb,Raindrop
285,/t/dd00038,Rain on surface
286,/m/0j6m2,Stream
287,/m/0j2kx,Waterfall
288,/m/05kq4,Ocean
289,/m/034srq,"Waves, surf"
290,/m/06wzb,Steam
291,/m/07swgks,Gurgling
292,/m/02_41,Fire
293,/m/07pzfmf,Crackle
294,/m/07yv9,Vehicle
295,/m/019jd,"Boat, Water vehicle"
296,/m/0hsrw,"Sailboat, sailing ship"
297,/m/056ks2,"Rowboat, canoe, kayak"
298,/m/02rlv9,"Motorboat, speedboat"
299,/m/06q74,Ship
300,/m/012f08,Motor vehicle (road)
301,/m/0k4j,Car
302,/m/0912c9,"Vehicle horn, car horn, honking"
303,/m/07qv_d5,Toot
304,/m/02mfyn,Car alarm
305,/m/04gxbd,"Power windows, electric windows"
306,/m/07rknqz,Skidding
307,/m/0h9mv,Tire squeal
308,/t/dd00134,Car passing by
309,/m/0ltv,"Race car, auto racing"
310,/m/07r04,Truck
311,/m/0gvgw0,Air brake
312,/m/05x_td,"Air horn, truck horn"
313,/m/02rhddq,Reversing beeps
314,/m/03cl9h,"Ice cream truck, ice cream van"
315,/m/01bjv,Bus
316,/m/03j1ly,Emergency vehicle
317,/m/04qvtq,Police car (siren)
318,/m/012n7d,Ambulance (siren)
319,/m/012ndj,"Fire engine, fire truck (siren)"
320,/m/04_sv,Motorcycle
321,/m/0btp2,"Traffic noise, roadway noise"
322,/m/06d_3,Rail transport
323,/m/07jdr,Train
324,/m/04zmvq,Train whistle
325,/m/0284vy3,Train horn
326,/m/01g50p,"Railroad car, train wagon"
327,/t/dd00048,Train wheels squealing
328,/m/0195fx,"Subway, metro, underground"
329,/m/0k5j,Aircraft
330,/m/014yck,Aircraft engine
331,/m/04229,Jet engine
332,/m/02l6bg,"Propeller, airscrew"
333,/m/09ct_,Helicopter
334,/m/0cmf2,"Fixed-wing aircraft, airplane"
335,/m/0199g,Bicycle
336,/m/06_fw,Skateboard
337,/m/02mk9,Engine
338,/t/dd00065,Light engine (high frequency)
339,/m/08j51y,"Dental drill, dentist's drill"
340,/m/01yg9g,Lawn mower
341,/m/01j4z9,Chainsaw
342,/t/dd00066,Medium engine (mid frequency)
343,/t/dd00067,Heavy engine (low frequency)
344,/m/01h82_,Engine knocking
345,/t/dd00130,Engine starting
346,/m/07pb8fc,Idling
347,/m/07q2z82,"Accelerating, revving, vroom"
348,/m/02dgv,Door
349,/m/03wwcy,Doorbell
350,/m/07r67yg,Ding-dong
351,/m/02y_763,Sliding door
352,/m/07rjzl8,Slam
353,/m/07r4wb8,Knock
354,/m/07qcpgn,Tap
355,/m/07q6cd_,Squeak
356,/m/0642b4,Cupboard open or close
357,/m/0fqfqc,Drawer open or close
358,/m/04brg2,"Dishes, pots, and pans"
359,/m/023pjk,"Cutlery, silverware"
360,/m/07pn_8q,Chopping (food)
361,/m/0dxrf,Frying (food)
362,/m/0fx9l,Microwave oven
363,/m/02pjr4,Blender
364,/m/02jz0l,"Water tap, faucet"
365,/m/0130jx,Sink (filling or washing)
366,/m/03dnzn,Bathtub (filling or washing)
367,/m/03wvsk,Hair dryer
368,/m/01jt3m,Toilet flush
369,/m/012xff,Toothbrush
370,/m/04fgwm,Electric toothbrush
371,/m/0d31p,Vacuum cleaner
372,/m/01s0vc,Zipper (clothing)
373,/m/03v3yw,Keys jangling
374,/m/0242l,Coin (dropping)
375,/m/01lsmm,Scissors
376,/m/02g901,"Electric shaver, electric razor"
377,/m/05rj2,Shuffling cards
378,/m/0316dw,Typing
379,/m/0c2wf,Typewriter
380,/m/01m2v,Computer keyboard
381,/m/081rb,Writing
382,/m/07pp_mv,Alarm
383,/m/07cx4,Telephone
384,/m/07pp8cl,Telephone bell ringing
385,/m/01hnzm,Ringtone
386,/m/02c8p,"Telephone dialing, DTMF"
387,/m/015jpf,Dial tone
388,/m/01z47d,Busy signal
389,/m/046dlr,Alarm clock
390,/m/03kmc9,Siren
391,/m/0dgbq,Civil defense siren
392,/m/030rvx,Buzzer
393,/m/01y3hg,"Smoke detector, smoke alarm"
394,/m/0c3f7m,Fire alarm
395,/m/04fq5q,Foghorn
396,/m/0l156k,Whistle
397,/m/06hck5,Steam whistle
398,/t/dd00077,Mechanisms
399,/m/02bm9n,"Ratchet, pawl"
400,/m/01x3z,Clock
401,/m/07qjznt,Tick
402,/m/07qjznl,Tick-tock
403,/m/0l7xg,Gears
404,/m/05zc1,Pulleys
405,/m/0llzx,Sewing machine
406,/m/02x984l,Mechanical fan
407,/m/025wky1,Air conditioning
408,/m/024dl,Cash register
409,/m/01m4t,Printer
410,/m/0dv5r,Camera
411,/m/07bjf,Single-lens reflex camera
412,/m/07k1x,Tools
413,/m/03l9g,Hammer
414,/m/03p19w,Jackhammer
415,/m/01b82r,Sawing
416,/m/02p01q,Filing (rasp)
417,/m/023vsd,Sanding
418,/m/0_ksk,Power tool
419,/m/01d380,Drill
420,/m/014zdl,Explosion
421,/m/032s66,"Gunshot, gunfire"
422,/m/04zjc,Machine gun
423,/m/02z32qm,Fusillade
424,/m/0_1c,Artillery fire
425,/m/073cg4,Cap gun
426,/m/0g6b5,Fireworks
427,/g/122z_qxw,Firecracker
428,/m/07qsvvw,"Burst, pop"
429,/m/07pxg6y,Eruption
430,/m/07qqyl4,Boom
431,/m/083vt,Wood
432,/m/07pczhz,Chop
433,/m/07pl1bw,Splinter
434,/m/07qs1cx,Crack
435,/m/039jq,Glass
436,/m/07q7njn,"Chink, clink"
437,/m/07rn7sz,Shatter
438,/m/04k94,Liquid
439,/m/07rrlb6,"Splash, splatter"
440,/m/07p6mqd,Slosh
441,/m/07qlwh6,Squish
442,/m/07r5v4s,Drip
443,/m/07prgkl,Pour
444,/m/07pqc89,"Trickle, dribble"
445,/t/dd00088,Gush
446,/m/07p7b8y,Fill (with liquid)
447,/m/07qlf79,Spray
448,/m/07ptzwd,Pump (liquid)
449,/m/07ptfmf,Stir
450,/m/0dv3j,Boiling
451,/m/0790c,Sonar
452,/m/0dl83,Arrow
453,/m/07rqsjt,"Whoosh, swoosh, swish"
454,/m/07qnq_y,"Thump, thud"
455,/m/07rrh0c,Thunk
456,/m/0b_fwt,Electronic tuner
457,/m/02rr_,Effects unit
458,/m/07m2kt,Chorus effect
459,/m/018w8,Basketball bounce
460,/m/07pws3f,Bang
461,/m/07ryjzk,"Slap, smack"
462,/m/07rdhzs,"Whack, thwack"
463,/m/07pjjrj,"Smash, crash"
464,/m/07pc8lb,Breaking
465,/m/07pqn27,Bouncing
466,/m/07rbp7_,Whip
467,/m/07pyf11,Flap
468,/m/07qb_dv,Scratch
469,/m/07qv4k0,Scrape
470,/m/07pdjhy,Rub
471,/m/07s8j8t,Roll
472,/m/07plct2,Crushing
473,/t/dd00112,"Crumpling, crinkling"
474,/m/07qcx4z,Tearing
475,/m/02fs_r,"Beep, bleep"
476,/m/07qwdck,Ping
477,/m/07phxs1,Ding
478,/m/07rv4dm,Clang
479,/m/07s02z0,Squeal
480,/m/07qh7jl,Creak
481,/m/07qwyj0,Rustle
482,/m/07s34ls,Whir
483,/m/07qmpdm,Clatter
484,/m/07p9k1k,Sizzle
485,/m/07qc9xj,Clicking
486,/m/07rwm0c,Clickety-clack
487,/m/07phhsh,Rumble
488,/m/07qyrcz,Plop
489,/m/07qfgpx,"Jingle, tinkle"
490,/m/07rcgpl,Hum
491,/m/07p78v5,Zing
492,/t/dd00121,Boing
493,/m/07s12q4,Crunch
494,/m/028v0c,Silence
495,/m/01v_m0,Sine wave
496,/m/0b9m1,Harmonic
497,/m/0hdsk,Chirp tone
498,/m/0c1dj,Sound effect
499,/m/07pt_g0,Pulse
500,/t/dd00125,"Inside, small room"
501,/t/dd00126,"Inside, large room or hall"
502,/t/dd00127,"Inside, public space"
503,/t/dd00128,"Outside, urban or manmade"
504,/t/dd00129,"Outside, rural or natural"
505,/m/01b9nn,Reverberation
506,/m/01jnbd,Echo
507,/m/096m7z,Noise
508,/m/06_y0by,Environmental noise
509,/m/07rgkc5,Static
510,/m/06xkwv,Mains hum
511,/m/0g12c5,Distortion
512,/m/08p9q4,Sidetone
513,/m/07szfh9,Cacophony
514,/m/0chx_,White noise
515,/m/0cj0r,Pink noise
516,/m/07p_0gm,Throbbing
517,/m/01jwx6,Vibration
518,/m/07c52,Television
519,/m/06bz3,Radio
520,/m/07hvw1,Field recording
1 index mid display_name
2 0 /m/09x0r Speech
3 1 /m/0ytgt Child speech, kid speaking
4 2 /m/01h8n0 Conversation
5 3 /m/02qldy Narration, monologue
6 4 /m/0261r1 Babbling
7 5 /m/0brhx Speech synthesizer
8 6 /m/07p6fty Shout
9 7 /m/07q4ntr Bellow
10 8 /m/07rwj3x Whoop
11 9 /m/07sr1lc Yell
12 10 /t/dd00135 Children shouting
13 11 /m/03qc9zr Screaming
14 12 /m/02rtxlg Whispering
15 13 /m/01j3sz Laughter
16 14 /t/dd00001 Baby laughter
17 15 /m/07r660_ Giggle
18 16 /m/07s04w4 Snicker
19 17 /m/07sq110 Belly laugh
20 18 /m/07rgt08 Chuckle, chortle
21 19 /m/0463cq4 Crying, sobbing
22 20 /t/dd00002 Baby cry, infant cry
23 21 /m/07qz6j3 Whimper
24 22 /m/07qw_06 Wail, moan
25 23 /m/07plz5l Sigh
26 24 /m/015lz1 Singing
27 25 /m/0l14jd Choir
28 26 /m/01swy6 Yodeling
29 27 /m/02bk07 Chant
30 28 /m/01c194 Mantra
31 29 /t/dd00005 Child singing
32 30 /t/dd00006 Synthetic singing
33 31 /m/06bxc Rapping
34 32 /m/02fxyj Humming
35 33 /m/07s2xch Groan
36 34 /m/07r4k75 Grunt
37 35 /m/01w250 Whistling
38 36 /m/0lyf6 Breathing
39 37 /m/07mzm6 Wheeze
40 38 /m/01d3sd Snoring
41 39 /m/07s0dtb Gasp
42 40 /m/07pyy8b Pant
43 41 /m/07q0yl5 Snort
44 42 /m/01b_21 Cough
45 43 /m/0dl9sf8 Throat clearing
46 44 /m/01hsr_ Sneeze
47 45 /m/07ppn3j Sniff
48 46 /m/06h7j Run
49 47 /m/07qv_x_ Shuffle
50 48 /m/07pbtc8 Walk, footsteps
51 49 /m/03cczk Chewing, mastication
52 50 /m/07pdhp0 Biting
53 51 /m/0939n_ Gargling
54 52 /m/01g90h Stomach rumble
55 53 /m/03q5_w Burping, eructation
56 54 /m/02p3nc Hiccup
57 55 /m/02_nn Fart
58 56 /m/0k65p Hands
59 57 /m/025_jnm Finger snapping
60 58 /m/0l15bq Clapping
61 59 /m/01jg02 Heart sounds, heartbeat
62 60 /m/01jg1z Heart murmur
63 61 /m/053hz1 Cheering
64 62 /m/028ght Applause
65 63 /m/07rkbfh Chatter
66 64 /m/03qtwd Crowd
67 65 /m/07qfr4h Hubbub, speech noise, speech babble
68 66 /t/dd00013 Children playing
69 67 /m/0jbk Animal
70 68 /m/068hy Domestic animals, pets
71 69 /m/0bt9lr Dog
72 70 /m/05tny_ Bark
73 71 /m/07r_k2n Yip
74 72 /m/07qf0zm Howl
75 73 /m/07rc7d9 Bow-wow
76 74 /m/0ghcn6 Growling
77 75 /t/dd00136 Whimper (dog)
78 76 /m/01yrx Cat
79 77 /m/02yds9 Purr
80 78 /m/07qrkrw Meow
81 79 /m/07rjwbb Hiss
82 80 /m/07r81j2 Caterwaul
83 81 /m/0ch8v Livestock, farm animals, working animals
84 82 /m/03k3r Horse
85 83 /m/07rv9rh Clip-clop
86 84 /m/07q5rw0 Neigh, whinny
87 85 /m/01xq0k1 Cattle, bovinae
88 86 /m/07rpkh9 Moo
89 87 /m/0239kh Cowbell
90 88 /m/068zj Pig
91 89 /t/dd00018 Oink
92 90 /m/03fwl Goat
93 91 /m/07q0h5t Bleat
94 92 /m/07bgp Sheep
95 93 /m/025rv6n Fowl
96 94 /m/09b5t Chicken, rooster
97 95 /m/07st89h Cluck
98 96 /m/07qn5dc Crowing, cock-a-doodle-doo
99 97 /m/01rd7k Turkey
100 98 /m/07svc2k Gobble
101 99 /m/09ddx Duck
102 100 /m/07qdb04 Quack
103 101 /m/0dbvp Goose
104 102 /m/07qwf61 Honk
105 103 /m/01280g Wild animals
106 104 /m/0cdnk Roaring cats (lions, tigers)
107 105 /m/04cvmfc Roar
108 106 /m/015p6 Bird
109 107 /m/020bb7 Bird vocalization, bird call, bird song
110 108 /m/07pggtn Chirp, tweet
111 109 /m/07sx8x_ Squawk
112 110 /m/0h0rv Pigeon, dove
113 111 /m/07r_25d Coo
114 112 /m/04s8yn Crow
115 113 /m/07r5c2p Caw
116 114 /m/09d5_ Owl
117 115 /m/07r_80w Hoot
118 116 /m/05_wcq Bird flight, flapping wings
119 117 /m/01z5f Canidae, dogs, wolves
120 118 /m/06hps Rodents, rats, mice
121 119 /m/04rmv Mouse
122 120 /m/07r4gkf Patter
123 121 /m/03vt0 Insect
124 122 /m/09xqv Cricket
125 123 /m/09f96 Mosquito
126 124 /m/0h2mp Fly, housefly
127 125 /m/07pjwq1 Buzz
128 126 /m/01h3n Bee, wasp, etc.
129 127 /m/09ld4 Frog
130 128 /m/07st88b Croak
131 129 /m/078jl Snake
132 130 /m/07qn4z3 Rattle
133 131 /m/032n05 Whale vocalization
134 132 /m/04rlf Music
135 133 /m/04szw Musical instrument
136 134 /m/0fx80y Plucked string instrument
137 135 /m/0342h Guitar
138 136 /m/02sgy Electric guitar
139 137 /m/018vs Bass guitar
140 138 /m/042v_gx Acoustic guitar
141 139 /m/06w87 Steel guitar, slide guitar
142 140 /m/01glhc Tapping (guitar technique)
143 141 /m/07s0s5r Strum
144 142 /m/018j2 Banjo
145 143 /m/0jtg0 Sitar
146 144 /m/04rzd Mandolin
147 145 /m/01bns_ Zither
148 146 /m/07xzm Ukulele
149 147 /m/05148p4 Keyboard (musical)
150 148 /m/05r5c Piano
151 149 /m/01s0ps Electric piano
152 150 /m/013y1f Organ
153 151 /m/03xq_f Electronic organ
154 152 /m/03gvt Hammond organ
155 153 /m/0l14qv Synthesizer
156 154 /m/01v1d8 Sampler
157 155 /m/03q5t Harpsichord
158 156 /m/0l14md Percussion
159 157 /m/02hnl Drum kit
160 158 /m/0cfdd Drum machine
161 159 /m/026t6 Drum
162 160 /m/06rvn Snare drum
163 161 /m/03t3fj Rimshot
164 162 /m/02k_mr Drum roll
165 163 /m/0bm02 Bass drum
166 164 /m/011k_j Timpani
167 165 /m/01p970 Tabla
168 166 /m/01qbl Cymbal
169 167 /m/03qtq Hi-hat
170 168 /m/01sm1g Wood block
171 169 /m/07brj Tambourine
172 170 /m/05r5wn Rattle (instrument)
173 171 /m/0xzly Maraca
174 172 /m/0mbct Gong
175 173 /m/016622 Tubular bells
176 174 /m/0j45pbj Mallet percussion
177 175 /m/0dwsp Marimba, xylophone
178 176 /m/0dwtp Glockenspiel
179 177 /m/0dwt5 Vibraphone
180 178 /m/0l156b Steelpan
181 179 /m/05pd6 Orchestra
182 180 /m/01kcd Brass instrument
183 181 /m/0319l French horn
184 182 /m/07gql Trumpet
185 183 /m/07c6l Trombone
186 184 /m/0l14_3 Bowed string instrument
187 185 /m/02qmj0d String section
188 186 /m/07y_7 Violin, fiddle
189 187 /m/0d8_n Pizzicato
190 188 /m/01xqw Cello
191 189 /m/02fsn Double bass
192 190 /m/085jw Wind instrument, woodwind instrument
193 191 /m/0l14j_ Flute
194 192 /m/06ncr Saxophone
195 193 /m/01wy6 Clarinet
196 194 /m/03m5k Harp
197 195 /m/0395lw Bell
198 196 /m/03w41f Church bell
199 197 /m/027m70_ Jingle bell
200 198 /m/0gy1t2s Bicycle bell
201 199 /m/07n_g Tuning fork
202 200 /m/0f8s22 Chime
203 201 /m/026fgl Wind chime
204 202 /m/0150b9 Change ringing (campanology)
205 203 /m/03qjg Harmonica
206 204 /m/0mkg Accordion
207 205 /m/0192l Bagpipes
208 206 /m/02bxd Didgeridoo
209 207 /m/0l14l2 Shofar
210 208 /m/07kc_ Theremin
211 209 /m/0l14t7 Singing bowl
212 210 /m/01hgjl Scratching (performance technique)
213 211 /m/064t9 Pop music
214 212 /m/0glt670 Hip hop music
215 213 /m/02cz_7 Beatboxing
216 214 /m/06by7 Rock music
217 215 /m/03lty Heavy metal
218 216 /m/05r6t Punk rock
219 217 /m/0dls3 Grunge
220 218 /m/0dl5d Progressive rock
221 219 /m/07sbbz2 Rock and roll
222 220 /m/05w3f Psychedelic rock
223 221 /m/06j6l Rhythm and blues
224 222 /m/0gywn Soul music
225 223 /m/06cqb Reggae
226 224 /m/01lyv Country
227 225 /m/015y_n Swing music
228 226 /m/0gg8l Bluegrass
229 227 /m/02x8m Funk
230 228 /m/02w4v Folk music
231 229 /m/06j64v Middle Eastern music
232 230 /m/03_d0 Jazz
233 231 /m/026z9 Disco
234 232 /m/0ggq0m Classical music
235 233 /m/05lls Opera
236 234 /m/02lkt Electronic music
237 235 /m/03mb9 House music
238 236 /m/07gxw Techno
239 237 /m/07s72n Dubstep
240 238 /m/0283d Drum and bass
241 239 /m/0m0jc Electronica
242 240 /m/08cyft Electronic dance music
243 241 /m/0fd3y Ambient music
244 242 /m/07lnk Trance music
245 243 /m/0g293 Music of Latin America
246 244 /m/0ln16 Salsa music
247 245 /m/0326g Flamenco
248 246 /m/0155w Blues
249 247 /m/05fw6t Music for children
250 248 /m/02v2lh New-age music
251 249 /m/0y4f8 Vocal music
252 250 /m/0z9c A capella
253 251 /m/0164x2 Music of Africa
254 252 /m/0145m Afrobeat
255 253 /m/02mscn Christian music
256 254 /m/016cjb Gospel music
257 255 /m/028sqc Music of Asia
258 256 /m/015vgc Carnatic music
259 257 /m/0dq0md Music of Bollywood
260 258 /m/06rqw Ska
261 259 /m/02p0sh1 Traditional music
262 260 /m/05rwpb Independent music
263 261 /m/074ft Song
264 262 /m/025td0t Background music
265 263 /m/02cjck Theme music
266 264 /m/03r5q_ Jingle (music)
267 265 /m/0l14gg Soundtrack music
268 266 /m/07pkxdp Lullaby
269 267 /m/01z7dr Video game music
270 268 /m/0140xf Christmas music
271 269 /m/0ggx5q Dance music
272 270 /m/04wptg Wedding music
273 271 /t/dd00031 Happy music
274 272 /t/dd00033 Sad music
275 273 /t/dd00034 Tender music
276 274 /t/dd00035 Exciting music
277 275 /t/dd00036 Angry music
278 276 /t/dd00037 Scary music
279 277 /m/03m9d0z Wind
280 278 /m/09t49 Rustling leaves
281 279 /t/dd00092 Wind noise (microphone)
282 280 /m/0jb2l Thunderstorm
283 281 /m/0ngt1 Thunder
284 282 /m/0838f Water
285 283 /m/06mb1 Rain
286 284 /m/07r10fb Raindrop
287 285 /t/dd00038 Rain on surface
288 286 /m/0j6m2 Stream
289 287 /m/0j2kx Waterfall
290 288 /m/05kq4 Ocean
291 289 /m/034srq Waves, surf
292 290 /m/06wzb Steam
293 291 /m/07swgks Gurgling
294 292 /m/02_41 Fire
295 293 /m/07pzfmf Crackle
296 294 /m/07yv9 Vehicle
297 295 /m/019jd Boat, Water vehicle
298 296 /m/0hsrw Sailboat, sailing ship
299 297 /m/056ks2 Rowboat, canoe, kayak
300 298 /m/02rlv9 Motorboat, speedboat
301 299 /m/06q74 Ship
302 300 /m/012f08 Motor vehicle (road)
303 301 /m/0k4j Car
304 302 /m/0912c9 Vehicle horn, car horn, honking
305 303 /m/07qv_d5 Toot
306 304 /m/02mfyn Car alarm
307 305 /m/04gxbd Power windows, electric windows
308 306 /m/07rknqz Skidding
309 307 /m/0h9mv Tire squeal
310 308 /t/dd00134 Car passing by
311 309 /m/0ltv Race car, auto racing
312 310 /m/07r04 Truck
313 311 /m/0gvgw0 Air brake
314 312 /m/05x_td Air horn, truck horn
315 313 /m/02rhddq Reversing beeps
316 314 /m/03cl9h Ice cream truck, ice cream van
317 315 /m/01bjv Bus
318 316 /m/03j1ly Emergency vehicle
319 317 /m/04qvtq Police car (siren)
320 318 /m/012n7d Ambulance (siren)
321 319 /m/012ndj Fire engine, fire truck (siren)
322 320 /m/04_sv Motorcycle
323 321 /m/0btp2 Traffic noise, roadway noise
324 322 /m/06d_3 Rail transport
325 323 /m/07jdr Train
326 324 /m/04zmvq Train whistle
327 325 /m/0284vy3 Train horn
328 326 /m/01g50p Railroad car, train wagon
329 327 /t/dd00048 Train wheels squealing
330 328 /m/0195fx Subway, metro, underground
331 329 /m/0k5j Aircraft
332 330 /m/014yck Aircraft engine
333 331 /m/04229 Jet engine
334 332 /m/02l6bg Propeller, airscrew
335 333 /m/09ct_ Helicopter
336 334 /m/0cmf2 Fixed-wing aircraft, airplane
337 335 /m/0199g Bicycle
338 336 /m/06_fw Skateboard
339 337 /m/02mk9 Engine
340 338 /t/dd00065 Light engine (high frequency)
341 339 /m/08j51y Dental drill, dentist's drill
342 340 /m/01yg9g Lawn mower
343 341 /m/01j4z9 Chainsaw
344 342 /t/dd00066 Medium engine (mid frequency)
345 343 /t/dd00067 Heavy engine (low frequency)
346 344 /m/01h82_ Engine knocking
347 345 /t/dd00130 Engine starting
348 346 /m/07pb8fc Idling
349 347 /m/07q2z82 Accelerating, revving, vroom
350 348 /m/02dgv Door
351 349 /m/03wwcy Doorbell
352 350 /m/07r67yg Ding-dong
353 351 /m/02y_763 Sliding door
354 352 /m/07rjzl8 Slam
355 353 /m/07r4wb8 Knock
356 354 /m/07qcpgn Tap
357 355 /m/07q6cd_ Squeak
358 356 /m/0642b4 Cupboard open or close
359 357 /m/0fqfqc Drawer open or close
360 358 /m/04brg2 Dishes, pots, and pans
361 359 /m/023pjk Cutlery, silverware
362 360 /m/07pn_8q Chopping (food)
363 361 /m/0dxrf Frying (food)
364 362 /m/0fx9l Microwave oven
365 363 /m/02pjr4 Blender
366 364 /m/02jz0l Water tap, faucet
367 365 /m/0130jx Sink (filling or washing)
368 366 /m/03dnzn Bathtub (filling or washing)
369 367 /m/03wvsk Hair dryer
370 368 /m/01jt3m Toilet flush
371 369 /m/012xff Toothbrush
372 370 /m/04fgwm Electric toothbrush
373 371 /m/0d31p Vacuum cleaner
374 372 /m/01s0vc Zipper (clothing)
375 373 /m/03v3yw Keys jangling
376 374 /m/0242l Coin (dropping)
377 375 /m/01lsmm Scissors
378 376 /m/02g901 Electric shaver, electric razor
379 377 /m/05rj2 Shuffling cards
380 378 /m/0316dw Typing
381 379 /m/0c2wf Typewriter
382 380 /m/01m2v Computer keyboard
383 381 /m/081rb Writing
384 382 /m/07pp_mv Alarm
385 383 /m/07cx4 Telephone
386 384 /m/07pp8cl Telephone bell ringing
387 385 /m/01hnzm Ringtone
388 386 /m/02c8p Telephone dialing, DTMF
389 387 /m/015jpf Dial tone
390 388 /m/01z47d Busy signal
391 389 /m/046dlr Alarm clock
392 390 /m/03kmc9 Siren
393 391 /m/0dgbq Civil defense siren
394 392 /m/030rvx Buzzer
395 393 /m/01y3hg Smoke detector, smoke alarm
396 394 /m/0c3f7m Fire alarm
397 395 /m/04fq5q Foghorn
398 396 /m/0l156k Whistle
399 397 /m/06hck5 Steam whistle
400 398 /t/dd00077 Mechanisms
401 399 /m/02bm9n Ratchet, pawl
402 400 /m/01x3z Clock
403 401 /m/07qjznt Tick
404 402 /m/07qjznl Tick-tock
405 403 /m/0l7xg Gears
406 404 /m/05zc1 Pulleys
407 405 /m/0llzx Sewing machine
408 406 /m/02x984l Mechanical fan
409 407 /m/025wky1 Air conditioning
410 408 /m/024dl Cash register
411 409 /m/01m4t Printer
412 410 /m/0dv5r Camera
413 411 /m/07bjf Single-lens reflex camera
414 412 /m/07k1x Tools
415 413 /m/03l9g Hammer
416 414 /m/03p19w Jackhammer
417 415 /m/01b82r Sawing
418 416 /m/02p01q Filing (rasp)
419 417 /m/023vsd Sanding
420 418 /m/0_ksk Power tool
421 419 /m/01d380 Drill
422 420 /m/014zdl Explosion
423 421 /m/032s66 Gunshot, gunfire
424 422 /m/04zjc Machine gun
425 423 /m/02z32qm Fusillade
426 424 /m/0_1c Artillery fire
427 425 /m/073cg4 Cap gun
428 426 /m/0g6b5 Fireworks
429 427 /g/122z_qxw Firecracker
430 428 /m/07qsvvw Burst, pop
431 429 /m/07pxg6y Eruption
432 430 /m/07qqyl4 Boom
433 431 /m/083vt Wood
434 432 /m/07pczhz Chop
435 433 /m/07pl1bw Splinter
436 434 /m/07qs1cx Crack
437 435 /m/039jq Glass
438 436 /m/07q7njn Chink, clink
439 437 /m/07rn7sz Shatter
440 438 /m/04k94 Liquid
441 439 /m/07rrlb6 Splash, splatter
442 440 /m/07p6mqd Slosh
443 441 /m/07qlwh6 Squish
444 442 /m/07r5v4s Drip
445 443 /m/07prgkl Pour
446 444 /m/07pqc89 Trickle, dribble
447 445 /t/dd00088 Gush
448 446 /m/07p7b8y Fill (with liquid)
449 447 /m/07qlf79 Spray
450 448 /m/07ptzwd Pump (liquid)
451 449 /m/07ptfmf Stir
452 450 /m/0dv3j Boiling
453 451 /m/0790c Sonar
454 452 /m/0dl83 Arrow
455 453 /m/07rqsjt Whoosh, swoosh, swish
456 454 /m/07qnq_y Thump, thud
457 455 /m/07rrh0c Thunk
458 456 /m/0b_fwt Electronic tuner
459 457 /m/02rr_ Effects unit
460 458 /m/07m2kt Chorus effect
461 459 /m/018w8 Basketball bounce
462 460 /m/07pws3f Bang
463 461 /m/07ryjzk Slap, smack
464 462 /m/07rdhzs Whack, thwack
465 463 /m/07pjjrj Smash, crash
466 464 /m/07pc8lb Breaking
467 465 /m/07pqn27 Bouncing
468 466 /m/07rbp7_ Whip
469 467 /m/07pyf11 Flap
470 468 /m/07qb_dv Scratch
471 469 /m/07qv4k0 Scrape
472 470 /m/07pdjhy Rub
473 471 /m/07s8j8t Roll
474 472 /m/07plct2 Crushing
475 473 /t/dd00112 Crumpling, crinkling
476 474 /m/07qcx4z Tearing
477 475 /m/02fs_r Beep, bleep
478 476 /m/07qwdck Ping
479 477 /m/07phxs1 Ding
480 478 /m/07rv4dm Clang
481 479 /m/07s02z0 Squeal
482 480 /m/07qh7jl Creak
483 481 /m/07qwyj0 Rustle
484 482 /m/07s34ls Whir
485 483 /m/07qmpdm Clatter
486 484 /m/07p9k1k Sizzle
487 485 /m/07qc9xj Clicking
488 486 /m/07rwm0c Clickety-clack
489 487 /m/07phhsh Rumble
490 488 /m/07qyrcz Plop
491 489 /m/07qfgpx Jingle, tinkle
492 490 /m/07rcgpl Hum
493 491 /m/07p78v5 Zing
494 492 /t/dd00121 Boing
495 493 /m/07s12q4 Crunch
496 494 /m/028v0c Silence
497 495 /m/01v_m0 Sine wave
498 496 /m/0b9m1 Harmonic
499 497 /m/0hdsk Chirp tone
500 498 /m/0c1dj Sound effect
501 499 /m/07pt_g0 Pulse
502 500 /t/dd00125 Inside, small room
503 501 /t/dd00126 Inside, large room or hall
504 502 /t/dd00127 Inside, public space
505 503 /t/dd00128 Outside, urban or manmade
506 504 /t/dd00129 Outside, rural or natural
507 505 /m/01b9nn Reverberation
508 506 /m/01jnbd Echo
509 507 /m/096m7z Noise
510 508 /m/06_y0by Environmental noise
511 509 /m/07rgkc5 Static
512 510 /m/06xkwv Mains hum
513 511 /m/0g12c5 Distortion
514 512 /m/08p9q4 Sidetone
515 513 /m/07szfh9 Cacophony
516 514 /m/0chx_ White noise
517 515 /m/0cj0r Pink noise
518 516 /m/07p_0gm Throbbing
519 517 /m/01jwx6 Vibration
520 518 /m/07c52 Television
521 519 /m/06bz3 Radio
522 520 /m/07hvw1 Field recording
File diff suppressed because one or more lines are too long
@@ -0,0 +1,75 @@
{% load i18n %}
{% if error %}
<section class="results-card error-card" role="alert">
<h2>{% trans "Analysis unavailable" %}</h2>
<p>{{ error }}</p>
</section>
{% else %}
<section class="results-card" tabindex="-1">
<div class="result-heading">
<div>
<h2>{% trans "Analysis complete" %}</h2>
<p>{{ result.filename|default:"Audio file" }}</p>
</div>
<span class="result-status">{% trans "Ready" %}</span>
</div>
<div class="meta">
<span>{% blocktrans with duration=result.duration_seconds|default:"—" %}{{ duration }} seconds{% endblocktrans %}</span>
<span>{% blocktrans with frames=result.frames_analysed|default:"—" %}{{ frames }} frames analysed{% endblocktrans %}</span>
<span>{% blocktrans with rate=result.yamnet_sample_rate|default:"—" %}{{ rate }} Hz model rate{% endblocktrans %}</span>
</div>
<div class="legend" aria-label="{% trans "Result legend" %}">
{% if firework_count %}<span class="firework">✦ {% blocktrans count count=firework_count %}{{ count }} firework-related signal{% plural %}{{ count }} firework-related signals{% endblocktrans %}</span>{% endif %}
{% if speech_count %}<span class="speech">● {% blocktrans count count=speech_count %}{{ count }} speech/privacy signal{% plural %}{{ count }} speech/privacy signals{% endblocktrans %}</span>{% endif %}
</div>
<div class="result-grid">
<section class="result-group" aria-labelledby="top-predictions">
<h3 id="top-predictions">{% trans "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">{% trans "No overall predictions were returned." %}</p>{% endif %}
</section>
<section class="result-group" aria-labelledby="peak-predictions">
<h3 id="peak-predictions">{% trans "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">{% trans "No peak events were returned." %}</p>{% endif %}
</section>
</div>
{% if pending %}
<div class="review-submission" role="status">
<div><strong>{% trans "Sent to Pending Review" %}</strong><p>{% trans "An administrator will review this recording." %}</p></div>
</div>
{% endif %}
{% if submission_token %}
<div class="review-submission" id="review-submission">
<input type="hidden" name="classification_token" value="{{ submission_token }}">
<div><strong>{% trans "Submit this sample for review" %}</strong><p>{% trans "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">{% trans "Send to Pending →" %}</button>
</div>
{% endif %}
</section>
{% endif %}
@@ -0,0 +1,50 @@
{% load i18n vite %}
<!doctype html>
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>{% trans "Report fireworks · Sound Signal" %}</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
{% vite_asset "frontend/src/entries/dashboard.js" %}
{% include "js_translations.html" %}
{% include "fireworks_detect/includes/browser_processing_config.html" %}
</head>
<body class="dashboard-page">
{% if user.is_authenticated %}<a class="profile-circle" href="{% url "user_settings" %}" aria-label="{% blocktrans with username=user.get_username %}Open settings for {{ username }}{% endblocktrans %}" title="{% trans "Settings" %}">{{ user.get_username|first|upper }}</a>{% endif %}
<main class="dashboard-shell">
{% include "fireworks_detect/includes/navigation.html" %}
<section class="dashboard-intro" aria-labelledby="dashboard-title">
<p class="dashboard-kicker">{% trans "Community reporting" %}</p>
<h1 id="dashboard-title">{% trans "Report what you heard." %}</h1>
<p>{% trans "Quickly log fireworks when they happen. Your optional location is represented as an H3 cell on the map, rather than as precise coordinates." %}</p>
</section>
<section class="dashboard-section" aria-label="{% trans "Quick fireworks report" %}">
<div class="dashboard-report">
{% include "fireworks_detect/includes/manual_report_form.html" %}
</div>
</section>
<section class="dashboard-section dashboard-map" aria-labelledby="dashboard-map-title">
<header class="dashboard-section__header">
<div><p class="dashboard-kicker">{% trans "Recent reports" %}</p><h2 id="dashboard-map-title">{% trans "Activity map" %}</h2></div>
<a class="dashboard-link" href="{% url "fireworks_detect:map" %}">{% trans "Open map controls" %} <span aria-hidden="true">→</span></a>
</header>
{% include "fireworks_detect/includes/map_panel.html" %}
</section>
<section class="dashboard-section" aria-labelledby="dashboard-audio-title">
<header class="dashboard-section__header">
<div><p class="dashboard-kicker">{% trans "Audio analysis" %}</p><h2 id="dashboard-audio-title">{% trans "Classify a recording" %}</h2></div>
</header>
<div class="upload-card dashboard-upload">
{% include "fireworks_detect/includes/audio_upload_form.html" %}
</div>
</section>
</main>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
</body>
</html>
@@ -0,0 +1,28 @@
{% load i18n %}
{% if event.source_type == "manual" %}
<h2>{% trans "Manual fireworks report" %}</h2>
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" %}Approved {{ date }} · Reported manually{% endblocktrans %}</p>
<h3>{% trans "Report details" %}</h3>
<div class="prediction prediction--firework"><strong>{% trans "Occurrences" %}</strong><span>{{ event.occurrences }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Location" %}</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Captured location" %}</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Direction" %}</strong><span>{{ event.direction_display }}</span></div>
{% if event.direction_accuracy_degrees is not None %}<div class="prediction prediction--firework"><strong>{% trans "Compass accuracy" %}</strong><span>±{{ event.direction_accuracy_degrees|floatformat:"-1" }}°</span></div>{% endif %}
<div class="prediction prediction--firework"><strong>{% trans "Visually confirmed" %}</strong><span>{% if event.visually_confirmed %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</span></div>
<p class="empty">{% trans "This was a manual report; there is no audio classification attached." %}</p>
{% else %}
<h2>{{ event.original_filename }}</h2>
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" duration=result.duration_seconds|default:"—" frames=result.frames_analysed|default:"—" %}Approved {{ date }} · {{ duration }} seconds · {{ frames }} frames{% endblocktrans %}</p>
<h3>{% trans "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">{% trans "No predictions returned." %}</p>
{% endfor %}
<h3>{% trans "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">{% trans "No peak events returned." %}</p>
{% endfor %}
{% endif %}
@@ -0,0 +1,2 @@
{% load i18n vite %}
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Events · Sound Signal" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}{% include "js_translations.html" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" with active_page="events" %}<p class="eyebrow">{% trans "Reviewed signal archive" %}</p><h1>{% trans "Approved events." %}</h1><p class="lede">{% trans "This feed refreshes automatically every three seconds after a pending sample is approved in admin." %}</p><div class="grid"><section class="panel"><h2>{% trans "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">{% trans "Loading events…" %}</p></div></section><section class="panel detail" id="event-detail"><h2>{% trans "Select an event" %}</h2><p class="empty">{% trans "Choose an approved event to inspect its classification details." %}</p></section></div></main></body></html>
@@ -0,0 +1,21 @@
{% load i18n %}
{% if events %}
{% for event in events %}
<button class="event {% if event.source_type == "manual" %}event--manual{% else %}event--sensor{% endif %}" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
<span class="event__content">
{% if event.source_type == "manual" %}
<span class="event__source">{% trans "Manual report" %}</span>
<strong>{% trans "Manual fireworks report" %}</strong><br>
<small>{% blocktrans count count=event.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}{% if event.location %} · {{ event.location }}{% endif %}</small>
{% else %}
<span class="event__source">{% trans "Sensor classification" %}</span>
<strong>{{ event.primary_label }}</strong><br>
<small>{{ event.original_filename }} · {{ event.duration }}s</small>
{% endif %}
</span>
<span class="badge">{% if event.source_type == "manual" %}{% trans "Manual" %} →{% else %}{{ event.primary_score }} →{% endif %}</span>
</button>
{% endfor %}
{% else %}
<p class="empty">{% trans "No approved events yet. Submit a classification, then approve it from the Pending page in admin." %}</p>
{% endif %}
@@ -0,0 +1,34 @@
{% load i18n vite %}
<!DOCTYPE html>
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% trans "Sound Signal · Fireworks detection" %}</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
{% vite_asset "frontend/src/entries/fireworks-home.js" %}
{% include "js_translations.html" %}
{% include "fireworks_detect/includes/browser_processing_config.html" %}
</head>
<body>
<main class="shell">
{% include "fireworks_detect/includes/navigation.html" with active_page="analyse" %}
<section class="intro" aria-labelledby="page-title">
<p class="kicker">{% trans "Audio event analysis" %}</p>
<h1 id="page-title">{% trans "See what your audio heard." %}</h1>
<p class="lede">{% blocktrans trimmed %}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.{% endblocktrans %}</p>
<a href="https://pixabay.com/sound-effects/search/fireworks/" class="button" target="_blank">{% trans "Here are some samples to test with" %}</a>
<br /><br />
</section>
<section class="upload-card" aria-label="{% trans "Upload audio for classification" %}">
{% include "fireworks_detect/includes/audio_upload_form.html" %}
</section>
</main>
</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,37 @@
{% load i18n %}
<form class="upload-form audio-upload--idle" 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" data-scroll-to-results="true">
{% 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" id="upload-progress-circle"><span class="upload-icon__content" id="upload-icon-content" aria-hidden="true">↑</span></span>
<strong>{% trans "Drop an audio file here" %}</strong>
<span>{% trans "or click to browse your device" %}</span>
</span>
<span class="file-name" id="file-name">{% trans "No file selected" %}</span>
</label>
{% if browser_processing_config.browserProcessingBeta %}
<div class="browser-mode">
<label class="browser-mode__label" for="browser-processing-toggle">
<input id="browser-processing-toggle" type="checkbox">
<span>{% trans "Process recording in this browser (Beta)" %}</span>
</label>
<p>{% trans "When enabled, BoomCast extracts and checks audio on this device before uploading it. When disabled, recordings are processed by the server as usual." %}</p>
</div>
{% endif %}
<div class="form-footer">
<p class="file-note">{% trans "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>{% trans "Analyse audio" %}</button>
<button class="upload-cancel" type="button" hidden>{% trans "Cancel upload" %}</button>
</div>
<section class="browser-gate" id="browser-gate" hidden aria-live="polite">
<strong id="browser-gate-title"></strong>
<p id="browser-gate-message"></p>
<div class="browser-gate-actions">
<button type="button" id="browser-gate-choose">{% trans "Choose another recording" %}</button>
<button type="button" id="browser-gate-override">{% trans "Submit for manual review anyway" %}</button>
</div>
</section>
<section id="classification-results" aria-live="polite" aria-label="{% trans "Classification results" %}"></section>
</form>
<p id="upload-status" role="status" aria-live="polite"></p>
@@ -0,0 +1 @@
{{ browser_processing_config|json_script:"boomcast-browser-config" }}
@@ -0,0 +1,16 @@
{% load i18n %}
<div class="manual-direction-panel{% if measuring %} manual-direction-panel--open{% endif %}" id="manual-direction-panel" data-state="{% if measuring %}ready{% else %}idle{% endif %}">
{% if measuring %}
<div class="manual-direction-panel__topline">
<strong class="manual-direction-panel__heading">{% trans "Capture direction" %}</strong>
<button class="manual-direction-panel__close" type="button" hx-get="{% url 'fireworks_detect:manual_direction_panel' %}" hx-target="#manual-direction-panel" hx-swap="outerHTML" aria-label="{% trans 'Close direction capture' %}">×</button>
</div>
<p class="manual-direction-panel__copy">{% trans "Point the top of your phone toward the fireworks, then capture a single compass reading." %}</p>
<div id="manual-direction-status" class="manual-direction-panel__status" aria-live="polite"></div>
<button id="manual-capture-direction" class="manual-direction-panel__button" type="button">{% trans "Start measuring direction" %}</button>
{% else %}
<strong class="manual-direction-panel__heading">{% trans "Direction" %} <span>({% trans "optional" %})</span></strong>
<p id="manual-direction-summary" class="manual-direction-panel__summary">{% trans "Not captured" %}</p>
<button class="manual-direction-panel__open" type="button" hx-get="{% url 'fireworks_detect:manual_direction_panel' %}?mode=measure" hx-target="#manual-direction-panel" hx-swap="outerHTML">{% trans "Capture direction" %}</button>
{% endif %}
</div>
@@ -0,0 +1,76 @@
{% load i18n %}
<section class="manual-report" aria-labelledby="manual-report-title">
<header class="manual-report__header">
<p class="eyebrow">{% trans "Quick report" %}</p>
<div class="manual-report__heading-row"><span class="manual-report__fire" aria-hidden="true">🔥</span><h2 class="manual-report__title" id="manual-report-title">{% trans "Report fireworks now" %}</h2></div>
<p class="manual-report__intro">{% trans "Did you hear a bang? Report what you heard in a few taps." %}</p>
<div class="report-clock" role="group" aria-label="{% trans 'Report time' %}">
<span class="report-clock__label" aria-hidden="true">{% trans "Report time" %}</span>
<div class="report-clock__display">
<time id="manual-report-time" class="report-clock__time" aria-label="{% trans 'Now' %}">
<span id="report-clock-hours" aria-hidden="true">--</span><span class="report-clock__colon" aria-hidden="true">:</span><span id="report-clock-minutes" aria-hidden="true">--</span>
</time>
<span class="report-clock__now" aria-hidden="true"><span class="report-clock__dot"></span>{% trans "Now" %}</span>
</div>
</div>
</header>
<form id="manual-report-form" action="{% url "fireworks_detect:submit_manual_pending" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="manual-latitude" name="latitude" type="hidden">
<input id="manual-longitude" name="longitude" type="hidden">
<input id="manual-direction-degrees" name="direction_degrees" type="hidden">
<input id="manual-direction-accuracy" name="direction_accuracy_degrees" type="hidden">
<div class="manual-report__primary">
<div class="manual-report__quantity">
<label class="manual-report__label" for="manual-occurrences">{% trans "How many times did you hear it?" %}</label>
<div class="manual-report__stepper">
<button id="manual-decrease" type="button" aria-label="{% trans 'Decrease occurrences' %}">−</button>
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric">
<button id="manual-increase" type="button" aria-label="{% trans 'Increase occurrences' %}">+</button>
</div>
</div>
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
</div>
<section class="manual-report__supporting" data-state="off" aria-labelledby="manual-listening-title">
<div class="manual-report__supporting-header">
<span class="manual-report__microphone" aria-hidden="true">🎙</span>
<div>
<h3 id="manual-listening-title">{% trans "Automatic detection" %}</h3>
<span id="burst-state" class="burst-listener__state" aria-live="polite">{% trans "Not listening" %}</span>
</div>
</div>
<div class="burst-listener" data-state="off">
<button id="burst-start" class="burst-listener__button" type="button">{% trans "Start listening" %}</button>
<div id="burst-panel" class="burst-listener__panel" hidden>
<strong id="burst-heading" aria-live="polite"></strong>
<canvas id="burst-waveform" width="600" height="90" aria-label="{% trans 'Live microphone waveform' %}"></canvas>
<p id="burst-detail"></p>
<audio id="burst-preview" controls hidden></audio>
<div class="burst-listener__actions">
<button id="burst-resume" type="button" hidden>{% trans "Resume listening" %}</button>
<button id="burst-discard" type="button" hidden>{% trans "Discard clip" %}</button>
<button id="burst-stop" type="button">{% trans "Stop listening" %}</button>
</div>
</div>
<p id="burst-error" role="alert" hidden></p>
</div>
</section>
<button id="manual-submit" class="manual-report__submit" type="button"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
</form>
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
<div id="manual-compass-home">
<div id="manual-compass" class="manual-compass" role="img" aria-label="{% trans 'Compass direction' %}" hidden>
<div class="manual-compass__dial" aria-hidden="true">
<div id="manual-compass-rose" class="manual-compass__rose">
<span class="manual-compass__north">N</span>
<span class="manual-compass__east">E</span>
<span class="manual-compass__south">S</span>
<span class="manual-compass__west">W</span>
</div>
<span class="manual-compass__pointer"></span>
<span class="manual-compass__center"></span>
</div>
<span id="manual-compass-heading" class="manual-compass__heading"></span>
</div>
</div>
</section>
@@ -0,0 +1,9 @@
{% load i18n %}
<section class="map-panel" aria-label="{% trans "Manual fireworks report map" %}">
<div class="map-header"><strong>{% trans "Manual reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }} · sensor layer disabled{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of manual fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Manual reports" %}</h2><div><span class="legend-dot"></span> {% trans "Report marker at H3-cell centre" %}</div><div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div><div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div></aside>
</div>
</section>
{{ h3_cells|json_script:"h3-cells-data" }}
{{ map_events|json_script:"map-events-data" }}
@@ -0,0 +1,33 @@
{% load i18n %}
<header class="fireworks-header">
<button class="fireworks-menu-toggle" type="button" aria-label="{% trans "Open menu" %}" data-open-label="{% trans "Open menu" %}" data-close-label="{% trans "Close menu" %}" aria-controls="fireworks-header-controls" aria-expanded="false"><span></span><span></span><span></span></button>
<a class="fireworks-brand" href="{% url "fireworks_detect:fireworks" %}"><span class="brand-mark">✦</span> Sound Signal</a>
<div class="fireworks-header__controls" id="fireworks-header-controls">
<nav class="fireworks-nav" aria-label="{% trans "Fireworks navigation" %}">
<a href="{% url "fireworks_detect:fireworks" %}"{% if active_page == "analyse" %} aria-current="page"{% endif %}>{% trans "Analyse" %}</a>
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>{% trans "Map" %}</a>
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>{% trans "Events" %}</a>
{% if request.user.is_authenticated %}
<form action="{% url 'logout' %}" method="post">
{% csrf_token %}
<button type="submit">{% trans "Sign out" %}</button>
</form>
{% else %}
<a href="{% url 'login' %}">{% trans "Sign in" %}</a>
{% endif %}
</nav>
{% if not request.user.is_authenticated %}
<form class="public-language" action="{% url 'set_anonymous_language' %}" method="post" style="display:flex;align-items:center;gap:.3rem;color:var(--muted,#aab9d8);font-size:.78rem">
{% csrf_token %}
<input type="hidden" name="next" value="{{ request.get_full_path }}">
<label for="public-language-choice">{% trans "Language" %}</label>
<select id="public-language-choice" name="language" style="border:1px solid var(--line,#2b3d68);border-radius:.5rem;padding:.4rem;color:inherit;background:transparent;font:inherit">
<option value="nl"{% if request.LANGUAGE_CODE == 'nl' %} selected{% endif %}>Nederlands</option>
<option value="en"{% if request.LANGUAGE_CODE == 'en' %} selected{% endif %}>English</option>
</select>
<button type="submit" style="border:1px solid var(--line,#2b3d68);border-radius:.5rem;padding:.4rem;color:inherit;background:transparent;font:inherit;cursor:pointer">OK</button>
</form>
{% endif %}
<button class="theme-toggle theme-toggle--inline" type="button" aria-label="{% trans "Switch theme" %}"></button>
</div>
</header>
@@ -0,0 +1,17 @@
{% load i18n %}
<div id="manual-submission" class="manual-submission{% if error %} manual-submission--error{% else %} manual-submission--success{% endif %}" role="status" data-result="{% if error %}error{% else %}success{% endif %}">
{% if error %}
<span class="manual-submission__icon" aria-hidden="true">!</span>
<strong>{% trans "Could not report fireworks" %}</strong>
<p>{{ error }}</p>
{% else %}
<span class="manual-submission__icon" aria-hidden="true">✓</span>
<strong>{% trans "Report received!" %}</strong>
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
<p class="manual-submission__summary">
{{ pending.created_at|date:"H:i" }} ·
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
{% if direction_label %} · {{ direction_label }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
</p>
{% endif %}
</div>
@@ -0,0 +1,35 @@
{% load i18n vite %}
<!DOCTYPE html>
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% trans "Signal map · Sound Signal" %}</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
{% vite_asset "frontend/src/entries/map.js" %}
{% include "js_translations.html" %}
</head>
<body>
<main class="shell">
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
<section class="headline" aria-labelledby="map-title">
<div><p class="kicker">{% trans "Manual report intelligence" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "Reviewed manual reports with a captured location appear as their H3 cell, not their precise coordinates. Saved phone compass readings show the reported direction of the sound." %}</p>
</section>
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="{% trans "Map filters" %}">
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" disabled><option selected>{% trans "Manual reports" %}</option><option>{% trans "Sensor events — coming soon" %}</option></select></div>
<div class="filter"><label for="range">{% trans "Period" %}</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>{% trans "Last 7 days" %}</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>{% trans "Last 2 weeks" %}</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>{% trans "Last 30 days" %}</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>{% trans "All time" %}</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>{% trans "Custom range" %}</option></select></div>
<div class="filter"><label for="from-date">{% trans "From" %}</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
<div class="filter"><label for="to-date">{% trans "To" %}</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
<div class="filter"><label for="visual">{% trans "Visual confirmation" %}</label><select id="visual" name="visual"><option value="all" {% if map_filters.visual == "all" %}selected{% endif %}>{% trans "Any report" %}</option><option value="yes" {% if map_filters.visual == "yes" %}selected{% endif %}>{% trans "Visually confirmed" %}</option><option value="no" {% if map_filters.visual == "no" %}selected{% endif %}>{% trans "Not visually confirmed" %}</option></select></div>
<button class="filter-submit" type="submit">{% trans "Apply filters" %}</button>
<span class="map-tag">{% blocktrans count count=mapped_event_count %}{{ count }} report{% plural %}{{ count }} reports{% endblocktrans %}</span>
</form>
{% include "fireworks_detect/includes/map_panel.html" %}
</main>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
</body>
</html>
@@ -0,0 +1,4 @@
{% load i18n %}
<div class="review-submission" id="review-submission" role="status">
{% if error %}<div><strong>{% trans "Could not submit this sample" %}</strong><p>{{ error }}</p></div>{% else %}<div><strong>{% trans "Sent to Pending" %}</strong><p>{% blocktrans with filename=pending.original_filename %}{{ filename }} is ready for administrator review.{% endblocktrans %}</p></div><a href="{% url 'fireworks_detect:events' %}">{% trans "View events" %}</a>{% endif %}
</div>
+43
View File
@@ -0,0 +1,43 @@
{% load i18n vite %}
<!DOCTYPE html>
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% trans "Sound Signal · Fireworks detection" %}</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
{% vite_asset "frontend/src/entries/legacy-fireworks-home.js" %}
</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">{% trans "Audio event analysis" %}</p>
<h1 id="page-title">{% trans "See what your audio heard." %}</h1>
<p class="lede">{% trans "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="{% trans "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>{% trans "Drop an audio file here" %}</strong>
<span>{% trans "or click to browse your device" %}</span>
</span>
<span class="file-name" id="file-name">{% trans "No file selected" %}</span>
</label>
<div class="form-footer">
<p class="file-note">{% trans "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>{% trans "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="{% trans "Classification results" %}"></section>
</main>
</body>
</html>
+161
View File
@@ -0,0 +1,161 @@
import json
from tempfile import TemporaryDirectory
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core import signing
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files.storage import FileSystemStorage
from django.test import TestCase, override_settings
from django.urls import reverse
from .browser_policy import advisory_browser_metadata
from .models import BrowserProcessingSettings, ClassificationRule, PendingEvent
class BrowserProcessingBetaTests(TestCase):
def test_setting_defaults_off_and_admin_can_toggle_it(self):
self.assertFalse(BrowserProcessingSettings.enabled())
settings = BrowserProcessingSettings.objects.get(pk=1)
self.assertFalse(settings.browser_processing_beta_enabled)
staff = get_user_model().objects.create_superuser("beta-admin", "beta@example.com", "password")
self.client.force_login(staff)
changelist = self.client.get(reverse("admin:fireworks_detect_browserprocessingsettings_changelist"))
self.assertContains(changelist, "Disabled — normal submission")
url = reverse("admin:fireworks_detect_browserprocessingsettings_change", args=[settings.pk])
self.assertContains(self.client.get(url), "Browser-side media processing (Beta)")
self.assertEqual(self.client.post(url, {"browser_processing_beta_enabled": "on", "_save": "Save"}).status_code, 302)
self.assertTrue(BrowserProcessingSettings.enabled())
self.assertEqual(self.client.post(url, {"_save": "Save"}).status_code, 302)
self.assertFalse(BrowserProcessingSettings.enabled())
self.assertEqual(BrowserProcessingSettings.objects.count(), 1)
def test_policy_and_page_config_are_empty_while_disabled(self):
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
response = self.client.get(reverse("fireworks_detect:browser_policy"))
self.assertEqual(response.json(), {
"version": 1, "browser_processing_beta_enabled": False,
"whitelist": [], "privacy_sensitive_speech": [], "thresholds": {},
"model_version": "google-yamnet-1", "model_url": "", "class_map_url": "",
})
self.assertIn("no-cache", response["Cache-Control"])
for url in (reverse("hello"), reverse("fireworks_detect:fireworks")):
page = self.client.get(url)
self.assertContains(page, '"browserProcessingBeta": false')
self.assertContains(page, 'id="boomcast-browser-config"')
self.assertNotContains(page, 'id="browser-processing-toggle"')
def test_frontend_toggle_only_appears_when_admin_enables_beta_and_defaults_off(self):
for url in (reverse("hello"), reverse("fireworks_detect:fireworks")):
self.assertNotContains(self.client.get(url), 'id="browser-processing-toggle"')
BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True)
for url in (reverse("hello"), reverse("fireworks_detect:fireworks")):
page = self.client.get(url)
self.assertContains(page, 'id="browser-processing-toggle" type="checkbox"')
self.assertNotContains(page, 'id="browser-processing-toggle" type="checkbox" checked')
self.assertContains(page, 'accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus"')
def test_enabled_policy_reuses_current_rules_and_exposes_no_secrets(self):
BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True)
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
ClassificationRule.objects.create(value="Disabled sound", rule_type=ClassificationRule.RuleType.WHITELIST, enabled=False)
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
ClassificationRule.objects.create(value="Music", rule_type=ClassificationRule.RuleType.BLACKLIST)
policy = self.client.get(reverse("fireworks_detect:browser_policy")).json()
self.assertTrue(policy["browser_processing_beta_enabled"])
self.assertEqual(policy["whitelist"], ["Fireworks"])
self.assertIn("Speech", policy["privacy_sensitive_speech"])
self.assertEqual(policy["thresholds"], {"relevance": 0.5, "speech": 0.5})
self.assertEqual(policy["model_url"], "/static/browser-yamnet/model.json")
self.assertNotIn("token", json.dumps(policy).lower())
BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=False)
self.assertFalse(self.client.get(reverse("fireworks_detect:browser_policy")).json()["browser_processing_beta_enabled"])
@patch("fireworks_detect.views.urlopen")
def test_old_upload_and_advisory_metadata_keep_server_classifier_authoritative(self, urlopen):
reply = MagicMock()
reply.read.return_value = b'{"predictions": [{"class": "Speech", "score": 0.9}]}'
urlopen.return_value.__enter__.return_value = reply
url = reverse("fireworks_detect:classify_upload")
audio = lambda: SimpleUploadedFile("sample.wav", b"RIFF0000WAVEdata", content_type="audio/wav")
old = self.client.post(url, {"audio": audio()})
self.assertEqual(old.status_code, 200)
self.assertContains(old, "Speech")
metadata = json.dumps({
"browser_processing_used": True, "browser_processing_version": 1,
"browser_gate_result": "whitelist_match", "browser_override": False,
"secret": "ignored",
})
future = self.client.post(url, {"audio": audio(), "browser_processing_metadata": metadata})
self.assertEqual(future.status_code, 200)
self.assertContains(future, "Speech")
self.assertNotContains(future, "whitelist_match")
self.assertEqual(urlopen.call_count, 2)
self.assertNotIn(b"whitelist_match", urlopen.call_args.args[0].data)
self.assertEqual(advisory_browser_metadata({"browser_processing_metadata": metadata}), {
"browser_processing_used": True, "browser_processing_version": 1,
"browser_gate_result": "whitelist_match", "browser_override": False,
})
self.assertEqual(advisory_browser_metadata({"browser_processing_metadata": '{"browser_gate_result": []}'}), {})
def test_pending_submission_accepts_metadata_without_storing_it_as_classification(self):
payload = {"predictions": [{"class": "Fireworks", "score": 0.8}]}
token = signing.dumps(payload, salt="fireworks_detect.classification")
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root), patch.object(
PendingEvent._meta.get_field("audio_file"), "storage", FileSystemStorage(location=media_root)
):
response = self.client.post(reverse("fireworks_detect:submit_pending"), {
"audio": SimpleUploadedFile("sample.wav", b"RIFF0000WAVEdata", content_type="audio/wav"),
"classification_token": token,
"browser_processing_metadata": '{"browser_processing_used": true, "browser_gate_result": "whitelist_match"}',
})
self.assertEqual(response.status_code, 200)
self.assertEqual(PendingEvent.objects.get().classifier_response, payload)
@patch("fireworks_detect.views.urlopen")
def test_speech_override_runs_server_classifier_and_enters_pending(self, urlopen):
reply = MagicMock()
reply.read.return_value = b'{"predictions": [{"class": "Speech", "score": 0.9}]}'
urlopen.return_value.__enter__.return_value = reply
BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True)
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root), patch.object(
PendingEvent._meta.get_field("audio_file"), "storage", FileSystemStorage(location=media_root)
):
response = self.client.post(reverse("fireworks_detect:classify_upload"), {
"audio": SimpleUploadedFile("speech.wav", b"RIFF0000WAVEdata", content_type="audio/wav"),
"browser_processing_metadata": json.dumps({
"browser_processing_used": True, "browser_processing_version": 1,
"browser_gate_result": "speech_only", "browser_override": True,
}),
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "review-submission")
pending = PendingEvent.objects.get()
self.assertEqual(pending.classifier_response, {"predictions": [{"class": "Speech", "score": 0.9}]})
self.assertEqual(urlopen.call_count, 1)
self.assertNotIn(b"speech_only", urlopen.call_args.args[0].data)
@patch("fireworks_detect.views.urlopen")
def test_no_match_override_enters_pending_and_forged_whitelist_does_not_skip_classifier(self, urlopen):
reply = MagicMock()
reply.read.return_value = b'{"predictions": [{"class": "Music", "score": 0.9}]}'
urlopen.return_value.__enter__.return_value = reply
BrowserProcessingSettings.objects.update(browser_processing_beta_enabled=True)
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root), patch.object(
PendingEvent._meta.get_field("audio_file"), "storage", FileSystemStorage(location=media_root)
):
response = self.client.post(reverse("fireworks_detect:classify_upload"), {
"audio": SimpleUploadedFile("music.wav", b"RIFF0000WAVEdata", content_type="audio/wav"),
"browser_processing_metadata": '{"browser_gate_result":"no_match","browser_override":true}',
})
self.assertEqual(response.status_code, 200)
self.assertEqual(PendingEvent.objects.count(), 1)
response = self.client.post(reverse("fireworks_detect:classify_upload"), {
"audio": SimpleUploadedFile("sample.wav", b"RIFF0000WAVEdata", content_type="audio/wav"),
"browser_processing_metadata": '{"browser_gate_result":"whitelist_match","browser_override":false}',
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Music")
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(urlopen.call_count, 2)
+421
View File
@@ -0,0 +1,421 @@
from datetime import timedelta
from decimal import Decimal
from unittest.mock import MagicMock, patch
from urllib.error import URLError
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.messages import get_messages, constants as message_levels
from django.db import IntegrityError, transaction
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from .h3_utils import cell_from_coordinates, h3_resolution
from .models import ClassificationRule, Event, PendingEvent
class ClassificationRuleApiTests(TestCase):
def test_whitelist_returns_only_enabled_whitelist_entries_in_value_order(self):
ClassificationRule.objects.create(value="Explosion", rule_type=ClassificationRule.RuleType.WHITELIST)
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
ClassificationRule.objects.create(value="Disabled firework", rule_type=ClassificationRule.RuleType.WHITELIST, enabled=False)
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
response = self.client.get(reverse("classification_rules:whitelist"))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"classifications": ["Explosion", "Fireworks"]})
def test_blacklist_returns_only_enabled_blacklist_entries_in_value_order(self):
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
ClassificationRule.objects.create(value="Conversation", rule_type=ClassificationRule.RuleType.BLACKLIST)
ClassificationRule.objects.create(value="Disabled music", rule_type=ClassificationRule.RuleType.BLACKLIST, enabled=False)
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
response = self.client.get(reverse("classification_rules:blacklist"))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"classifications": ["Conversation", "Speech"]})
def test_classification_rule_is_unique_within_a_rule_type(self):
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
with transaction.atomic():
with self.assertRaises(IntegrityError):
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.BLACKLIST)
class ManualPendingEventTests(TestCase):
def setUp(self):
self.client.cookies["django_language"] = "en"
def test_manual_report_creates_a_timestamped_pending_event(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "4",
"latitude": "52.1234567",
"longitude": "5.9876543",
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Report received!")
self.assertContains(response, "4 occurrences")
self.assertContains(response, 'data-result="success"')
pending = PendingEvent.objects.get()
self.assertEqual(pending.original_filename, "Manual fireworks report")
self.assertEqual(pending.source_type, PendingEvent.SourceType.MANUAL)
self.assertEqual(pending.occurrences, 4)
self.assertEqual(pending.latitude, Decimal("52.123457"))
self.assertEqual(pending.longitude, Decimal("5.987654"))
self.assertEqual(pending.h3_cell, cell_from_coordinates(pending.latitude, pending.longitude))
self.assertIsNone(pending.direction_degrees)
self.assertIsNone(pending.direction_accuracy_degrees)
self.assertEqual(pending.direction_source, "")
self.assertFalse(pending.sensor)
self.assertFalse(pending.audio_file)
self.assertEqual(pending.classifier_response, {})
self.assertIsNotNone(pending.created_at)
def test_manual_report_rejects_an_invalid_occurrence_count(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "0"})
self.assertEqual(response.status_code, 400)
self.assertContains(response, "Choose between 1 and 1,000 occurrences.", status_code=400)
self.assertContains(response, 'data-result="error"', status_code=400)
self.assertFalse(PendingEvent.objects.exists())
def test_manual_report_accepts_optional_wav_on_the_same_pending_event(self):
from tempfile import TemporaryDirectory
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
wav = SimpleUploadedFile("browser.wav", b"RIFF" + b"\x00" * 4 + b"WAVEfmt ", content_type="audio/wav")
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "1", "audio": wav})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
self.assertEqual(pending.source_type, PendingEvent.SourceType.MANUAL)
self.assertIn("sound-signal-manual-", pending.audio_file.name)
self.assertNotIn("browser.wav", pending.audio_file.name)
def test_manual_report_rejects_non_wav_attachment(self):
audio = SimpleUploadedFile("bad.wav", b"not a WAV file", content_type="audio/wav")
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "1", "audio": audio})
self.assertEqual(response.status_code, 400)
self.assertFalse(PendingEvent.objects.exists())
def test_pending_admin_change_page_renders_for_manual_audio(self):
staff = get_user_model().objects.create_superuser("pending-reviewer", "reviewer@example.com", "test-password")
pending = PendingEvent.objects.create(
original_filename="Manual fireworks report",
classifier_response={},
source_type=PendingEvent.SourceType.MANUAL,
audio_file="fireworks_audio/example.wav",
)
self.client.force_login(staff)
response = self.client.get(reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk]))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'class="audio-play"')
def test_event_details_and_source_type_are_kept_when_a_pending_event_is_approved(self):
pending = PendingEvent.objects.create(
original_filename="Manual fireworks report",
classifier_response={},
source_type=PendingEvent.SourceType.MANUAL,
occurrences=3,
location="Back garden",
latitude=Decimal("52.123456"),
longitude=Decimal("5.987654"),
h3_cell=cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")),
direction_degrees=237,
direction_accuracy_degrees=8,
direction_source="device_compass",
visually_confirmed=True,
)
event = pending.approve()
self.assertEqual(event.source_type, PendingEvent.SourceType.MANUAL)
self.assertEqual(event.occurrences, 3)
self.assertEqual(event.location, "Back garden")
self.assertEqual(event.latitude, Decimal("52.123456"))
self.assertEqual(event.longitude, Decimal("5.987654"))
self.assertEqual(event.h3_cell, pending.h3_cell)
self.assertEqual(event.direction_degrees, 237)
self.assertEqual(event.direction_accuracy_degrees, 8)
self.assertEqual(event.direction_source, "device_compass")
self.assertTrue(event.visually_confirmed)
def test_existing_style_records_default_to_sensor_source_type(self):
pending = PendingEvent.objects.create(original_filename="recording.wav", classifier_response={})
self.assertEqual(pending.source_type, PendingEvent.SourceType.SENSOR)
def test_home_page_includes_the_manual_report_form(self):
response = self.client.get(reverse("hello"))
self.assertContains(response, "Report fireworks now")
self.assertContains(response, "I heard fireworks")
self.assertContains(response, "Capture direction")
self.assertContains(response, 'id="manual-decrease"')
self.assertContains(response, 'id="manual-increase"')
self.assertContains(response, 'id="manual-direction-panel"')
self.assertContains(response, 'hx-get="/fireworks/manual-direction/?mode=measure"')
self.assertContains(response, 'id="manual-compass"')
self.assertContains(response, 'aria-label="Compass direction" hidden')
self.assertContains(response, "htmx.min.js")
self.assertContains(response, "/static/vite/")
self.assertContains(response, 'type="module"')
self.assertContains(response, "Activity map")
self.assertContains(response, "Open map controls")
self.assertContains(response, "Classify a recording")
def test_direction_subsection_opens_and_closes_with_htmx_fragments(self):
url = reverse("fireworks_detect:manual_direction_panel")
measuring = self.client.get(url, {"mode": "measure"}, HTTP_HX_REQUEST="true")
self.assertContains(measuring, 'id="manual-capture-direction"')
self.assertContains(measuring, 'hx-target="#manual-direction-panel"')
closed = self.client.get(url, HTTP_HX_REQUEST="true")
self.assertContains(closed, 'id="manual-direction-summary"')
self.assertNotContains(closed, 'id="manual-capture-direction"')
def test_dutch_report_labels_and_direction_are_translated(self):
self.client.cookies["django_language"] = "nl"
page = self.client.get(reverse("hello"))
self.assertContains(page, "Hoe vaak hoorde je het?")
self.assertContains(page, "Ik hoorde vuurwerk")
self.assertContains(page, "Start luisteren")
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "1", "direction_degrees": "192",
})
self.assertContains(response, "Melding ontvangen!")
self.assertContains(response, "Zuid 192°")
def test_old_route_preserves_the_previous_landing_page(self):
response = self.client.get(reverse("old_home"))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Welcome Joren")
self.assertContains(response, "Open fireworks detector")
def test_manual_event_appears_in_the_normal_event_list_with_its_details(self):
event = Event.objects.create(
original_filename="Manual fireworks report",
classifier_response={},
source_type=Event.SourceType.MANUAL,
occurrences=5,
location="Back garden",
latitude=Decimal("52.123456"),
longitude=Decimal("5.987654"),
direction_degrees=237,
direction_accuracy_degrees=8,
visually_confirmed=True,
)
list_response = self.client.get(reverse("fireworks_detect:events_list"))
self.assertContains(list_response, "Manual fireworks report")
self.assertContains(list_response, "5 occurrences")
self.assertContains(list_response, "Back garden")
detail_response = self.client.get(reverse("fireworks_detect:event_detail", args=[event.pk]))
self.assertContains(detail_response, "Report details")
self.assertContains(detail_response, "Visually confirmed")
self.assertContains(detail_response, "Captured location")
self.assertContains(detail_response, cell_from_coordinates(event.latitude, event.longitude))
self.assertNotContains(detail_response, "52.123456, 5.987654")
self.assertContains(detail_response, "237° (SW)")
self.assertContains(detail_response, "Compass accuracy")
@override_settings(FIREWORKS_H3_RESOLUTION=8)
def test_h3_resolution_is_configurable(self):
self.assertEqual(h3_resolution(), 8)
self.assertTrue(cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")))
def test_map_uses_manual_h3_data_and_excludes_sensor_events(self):
manual_cell = cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654"))
sensor_cell = cell_from_coordinates(Decimal("53.123456"), Decimal("5.987654"))
Event.objects.create(
original_filename="Manual fireworks report",
classifier_response={},
source_type=Event.SourceType.MANUAL,
occurrences=4,
latitude=Decimal("52.123456"),
longitude=Decimal("5.987654"),
h3_cell=manual_cell,
visually_confirmed=True,
direction_degrees=237,
direction_accuracy_degrees=8,
)
Event.objects.create(
original_filename="Sensor recording.wav",
classifier_response={},
source_type=Event.SourceType.SENSOR,
occurrences=9,
latitude=Decimal("53.123456"),
longitude=Decimal("5.987654"),
h3_cell=sensor_cell,
)
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all"})
self.assertContains(response, "H3 resolution 9")
self.assertContains(response, "map-events-data")
self.assertContains(response, manual_cell)
self.assertContains(response, '"direction_degrees": 237.0')
self.assertContains(response, "data-h3-resolution")
self.assertContains(response, 'type="module"')
self.assertContains(response, "sensor layer disabled")
self.assertContains(response, "Sensor events — coming soon")
self.assertNotContains(response, sensor_cell)
self.assertNotContains(response, "52.123456")
self.assertNotContains(response, "H3 demo cell")
def test_map_date_range_filters_manual_reports(self):
recent_cell = cell_from_coordinates(Decimal("52.400000"), Decimal("5.700000"))
older_cell = cell_from_coordinates(Decimal("53.400000"), Decimal("5.700000"))
Event.objects.create(
original_filename="Recent manual report", classifier_response={},
source_type=Event.SourceType.MANUAL, latitude=Decimal("52.400000"),
longitude=Decimal("5.700000"), h3_cell=recent_cell,
)
older = Event.objects.create(
original_filename="Older manual report", classifier_response={},
source_type=Event.SourceType.MANUAL, latitude=Decimal("53.400000"),
longitude=Decimal("5.700000"), h3_cell=older_cell,
)
Event.objects.filter(pk=older.pk).update(created_at=timezone.now() - timedelta(days=8))
response = self.client.get(reverse("fireworks_detect:map"), {"range": "7"})
self.assertContains(response, recent_cell)
self.assertNotContains(response, older_cell)
self.assertContains(response, "Last 7 days")
def test_manual_report_saves_a_valid_compass_direction_and_accuracy(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "2",
"direction_degrees": "237",
"direction_accuracy_degrees": "8",
})
self.assertContains(response, "2 occurrences")
self.assertContains(response, "Southwest 237°")
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
self.assertEqual(pending.direction_degrees, 237)
self.assertEqual(pending.direction_accuracy_degrees, 8)
self.assertEqual(pending.direction_source, "device_compass")
self.assertEqual(pending.direction_cardinal, "SW")
def test_zero_degree_direction_is_valid_and_accuracy_may_be_absent(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "1",
"direction_degrees": "0",
})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
self.assertEqual(pending.direction_degrees, 0)
self.assertIsNone(pending.direction_accuracy_degrees)
self.assertEqual(pending.direction_cardinal, "N")
def test_invalid_directions_are_rejected_by_model_validation_and_not_saved_by_manual_submission(self):
for invalid_direction in (-1, 360):
pending = PendingEvent(
original_filename="Manual fireworks report",
classifier_response={},
direction_degrees=invalid_direction,
)
with self.assertRaises(ValidationError):
pending.full_clean()
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "1",
"direction_degrees": str(invalid_direction),
})
self.assertEqual(response.status_code, 200)
saved = PendingEvent.objects.latest("created_at")
self.assertIsNone(saved.direction_degrees)
self.assertIsNone(saved.direction_accuracy_degrees)
self.assertEqual(saved.direction_source, "")
class PendingClassificationAdminTests(TestCase):
def setUp(self):
self.client.cookies["django_language"] = "en"
self.staff = get_user_model().objects.create_superuser("classifier-reviewer", "classifier@example.com", "test-password")
self.client.force_login(self.staff)
def test_classify_button_saves_json_without_approving(self):
from tempfile import TemporaryDirectory
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
audio = SimpleUploadedFile("sample.wav", b"RIFF" + b"\x00" * 4 + b"WAVEdata", content_type="audio/wav")
pending = PendingEvent.objects.create(original_filename="Manual fireworks report", classifier_response={"manual_note": "keep"}, source_type=PendingEvent.SourceType.MANUAL, audio_file=audio)
url = reverse("admin:fireworks_detect_pendingevent_classify", args=[pending.pk])
change = self.client.get(reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk]))
self.assertContains(change, url)
mocked_response = MagicMock()
mocked_response.read.return_value = b'{"predictions": [{"class": "Fireworks", "score": 0.91}]}'
mocked_response.__enter__.return_value = mocked_response
with patch("fireworks_detect.admin.urlopen", return_value=mocked_response) as classifier_call:
response = self.client.post(url)
self.assertEqual(response.status_code, 302)
request = classifier_call.call_args.args[0]
self.assertIn(b'name="file"', request.data)
self.assertIn(b"RIFF", request.data)
pending.refresh_from_db()
self.assertEqual(pending.classifier_response["predictions"][0]["class"], "Fireworks")
self.assertEqual(pending.classifier_response["manual_note"], "keep")
self.assertTrue(PendingEvent.objects.filter(pk=pending.pk).exists())
self.assertFalse(Event.objects.exists())
def test_classify_requires_post_and_audio(self):
pending = PendingEvent.objects.create(original_filename="Manual report", classifier_response={})
url = reverse("admin:fireworks_detect_pendingevent_classify", args=[pending.pk])
self.assertEqual(self.client.get(url).status_code, 405)
self.assertEqual(self.client.post(url).status_code, 302)
pending.refresh_from_db()
self.assertEqual(pending.classifier_response, {})
def test_classifier_failure_preserves_existing_json_and_pending_record(self):
from tempfile import TemporaryDirectory
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
pending = PendingEvent.objects.create(
original_filename="sample.wav",
classifier_response={"previous": "result"},
audio_file=SimpleUploadedFile("sample.wav", b"RIFFdata", content_type="audio/wav"),
)
url = reverse("admin:fireworks_detect_pendingevent_classify", args=[pending.pk])
with patch("fireworks_detect.admin.urlopen", side_effect=URLError("offline")):
response = self.client.post(url, follow=True)
self.assertEqual(response.status_code, 200)
self.assertTrue(any(message.level == message_levels.ERROR for message in get_messages(response.wsgi_request)))
pending.refresh_from_db()
self.assertEqual(pending.classifier_response, {"previous": "result"})
self.assertTrue(PendingEvent.objects.filter(pk=pending.pk).exists())
def test_view_only_staff_cannot_classify(self):
pending = PendingEvent.objects.create(original_filename="sample.wav", classifier_response={}, audio_file="fireworks_audio/sample.wav")
viewer = get_user_model().objects.create_user("viewer", "viewer@example.com", "test-password", is_staff=True)
viewer.user_permissions.add(Permission.objects.get(codename="view_pendingevent"))
self.client.force_login(viewer)
change = self.client.get(reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk]))
self.assertEqual(change.status_code, 200)
self.assertNotContains(change, reverse("admin:fireworks_detect_pendingevent_classify", args=[pending.pk]))
response = self.client.post(reverse("admin:fireworks_detect_pendingevent_classify", args=[pending.pk]))
self.assertEqual(response.status_code, 403)
+37
View File
@@ -0,0 +1,37 @@
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,
manual_direction_panel,
submit_manual_pending_event,
submit_pending_event,
sensor_heartbeat,
browser_processing_policy,
)
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("browser-policy/", browser_processing_policy, name="browser_policy"),
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
path("submit-pending/", submit_pending_event, name="submit_pending"),
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
path("manual-direction/", manual_direction_panel, name="manual_direction_panel"),
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"),
]
+528
View File
@@ -0,0 +1,528 @@
import math
from datetime import timedelta
from decimal import Decimal, InvalidOperation
import json
import logging
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.utils import timezone
from django.utils.dateparse import parse_date
from django.utils.translation import gettext as _
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 .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
from .browser_policy import advisory_browser_metadata, browser_config, browser_policy
from .models import BrowserProcessingSettings, ClassificationRule, 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"}
logger = logging.getLogger(__name__)
@require_http_methods(["GET"])
@never_cache
def browser_processing_policy(request):
return JsonResponse(browser_policy())
@never_cache
def fireworks_view(request):
return render(request, "fireworks_detect/home.html", {"browser_processing_config": browser_config()})
MAP_DATE_RANGES = {
"7": 7,
"14": 14,
"30": 30,
"all": None,
"custom": None,
}
def _map_filters(request):
"""Return the selected map filters, using an inclusive date range."""
selected_range = request.GET.get("range", "14")
if selected_range not in MAP_DATE_RANGES:
selected_range = "14"
if selected_range == "custom":
date_from = parse_date(request.GET.get("from", ""))
date_to = parse_date(request.GET.get("to", ""))
elif MAP_DATE_RANGES[selected_range]:
date_to = timezone.localdate()
date_from = date_to - timedelta(days=MAP_DATE_RANGES[selected_range] - 1)
else:
date_from = date_to = None
visual = request.GET.get("visual", "all")
if visual not in {"all", "yes", "no"}:
visual = "all"
return {
"date_from": date_from,
"date_to": date_to,
"range": selected_range,
"visual": visual,
}
def _events_for_map(filters):
"""Create privacy-preserving map data for reviewed manual reports only."""
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
if filters["date_from"]:
events = events.filter(created_at__date__gte=filters["date_from"])
if filters["date_to"]:
events = events.filter(created_at__date__lte=filters["date_to"])
if filters["visual"] == "yes":
events = events.filter(visually_confirmed=True)
elif filters["visual"] == "no":
events = events.filter(visually_confirmed=False)
cells = {}
mapped_events = []
for event in events.values(
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
"direction_degrees", "direction_accuracy_degrees", "created_at",
):
# Coordinates are used only here to derive an H3 cell; they never leave the server.
h3_cell = event["h3_cell"] or cell_from_coordinates(event["latitude"], event["longitude"])
center = cell_center(h3_cell) if h3_cell else None
boundary = cell_boundary(h3_cell) if h3_cell else None
if not center or not boundary:
continue
aggregate = cells.setdefault(h3_cell, {
"cell": h3_cell,
"boundary": boundary,
"center": center,
"reports": 0,
"occurrences": 0,
})
aggregate["reports"] += 1
aggregate["occurrences"] += event["occurrences"]
mapped_events.append({
"cell": h3_cell,
"center": center,
"occurrences": event["occurrences"],
"visually_confirmed": event["visually_confirmed"],
# A day is sufficient for this map and avoids sharing a precise report time.
"reported_on": event["created_at"].date().isoformat(),
"direction_degrees": float(event["direction_degrees"]) if event["direction_degrees"] is not None else None,
"direction_accuracy_degrees": (
float(event["direction_accuracy_degrees"])
if event["direction_accuracy_degrees"] is not None else None
),
})
return mapped_events, list(cells.values())
@never_cache
def fireworks_map_view(request):
filters = _map_filters(request)
map_events, h3_cells = _events_for_map(filters)
return render(request, "fireworks_detect/map.html", {
"h3_resolution": h3_resolution(),
"h3_cells": h3_cells,
"map_events": map_events,
"mapped_event_count": len(map_events),
"map_filters": {
"date_from": filters["date_from"].isoformat() if filters["date_from"] else "",
"date_to": filters["date_to"].isoformat() if filters["date_to"] else "",
"range": filters["range"],
"visual": filters["visual"],
},
})
@never_cache
def dashboard_view(request):
map_events, h3_cells = _events_for_map({
"date_from": None,
"date_to": None,
"range": "all",
"visual": "all",
})
return render(request, "fireworks_detect/dashboard.html", {
"h3_resolution": h3_resolution(),
"h3_cells": h3_cells,
"map_events": map_events,
"browser_processing_config": browser_config(),
})
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 = getattr(uploaded_file, "content_type", None) 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."))
metadata = advisory_browser_metadata(request.POST)
if metadata:
logger.info("Browser beta diagnostics (advisory only): %s", metadata)
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, _("The classifier returned an error (HTTP %(code)s).") % {"code": 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)
override = (
BrowserProcessingSettings.enabled()
and metadata.get("browser_override") is True
and metadata.get("browser_gate_result") in {"speech_only", "no_match"}
)
if override:
# The browser gate is advisory. Always classify server-side first, then
# force this explicit override into Pending Review regardless of scores.
pending = PendingEvent.objects.create(
audio_file=uploaded_file,
original_filename=uploaded_file.name,
classifier_response=payload,
)
context["pending"] = pending
logger.info("Browser override sent to Pending Review: %s", pending.pk)
else:
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):
metadata = advisory_browser_metadata(request.POST)
if metadata:
logger.info("Browser beta submission diagnostics (advisory only): %s", metadata)
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})
def _manual_coordinates(request):
try:
latitude = Decimal(request.POST.get("latitude", ""))
longitude = Decimal(request.POST.get("longitude", ""))
if not -90 <= latitude <= 90 or not -180 <= longitude <= 180:
return None, None
return latitude.quantize(Decimal("0.000001")), longitude.quantize(Decimal("0.000001"))
except (InvalidOperation, TypeError, ValueError):
return None, None
def _manual_direction(request):
try:
heading = float(request.POST.get("direction_degrees", ""))
except (TypeError, ValueError):
return None, None
if not math.isfinite(heading) or not 0 <= heading < 360:
return None, None
try:
accuracy = float(request.POST.get("direction_accuracy_degrees", ""))
except (TypeError, ValueError):
accuracy = None
if accuracy is not None and (not math.isfinite(accuracy) or accuracy < 0):
accuracy = None
return heading, accuracy
@require_http_methods(["GET"])
@never_cache
def manual_direction_panel(request):
return render(request, "fireworks_detect/includes/manual_direction_panel.html", {
"measuring": request.GET.get("mode") == "measure",
})
@require_http_methods(["POST"])
@never_cache
def submit_manual_pending_event(request):
try:
occurrences = int(request.POST.get("occurrences", ""))
except (TypeError, ValueError):
occurrences = 0
if not 1 <= occurrences <= 1000:
return render(
request,
"fireworks_detect/manual_pending_submission.html",
{"error": _("Choose between 1 and 1,000 occurrences.")},
status=400,
)
uploaded_file = request.FILES.get("audio")
if uploaded_file:
if uploaded_file.size > MAX_AUDIO_SIZE or uploaded_file.content_type not in ("audio/wav", "audio/wave", "audio/x-wav"):
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Please attach a WAV clip no larger than 25 MiB.")}, status=400)
header = uploaded_file.read(12)
uploaded_file.seek(0)
if len(header) != 12 or header[:4] != b"RIFF" or header[8:] != b"WAVE":
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("The attached audio is not a WAV file.")}, status=400)
uploaded_file.name = f"sound-signal-manual-{timezone.now():%Y%m%d-%H%M%S}-{uuid.uuid4().hex[:8]}.wav"
latitude, longitude = _manual_coordinates(request)
h3_cell = cell_from_coordinates(latitude, longitude)
direction_degrees, direction_accuracy_degrees = _manual_direction(request)
pending = PendingEvent.objects.create(
audio_file=uploaded_file,
original_filename="Manual fireworks report",
classifier_response={},
source_type=PendingEvent.SourceType.MANUAL,
occurrences=occurrences,
latitude=latitude,
longitude=longitude,
h3_cell=h3_cell or "",
direction_degrees=direction_degrees,
direction_accuracy_degrees=direction_accuracy_degrees,
direction_source="device_compass" if direction_degrees is not None else "",
)
direction_names = {
"N": _("North"), "NE": _("Northeast"), "E": _("East"), "SE": _("Southeast"),
"S": _("South"), "SW": _("Southwest"), "W": _("West"), "NW": _("Northwest"),
}
return render(request, "fireworks_detect/manual_pending_submission.html", {
"pending": pending,
"direction_label": direction_names.get(pending.direction_cardinal) if direction_degrees is not None else "",
})
@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
context["event_h3_cell"] = event.h3_cell or cell_from_coordinates(event.latitude, event.longitude)
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()})
@require_http_methods(["GET"])
def classification_whitelist(request):
classifications = ClassificationRule.objects.filter(
rule_type=ClassificationRule.RuleType.WHITELIST,
enabled=True,
).order_by("value").values_list("value", flat=True)
return JsonResponse({"classifications": list(classifications)})
@require_http_methods(["GET"])
def classification_blacklist(request):
classifications = ClassificationRule.objects.filter(
rule_type=ClassificationRule.RuleType.BLACKLIST,
enabled=True,
).order_by("value").values_list("value", flat=True)
return JsonResponse({"classifications": list(classifications)})
+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)
@@ -0,0 +1,2 @@
import "../styles/pages/admin-audio-preview.css";
import "../scripts/admin-audio-preview.js";
+1
View File
@@ -0,0 +1 @@
import "../styles/pages/admin-login.css";
+12
View File
@@ -0,0 +1,12 @@
import "../styles/components/fireworks-navigation.css";
import "../styles/pages/fireworks-home.css";
import "../styles/pages/map.css";
import "../styles/pages/dashboard.css";
import "../styles/components/burst-listener.css";
import "../styles/components/manual-compass.css";
import "../styles/components/manual-report-structure.css";
import "../styles/theme.css";
import "../scripts/theme.js";
import "../scripts/manual-report.js";
import "../scripts/audio-upload.js";
import "../scripts/event-map.js";

Some files were not shown because too many files have changed in this diff Show More