Compare commits

..
Author SHA1 Message Date
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
503 changed files with 2026 additions and 38673 deletions
-7
View File
@@ -1,10 +1,3 @@
vite_integration/static/vite/*
!vite_integration/static/vite/.gitkeep
node_modules/
# Local database and uploaded media
/db.sqlite3
/media/
# Local archives
*.zip
-11
View File
@@ -1,11 +0,0 @@
# Burst Events
A report with at least three `occurrences` is a Burst Event. `event_kind`, `is_burst`, `bangs_per_15_minutes`, and `burst_intensity` are derived properties on both PendingEvent and Event; they are never stored separately. One or two occurrences are ordinary reports.
`captured_at` is the reported occurrence time for a manual report. PendingEvent `created_at` is its actual submission time; approval copies that value into Event `submitted_at`, while Event `approved_at` remains the approval time. Older Events have an unknown `submitted_at` because their original submission time cannot be reconstructed. `occurrence_time_approximate` records uncertainty about the reported time. No individual bang times are inferred from an aggregate report.
`observation_duration_minutes` holds a window only when the reporter explicitly accepts an estimate, or when a future source provides a measured window. `observation_duration_kind` distinguishes `estimated` from `measured`; a blank kind or duration means intensity is unavailable. The quick form suggests 15 minutes and asks the reporter to accept that estimate. Existing records migrate with an unknown duration, preserving their counts without inventing an intensity.
The normalised rate is `occurrences × 15 / observation_duration_minutes`. Provisional presentation bands live in `fireworks_detect/bursts.py`: light below 5, moderate from 5 to below 10, intense from 10 per 15 minutes. This describes **frequency, not loudness**. The map event JSON exposes the count, event kind, duration, duration kind, rate, intensity, and approximate-time flag for future timeline work. No timeline is rendered in this pass.
Quick reports remain Pending until moderated. The browser can enhance the form, while the POST endpoint also accepts an ordinary server-rendered form submission with no microphone, classifier, or JavaScript. A reporter can correct the count and estimated duration before moderation through a session-scoped receipt form; each correction creates a ManualReportRevision. Corrections do not change the original occurrence or submission time.
-28
View File
@@ -1,28 +0,0 @@
# Burst Listening iPhone PWA field test
This feature is a foreground experiment. An installed PWA, Guided Access, or a
screen wake lock cannot guarantee microphone continuity after screen lock,
backgrounding, an incoming call, or iOS memory pressure. Keep the screen on
and watch the visible stream state. Do not count time after an interruption as
covered listening time.
For each run, record the iPhone model, iOS version, browser/PWA mode, network,
selected test setup, start/end time, and battery levels. Export the diagnostic
JSON before closing the review page. Compare its last client audio frame,
last server heartbeat, server timeout detection, and first resumed observation.
The interval between them is uncertain; neither timestamp proves when the mic
stopped. A server timeout proves only that HTTP heartbeats stopped arriving.
| Duration | Setup | Stimulus and checks |
| --- | --- | --- |
| 10 min | Foreground, screen on | Four spaced bangs; verify four playable clips, quiet interval, stop/review/submit. |
| 15 min | Installed Home Screen PWA, Guided Access with Display Auto-Lock Never | Four spaced bangs and two close bangs; check clip grouping, waveform, timer, battery, memory and server timeline. |
| 20 min | Foreground with optional Wake Lock | Verify auto-stop, bounded clips, upload retries, cleanup and server expiry. |
| Short runs | Manual lock, natural auto-lock, background/foreground, incoming call, low battery, network loss/reconnect | Confirm visible interruption, no automatic restart, recovered clips and uncertainty interval. |
The shared server watchdog must be running for the independent 15-second
heartbeat-lost diagnostic. Start the provided systemd user service or run
`python manage.py watch_burst_sessions --interval 5` under the same environment
as Django. The 10/15/20-minute physical iPhone scenarios remain unverified
until tested on a device. Local browser tests cannot emulate iOS suspension or
microphone access under Guided Access.
-105
View File
@@ -1,105 +0,0 @@
# Field notes: specification review and implementation
## Review decisions
The requested separation between recorded evidence and human context fits the
application. Inspection found these differences from the illustrative spec:
1. **Bursts are Event/PendingEvent records with occurrences >= 3**, not separate
incidents. The live browser listener has no server-side event until submission.
`FieldNoteContext` is a small, author-owned association record, with no incident
timestamps, count, audio or classification of its own. It holds a draft UUID and
later references the existing PendingEvent or Event. Multiple notes attach once
to that report rather than being copied across individual bangs.
2. **Pending manual ownership was session-based.** Note contexts preserve author
attribution across sessions without inventing ownership for old reports. New
draft tokens are signed, author-bound and expire after seven days. A submitted
token cannot be reused for another report; the UI rotates it on success. Late
note saves still follow the original report through moderation.
3. **The frontend uses custom SCSS, HTMX and existing theme tokens**, not Bootstrap.
These conventions are reused; no second CSS framework is introduced.
4. **There was no incident export pipeline or event merge UI.** Added CSV/JSON
note exports through one permission-filtered service. PDF export and event
regrouping interfaces remain outside this pass. A tested regrouping service
preserves note provenance for future merge operations.
5. **Corrections are new notes.** No edit/delete route or editable admin form is
provided. This keeps original text and entry timestamps unchanged. Verification
labels describe the author's stated assessment, not automated validation.
6. **Timezone follows Django's active timezone**, currently Europe/Amsterdam;
there is no per-user timezone setting. Datetimes are stored timezone-aware,
with the timezone shown beside entry/observation times. Adding a user timezone
preference later can use the same fields.
## Privacy and permissions
- Notes default to private, unknown source and unverified. Only content is required.
- An authenticated author can read/create their own notes. Reportable notes are
still not public and do not become verified.
- Approved events are already public; authenticated users may add their own notes
to them. Pending targets require existing session ownership, sensor ownership,
a note context owned by that user, or staff `view_pendingevent` permission.
- `view_all_fieldnotes` explicitly allows reading other authors' private notes.
Staff status alone does not. Django superusers have this permission.
- `export_reportable_fieldnotes` explicitly allows exporting other authors'
reportable notes. Without it, exports contain only the caller's reportable notes.
**Private notes are excluded even for superusers.** Read-all permission does not
imply export-all permission.
- Every export starts with `field_notes.reportable_notes(user)`. Future PDF/API
reporting must use this service, rather than `visible_to()` or raw relations.
- CSV escapes formula-like user values; HTML renders escaped plain text and keeps
line breaks. Public event/map responses do not serialize note data.
- Link operations are author-only, POST/CSRF-protected, and only accept an existing
approved event. Existing linked notes cannot be silently reparented through the
user endpoint. Each standalone observation context can hold several live notes;
linking it moves that observation's notes together.
- Admin is read-only and uses the same visibility boundary. Association history
is similarly scoped. ORM `save()` rejects note/history edits; direct SQL or
`QuerySet.update()` is not an application editing interface and must not be used
to bypass this policy.
## Lifecycle and interfaces
- The dashboard's Add field note form is adjacent to quick reporting and updates
only its own HTMX region, leaving listener/audio controls mounted and running.
- Submission binds the draft context to Pending Review. Approval atomically moves
contexts to the approved Event and records the moderator (or system/null actor
for non-request approvals). Notes retain their original entry timestamps.
- Denial/deletion clears the foreign key but preserves the note and its historical
target ID. The observation remains available in My field notes.
- `regroup_event_notes(actor, source, target)` requires staff, `change_event` and
`view_all_fieldnotes`. Existing or future merge code must call it inside its
transaction before deleting the source. It moves associations without copying
notes and records previous/current event IDs. No automatic grouping is added.
- Historical event details show only visible notes and counts. Direct event pages
and the archive now have normal links for no-JavaScript access.
- `/fireworks/notes/` creates standalone observations and lists accessible notes;
event/pending filters provide contextual forms. `/fireworks/notes/export/json/`
and `/fireworks/notes/export/csv/` export authorised reportable notes, optionally
filtered by approved event ID.
- Standard POST forms redirect after saving. HTMX forms return their own updated
region; validation responses intentionally use HTTP 200 so HTMX renders errors.
- Occurrence and entry dates are displayed separately. New information is appended
chronologically; author-supplied observed time does not reorder entry history.
## Validation and deployment
Migration `0014` adds three tables, constraints and an author/time index. It does
not rewrite existing event data. Apply with `python manage.py migrate` after
updating the application; build assets with the existing `npm run build` command.
No firmware changes or version bump are needed for this Django-only feature.
Automated tests cover defaults, escaping, anonymous/cross-user access, explicit
staff permissions, private export exclusion (including superuser), source and
uncertainty preservation, observed/entry timestamps, append-only saves, invalid
forms, active draft binding, approval, late saves, stale-token rejection,
standalone linking, regrouping and denied-report retention.
Browser verification uses the actual Django application with an isolated SQLite
DB under `/tmp`. It covers HTMX note saves during a **synthetic browser audio
stream**, listener continuity, report binding/token rotation, historical notes,
mobile/desktop layouts, dark/light appearance, accessibility labels, exports and
standard form submission in a JavaScript-disabled browser context. This is not a
microphone/hardware validation and does not claim classification accuracy.
Out of scope: attachments, CCTV files, witness identity management, PDF generation,
new incident/merge interfaces, full timeline redesign, or changing detection logic.
-245
View File
@@ -1,245 +0,0 @@
# 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.
-56
View File
@@ -105,59 +105,3 @@ 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`.
### Burst Listening watchdog
Run one shared `watch_burst_sessions` process alongside Django so a suspended PWA is
marked heartbeat-lost independently of browser JavaScript. A systemd user service
is provided at `deploy/systemd/watch-burst-sessions.service`; enable it for the
same user and Python environment as Django. `--once` is available for tests and
manual checks. A one-minute cron job cannot meet the 15-second timeout target.
For a user service: copy the unit to `~/.config/systemd/user/`, run
`systemctl --user daemon-reload`, then
`systemctl --user enable --now watch-burst-sessions.service`.
-32
View File
@@ -1,32 +0,0 @@
# Waveshare V2 firmware integration status
The owner has confirmed a non-touch Waveshare ESP32-S3-ePaper-1.54 V2 board. The firmware now lives at `../arduino/BoomCast_Waveshare_Arduino/`; that folder is currently **outside** the Django Git worktree (`django/`). Its sketch, build guide, source, pinned preparation script, local-config example, ignore rules, and hardware/API/checklist documents are there.
The official Waveshare support was inspected at commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`. The Arduino audio `board_cfg.h` and explicitly V2 ESP-IDF audio example agree on ES8311 I2S pins. The official Arduino SD example uses CLK/D0/CMD 39/40/41. The firmware uses those pins. Waveshare documents V2 as 8 MB flash and 8 MB PSRAM and says V1/V2 examples are not interchangeable.
## Implemented in source
- Audio reads now check the codec return code, clear input buffers first, discard failed blocks, abort a capture after a read error, select one fixed microphone slot, and count read/recording errors. Capture duration uses the available pre-roll plus the requested post-roll; UTC capture-start and trigger timestamps are retained when time is valid.
- SD commits use checked WAV and sidecar writes, flush/fsync/close, WAV length/header validation, final renames, interrupted-commit recovery, a queue commit marker, oldest-first selection across the directory, an event-count cap, and a free-space reserve. Incomplete files are excluded from upload.
- Uploads stream file contents through `WiFiClientSecure` with a trusted CA, require HTTPS, send the actual `/api/pending/` fields, parse JSON receipts, verify the echoed event ID and submission ID, and retain files after ambiguous responses. Automatic retries use bounded exponential backoff and jitter. Source-embedded token placeholders were replaced with an ignored local header and optional NVS token; shared setup and management passwords were replaced with per-device NVS passwords.
- ePaper owner status reflects listening, recording, queue/offline, uploading, successful submission, retry failure, and audio error counters.
- Django now returns `event_id` in first and duplicate receipts and accepts an explicit `time_state=unknown` when the device clock was not synchronized. The same Pending Review and classifier pipeline remains in use.
## Verification performed
- Official Waveshare pin/support comparison at the pinned commit.
- The pinned `prepare_from_waveshare.sh` completed successfully against a checkout at that commit.
- Arduino CLI 1.5.1 compiled the sketch for ESP32-S3 with ESP32 core 3.3.0, 8 MB flash, OPI PSRAM, and the 8 MB partition scheme. The only emitted warnings were in copied Waveshare support and Espressif touch APIs.
- The `fireworks_detect` Django suite passed: 39 tests. Firmware-shaped unknown-time and receipt fields have focused backend tests.
- Firmware `.gitignore` patterns were checked for local credentials, copied support, and build artifacts.
## Still open
- **Firmware compile passed; no flash was performed.** Arduino CLI 1.5.1 compiled the sketch with ESP32 core 3.3.0, Waveshare support at the pinned commit, LVGL 8.4.0, ArduinoJson 7.4.3, 8 MB flash, and OPI PSRAM. The build reports 1,350,599 bytes of program storage (40%) and 99,368 bytes of global dynamic memory (30%). Device runtime RAM use is unmeasured.
- **No physical V2 test was performed.** The fixed microphone slot, actual audio fidelity, short successful codec reads, ePaper refresh, SD power-cut behavior, TLS handshake, and offline recovery need the real board.
- Waveshare's codec API reports read success/failure but not a byte count; a successful short read cannot be detected through the current wrapper.
- FAT does not provide an atomic transaction spanning WAV and sidecar. Valid interrupted commits are recovered; incomplete/orphan files remain on SD for manual inspection rather than being uploaded or overwritten.
- The uploader currently runs synchronously in the main loop. During a slow HTTPS attempt, the local web UI and display update may pause. Verify this on hardware and move upload to a worker task if it affects usability or watchdog health.
- Arduino source is not tracked by the current Django Git repository. Decide on a project-wide repository or a dedicated firmware repository before relying on source control for deployment.
See `../arduino/BoomCast_Waveshare_Arduino/docs/validation-checklist.md` for the pending physical acceptance checks. Do not treat this source review or the Django tests as hardware validation.
-11
View File
@@ -1,11 +0,0 @@
# Sensor submission contract (v1)
`POST /api/pending/` accepts `multipart/form-data` from an active, registered sensor. Send `Authorization: Bearer <sensor token>`. The token determines the sensor and owner; send the sensor's database ID in `sensor_id` as an assertion, never as authority.
Required parts: `file` (16-bit PCM mono WAV), `sensor_id`, `event_id` (1–100 ASCII letters, digits, `_` or `-`), `captured_at` (UTC ISO 8601 timestamp with offset or Unix seconds, or omit it with `time_state=unknown` when the device clock was not synchronized), `duration_seconds` (positive number matching the WAV within 0.1 seconds), and `firmware_version` (1–64 printable characters). Optional: `trigger_type` (short label), `signal_rms`, `signal_peak` (finite nonnegative numbers), and `latitude`/`longitude` (untrusted device claims, retained only as metadata). No client location is promoted to the trusted event location.
WAV data must be PCM, mono, 16-bit, at 16 kHz, at most 25 MiB, and 0.1–30 seconds long. A successful first submission returns HTTP 201 with `event_id`, `submission_id`, `status: pending`, and classifier results. A repeat of the same `(sensor, event_id)` returns HTTP 200 with the same `event_id`, `submission_id`, and `duplicate: true`; a different body with the same ID returns HTTP 409. Errors have `code` and `detail` fields. HTTP 429 means retry after the `Retry-After` interval. HTTP 502 means classification failed and the device should retain the queued clip.
The existing `/fireworks/classify/` route remains available for older clients. New firmware should use this contract. Pending audio stays behind the staff-only playback route and follows the existing accept/reject workflow and storage lifetime.
`captured_at` means the start of the actual recorded WAV. Optional `capture_started_at`, `triggered_at`, and `queued_at` are UTC ISO 8601 timestamps; `time_state=unknown` leaves the database capture time null. A missing timestamp without that explicit state is invalid.
BIN
View File
Binary file not shown.
@@ -1,7 +0,0 @@
[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
@@ -1,11 +0,0 @@
[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
@@ -1,13 +0,0 @@
[Unit]
Description=BoomCast Burst Listening heartbeat watchdog
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/jorenmartijn/python/django
ExecStart=/home/jorenmartijn/python/.venv/bin/python /home/jorenmartijn/python/django/manage.py watch_burst_sessions --interval 5
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
-25
View File
@@ -1,25 +0,0 @@
# BoomCast read-only MCP
The stateless Streamable HTTP endpoint is `POST /mcp/` on the **existing Django web server**. The normal local development command uses `127.0.0.1:8000`; MCP needs no second port or process. Use the public HTTPS Django origin for a remote client. Do not expose the local HTTP listener directly.
Run migrations, then issue a separate credential for an active user who has both `fireworks_detect.view_event` and `fireworks_detect.view_pendingevent` permissions:
```sh
python manage.py migrate
python manage.py create_mcp_token USERNAME --name "My MCP client"
```
The command prints the token once. Configure the MCP client with a Streamable HTTP URL such as `https://django.jorendegraaf.eu/mcp/` and header `Authorization: Bearer bmcp_...`. Refresh the client's MCP tools after configuring it. A sensor `ss_...` Bearer token, browser login cookie, or anonymous request cannot access the endpoint. To revoke a credential, set its `McpAccessToken.revoked_at` in Django admin/shell (or delete the record). Removing either Django view permission or deactivating the user also denies access. MCP uses the same Django user permission backend as admin; no write permissions are needed.
Available tools: `submissions_list`, `submissions_get`, `submissions_stats`, and `pending_summary`. Date filters use `YYYY-MM-DD` and apply to review date. A query covers at most 366 days; if omitted, the default is the most recent 366 days. List pages are capped at 100 items and offset 10,000. The endpoint is limited to 120 requests per minute per user. It accepts JSON responses for MCP initialize, tool discovery and tool calls. It supports no write methods or server state changes.
Only approved `Event` rows are individually available. The existing review workflow **deletes denied `PendingEvent` rows**, so historical denial statistics and manually confirmed sound classes do not exist in the current data model. MCP reports `review_outcome: approved`, `confirmed_classification: null`, and `confirmed_classification_available: false` rather than treating a YAMNet prediction as a human confirmation. Pending results contain counts only. The only location field is the existing H3 cell or a cell calculated using the configured H3 resolution; exact coordinates, audio, filenames, free-text locations, notes, sensor identity, and raw classifier responses are omitted.
For a quick protocol check after client setup:
```sh
curl -sS https://django.jorendegraaf.eu/mcp/ \
-H "Authorization: Bearer $BOOMCAST_MCP_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7 -122
View File
@@ -7,23 +7,13 @@ from django.core.exceptions import PermissionDenied
from django.http import HttpResponseNotAllowed
from django.shortcuts import get_object_or_404, redirect
from django.urls import path, reverse
from django.utils.html import format_html, format_html_join
from django.utils.html import format_html
from django.utils.translation import gettext as _, gettext_lazy, ngettext
from .models import BrowserProcessingSettings, BurstCapture, BurstSession, ClassificationRule, Event, ManualReportRevision, McpAccessToken, PendingEvent, Sensor
from .models import ClassificationRule, Event, PendingEvent, Sensor
from . import views as classifier_views
@admin.register(McpAccessToken)
class McpAccessTokenAdmin(admin.ModelAdmin):
list_display = ("user", "name", "created_at", "revoked_at")
readonly_fields = ("user", "name", "token_hash", "created_at")
fields = ("user", "name", "created_at", "revoked_at")
def has_add_permission(self, request):
return False
@admin.register(ClassificationRule)
class ClassificationRuleAdmin(admin.ModelAdmin):
list_display = ("value", "rule_type", "enabled")
@@ -31,39 +21,12 @@ class ClassificationRuleAdmin(admin.ModelAdmin):
search_fields = ("value",)
@admin.register(BrowserProcessingSettings)
class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
list_display = ("beta_status",)
readonly_fields = ("beta_status",)
fieldsets = (
(gettext_lazy("Browser-side media processing (Beta)"), {
"fields": ("beta_status", "browser_processing_beta_enabled"),
"description": gettext_lazy(
"Enables experimental client-side video audio extraction and YAMNet pre-classification. "
"Browser compatibility may vary. Disabling this restores the normal server-side submission flow."
),
}),
)
@admin.display(description=gettext_lazy("Beta status"))
def beta_status(self, obj):
if obj and obj.browser_processing_beta_enabled:
return format_html('<strong style="color:#166534">{}</strong>', _("Enabled"))
return format_html('<strong style="color:#991b1b">{}</strong>', _("Disabled — normal submission"))
def has_add_permission(self, request):
return super().has_add_permission(request) and not BrowserProcessingSettings.objects.exists()
def has_delete_permission(self, request, obj=None):
return False
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "source_type", "sensor", "occurrences", "event_kind", "observation_duration_minutes", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
list_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", "observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
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"))
@@ -78,25 +41,6 @@ class ClassificationAdmin(admin.ModelAdmin):
@admin.register(PendingEvent)
class PendingEventAdmin(ClassificationAdmin):
actions = ("approve_selected", "deny_selected")
list_display = ("original_filename", "source_type", "sensor", "sensor_owner", "captured_at", "created_at", "primary_label", "primary_score", "duration")
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata")
fields = ClassificationAdmin.fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures", "pretty_classifier_response")
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures")
@admin.display(description=gettext_lazy("Burst captures"))
def burst_captures(self, obj):
if not hasattr(obj, "burst_session"):
return "—"
parts = []
for capture in obj.burst_session.captures.all():
url = reverse("fireworks_detect:burst_capture_audio", args=[capture.pk])
parts.append(format_html('<details><summary>{} · {}s{}</summary><audio controls preload="none" src="{}"></audio></details>', capture.captured_at, f"{capture.duration_seconds:.1f}", " · primary" if capture.is_primary else "", url))
return format_html("<div>{}</div>", format_html_join("", "{}", ((part,) for part in parts)))
@admin.display(description=gettext_lazy("Sensor owner"))
def sensor_owner(self, obj):
return obj.sensor.owner if obj.sensor and obj.sensor.owner_id else "—"
change_form_template = "admin/fireworks_detect/pending_change_form.html"
def get_urls(self):
@@ -155,7 +99,7 @@ class PendingEventAdmin(ClassificationAdmin):
def approve_selected(self, request, queryset):
approved = 0
for pending in queryset:
pending.approve(actor=request.user)
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)
@@ -170,28 +114,13 @@ class PendingEventAdmin(ClassificationAdmin):
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
readonly_fields = ClassificationAdmin.readonly_fields + ("submitted_at", "approved_at")
fields = ClassificationAdmin.fields + ("submitted_at", "approved_at")
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
fields = ClassificationAdmin.fields + ("approved_at",)
def has_add_permission(self, request):
return False
@admin.register(ManualReportRevision)
class ManualReportRevisionAdmin(admin.ModelAdmin):
list_display = ("original_pending_id", "previous_occurrences", "new_occurrences", "previous_duration_minutes", "new_duration_minutes", "changed_at")
readonly_fields = list_display
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(Sensor)
class SensorAdmin(admin.ModelAdmin):
list_display = ("name", "owner", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix", "archived_at")
@@ -219,47 +148,3 @@ class SensorAdmin(admin.ModelAdmin):
sensor = queryset.get()
token = sensor.issue_token()
self.message_user(request, format_html(_("Copy this token now; it is not stored and will not be shown again: <code>{}</code>"), token), messages.WARNING)
from .models import FieldNote, FieldNoteAssociation
@admin.register(FieldNote)
class FieldNoteAdmin(admin.ModelAdmin):
list_display = ("id", "author", "category", "source_type", "verification_status", "visibility", "created_at")
list_filter = ("visibility", "category", "source_type", "verification_status")
readonly_fields = tuple(f.name for f in FieldNote._meta.fields)
search_fields = ("content",)
def get_queryset(self, request):
return super().get_queryset(request).visible_to(request.user).select_related("author", "context")
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(FieldNoteAssociation)
class FieldNoteAssociationAdmin(admin.ModelAdmin):
list_display = ("context", "actor", "reason", "created_at")
readonly_fields = tuple(f.name for f in FieldNoteAssociation._meta.fields)
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.has_perm("fireworks_detect.view_all_fieldnotes"):
return qs
return qs.filter(context__author=request.user)
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
-3
View File
@@ -3,6 +3,3 @@ from django.apps import AppConfig
class FireworksDetectConfig(AppConfig):
name = 'fireworks_detect'
def ready(self):
from . import signals # noqa: F401
-84
View File
@@ -1,84 +0,0 @@
"""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
-25
View File
@@ -1,25 +0,0 @@
"""Derived burst presentation rules; rates describe frequency, not loudness."""
from decimal import Decimal
BURST_MIN_BANGS = 3
DEFAULT_ESTIMATED_DURATION_MINUTES = 15
MODERATE_RATE_PER_15_MINUTES = Decimal("5")
INTENSE_RATE_PER_15_MINUTES = Decimal("10")
def burst_rate(bang_count, duration_minutes):
if bang_count < BURST_MIN_BANGS or not duration_minutes or duration_minutes <= 0:
return None
return Decimal(bang_count) * 15 / Decimal(duration_minutes)
def burst_intensity(bang_count, duration_minutes):
rate = burst_rate(bang_count, duration_minutes)
if rate is None:
return None
if rate >= INTENSE_RATE_PER_15_MINUTES:
return "intense"
if rate >= MODERATE_RATE_PER_15_MINUTES:
return "moderate"
return "light"
-100
View File
@@ -1,100 +0,0 @@
"""Central access checks and association/reporting services for field notes."""
import uuid
from django.contrib.auth import get_user_model
from django.core import signing
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.db.models import Q
from django.http import Http404
from .models import Event, PendingEvent, FieldNote, FieldNoteContext, FieldNoteAssociation
def draft_token(user):
if not user.is_authenticated:
return ""
return signing.dumps({"author": user.pk, "id": str(uuid.uuid4())}, salt="field-notes")
def token_id(user, token):
try:
data = signing.loads(token, salt="field-notes", max_age=7 * 86400)
if data["author"] != user.pk:
raise ValueError
return uuid.UUID(data["id"])
except (signing.BadSignature, ValueError, KeyError, TypeError):
raise PermissionDenied("Invalid or expired note context. Reload the reporting page.")
def accessible_pending(user, session_ids=()):
if not user.is_authenticated:
return PendingEvent.objects.none()
if user.is_staff and user.has_perm("fireworks_detect.view_pendingevent"):
return PendingEvent.objects.all()
return PendingEvent.objects.filter(Q(note_contexts__author=user) | Q(sensor__owner=user) | Q(pk__in=session_ids)).distinct()
def target_snapshot(context):
if context.event_id:
return {"kind": "event", "id": context.event_id}
if context.pending_event_id:
return {"kind": "pending", "id": context.pending_event_id}
return {}
def associate(context, *, event=None, pending=None, actor=None, reason):
previous = target_snapshot(context)
context.event = event
context.pending_event = pending
context.full_clean()
context.save(update_fields=["event", "pending_event"])
FieldNoteAssociation.objects.create(context=context, actor=actor, previous=previous,
target=target_snapshot(context), reason=reason)
@transaction.atomic
def context_for_token(user, token):
# Serialize draft-note creation and report binding for the same author.
get_user_model().objects.select_for_update().get(pk=user.pk)
context, _ = FieldNoteContext.objects.get_or_create(id=token_id(user, token), defaults={"author": user})
if context.author_id != user.pk:
raise PermissionDenied
return context
@transaction.atomic
def bind_report(user, token, pending):
if not user.is_authenticated or not token:
return
context = context_for_token(user, token)
if context.event_id or context.pending_event_id:
raise PermissionDenied("This note context already belongs to a report. Reload before reporting again.")
associate(context, pending=pending, actor=user, reason="submission")
@transaction.atomic
def link_standalone(user, context_id, event):
# Approved events are publicly accessible in the existing application.
context = FieldNoteContext.objects.select_for_update().filter(pk=context_id, author=user).first()
if not context or context.event_id or context.pending_event_id:
raise Http404
associate(context, event=event, actor=user, reason="linked")
return context
@transaction.atomic
def regroup_event_notes(user, source, target):
"""Hook for future event-merging code; does not modify detection records."""
if not (user.is_staff and user.has_perm("fireworks_detect.change_event") and
user.has_perm("fireworks_detect.view_all_fieldnotes")):
raise PermissionDenied
if source.pk == target.pk:
return
for context in FieldNoteContext.objects.select_for_update().filter(event=source):
associate(context, event=target, actor=user, reason="regrouped")
def reportable_notes(user):
"""All exports, including future PDF reports, must start with this queryset."""
return FieldNote.objects.reportable_to(user).select_related("author", "context")
-33
View File
@@ -1,33 +0,0 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import FieldNote
class FieldNoteForm(forms.ModelForm):
class Meta:
model = FieldNote
fields = ["content", "category", "source_type", "verification_status", "visibility", "observed_at"]
widgets = {
"content": forms.Textarea(attrs={"rows": 3, "placeholder": _("What did you observe or learn?")}),
"observed_at": forms.DateTimeInput(format="%Y-%m-%dT%H:%M", attrs={"type": "datetime-local"}),
}
labels = {"content": _("Note"), "observed_at": _("Observed at (optional)"),
"category": _("Category"), "source_type": _("Source"),
"verification_status": _("Verification status"), "visibility": _("Visibility")}
help_texts = {
"visibility": _("Private by default. Reportable permits authorised export; it does not mean verified or public."),
"observed_at": _("Local time (Europe/Amsterdam). The entry time is recorded separately."),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name in self.fields:
if name != "content":
self.fields[name].required = False
def clean(self):
data = super().clean()
for name in ("category", "source_type", "verification_status", "visibility"):
if not data.get(name):
data[name] = FieldNote._meta.get_field(name).get_default()
return data
@@ -1,25 +0,0 @@
"""Issue a separate, revocable read-only MCP credential."""
import hashlib
import secrets
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from fireworks_detect.models import McpAccessToken
class Command(BaseCommand):
help = "Issue a BoomCast MCP token for an existing user with both review view permissions."
def add_arguments(self, parser):
parser.add_argument("username")
parser.add_argument("--name", default="MCP client")
def handle(self, *args, **options):
user = get_user_model().objects.filter(username=options["username"], is_active=True).first()
if user is None or not (user.has_perm("fireworks_detect.view_event") and user.has_perm("fireworks_detect.view_pendingevent")):
raise CommandError("Active user with view_event and view_pendingevent permissions required")
token = "bmcp_" + secrets.token_urlsafe(36)
McpAccessToken.objects.create(user=user, name=options["name"], token_hash=hashlib.sha256(token.encode()).hexdigest())
self.stdout.write("Store this token securely; it is shown only once:")
self.stdout.write(token)
@@ -1,40 +0,0 @@
import time
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from fireworks_detect.models import BurstSession
class Command(BaseCommand):
help = "Check every active Burst Listening session independently for lost HTTP heartbeats."
def add_arguments(self, parser):
parser.add_argument("--once", action="store_true")
parser.add_argument("--interval", type=float, default=5)
def handle(self, *args, **options):
while True:
now = timezone.now()
BurstSession.objects.filter(ended_at__lt=now - timedelta(days=7)).exclude(diagnostic_events=[]).update(diagnostic_events=[])
for session in BurstSession.objects.filter(ended_at__isnull=True).exclude(status="expired").iterator():
if now > session.started_at + timedelta(minutes=21):
session.status = "expired"
session.ended_at = now
kind = "watchdog_expired"
elif now > (session.last_seen_at or session.started_at) + timedelta(seconds=15) and session.timeout_at is None:
session.status = "heartbeat_lost"
session.timeout_at = now
kind = "heartbeat_lost"
else:
continue
events = session.diagnostic_events
if len(events) >= 200:
events = events[:20] + events[-179:]
events.append({"kind": kind, "server_at": now.isoformat(), "last_seen_at": session.last_seen_at.isoformat() if session.last_seen_at else None})
session.diagnostic_events = events
session.save(update_fields=["status", "ended_at", "timeout_at", "diagnostic_events"])
if options["once"]:
break
time.sleep(max(1, options["interval"]))
-225
View File
@@ -1,225 +0,0 @@
"""Stateless, read-only MCP endpoint for reviewed BoomCast metadata."""
import hashlib
import json
from datetime import timedelta
from urllib.parse import urlsplit
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.db.models import Count
from django.db.models.functions import TruncDate
from django.http import JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date
from django.views.decorators.csrf import csrf_exempt
from .h3_utils import cell_from_coordinates
from .models import Event, PendingEvent
PROTOCOL_VERSION = "2025-06-18"
TOOLS = [
{"name": "submissions_list", "description": "Page through reviewed submissions only. Review outcome is approved; denied records are deleted by the review workflow.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "offset": {"type": "integer", "minimum": 0, "maximum": 10000}}, "additionalProperties": False}},
{"name": "submissions_get", "description": "Get one reviewed submission by Event ID; pending IDs are inaccessible.", "inputSchema": {"type": "object", "properties": {"id": {"type": "integer", "minimum": 1}}, "required": ["id"], "additionalProperties": False}},
{"name": "submissions_stats", "description": "Reviewed submission counts by day, predicted class, and confirmed review outcome.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}}, "additionalProperties": False}},
{"name": "pending_summary", "description": "Only aggregate count and counts by predicted class for pending review; no individual records.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
]
def _error(code, message, request_id=None):
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
def _reply(request_id, result):
return {"jsonrpc": "2.0", "id": request_id, "result": result}
def _prediction(record):
payload = record.classifier_response if isinstance(record.classifier_response, dict) else {}
predictions = payload.get("predictions", [])
if not isinstance(predictions, list):
return []
clean = []
for item in predictions[:10]:
if not isinstance(item, dict):
continue
label, score = item.get("class"), item.get("score")
if isinstance(label, str) and len(label) <= 255 and isinstance(score, (int, float)) and not isinstance(score, bool) and 0 <= score <= 1:
clean.append({"class": label, "score": score})
return clean
def _label(record):
prediction = _prediction(record)
return prediction[0]["class"] if prediction else "unclassified"
def _summary(event):
return {"id": event.pk, "occurrence_at": event.captured_at.isoformat() if event.captured_at else None,
"submitted_at": event.submitted_at.isoformat() if event.submitted_at else None,
"reviewed_at": event.approved_at.isoformat(), "source_type": event.source_type,
"predicted_classification": _label(event), "review_outcome": "approved",
"confirmed_classification": None}
def _detail(event):
result = _summary(event)
result.update({"predictions": _prediction(event), "occurrences": event.occurrences,
"occurrence_time_approximate": event.occurrence_time_approximate,
"generalized_location_h3": event.h3_cell or cell_from_coordinates(event.latitude, event.longitude) or None})
return result
def _filters(args):
start, end = args.get("date_from"), args.get("date_to")
if start is not None:
if not isinstance(start, str) or not parse_date(start) or parse_date(start).isoformat() != start:
raise ValueError("date_from must be YYYY-MM-DD")
start = parse_date(start)
if end is not None:
if not isinstance(end, str) or not parse_date(end) or parse_date(end).isoformat() != end:
raise ValueError("date_to must be YYYY-MM-DD")
end = parse_date(end)
if start and end and (end < start or end - start > timedelta(days=366)):
raise ValueError("date range must be ordered and at most 366 days")
if not end:
end = min(timezone.localdate(), start + timedelta(days=366)) if start else timezone.localdate()
if not start:
start = end - timedelta(days=366)
outcome = args.get("review_outcome")
if outcome is not None and outcome != "approved":
raise ValueError("review_outcome must be approved")
classification = args.get("classification")
if classification is not None and (not isinstance(classification, str) or not 1 <= len(classification) <= 255):
raise ValueError("classification must be a nonempty label")
queryset = Event.objects.all()
if start:
queryset = queryset.filter(approved_at__date__gte=start)
if end:
queryset = queryset.filter(approved_at__date__lte=end)
if classification:
queryset = queryset.filter(classifier_response__predictions__0__class=classification)
return queryset
def _validate(name, args):
schema = next((item["inputSchema"] for item in TOOLS if item["name"] == name), None)
if schema is None:
raise ValueError("Unknown tool")
if not isinstance(args, dict) or set(args) - set(schema["properties"]) or set(schema.get("required", [])) - set(args):
raise ValueError("Invalid tool arguments")
for key in ("limit", "offset", "id"):
if key in args and (type(args[key]) is not int or args[key] < (1 if key != "offset" else 0) or args[key] > (100 if key == "limit" else 10000 if key == "offset" else 2147483647)):
raise ValueError(f"Invalid {key}")
def _call(name, args):
_validate(name, args)
if name == "pending_summary":
counts = {}
for pending in PendingEvent.objects.only("classifier_response").iterator(chunk_size=500):
label = _label(pending)
counts[label] = counts.get(label, 0) + 1
return {"total": sum(counts.values()), "by_predicted_classification": counts}
if name == "submissions_get":
event = Event.objects.filter(pk=args["id"]).first()
if event is None:
raise LookupError("Reviewed submission not found")
return _detail(event)
queryset = _filters(args)
if name == "submissions_list":
limit, offset = args.get("limit", 25), args.get("offset", 0)
return {"total": queryset.count(), "limit": limit, "offset": offset,
"items": [_summary(item) for item in queryset.order_by("-approved_at", "-pk")[offset:offset + limit]]}
if name == "submissions_stats":
days = list(queryset.annotate(day=TruncDate("approved_at")).values("day").annotate(count=Count("pk")).order_by("day")[:367])
classes = {}
for event in queryset.only("classifier_response").iterator(chunk_size=500):
label = _label(event)
classes[label] = classes.get(label, 0) + 1
return {"total": sum(classes.values()), "by_day": [{"date": row["day"].isoformat(), "count": row["count"]} for row in days],
"by_predicted_classification": classes, "by_review_outcome": {"approved": sum(classes.values())},
"confirmed_classification_available": False}
raise ValueError("Unknown tool")
def _principal(request):
header = request.headers.get("Authorization", "")
if not header.startswith("Bearer "):
return None
token = header[7:].strip()
if not token.startswith("bmcp_") or len(token) > 120:
return None
from .models import McpAccessToken
digest = hashlib.sha256(token.encode()).hexdigest()
credential = McpAccessToken.objects.select_related("user").filter(token_hash=digest, revoked_at__isnull=True).first()
if not credential or not credential.user.is_active:
return None
return credential.user
@csrf_exempt
def mcp_endpoint(request):
if request.method != "POST":
response = JsonResponse({"detail": "POST only"}, status=405)
response["Allow"] = "POST"
return response
origin = request.headers.get("Origin")
if origin:
parsed = urlsplit(origin)
if parsed.scheme not in ("http", "https") or parsed.netloc != request.get_host():
return JsonResponse({"detail": "Origin not allowed"}, status=403)
user = _principal(request)
if user is None:
response = JsonResponse({"detail": "MCP Bearer token required"}, status=401)
response["WWW-Authenticate"] = 'Bearer realm="BoomCast MCP"'
return response
if not user.has_perm("fireworks_detect.view_event") or not user.has_perm("fireworks_detect.view_pendingevent"):
return JsonResponse({"detail": "Review read permissions required"}, status=403)
key = f"boomcast-mcp:{user.pk}"
if not cache.add(key, 1, 60):
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, 60)
count = 1
if count > 120:
response = JsonResponse({"detail": "Rate limit exceeded"}, status=429)
response["Retry-After"] = "60"
return response
if (request.META.get("CONTENT_LENGTH") or "").isdigit() and int(request.META["CONTENT_LENGTH"]) > 65536:
return JsonResponse(_error(-32600, "Request too large"), status=413)
if len(request.body) > 65536:
return JsonResponse(_error(-32600, "Request too large"), status=413)
try:
message = json.loads(request.body)
except (ValueError, UnicodeDecodeError):
return JsonResponse(_error(-32700, "Invalid JSON"), status=400)
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
return JsonResponse(_error(-32600, "Invalid request"), status=400)
request_id, method = message.get("id"), message["method"]
if method == "notifications/initialized" and "id" not in message:
from django.http import HttpResponse
return HttpResponse(status=202)
if "id" not in message or not (isinstance(request_id, (str, int)) and not isinstance(request_id, bool)):
return JsonResponse(_error(-32600, "Request ID required"), status=400)
if method == "initialize":
result = {"protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}}, "serverInfo": {"name": "boomcast-readonly", "version": "1.0.0"}}
elif method == "tools/list":
result = {"tools": TOOLS}
elif method == "tools/call":
params = message.get("params")
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
return JsonResponse(_error(-32602, "Invalid tool call", request_id))
try:
output = _call(params["name"], params.get("arguments", {}))
except ValueError as error:
result = {"content": [{"type": "text", "text": str(error)}], "isError": True}
except LookupError:
result = {"content": [{"type": "text", "text": "Reviewed submission not found"}], "isError": True}
else:
result = {"content": [{"type": "text", "text": json.dumps(output, ensure_ascii=False)}], "structuredContent": output}
else:
return JsonResponse(_error(-32601, "Method not found", request_id))
response = JsonResponse(_reply(request_id, result))
response["Cache-Control"] = "no-store"
return response
@@ -1,24 +0,0 @@
# 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)',
},
),
]
@@ -1,16 +0,0 @@
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),
]
@@ -1,60 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-09 13:05
import django.db.models.deletion
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0010_create_browser_processing_settings'),
]
operations = [
migrations.AddField(
model_name='event',
name='captured_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='device_metadata',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='event',
name='firmware_version',
field=models.CharField(blank=True, max_length=64),
),
migrations.AddField(
model_name='pendingevent',
name='captured_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='device_metadata',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='pendingevent',
name='firmware_version',
field=models.CharField(blank=True, max_length=64),
),
migrations.CreateModel(
name='SensorSubmission',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('event_id', models.CharField(max_length=100)),
('audio_sha256', models.CharField(max_length=64)),
('submission_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
('sensor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submissions', to='fireworks_detect.sensor')),
],
options={
'constraints': [models.UniqueConstraint(fields=('sensor', 'event_id'), name='unique_sensor_event_id')],
},
),
]
@@ -1,57 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-09 23:43
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0011_event_captured_at_event_device_metadata_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='event',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='ManualReportRevision',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('original_pending_id', models.PositiveBigIntegerField()),
('previous_occurrences', models.PositiveIntegerField()),
('new_occurrences', models.PositiveIntegerField()),
('previous_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('new_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('changed_at', models.DateTimeField(auto_now_add=True)),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
],
),
]
@@ -1,18 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-09 23:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0012_event_observation_duration_kind_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='submitted_at',
field=models.DateTimeField(blank=True, null=True),
),
]
@@ -1,86 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-13 07:57
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0013_event_submitted_at'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FieldNoteContext',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
('event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='note_contexts', to='fireworks_detect.event')),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='note_contexts', to='fireworks_detect.pendingevent')),
],
),
migrations.CreateModel(
name='FieldNoteAssociation',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('previous', models.JSONField(default=dict)),
('target', models.JSONField(default=dict)),
('reason', models.CharField(max_length=32)),
('created_at', models.DateTimeField(auto_now_add=True)),
('actor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('context', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='associations', to='fireworks_detect.fieldnotecontext')),
],
options={
'ordering': ['created_at', 'pk'],
},
),
migrations.CreateModel(
name='FieldNote',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField(max_length=10000)),
('category', models.CharField(choices=[('general', 'General'), ('witness', 'Witness'), ('people_vehicles', 'People / vehicles'), ('cctv', 'CCTV'), ('location_direction', 'Location / direction'), ('follow_up', 'Follow-up'), ('other', 'Other')], default='general', max_length=32)),
('source_type', models.CharField(choices=[('first_hand', 'First-hand'), ('second_hand', 'Second-hand'), ('unknown', 'Other / unknown')], default='unknown', max_length=24)),
('verification_status', models.CharField(choices=[('unverified', 'Unverified'), ('corroborated', 'Corroborated'), ('disputed', 'Disputed')], default='unverified', max_length=24)),
('visibility', models.CharField(choices=[('private', 'Private'), ('reportable', 'Reportable')], default='private', max_length=16)),
('observed_at', models.DateTimeField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='field_notes', to=settings.AUTH_USER_MODEL)),
('context', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='notes', to='fireworks_detect.fieldnotecontext')),
],
options={
'ordering': ['created_at', 'pk'],
'permissions': [('view_all_fieldnotes', 'Read all private field notes'), ('export_reportable_fieldnotes', 'Export reportable field notes from all authors')],
},
),
migrations.AddConstraint(
model_name='fieldnotecontext',
constraint=models.CheckConstraint(condition=models.Q(('event__isnull', False), ('pending_event__isnull', False), _negated=True), name='note_context_one_target'),
),
migrations.AddIndex(
model_name='fieldnote',
index=models.Index(fields=['author', 'created_at'], name='fieldnote_author_time'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('content', ''), _negated=True), name='fieldnote_nonempty'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('visibility__in', ['private', 'reportable'])), name='fieldnote_visibility'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('source_type__in', ['first_hand', 'second_hand', 'unknown'])), name='fieldnote_source'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('verification_status__in', ['unverified', 'corroborated', 'disputed'])), name='fieldnote_verification'),
),
]
@@ -1,51 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-15 10:53
import django.db.models.deletion
import django.utils.timezone
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0014_fieldnotecontext_fieldnoteassociation_fieldnote_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BurstSession',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('started_at', models.DateTimeField(default=django.utils.timezone.now)),
('ended_at', models.DateTimeField(blank=True, null=True)),
('maximum_minutes', models.PositiveSmallIntegerField(default=15)),
('status', models.CharField(default='listening', max_length=24)),
('last_seen_at', models.DateTimeField(blank=True, null=True)),
('last_audio_at', models.DateTimeField(blank=True, null=True)),
('last_audio_frame', models.PositiveBigIntegerField(default=0)),
('last_sequence', models.PositiveIntegerField(default=0)),
('timeout_at', models.DateTimeField(blank=True, null=True)),
('diagnostic_events', models.JSONField(default=list)),
('event', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='burst_session', to='fireworks_detect.event')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='burst_sessions', to=settings.AUTH_USER_MODEL)),
('pending_event', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='burst_session', to='fireworks_detect.pendingevent')),
],
),
migrations.CreateModel(
name='BurstCapture',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('captured_at', models.DateTimeField()),
('duration_seconds', models.FloatField()),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('is_primary', models.BooleanField(default=False)),
('session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='captures', to='fireworks_detect.burstsession')),
],
options={
'ordering': ['captured_at', 'pk'],
},
),
]
@@ -1,27 +0,0 @@
# Generated by Django 6.1.1 on 2026-10-16 15:29
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0015_burstsession_burstcapture'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='McpAccessToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('token_hash', models.CharField(max_length=64, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('revoked_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='boomcast_mcp_tokens', to=settings.AUTH_USER_MODEL)),
],
),
]
+1 -266
View File
@@ -1,6 +1,5 @@
import math
import secrets
import uuid
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
@@ -89,27 +88,6 @@ class ClassificationRule(models.Model):
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."""
@@ -117,19 +95,12 @@ class ClassifiedAudio(models.Model):
SENSOR = "sensor", _("Sensor")
MANUAL = "manual", _("Manual report")
class DurationKind(models.TextChoices):
ESTIMATED = "estimated", _("Estimated")
MEASURED = "measured", _("Measured")
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)
observation_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
observation_duration_kind = models.CharField(max_length=10, choices=DurationKind.choices, blank=True)
occurrence_time_approximate = models.BooleanField(default=False)
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)
@@ -139,9 +110,6 @@ class ClassifiedAudio(models.Model):
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)
captured_at = models.DateTimeField(null=True, blank=True)
firmware_version = models.CharField(max_length=64, blank=True)
device_metadata = models.JSONField(default=dict, blank=True)
class Meta:
abstract = True
@@ -161,10 +129,6 @@ class ClassifiedAudio(models.Model):
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 self.observation_duration_minutes is not None and not 1 <= self.observation_duration_minutes <= 1440:
errors["observation_duration_minutes"] = _("Observation duration must be between 1 and 1,440 minutes.")
if bool(self.observation_duration_minutes) != bool(self.observation_duration_kind):
errors["observation_duration_kind"] = _("A duration needs an estimated or measured source.")
if errors:
raise ValidationError(errors)
@@ -183,33 +147,6 @@ class ClassifiedAudio(models.Model):
return "—"
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
@property
def is_burst(self):
from .bursts import BURST_MIN_BANGS
return self.occurrences >= BURST_MIN_BANGS
@property
def event_kind(self):
return "burst" if self.is_burst else "ordinary"
@property
def bangs_per_15_minutes(self):
from .bursts import burst_rate
if not self.observation_duration_kind:
return None
return burst_rate(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity(self):
from .bursts import burst_intensity
if not self.observation_duration_kind:
return None
return burst_intensity(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity_display(self):
return {"light": _("Light"), "moderate": _("Moderate"), "intense": _("Intense")}.get(self.burst_intensity)
@property
def predictions(self):
@@ -265,21 +202,14 @@ class PendingEvent(ClassifiedAudio):
verbose_name_plural = _("Pending")
@transaction.atomic
def approve(self, actor=None):
def approve(self):
event = Event.objects.create(
submitted_at=self.created_at,
audio_file=self.audio_file.name,
sensor=self.sensor,
captured_at=self.captured_at,
firmware_version=self.firmware_version,
device_metadata=self.device_metadata,
original_filename=self.original_filename,
classifier_response=self.classifier_response,
source_type=self.source_type,
occurrences=self.occurrences,
observation_duration_minutes=self.observation_duration_minutes,
observation_duration_kind=self.observation_duration_kind,
occurrence_time_approximate=self.occurrence_time_approximate,
location=self.location,
latitude=self.latitude,
longitude=self.longitude,
@@ -289,24 +219,11 @@ class PendingEvent(ClassifiedAudio):
direction_accuracy_degrees=self.direction_accuracy_degrees,
direction_source=self.direction_source,
)
from .field_notes import associate
if hasattr(self, "burst_session"):
session = self.burst_session
session.pending_event = None
session.event = event
session.save(update_fields=["pending_event", "event"])
for context in self.note_contexts.select_for_update():
associate(context, event=event, actor=actor, reason="approved")
self.delete()
return event
def deny(self):
file_name = self.audio_file.name
if hasattr(self, "burst_session"):
for capture in self.burst_session.captures.all():
if capture.audio_file.name and capture.audio_file.name != file_name:
default_storage.delete(capture.audio_file.name)
self.burst_session.captures.all().delete()
self.delete()
if file_name:
default_storage.delete(file_name)
@@ -316,189 +233,7 @@ class Event(ClassifiedAudio):
"""A reviewed classification that is safe to appear in the event feed."""
approved_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
class Meta(ClassifiedAudio.Meta):
verbose_name = _("Event")
verbose_name_plural = _("Events")
class BurstSession(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="burst_sessions")
pending_event = models.OneToOneField(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL, related_name="burst_session")
event = models.OneToOneField(Event, null=True, blank=True, on_delete=models.SET_NULL, related_name="burst_session")
started_at = models.DateTimeField(default=timezone.now)
ended_at = models.DateTimeField(null=True, blank=True)
maximum_minutes = models.PositiveSmallIntegerField(default=15)
status = models.CharField(max_length=24, default="listening")
last_seen_at = models.DateTimeField(null=True, blank=True)
last_audio_at = models.DateTimeField(null=True, blank=True)
last_audio_frame = models.PositiveBigIntegerField(default=0)
last_sequence = models.PositiveIntegerField(default=0)
timeout_at = models.DateTimeField(null=True, blank=True)
diagnostic_events = models.JSONField(default=list)
class BurstCapture(models.Model):
session = models.ForeignKey(BurstSession, on_delete=models.CASCADE, related_name="captures")
captured_at = models.DateTimeField()
duration_seconds = models.FloatField()
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d")
is_primary = models.BooleanField(default=False)
class Meta:
ordering = ["captured_at", "pk"]
class ManualReportRevision(models.Model):
"""Record edits to a session-owned manual Pending report."""
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
original_pending_id = models.PositiveBigIntegerField()
previous_occurrences = models.PositiveIntegerField()
new_occurrences = models.PositiveIntegerField()
previous_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
new_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
changed_at = models.DateTimeField(auto_now_add=True)
class SensorSubmission(models.Model):
"""Durable idempotency receipt, retained after moderation."""
sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE, related_name="submissions")
event_id = models.CharField(max_length=100)
audio_sha256 = models.CharField(max_length=64)
submission_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=["sensor", "event_id"], name="unique_sensor_event_id")]
class FieldNoteContext(models.Model):
"""An author's note association, including drafts before a report exists.
This stores no detection/incident data; Event/PendingEvent remain canonical.
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
event = models.ForeignKey(Event, null=True, blank=True, on_delete=models.SET_NULL, related_name="note_contexts")
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL, related_name="note_contexts")
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.CheckConstraint(condition=~(models.Q(event__isnull=False) & models.Q(pending_event__isnull=False)), name="note_context_one_target")]
class FieldNoteQuerySet(models.QuerySet):
def visible_to(self, user):
if not user.is_authenticated or not user.is_active:
return self.none()
if user.is_active and user.has_perm("fireworks_detect.view_all_fieldnotes"):
return self
return self.filter(author=user)
def reportable_to(self, user):
if not user.is_authenticated or not user.is_active:
return self.none()
notes = self.filter(visibility="reportable")
if user.is_active and user.has_perm("fireworks_detect.export_reportable_fieldnotes"):
return notes
return notes.filter(author=user)
class FieldNote(models.Model):
class Category(models.TextChoices):
GENERAL = "general", _("General")
WITNESS = "witness", _("Witness")
PEOPLE = "people_vehicles", _("People / vehicles")
CCTV = "cctv", _("CCTV")
LOCATION = "location_direction", _("Location / direction")
FOLLOW_UP = "follow_up", _("Follow-up")
OTHER = "other", _("Other")
class Source(models.TextChoices):
FIRST_HAND = "first_hand", _("First-hand")
SECOND_HAND = "second_hand", _("Second-hand")
UNKNOWN = "unknown", _("Other / unknown")
class Verification(models.TextChoices):
UNVERIFIED = "unverified", _("Unverified")
CORROBORATED = "corroborated", _("Corroborated")
DISPUTED = "disputed", _("Disputed")
class Visibility(models.TextChoices):
PRIVATE = "private", _("Private")
REPORTABLE = "reportable", _("Reportable")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="field_notes")
context = models.ForeignKey(FieldNoteContext, on_delete=models.PROTECT, related_name="notes")
content = models.TextField(max_length=10000)
category = models.CharField(max_length=32, choices=Category.choices, default=Category.GENERAL)
source_type = models.CharField(max_length=24, choices=Source.choices, default=Source.UNKNOWN)
verification_status = models.CharField(max_length=24, choices=Verification.choices, default=Verification.UNVERIFIED)
visibility = models.CharField(max_length=16, choices=Visibility.choices, default=Visibility.PRIVATE)
observed_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = FieldNoteQuerySet.as_manager()
class Meta:
ordering = ["created_at", "pk"]
indexes = [models.Index(fields=["author", "created_at"], name="fieldnote_author_time")]
permissions = [
("view_all_fieldnotes", "Read all private field notes"),
("export_reportable_fieldnotes", "Export reportable field notes from all authors"),
]
constraints = [
models.CheckConstraint(condition=~models.Q(content=""), name="fieldnote_nonempty"),
models.CheckConstraint(condition=models.Q(visibility__in=["private", "reportable"]), name="fieldnote_visibility"),
models.CheckConstraint(condition=models.Q(source_type__in=["first_hand", "second_hand", "unknown"]), name="fieldnote_source"),
models.CheckConstraint(condition=models.Q(verification_status__in=["unverified", "corroborated", "disputed"]), name="fieldnote_verification"),
]
def clean(self):
super().clean()
if not self.content.strip():
raise ValidationError({"content": _("Enter a note.")})
if self.context_id and self.author_id != self.context.author_id:
raise ValidationError(_("The note and its context must have the same author."))
def save(self, *args, **kwargs):
if not self._state.adding:
raise ValidationError(_("Field notes are append-only. Add a follow-up to correct an earlier note."))
self.full_clean()
return super().save(*args, **kwargs)
class FieldNoteAssociation(models.Model):
"""Immutable provenance retained even when the original event is deleted."""
context = models.ForeignKey(FieldNoteContext, on_delete=models.PROTECT, related_name="associations")
actor = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
previous = models.JSONField(default=dict)
target = models.JSONField(default=dict)
reason = models.CharField(max_length=32)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["created_at", "pk"]
def save(self, *args, **kwargs):
if not self._state.adding:
raise ValidationError("Association history is append-only.")
return super().save(*args, **kwargs)
class McpAccessToken(models.Model):
"""Revocable credential for read-only MCP access; never stores the raw token."""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="boomcast_mcp_tokens")
name = models.CharField(max_length=100)
token_hash = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
revoked_at = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"{self.user}: {self.name}"
-126
View File
@@ -1,126 +0,0 @@
import csv
import json
from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from .field_notes import accessible_pending, associate, context_for_token, link_standalone, reportable_notes, token_id
from .forms import FieldNoteForm
from .models import Event, FieldNote, FieldNoteContext
def panel_context(request, params=None):
params = params if params is not None else request.GET
selected = [(k, params.get(k)) for k in ("event", "pending", "token") if params.get(k)]
if len(selected) > 1:
raise Http404
notes = FieldNote.objects.visible_to(request.user).select_related("author", "context__event", "context__pending_event").prefetch_related("context__associations")
target = None
kind, value = selected[0] if selected else ("", "")
try:
if kind == "event":
target = get_object_or_404(Event, pk=int(value))
notes = notes.filter(context__event=target)
elif kind == "pending":
target = get_object_or_404(accessible_pending(request.user, request.session.get("manual_pending_ids", [])), pk=int(value))
notes = notes.filter(context__pending_event=target)
elif kind == "token":
key = token_id(request.user, value)
notes = notes.filter(context_id=key)
except (ValueError, TypeError):
raise Http404
return {"field_notes": notes, "note_count": notes.count(), "note_form": FieldNoteForm(),
"note_kind": kind, "note_value": value, "note_target": target,
"note_panel_id": "live-field-notes" if kind == "token" else "field-notes",
"note_query": urlencode({kind: value}) if kind else "",
"note_events": Event.objects.all() if not kind else (),
"note_token": value if kind == "token" else ""}
@login_required
@never_cache
@require_http_methods(["GET", "POST"])
def notes(request):
params = request.POST if request.method == "POST" else request.GET
context = panel_context(request, params)
if request.method == "POST":
form = FieldNoteForm(request.POST)
if form.is_valid():
with transaction.atomic():
kind = context["note_kind"]
if kind == "token":
owner_context = context_for_token(request.user, context["note_value"])
else:
owner_context = FieldNoteContext.objects.create(author=request.user)
if kind:
associate(owner_context, event=context["note_target"] if kind == "event" else None,
pending=context["note_target"] if kind == "pending" else None,
actor=request.user, reason="created")
note = form.save(commit=False)
note.author = request.user
note.context = owner_context
note.save()
if request.headers.get("HX-Request") != "true":
return redirect(reverse("fireworks_detect:field_notes") + ("?" + context["note_query"] if context["note_query"] else ""))
context = panel_context(request, params)
context["note_saved"] = True
else:
context["note_form"] = form
# Invalid HTMX forms deliberately return 200 so HTMX renders field errors.
template = "fireworks_detect/notes/panel.html" if request.headers.get("HX-Request") == "true" else "fireworks_detect/notes/page.html"
return render(request, template, context)
@login_required
@never_cache
@require_http_methods(["POST"])
def link_note(request, context_id):
try:
event = get_object_or_404(Event, pk=int(request.POST.get("event", "")))
except (ValueError, TypeError):
raise Http404
link_standalone(request.user, context_id, event)
return redirect("fireworks_detect:field_notes")
@login_required
@never_cache
@require_http_methods(["GET"])
def export_notes(request, format):
notes = reportable_notes(request.user).prefetch_related("context__associations")
if request.GET.get("event"):
try:
event = get_object_or_404(Event, pk=int(request.GET["event"]))
except (ValueError, TypeError):
raise Http404
notes = notes.filter(context__event=event)
rows = [{"id": n.pk, "author": n.author.get_username(), "event_id": n.context.event_id,
"pending_event_id": n.context.pending_event_id, "content": n.content,
"category": n.category, "source_type": n.source_type,
"verification_status": n.verification_status, "visibility": n.visibility,
"observed_at": n.observed_at.isoformat() if n.observed_at else None,
"created_at": n.created_at.isoformat(), "updated_at": n.updated_at.isoformat(),
"association_history": [{"previous": a.previous, "target": a.target, "reason": a.reason,
"created_at": a.created_at.isoformat()} for a in n.context.associations.all()]}
for n in notes]
if format == "json":
response = JsonResponse({"notes": rows})
elif format == "csv":
response = HttpResponse(content_type="text/csv; charset=utf-8")
fields = ["id", "author", "event_id", "pending_event_id", "content", "category", "source_type", "verification_status", "visibility", "observed_at", "created_at", "updated_at", "association_history"]
writer = csv.DictWriter(response, fieldnames=fields)
writer.writeheader()
for row in rows:
row["association_history"] = json.dumps(row["association_history"])
# Prevent spreadsheet formula execution from user-authored text.
writer.writerow({k: "'" + v if isinstance(v, str) and v.lstrip().startswith(("=", "+", "-", "@")) else v for k, v in row.items()})
else:
raise Http404
response["Content-Disposition"] = f'attachment; filename="boomcast-field-notes.{format}"'
return response
-19
View File
@@ -1,19 +0,0 @@
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})
@@ -1,3 +0,0 @@
google-yamnet-1
source_revision=c651073789719ff39dcf51406733bbcaaafb43f2
tensorflow=2.21.0
File diff suppressed because one or more lines are too long
@@ -1,522 +0,0 @@
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
@@ -59,11 +59,6 @@
{% 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 }}">
@@ -3,13 +3,12 @@
<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">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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 %}
@@ -24,14 +23,7 @@
<section class="dashboard-section" aria-label="{% trans "Quick fireworks report" %}">
<div class="dashboard-report">
<button id="field-notes-toggle" class="field-notes-trigger" type="button" aria-label="{% trans 'Field notes' %}" aria-haspopup="dialog" aria-controls="field-notes-dialog" title="{% trans 'Field notes' %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 4.5h8l3 3V19a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V5.5a1 1 0 0 1 1-1h2Z"/><path d="M15.5 4.5V8H19M8.5 12h7M8.5 15.5h5"/></svg>
</button>
{% include "fireworks_detect/includes/manual_report_form.html" %}
<dialog id="field-notes-dialog" class="field-notes-dialog" aria-label="{% trans 'Field notes' %}">
<div class="field-notes-dialog__toolbar"><button id="field-notes-close" type="button" aria-label="{% trans 'Close field notes' %}">×</button></div>
{% if user.is_authenticated %}{% include "fireworks_detect/notes/panel.html" %}{% else %}<div class="field-notes-dialog__signin"><h2>{% trans "Field notes" %}</h2><p><a href="{% url 'login' %}?next=/">{% trans "Sign in to add private field notes" %}</a></p></div>{% endif %}
</dialog>
</div>
</section>
@@ -1,13 +1,9 @@
{% load i18n %}
{% if event.source_type == "manual" %}
<h2>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</h2>
<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 "Occurred" %}</strong><span>{% if event.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ event.captured_at|date:"j M Y, H:i"|default:"Unknown" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Submitted" %}</strong><span>{% if event.submitted_at %}{{ event.submitted_at|date:"j M Y, H:i" }}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
{% if event.is_burst %}<div class="prediction prediction--firework"><strong>{% trans "Duration" %}</strong><span>{% if event.observation_duration_minutes %}{{ event.observation_duration_minutes }} {% if event.observation_duration_kind == "estimated" %}{% trans "minutes (estimated)" %}{% else %}{% trans "minutes (measured)" %}{% endif %}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Intensity" %}</strong><span>{% if event.burst_intensity %}{{ event.burst_intensity_display }} · {{ event.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}{% else %}{% trans "Not rated" %}{% endif %}</span></div>{% endif %}
<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>
@@ -30,5 +26,3 @@
<p class="empty">{% trans "No peak events returned." %}</p>
{% endfor %}
{% endif %}
{% if request.user.is_authenticated %}{% include "fireworks_detect/notes/panel.html" %}{% else %}<p><a href="{% url 'login' %}?next={{ request.path|urlencode }}">{% trans "Sign in to add private field notes" %}</a></p>{% endif %}
@@ -1,2 +0,0 @@
{% 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 "Event · BoomCast" %}</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" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" %}<section class="panel">{% include "fireworks_detect/event_detail.html" %}</section></main></body></html>
@@ -1,2 +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">{% include "fireworks_detect/events_list.html" %}</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>
<!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>
@@ -1,11 +1,11 @@
{% load i18n %}
{% if events %}
{% for event in events %}
<a href="{% url 'fireworks_detect:event_detail' event.id %}" 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">
<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>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</strong><br>
<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>
@@ -14,7 +14,7 @@
{% endif %}
</span>
<span class="badge">{% if event.source_type == "manual" %}{% trans "Manual" %} →{% else %}{{ event.primary_score }} →{% endif %}</span>
</a>
</button>
{% endfor %}
{% else %}
<p class="empty">{% trans "No approved events yet. Submit a classification, then approve it from the Pending page in admin." %}</p>
@@ -9,7 +9,6 @@
<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>
@@ -27,7 +26,7 @@
<section class="upload-card" aria-label="{% trans "Upload audio for classification" %}">
{% include "fireworks_detect/includes/audio_upload_form.html" %}
</section>
</section>
</main>
</body>
@@ -1,37 +1,19 @@
{% 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">
<form class="upload-form" action="{% url "fireworks_detect:classify_upload" %}" method="post" enctype="multipart/form-data" hx-post="{% url "fireworks_detect:classify_upload" %}" hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-indicator="#upload-indicator">
{% csrf_token %}
<label class="drop-zone" id="drop-zone">
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
<span>
<span class="upload-icon" id="upload-progress-circle"><span class="upload-icon__content" id="upload-icon-content" aria-hidden="true">↑</span></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>
{% 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>
@@ -1 +0,0 @@
{{ browser_processing_config|json_script:"boomcast-browser-config" }}
@@ -1,16 +0,0 @@
{% 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>
@@ -1,113 +1,38 @@
{% 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>
<div class="report-clock__controls">
<span id="report-clock-mode" class="report-clock__now"><span class="report-clock__dot" aria-hidden="true"></span><span id="report-clock-mode-label">{% trans "Now" %}</span></span>
<button id="report-clock-edit" class="report-clock__edit" type="button" aria-label="{% trans 'Edit report time' %}" aria-controls="report-clock-editor" aria-expanded="false" title="{% trans 'Edit report time' %}"><span aria-hidden="true">✎</span></button>
</div>
</div>
<span id="report-clock-date" class="report-clock__date" hidden></span>
<button id="report-clock-reset" class="report-clock__reset" type="button" hidden>{% trans "Use now" %}</button>
<div id="report-clock-editor" class="report-clock__editor" hidden>
<div class="report-clock__fields">
<div><label for="report-clock-draft-date">{% trans "Date" %}</label><input id="report-clock-draft-date" type="date" aria-describedby="report-clock-error"></div>
<div><label for="report-clock-draft-time">{% trans "Time (24-hour)" %}</label><input id="report-clock-draft-time" type="text" inputmode="numeric" autocomplete="off" placeholder="14:30" maxlength="5" aria-describedby="report-clock-error"></div>
</div>
<p id="report-clock-error" class="report-clock__error" role="alert" hidden></p>
<label class="manual-report__check"><input id="manual-time-approximate" name="time_approximate" type="checkbox" form="manual-report-form" disabled> {% trans "Time is approximate" %}</label>
<div class="report-clock__actions"><button id="report-clock-apply" type="button">{% trans "Apply" %}</button><button id="report-clock-cancel" type="button">{% trans "Cancel" %}</button></div>
</div>
</div>
</header>
<form id="manual-report-form" action="{% url "fireworks_detect:submit_manual_pending" %}" method="post" enctype="multipart/form-data">
<p class="eyebrow">{% trans "Recording optional" %}</p>
<h2 class="manual-report__title" id="manual-report-title">{% trans "Report fireworks now" %}</h2>
<p class="manual-report__intro">{% trans "Choose how many times you heard fireworks, then send it straight to Pending. The report is timestamped now." %}</p>
<form id="manual-report-form" action="{% url "fireworks_detect:submit_manual_pending" %}" method="post" enctype="multipart/form-data" hx-post="{% url "fireworks_detect:submit_manual_pending" %}" hx-target="#manual-submission" hx-swap="outerHTML">
{% csrf_token %}
{% if note_token %}<input type="hidden" name="field_note_context" id="manual-note-context" value="{{ note_token }}">{% endif %}
<label class="manual-report__label" for="manual-occurrences">{% trans "Number of occurrences" %}</label>
<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">
<input id="manual-occurred-at" name="occurred_at" 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>
<p id="manual-burst-status" class="manual-report__burst-status" role="status">{% trans "Ordinary report" %}</p>
</div>
<div id="manual-burst-duration" class="manual-report__duration">
<label class="manual-report__label" for="manual-duration-minutes">{% trans "Estimated observation window (minutes, for 3+ bangs)" %}</label>
<input id="manual-duration-minutes" name="duration_minutes" type="number" min="1" max="1440" value="15" inputmode="numeric">
<label class="manual-report__check"><input id="manual-duration-confirmed" name="duration_confirmed" type="checkbox"> {% trans "Use this estimated window for burst intensity" %}</label>
<small>{% trans "Optional. Without an accepted window, BoomCast reports the count without an intensity rating." %}</small>
</div>
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
<label class="manual-report__check" for="manual-visually-confirmed"><input id="manual-visually-confirmed" name="visually_confirmed" type="checkbox"> {% trans "Visually confirmed" %}</label>
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric">
<div class="manual-direction-panel" id="manual-direction-panel" hidden>
<strong class="manual-direction-panel__heading">{% trans "Direction" %} <span>({% trans "optional" %})</span></strong>
<p class="manual-direction-panel__copy">{% trans "Point the top of your phone toward the fireworks, then capture a single compass reading." %}</p>
<button id="manual-capture-direction" class="manual-direction-panel__button" type="button">{% trans "Capture direction" %}</button>
<div id="manual-direction-status" class="manual-direction-panel__status" aria-live="polite"></div>
</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>
<button id="manual-submit" class="manual-report__submit" type="button">{% trans "I heard fireworks — send to Pending" %}</button>
<div class="burst-listener">
<button id="burst-start" class="burst-listener__button" type="button">{% trans "Listen for next bang" %}</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>
<div class="burst-listener" data-state="off">
<label class="manual-report__check"><input id="burst-mode" type="checkbox"> {% trans "Burst Listening experiment" %}</label>
<div id="burst-options" class="burst-listener__options" hidden>
{% if not request.user.is_authenticated %}<p>{% trans "Sign in before starting a Burst Listening session." %} <a href="{% url 'login' %}">{% trans "Sign in" %}</a></p>{% endif %}
<label for="burst-maximum">{% trans "Maximum listening time" %}</label>
<select id="burst-maximum"><option value="10">10 {% trans "minutes" %}</option><option value="15" selected>15 {% trans "minutes" %}</option><option value="20">20 {% trans "minutes" %}</option></select>
<label for="burst-test-mode">{% trans "Test setup" %}</label>
<select id="burst-test-mode"><option value="standard">Standard</option><option value="guided_access">Guided Access</option><option value="wake_lock">Wake Lock</option></select>
</div>
<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>
<p id="burst-diagnostics" role="status" hidden></p>
<button id="burst-manual-capture" type="button" hidden>{% trans "Capture now" %}</button>
<button id="burst-export" type="button" hidden>{% trans "Export diagnostics" %}</button>
<details id="burst-timeline" hidden><summary>{% trans "Diagnostic timeline" %}</summary><ol id="burst-timeline-list"></ol></details>
<div id="burst-review" hidden><h4>{% trans "Review burst captures" %}</h4><p id="burst-upload-error" role="alert" hidden></p><ol id="burst-capture-list"></ol></div>
<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="submit"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
<p id="burst-error" role="alert" hidden></p>
</div>
</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>
@@ -1,8 +1,8 @@
{% load i18n %}
<section class="map-panel" aria-label="{% trans "Reviewed fireworks report map" %}">
<div class="map-header"><strong>{% trans "Reviewed reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }}{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of reviewed fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Map legend" %}</h2>{% if map_source != "sensor" %}<div><span class="legend-dot"></span> {% trans "Manual report" %}</div>{% endif %}{% if map_source == "sensor" or map_source == "all" %}<div><span class="legend-sensor"></span> {% trans "Sensor event" %}</div>{% endif %}<div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div>{% if map_source != "sensor" %}<div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div>{% endif %}</aside>
<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" }}
@@ -7,15 +7,6 @@
<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 %}
<a href="{% url 'fireworks_detect:field_notes' %}">{% trans "Field notes" %}</a>
<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">
@@ -1,31 +1,8 @@
{% load i18n %}
<div id="manual-submission" class="manual-submission{% if error %} manual-submission--error{% else %} manual-submission--success{% endif %}" role="status" data-next-note-token="{{ next_note_token }}" data-result="{% if error %}error{% else %}success{% endif %}">
<div id="manual-submission" role="status">
{% if error %}
<span class="manual-submission__icon" aria-hidden="true">!</span>
<strong>{% trans "Could not report fireworks" %}</strong>
<p>{{ error }}</p>
<strong>{% trans "Could not report fireworks" %}</strong><p>{{ error }}</p>
{% else %}
<span class="manual-submission__icon" aria-hidden="true">✓</span>
<strong>{% if updated %}{% trans "Report updated!" %}{% else %}{% trans "Report received!" %}{% endif %}</strong>
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
<p class="manual-submission__summary">
{% if pending.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ pending.captured_at|date:"j M Y, H:i" }} ·
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
{% if pending.direction_degrees is not None %} · {{ direction_label|default:pending.direction_cardinal }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
</p>
<p>{% if pending.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Ordinary report" %}{% endif %} · {% trans "Submitted" %} {{ pending.created_at|date:"j M Y, H:i" }}</p>
{% if pending.is_burst %}<p>{% trans "Duration" %}: {% if pending.observation_duration_minutes %}{{ pending.observation_duration_minutes }} {% trans "minutes (estimated)" %}{% else %}{% trans "Unknown" %}{% endif %}</p>
<p>{% trans "Intensity" %}: {% if pending.burst_intensity %}{{ pending.burst_intensity_display }} ({{ pending.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}){% else %}{% trans "Not rated" %}{% endif %}</p>{% endif %}
<p>{% trans "Visually confirmed" %}: {% if pending.visually_confirmed %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</p>
{% if request.user.is_authenticated %}<p><a href="{% url 'fireworks_detect:field_notes' %}?pending={{ pending.pk }}">{% trans "Add or review field notes for this report" %}</a></p>{% endif %}
{% if editable %}<form class="manual-submission__edit" method="post" action="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-post="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-target="#manual-submission" hx-swap="outerHTML">
{% csrf_token %}
<label for="manual-edit-count">{% trans "Correct bang count" %}</label>
<input id="manual-edit-count" name="occurrences" type="number" min="1" max="1000" value="{{ pending.occurrences }}" required>
<label for="manual-edit-duration">{% trans "Estimated minutes for a burst" %}</label>
<input id="manual-edit-duration" name="duration_minutes" type="number" min="1" max="1440" value="{{ pending.observation_duration_minutes|default:15 }}">
<label><input name="duration_confirmed" type="checkbox" {% if pending.observation_duration_kind %}checked{% endif %}> {% trans "Use this estimated window" %}</label>
<button type="submit">{% trans "Update report" %}</button>
</form>{% endif %}
<strong>{% trans "Report sent to Pending" %}</strong><p>{% blocktrans count count=pending.occurrences with time=pending.created_at|date:"H:i" %}{{ count }} occurrence reported at {{ time }}.{% plural %}{{ count }} occurrences reported at {{ time }}.{% endblocktrans %}</p>
{% endif %}
</div>
@@ -14,12 +14,12 @@
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
<section class="headline" aria-labelledby="map-title">
<div><p class="kicker">{% trans "Reviewed sound reports" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "Reviewed reports with a stored location appear at their H3 cell centre, not their precise coordinates. Sensor events use only saved event locations; device-reported coordinates are not trusted for this map." %}</p>
<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" name="source"><option value="manual" {% if map_filters.source == "manual" %}selected{% endif %}>{% trans "Manual reports" %}</option><option value="sensor" {% if map_filters.source == "sensor" %}selected{% endif %}>{% trans "Sensor events" %}</option><option value="all" {% if map_filters.source == "all" %}selected{% endif %}>{% trans "Both sources" %}</option></select></div>
<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>
@@ -1,2 +0,0 @@
{% 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 "Field notes · BoomCast" %}</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" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" %}<section class="panel">{% include "fireworks_detect/notes/panel.html" %}<p>{% trans "Exports include only reportable notes you are authorised to export. Private notes are always excluded." %}</p><a href="{% url 'fireworks_detect:export_field_notes' 'json' %}">JSON</a> · <a href="{% url 'fireworks_detect:export_field_notes' 'csv' %}">CSV</a></section></main></body></html>
@@ -1,38 +0,0 @@
{% load i18n tz %}
<section class="field-notes" id="{{ note_panel_id|default:'live-field-notes' }}" aria-label="{% trans 'Field notes' %}">
<h2>{% trans "Field notes" %} <span class="field-notes__count">({{ note_count|default:0 }})</span></h2>
<p>{% trans "Human context, separate from detection evidence. Notes are private by default. Add a follow-up to correct an earlier entry." %}</p>
{% if note_target %}<p>{% trans "Report" %} #{{ note_target.pk }} · {{ note_target.occurrences }} {% trans "bangs" %}</p>{% endif %}
{% if note_saved %}<p role="status">{% trans "Field note saved." %}</p>{% endif %}
<details {% if note_form.errors %}open{% endif %}>
<summary>{% trans "Add field note" %}</summary>
<form method="post" action="{% url 'fireworks_detect:field_notes' %}" hx-post="{% url 'fireworks_detect:field_notes' %}" hx-target="closest .field-notes" hx-swap="outerHTML">
{% csrf_token %}
{% if note_token %}<input type="hidden" name="token" value="{{ note_token }}">{% elif note_kind %}<input type="hidden" name="{{ note_kind }}" value="{{ note_value }}">{% endif %}
{{ note_form.non_field_errors }}
<div class="field-notes__field">{{ note_form.content.label_tag }}{{ note_form.content }}{{ note_form.content.errors }}</div>
<details {% if note_form.errors %}open{% endif %}><summary>{% trans "Optional details" %}</summary>
<div class="field-notes__fields">
{% for field in note_form %}{% if field.name != 'content' %}<div class="field-notes__field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small id="{{ field.auto_id }}_helptext">{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}
</div>
</details>
<button type="submit">{% trans "Save field note" %}</button>
</form>
</details>
<ol class="field-notes__timeline">
{% for note in field_notes %}
<li>
<p class="field-notes__meta">{{ note.get_category_display }} · {{ note.author.get_username }} · {{ note.get_visibility_display }}</p>
<p class="field-notes__meta">{{ note.get_source_type_display }} · {{ note.get_verification_status_display }}</p>
<p class="field-notes__content">{{ note.content }}</p>
<p class="field-notes__meta">{% trans "Entered" %}: <time datetime="{{ note.created_at|date:'c' }}">{{ note.created_at|localtime|date:"j M Y, H:i T" }}</time>{% if note.observed_at %}<br>{% trans "Observed" %}: <time datetime="{{ note.observed_at|date:'c' }}">{{ note.observed_at|localtime|date:"j M Y, H:i T" }}</time>{% endif %}</p>
{% if note.context.event_id %}<a href="{% url 'fireworks_detect:event_detail' note.context.event_id %}">{% trans "Event" %} #{{ note.context.event_id }}</a>{% elif note.context.pending_event_id %}<a href="{% url 'fireworks_detect:field_notes' %}?pending={{ note.context.pending_event_id }}">{% trans "Pending report" %} #{{ note.context.pending_event_id }}</a>{% else %}<span>{% if note_token %}{% trans "Current observation — not yet submitted" %}{% else %}{% trans "Standalone observation" %}{% endif %}</span>{% endif %}
{% if note.context.associations.all %}<details><summary>{% trans "Association history" %}</summary><ul>{% for change in note.context.associations.all %}<li>{{ change.created_at|localtime|date:"j M Y, H:i" }} · {{ change.reason }} · {{ change.previous.kind|default:"standalone" }} {{ change.previous.id|default:"" }} → {{ change.target.kind }} {{ change.target.id }}</li>{% endfor %}</ul></details>{% endif %}
{% if not note_kind and not note.context.event_id and not note.context.pending_event_id and note.author_id == request.user.pk %}
<form method="post" action="{% url 'fireworks_detect:link_field_note' note.context_id %}">{% csrf_token %}<label for="link-{{ note.pk }}">{% trans "Link to an approved event" %}</label><select name="event" id="link-{{ note.pk }}" required><option value="">{% trans "Choose an event" %}</option>{% for item in note_events %}<option value="{{ item.pk }}">#{{ item.pk }} · {{ item.captured_at|default:item.created_at|date:"j M Y, H:i" }} · {{ item.occurrences }} {% trans "bangs" %}</option>{% endfor %}</select><button type="submit">{% trans "Link observation" %}</button></form>
{% endif %}
</li>
{% empty %}<li>{% trans "No field notes visible to you yet." %}</li>{% endfor %}
</ol>
<p><a href="{% url 'fireworks_detect:field_notes' %}">{% trans "My field notes" %}</a></p>
</section>
-161
View File
@@ -1,161 +0,0 @@
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)
-89
View File
@@ -1,89 +0,0 @@
import json
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .models import BurstSession
class BurstHeartbeatTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username="burst-a", password="test-password")
self.other = get_user_model().objects.create_user(username="burst-b", password="test-password")
self.client.force_login(self.user)
def start(self):
response = self.client.post(reverse("fireworks_detect:burst_start"), {"maximum_minutes": "15"})
self.assertEqual(response.status_code, 200)
return BurstSession.objects.get(pk=response.json()["id"])
def heartbeat(self, session, sequence=1, frames=100):
return self.client.post(reverse("fireworks_detect:burst_detail", args=[session.pk]), data=json.dumps({
"sequence": sequence, "audio_frames": frames, "elapsed_ms": 5000,
"wall_at": timezone.now().isoformat(), "track_state": "live", "visibility": "visible",
}), content_type="application/json")
def test_sessions_time_out_independently_and_recover(self):
lost = self.start()
active = self.start()
old = timezone.now() - timedelta(seconds=20)
BurstSession.objects.filter(pk=lost.pk).update(started_at=old, last_seen_at=old)
self.assertEqual(self.heartbeat(active).status_code, 200)
call_command("watch_burst_sessions", once=True)
lost.refresh_from_db()
active.refresh_from_db()
self.assertEqual(lost.status, "heartbeat_lost")
self.assertIsNotNone(lost.timeout_at)
self.assertEqual(active.status, "listening")
self.assertIsNone(active.timeout_at)
self.assertEqual(self.heartbeat(lost).status_code, 200)
lost.refresh_from_db()
self.assertEqual(lost.status, "listening")
self.assertTrue(any(item["kind"] == "heartbeat_recovered" for item in lost.diagnostic_events))
def test_replay_and_foreign_session_rejected(self):
session = self.start()
self.assertEqual(self.heartbeat(session).status_code, 200)
self.assertEqual(self.heartbeat(session).status_code, 400)
self.client.force_login(self.other)
self.assertEqual(self.heartbeat(session, sequence=2).status_code, 404)
self.assertEqual(self.client.get(reverse("fireworks_detect:burst_detail", args=[session.pk])).status_code, 404)
class BurstSubmissionTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username="burst-submit", password="test-password")
self.client.force_login(self.user)
self.client.cookies["django_language"] = "en"
def test_grouped_submission_creates_one_pending_with_two_clips(self):
from django.core.files.uploadedfile import SimpleUploadedFile
from .models import BurstCapture, PendingEvent
session = BurstSession.objects.create(owner=self.user, status="review", ended_at=timezone.now())
wav = b"RIFF" + b"\x00" * 4 + b"WAVEfmt " + b"\x00" * 40
clips = [SimpleUploadedFile(f"clip-{index}.wav", wav, content_type="audio/wav") for index in range(2)]
metadata = [{"captured_at": timezone.now().isoformat(), "duration_seconds": 2.0} for _ in clips]
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"burst_session_id": str(session.pk), "burst_audio": clips,
"burst_captures": json.dumps(metadata), "burst_primary": "1", "occurrences": "2",
"burst_predictions": json.dumps([{"class": "Fireworks", "score": 0.8}]),
})
self.assertEqual(response.status_code, 200)
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(BurstCapture.objects.filter(session=session).count(), 2)
self.assertEqual(PendingEvent.objects.get().classifier_response["classification_source"], "browser_yamnet_advisory")
self.assertEqual(BurstCapture.objects.get(session=session, is_primary=True).audio_file.name, PendingEvent.objects.get().audio_file.name)
from django.contrib import admin
self.assertIn("<audio", str(admin.site._registry[PendingEvent].burst_captures(PendingEvent.objects.get())))
self.assertEqual(self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"burst_session_id": str(session.pk), "burst_audio": clips,
"burst_captures": json.dumps(metadata), "burst_primary": "1", "occurrences": "2",
"burst_predictions": json.dumps([{"class": "Fireworks", "score": 0.8}]),
}).status_code, 409)
PendingEvent.objects.get().approve(actor=self.user)
session.refresh_from_db()
self.assertIsNotNone(session.event_id)
self.assertEqual(session.captures.count(), 2)
-182
View File
@@ -1,182 +0,0 @@
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied, ValidationError
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .field_notes import draft_token, regroup_event_notes, reportable_notes
from .models import Event, FieldNote, FieldNoteContext, FieldNoteAssociation, PendingEvent
class FieldNotesTests(TestCase):
def setUp(self):
User = get_user_model()
self.alice = User.objects.create_user('alice', password='test-password')
self.bob = User.objects.create_user('bob', password='test-password')
self.event = Event.objects.create(original_filename='Burst', classifier_response={}, source_type='manual', occurrences=15)
self.url = reverse('fireworks_detect:field_notes')
self.client.force_login(self.alice)
def note(self, user=None, visibility='private', **kwargs):
user = user or self.alice
context = FieldNoteContext.objects.create(author=user, event=self.event)
return FieldNote.objects.create(author=user, context=context, content='A private observation', visibility=visibility, **kwargs)
def test_only_content_required_private_defaults_plain_text(self):
response = self.client.post(self.url, {'content': '<script>alert(1)</script>\nSecond line'})
self.assertEqual(response.status_code, 302)
note = FieldNote.objects.get()
self.assertEqual(note.visibility, 'private')
self.assertEqual(note.source_type, 'unknown')
self.assertEqual(note.verification_status, 'unverified')
response = self.client.get(self.url)
self.assertContains(response, '&lt;script&gt;')
self.assertNotContains(response, '<script>alert(1)</script>')
def test_cross_user_read_create_link_and_export_are_scoped(self):
note = self.note()
self.client.force_login(self.bob)
self.assertNotContains(self.client.get(self.url), note.content)
self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), note.content)
response = self.client.post(self.url, {'content':'forged', 'token':draft_token(self.alice)})
self.assertEqual(response.status_code, 403)
self.assertEqual(self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event': self.event.pk}).status_code, 404)
self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes'], [])
def test_anonymous_cannot_create_read_or_export_notes(self):
self.note()
self.client.logout()
self.assertEqual(self.client.post(self.url, {'content':'no'}).status_code, 302)
self.assertEqual(self.client.get(self.url).status_code, 302)
self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), 'A private observation')
self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).status_code, 302)
def test_export_always_excludes_private_even_for_superuser(self):
self.note()
public = self.note(visibility='reportable', source_type='second_hand')
self.note(self.bob, visibility='reportable')
self.assertEqual(list(reportable_notes(self.alice)), [public])
self.alice.is_superuser = self.alice.is_staff = True
self.alice.save()
for format in ['json','csv']:
response = self.client.get(reverse('fireworks_detect:export_field_notes', args=[format]))
self.assertEqual(response.status_code, 200)
self.assertNotIn('"visibility": "private"', response.content.decode())
rows = self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes']
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0]['source_type'], 'second_hand')
self.assertEqual(rows[0]['verification_status'], 'unverified')
def test_reportable_does_not_grant_other_users_read_access(self):
note = self.note(visibility='reportable')
self.client.force_login(self.bob)
self.assertNotContains(self.client.get(self.url), note.content)
def test_observed_time_entry_time_and_append_only(self):
self.client.post(self.url, {'content':'Later information', 'observed_at':'2026-10-09T14:00'})
note = FieldNote.objects.get()
self.assertTrue(timezone.is_aware(note.observed_at))
self.assertLess(note.observed_at, note.created_at)
entered = note.created_at
note.content = 'rewrite'
with self.assertRaises(ValidationError): note.save()
note.refresh_from_db()
self.assertEqual(note.content, 'Later information')
self.assertEqual(note.created_at, entered)
def test_invalid_forms_render_with_and_without_htmx(self):
for headers in [{}, {'HTTP_HX_REQUEST':'true'}]:
response = self.client.post(self.url, {'content':' ', 'visibility':'public'}, **headers)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'errorlist')
self.assertFalse(FieldNote.objects.exists())
def test_live_notes_bind_to_report_and_survive_approval(self):
token = draft_token(self.alice)
self.client.post(self.url, {'token':token, 'content':'Heard during listening'}, HTTP_HX_REQUEST='true')
note = FieldNote.objects.get()
original_time = note.created_at
response = self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'15', 'field_note_context':token})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
note.context.refresh_from_db()
self.assertEqual(note.context.pending_event_id, pending.pk)
event = pending.approve(actor=self.alice)
note.context.refresh_from_db()
self.assertEqual(note.context.event_id, event.pk)
self.assertIsNone(note.context.pending_event_id)
note.refresh_from_db()
self.assertEqual(note.created_at, original_time)
self.assertEqual(note.context.associations.count(), 2)
self.assertEqual(note.context.associations.last().actor_id, self.alice.pk)
# A note submitted from an already-open form follows the approved report.
self.client.post(self.url, {'token':token, 'content':'Late save'})
self.assertEqual(FieldNote.objects.get(content='Late save').context.event_id, event.pk)
# Reusing a report token cannot reparent existing notes or create a report.
self.assertEqual(self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'1', 'field_note_context':token}).status_code, 403)
self.assertFalse(PendingEvent.objects.exists())
def test_pending_access_checked_and_historical_append(self):
pending = PendingEvent.objects.create(original_filename='secret', classifier_response={})
self.assertEqual(self.client.get(self.url, {'pending':pending.pk}).status_code, 404)
self.assertEqual(self.client.post(self.url, {'pending':pending.pk,'content':'no'}).status_code, 404)
self.assertEqual(self.client.post(self.url, {'event':self.event.pk,'content':'Historical follow-up'}).status_code, 302)
self.assertEqual(FieldNote.objects.get().context.event_id, self.event.pk)
def test_standalone_link_and_regroup_preserve_provenance(self):
self.client.post(self.url, {'content':'Possible camera lead'})
note = FieldNote.objects.get()
response = self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event':self.event.pk})
self.assertEqual(response.status_code, 302)
target = Event.objects.create(original_filename='Grouped burst', classifier_response={}, occurrences=20)
with self.assertRaises(PermissionDenied): regroup_event_notes(self.alice, self.event, target)
self.alice.is_superuser = self.alice.is_staff = True; self.alice.save()
regroup_event_notes(self.alice, self.event, target)
self.event.delete()
note.context.refresh_from_db()
self.assertEqual(note.context.event_id, target.pk)
self.assertEqual(note.context.associations.count(), 2)
self.assertEqual(note.context.associations.last().previous['id'], self.event.pk or note.context.associations.first().target['id'])
self.assertEqual(FieldNote.objects.count(), 1)
def test_denied_report_retains_notes_and_original_reference(self):
token = draft_token(self.alice)
self.client.post(self.url, {'token':token,'content':'Retain observation'})
self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'3','field_note_context':token})
pending = PendingEvent.objects.get(); old_id = pending.pk; pending.deny()
note = FieldNote.objects.get()
self.assertIsNone(note.context.pending_event_id)
self.assertEqual(note.context.associations.get().target, {'kind':'pending','id':old_id})
def test_staff_needs_explicit_permission_for_private_notes(self):
self.note()
self.bob.is_staff = True; self.bob.save()
self.assertFalse(FieldNote.objects.visible_to(self.bob).exists())
self.bob.user_permissions.add(Permission.objects.get(codename='view_all_fieldnotes'))
bob = get_user_model().objects.get(pk=self.bob.pk)
self.assertEqual(FieldNote.objects.visible_to(bob).count(), 1)
self.assertFalse(reportable_notes(bob).exists())
def test_csv_formula_is_escaped(self):
ctx = FieldNoteContext.objects.create(author=self.alice)
FieldNote.objects.create(author=self.alice, context=ctx, content='=1+1', visibility='reportable')
self.assertContains(self.client.get(reverse('fireworks_detect:export_field_notes', args=['csv'])), "'=1+1")
def test_note_posts_require_csrf(self):
from django.test import Client
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.alice)
self.assertEqual(browser.post(self.url, {"content":"forged"}).status_code, 403)
self.assertFalse(FieldNote.objects.exists())
def test_history_orders_by_entry_not_backdated_observation(self):
first = self.note(observed_at=timezone.now())
second = self.note(observed_at=timezone.now()-timedelta(days=7))
self.assertEqual(list(FieldNote.objects.values_list("pk", flat=True)), [first.pk, second.pk])
self.client.force_login(self.bob)
self.bob.user_permissions.add(Permission.objects.get(codename="export_reportable_fieldnotes"))
# Export permission does not grant read access to private history.
self.assertNotContains(self.client.get(self.url), first.content)

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