browser audio processing phase 1
This commit is contained in:
BIN
Binary file not shown.
@@ -10,7 +10,7 @@ from django.urls import path, reverse
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext as _, gettext_lazy, ngettext
|
||||
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
|
||||
from . import views as classifier_views
|
||||
|
||||
|
||||
@@ -21,6 +21,33 @@ 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", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("source_type", "visually_confirmed", "created_at")
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Public, advisory configuration for the optional browser processing beta."""
|
||||
|
||||
import json
|
||||
|
||||
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", "no_match", "unavailable", "error"}
|
||||
|
||||
|
||||
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": {},
|
||||
}
|
||||
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))
|
||||
policy["privacy_sensitive_speech"] = [
|
||||
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)
|
||||
]
|
||||
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
|
||||
return metadata
|
||||
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-02 14:31
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0008_sensor_owner_sensor_archived_at'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='BrowserProcessingSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('browser_processing_beta_enabled', models.BooleanField(default=False)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Browser-side media processing (Beta)',
|
||||
'verbose_name_plural': 'Browser-side media processing (Beta)',
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def create_disabled_settings(apps, schema_editor):
|
||||
Settings = apps.get_model("fireworks_detect", "BrowserProcessingSettings")
|
||||
Settings.objects.get_or_create(pk=1, defaults={"browser_processing_beta_enabled": False})
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("fireworks_detect", "0009_browserprocessingsettings"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(create_disabled_settings, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -88,6 +88,27 @@ 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."""
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<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 %}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<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>
|
||||
@@ -30,4 +31,4 @@
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
</html>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{% load i18n %}
|
||||
<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">
|
||||
<form class="upload-form audio-upload--idle" action="{% url "fireworks_detect:classify_upload" %}" method="post" enctype="multipart/form-data" hx-post="{% url "fireworks_detect:classify_upload" %}" hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-indicator="#upload-indicator" data-scroll-to-results="true">
|
||||
{% csrf_token %}
|
||||
<label class="drop-zone" id="drop-zone">
|
||||
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
|
||||
<span>
|
||||
<span class="upload-icon">↑</span>
|
||||
<span class="upload-icon" id="upload-progress-circle"><span class="upload-icon__content" id="upload-icon-content" aria-hidden="true">↑</span></span>
|
||||
<strong>{% trans "Drop an audio file here" %}</strong>
|
||||
<span>{% trans "or click to browse your device" %}</span>
|
||||
</span>
|
||||
@@ -13,6 +13,7 @@
|
||||
<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 id="classification-results" aria-live="polite" aria-label="{% trans "Classification results" %}"></section>
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{{ browser_processing_config|json_script:"boomcast-browser-config" }}
|
||||
@@ -0,0 +1,101 @@
|
||||
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": {},
|
||||
})
|
||||
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"')
|
||||
|
||||
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.assertEqual(policy["privacy_sensitive_speech"], ["Speech"])
|
||||
self.assertEqual(policy["thresholds"], {})
|
||||
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)
|
||||
@@ -13,6 +13,7 @@ from .views import (
|
||||
submit_manual_pending_event,
|
||||
submit_pending_event,
|
||||
sensor_heartbeat,
|
||||
browser_processing_policy,
|
||||
)
|
||||
|
||||
app_name = "fireworks_detect"
|
||||
@@ -22,6 +23,7 @@ urlpatterns = [
|
||||
path("map/", fireworks_map_view, name="map"),
|
||||
path("classify/", classify_audio, name="classify"),
|
||||
path("classify/upload/", classify_upload, name="classify_upload"),
|
||||
path("browser-policy/", browser_processing_policy, name="browser_policy"),
|
||||
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
|
||||
path("submit-pending/", submit_pending_event, name="submit_pending"),
|
||||
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
|
||||
|
||||
@@ -2,6 +2,7 @@ import math
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -20,6 +21,7 @@ from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
|
||||
from .browser_policy import advisory_browser_metadata, browser_config, browser_policy
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
@@ -35,11 +37,18 @@ SPEECH_TERMS = (
|
||||
"speaking", "speech synthesizer",
|
||||
)
|
||||
AUDIO_EXTENSIONS = {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".weba"}
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
@never_cache
|
||||
def browser_processing_policy(request):
|
||||
return JsonResponse(browser_policy())
|
||||
|
||||
|
||||
@never_cache
|
||||
def fireworks_view(request):
|
||||
return render(request, "fireworks_detect/home.html")
|
||||
return render(request, "fireworks_detect/home.html", {"browser_processing_config": browser_config()})
|
||||
|
||||
|
||||
MAP_DATE_RANGES = {
|
||||
@@ -157,6 +166,7 @@ def dashboard_view(request):
|
||||
"h3_resolution": h3_resolution(),
|
||||
"h3_cells": h3_cells,
|
||||
"map_events": map_events,
|
||||
"browser_processing_config": browser_config(),
|
||||
})
|
||||
|
||||
|
||||
@@ -248,6 +258,10 @@ def classify_upload(request):
|
||||
if uploaded_file.size > MAX_AUDIO_SIZE:
|
||||
return _render_error(request, _("This demo accepts audio files up to 25 MiB."))
|
||||
|
||||
metadata = advisory_browser_metadata(request.POST)
|
||||
if metadata:
|
||||
logger.info("Browser beta diagnostics (advisory only): %s", metadata)
|
||||
|
||||
body, content_type = _encode_audio_multipart(uploaded_file)
|
||||
classifier_request = Request(
|
||||
CLASSIFIER_URL,
|
||||
@@ -279,6 +293,9 @@ def classify_upload(request):
|
||||
@require_http_methods(["POST"])
|
||||
@never_cache
|
||||
def submit_pending_event(request):
|
||||
metadata = advisory_browser_metadata(request.POST)
|
||||
if metadata:
|
||||
logger.info("Browser beta submission diagnostics (advisory only): %s", metadata)
|
||||
uploaded_file = request.FILES.get("audio")
|
||||
token = request.POST.get("classification_token")
|
||||
if not uploaded_file:
|
||||
|
||||
@@ -1,31 +1,215 @@
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
import { BrowserSubmissionProcessor } from "./browser-submission-processor.js";
|
||||
|
||||
const form = document.querySelector('.upload-form');
|
||||
const dropZone = document.querySelector('#drop-zone');
|
||||
const fileInput = document.querySelector('#audio-file');
|
||||
const fileName = document.querySelector('#file-name');
|
||||
const status = document.querySelector('#upload-status');
|
||||
const showFile = (file) => { fileName.textContent = file ? file.name : (t.noFile || 'No file selected'); };
|
||||
const form = document.querySelector(".upload-form");
|
||||
|
||||
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
|
||||
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
|
||||
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
|
||||
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
|
||||
form.addEventListener('htmx:beforeRequest', () => { status.textContent = (t.analysing || 'Analysing your recording…'); form.setAttribute('aria-busy', 'true'); });
|
||||
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
|
||||
form.addEventListener('htmx:responseError', () => { status.textContent = (t.analysisFailed || 'Analysis could not be completed.'); });
|
||||
document.body.addEventListener('htmx:beforeSwap', (event) => {
|
||||
if (event.detail.xhr.status >= 400) {
|
||||
event.detail.shouldSwap = true;
|
||||
event.detail.isError = false;
|
||||
if (form) {
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
const dropZone = form.querySelector("#drop-zone");
|
||||
const fileInput = form.querySelector("#audio-file");
|
||||
const fileName = form.querySelector("#file-name");
|
||||
const circle = form.querySelector("#upload-progress-circle");
|
||||
const iconContent = form.querySelector("#upload-icon-content");
|
||||
const submit = form.querySelector('button[type="submit"]');
|
||||
const cancel = form.querySelector(".upload-cancel");
|
||||
const results = form.querySelector("#classification-results");
|
||||
const status = document.querySelector("#upload-status");
|
||||
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const states = ["idle", "file-selected", "uploading", "processing", "success", "error", "cancelled"];
|
||||
let request = null;
|
||||
let busy = false;
|
||||
let uploadComplete = false;
|
||||
let processingTimer = null;
|
||||
let preparing = false;
|
||||
const browserProcessor = new BrowserSubmissionProcessor();
|
||||
if (!browserProcessor.isEnabled()) {
|
||||
console.log("[BoomCast][BrowserBeta] Feature disabled; using legacy submission flow.");
|
||||
}
|
||||
|
||||
function setUploadState(state, { progress = null, message = "" } = {}) {
|
||||
for (const name of states) form.classList.toggle(`audio-upload--${name}`, name === state);
|
||||
const active = state === "uploading" || state === "processing";
|
||||
busy = active;
|
||||
submit.disabled = active;
|
||||
fileInput.disabled = active;
|
||||
cancel.hidden = !active;
|
||||
if (active) form.setAttribute("aria-busy", "true");
|
||||
else form.removeAttribute("aria-busy");
|
||||
|
||||
if (state === "uploading") {
|
||||
circle.setAttribute("role", "progressbar");
|
||||
circle.setAttribute("aria-label", t.uploadingAudio || "Uploading audio");
|
||||
circle.setAttribute("aria-valuemin", "0");
|
||||
circle.setAttribute("aria-valuemax", "100");
|
||||
if (progress === null) {
|
||||
circle.removeAttribute("aria-valuenow");
|
||||
circle.setAttribute("aria-valuetext", t.uploadingAudio || "Uploading audio");
|
||||
iconContent.textContent = "↑";
|
||||
} else {
|
||||
circle.setAttribute("aria-valuenow", String(progress));
|
||||
circle.setAttribute("aria-valuetext", `${t.uploadingAudio || "Uploading audio"}: ${progress}%`);
|
||||
circle.style.setProperty("--upload-progress", `${progress}%`);
|
||||
iconContent.textContent = `${progress}%`;
|
||||
}
|
||||
status.textContent = progress === null ? (t.uploadingAudio || "Uploading audio…") : "";
|
||||
} else {
|
||||
circle.removeAttribute("role");
|
||||
circle.removeAttribute("aria-label");
|
||||
circle.removeAttribute("aria-valuemin");
|
||||
circle.removeAttribute("aria-valuemax");
|
||||
circle.removeAttribute("aria-valuenow");
|
||||
circle.removeAttribute("aria-valuetext");
|
||||
iconContent.textContent = state === "processing" ? "◉" : state === "success" ? "✓" : state === "error" ? "!" : "↑";
|
||||
status.textContent = message || ({
|
||||
processing: t.uploadCompleteAnalysing || "Upload complete. Analysing audio…",
|
||||
success: t.analysisComplete || "Analysis complete.",
|
||||
cancelled: t.uploadCancelled || "Upload cancelled.",
|
||||
}[state] || "");
|
||||
}
|
||||
}
|
||||
|
||||
function showFile(file) {
|
||||
fileName.textContent = file ? file.name : (t.noFile || "No file selected");
|
||||
if (!busy) setUploadState(file ? "file-selected" : "idle");
|
||||
if (file) console.log("[boomcast-upload] file selected", { size: file.size, type: file.type });
|
||||
}
|
||||
|
||||
function fail(message, detail) {
|
||||
clearTimeout(processingTimer);
|
||||
console.error("[boomcast-upload] upload failed", detail);
|
||||
setUploadState("error", { message });
|
||||
request = null;
|
||||
}
|
||||
|
||||
function finishUpload(xhr) {
|
||||
if (uploadComplete) return;
|
||||
uploadComplete = true;
|
||||
console.log("[boomcast-upload] upload complete, awaiting classifier");
|
||||
// Give a real 100% progress event one paint before showing the separate server state.
|
||||
processingTimer = window.setTimeout(() => {
|
||||
if (request === xhr && busy) setUploadState("processing");
|
||||
}, 120);
|
||||
}
|
||||
|
||||
function handleResponse(xhr) {
|
||||
clearTimeout(processingTimer);
|
||||
request = null;
|
||||
let fragment;
|
||||
try {
|
||||
fragment = new DOMParser().parseFromString(xhr.responseText, "text/html");
|
||||
} catch (error) {
|
||||
fail(t.analysisFailed || "Analysis could not be completed.", error);
|
||||
return;
|
||||
}
|
||||
const card = fragment.querySelector(".results-card");
|
||||
if (!card) {
|
||||
fail(t.analysisFailed || "Analysis could not be completed.", `Unexpected response (HTTP ${xhr.status})`);
|
||||
return;
|
||||
}
|
||||
results.replaceChildren(document.importNode(card, true));
|
||||
window.htmx?.process(results);
|
||||
if (xhr.status >= 400 || card.classList.contains("error-card")) {
|
||||
const message = card.querySelector("p")?.textContent || (t.analysisFailed || "Analysis could not be completed.");
|
||||
console.error("[boomcast-upload] classification failed", { status: xhr.status, message });
|
||||
setUploadState("error", { message });
|
||||
return;
|
||||
}
|
||||
console.log("[boomcast-upload] classification response received", xhr.status);
|
||||
setUploadState("success");
|
||||
if (form.dataset.scrollToResults === "true") {
|
||||
results.scrollIntoView({ behavior: reducedMotion.matches ? "instant" : "smooth", block: "start" });
|
||||
}
|
||||
}
|
||||
|
||||
fileInput.addEventListener("change", () => showFile(fileInput.files[0]));
|
||||
["dragenter", "dragover"].forEach((name) => dropZone.addEventListener(name, (event) => {
|
||||
event.preventDefault();
|
||||
if (!busy) dropZone.classList.add("dragging");
|
||||
}));
|
||||
["dragleave", "drop"].forEach((name) => dropZone.addEventListener(name, (event) => {
|
||||
event.preventDefault();
|
||||
dropZone.classList.remove("dragging");
|
||||
}));
|
||||
dropZone.addEventListener("drop", (event) => {
|
||||
if (busy || !event.dataTransfer.files.length) return;
|
||||
fileInput.files = event.dataTransfer.files;
|
||||
showFile(fileInput.files[0]);
|
||||
});
|
||||
|
||||
function startUpload(file, metadata = null) {
|
||||
const formData = new FormData(form);
|
||||
formData.set("audio", file);
|
||||
if (metadata) formData.set("browser_processing_metadata", JSON.stringify(metadata));
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
request = xhr;
|
||||
uploadComplete = false;
|
||||
results.replaceChildren();
|
||||
setUploadState("uploading");
|
||||
console.log("[boomcast-upload] upload started", { size: file.size, type: file.type });
|
||||
xhr.open("POST", form.action);
|
||||
xhr.upload.addEventListener("progress", (progressEvent) => {
|
||||
if (uploadComplete) return;
|
||||
if (!progressEvent.lengthComputable || progressEvent.total <= 0) return;
|
||||
const percent = Math.min(100, Math.round(progressEvent.loaded / progressEvent.total * 100));
|
||||
if (percent !== Number(circle.getAttribute("aria-valuenow"))) {
|
||||
setUploadState("uploading", { progress: percent });
|
||||
console.log("[boomcast-upload] upload progress", percent);
|
||||
}
|
||||
if (progressEvent.loaded >= progressEvent.total && !uploadComplete) {
|
||||
finishUpload(xhr);
|
||||
}
|
||||
});
|
||||
window.addEventListener('pageshow', (event) => {
|
||||
if (event.persisted) {
|
||||
fileInput.value = '';
|
||||
showFile();
|
||||
status.textContent = '';
|
||||
document.querySelector('#classification-results').replaceChildren();
|
||||
}
|
||||
xhr.upload.addEventListener("load", () => {
|
||||
finishUpload(xhr);
|
||||
});
|
||||
|
||||
xhr.addEventListener("load", () => handleResponse(xhr));
|
||||
xhr.addEventListener("error", () => fail(t.uploadFailed || "Upload failed. Check your connection and try again.", "Network error"));
|
||||
xhr.addEventListener("timeout", () => fail(t.uploadFailed || "Upload failed. Check your connection and try again.", "Request timed out"));
|
||||
xhr.addEventListener("abort", () => {
|
||||
clearTimeout(processingTimer);
|
||||
request = null;
|
||||
setUploadState("cancelled");
|
||||
console.log("[boomcast-upload] upload cancelled");
|
||||
});
|
||||
xhr.send(formData);
|
||||
}
|
||||
|
||||
// Capture before HTMX's bubbling submit listener; the hx-* attributes remain a fallback.
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (busy || preparing) return;
|
||||
if (!form.reportValidity()) return;
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
if (!browserProcessor.isEnabled()) {
|
||||
startUpload(file);
|
||||
return;
|
||||
}
|
||||
preparing = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.preparingRecording || "Preparing recording…";
|
||||
browserProcessor.prepare(file).then(({ file: preparedFile, metadata }) => {
|
||||
preparing = false;
|
||||
submit.disabled = false;
|
||||
startUpload(preparedFile || file, metadata);
|
||||
}).catch((error) => {
|
||||
console.error("[BoomCast][BrowserBeta] Initialisation failed:", error);
|
||||
browserProcessor.cleanup();
|
||||
console.log("[BoomCast][BrowserBeta] Restoring legacy submission flow.");
|
||||
preparing = false;
|
||||
submit.disabled = false;
|
||||
startUpload(file);
|
||||
});
|
||||
}, true);
|
||||
|
||||
cancel.addEventListener("click", () => request?.abort());
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) {
|
||||
request?.abort();
|
||||
fileInput.value = "";
|
||||
results.replaceChildren();
|
||||
showFile();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
const PREFIX = "[BoomCast][BrowserBeta]";
|
||||
|
||||
export function readBrowserProcessingConfig() {
|
||||
const element = document.querySelector("#boomcast-browser-config");
|
||||
if (!element) return { browserProcessingBeta: false };
|
||||
try {
|
||||
return JSON.parse(element.textContent);
|
||||
} catch (error) {
|
||||
console.error(`${PREFIX} Configuration unavailable:`, error);
|
||||
return { browserProcessingBeta: false };
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSubmissionProcessor {
|
||||
constructor(config = readBrowserProcessingConfig()) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
isEnabled() {
|
||||
return this.config.browserProcessingBeta === true;
|
||||
}
|
||||
|
||||
canProcess(file) {
|
||||
return this.isEnabled() && Boolean(file) && /^(audio|video)\//.test(file.type);
|
||||
}
|
||||
|
||||
async prepare(file) {
|
||||
if (!this.isEnabled()) return { file, metadata: null };
|
||||
console.log(`${PREFIX} Initialising beta submission pipeline.`);
|
||||
console.log(`${PREFIX} File selected:`, { type: file?.type || "", size: file?.size || 0 });
|
||||
if (!this.canProcess(file)) {
|
||||
console.log(`${PREFIX} Browser preprocessing unavailable; falling back.`);
|
||||
return { file, metadata: null };
|
||||
}
|
||||
let policyTimeout;
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
policyTimeout = setTimeout(() => controller.abort(), 5000);
|
||||
const response = await fetch(this.config.policyUrl, {
|
||||
cache: "no-store", credentials: "same-origin", signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`Policy HTTP ${response.status}`);
|
||||
const policy = await response.json();
|
||||
if (!policy.browser_processing_beta_enabled || policy.version !== this.config.policyVersion) {
|
||||
console.log(`${PREFIX} Browser beta disabled or policy changed; using legacy submission flow.`);
|
||||
return { file, metadata: null };
|
||||
}
|
||||
// Pass 1 has no local classifier or transcoder. Keep the original file.
|
||||
console.log(`${PREFIX} Browser processing shell ready; using original recording.`);
|
||||
return {
|
||||
file,
|
||||
metadata: {
|
||||
browser_processing_used: false,
|
||||
browser_processing_version: policy.version,
|
||||
browser_gate_result: "unavailable",
|
||||
browser_override: false,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`${PREFIX} Initialisation failed:`, error);
|
||||
this.cleanup();
|
||||
console.log(`${PREFIX} Restoring legacy submission flow.`);
|
||||
return { file, metadata: null };
|
||||
} finally {
|
||||
clearTimeout(policyTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
// Future passes can release workers, object URLs, and model tensors here.
|
||||
console.log("[BoomCast][Cleanup] Browser beta resources released.");
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,7 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
.drop-zone .upload-icon {
|
||||
display: grid;
|
||||
width: 4rem;
|
||||
aspect-ratio: 1;
|
||||
@@ -140,6 +140,38 @@
|
||||
background: #4777c94d;
|
||||
}
|
||||
|
||||
.drop-zone .upload-icon__content { position: relative; z-index: 1; margin: 0; color: inherit; font-size: inherit; font-weight: 850; }
|
||||
.audio-upload--uploading .upload-icon,
|
||||
.audio-upload--processing .upload-icon,
|
||||
.audio-upload--success .upload-icon,
|
||||
.audio-upload--error .upload-icon { position: relative; width: 5.5rem; margin-bottom: .25rem; color: #fff; font-size: 1.25rem; box-shadow: 0 0 0 .35rem #334e8d70, 0 .6rem 2rem #101a3fa6; }
|
||||
.audio-upload--uploading .upload-icon { background: conic-gradient(#91baff var(--upload-progress, 0%), #334b82 0); }
|
||||
.audio-upload--processing .upload-icon { background: #405caa; }
|
||||
.audio-upload--processing .upload-icon::after { content: ""; position: absolute; inset: -.42rem; border: 3px solid #9fc5ff; border-right-color: transparent; border-radius: 50%; animation: spin 1.5s linear infinite; }
|
||||
.audio-upload--success .upload-icon { background: #147d6c; }
|
||||
.audio-upload--error .upload-icon { background: #9d385b; }
|
||||
.audio-upload--uploading .drop-zone,
|
||||
.audio-upload--processing .drop-zone { border-color: #7296d5; background: linear-gradient(135deg, #18284c, #242046); }
|
||||
.audio-upload--uploading .drop-zone strong,
|
||||
.audio-upload--processing .drop-zone strong,
|
||||
.audio-upload--uploading .drop-zone > span > span:not(.upload-icon),
|
||||
.audio-upload--processing .drop-zone > span > span:not(.upload-icon),
|
||||
.audio-upload--uploading .file-name,
|
||||
.audio-upload--processing .file-name { opacity: .35; }
|
||||
.audio-upload--uploading .drop-zone,
|
||||
.audio-upload--processing .drop-zone { cursor: default; }
|
||||
.audio-upload--uploading .drop-zone:hover,
|
||||
.audio-upload--processing .drop-zone:hover { transform: none; }
|
||||
.upload-cancel[hidden] { display: none; }
|
||||
#classification-results { scroll-margin-top: 1.5rem; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.audio-upload--processing .upload-icon::after { animation: none; }
|
||||
.audio-upload--uploading .drop-zone,
|
||||
.audio-upload--processing .drop-zone,
|
||||
.audio-upload--uploading .upload-icon,
|
||||
.audio-upload--processing .upload-icon { transition: none; }
|
||||
}
|
||||
|
||||
.drop-zone strong {
|
||||
display: block;
|
||||
font-size: 1.15rem;
|
||||
@@ -477,4 +509,3 @@
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,12 @@
|
||||
background: var(--theme-surface-raised) !important;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] .audio-upload--uploading .drop-zone,
|
||||
:root[data-theme="light"] .audio-upload--processing .drop-zone {
|
||||
border-color: #7296d5 !important;
|
||||
background: #e4ebff !important;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] input,
|
||||
:root[data-theme="light"] select,
|
||||
:root[data-theme="light"] textarea,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { BrowserSubmissionProcessor } from "../src/scripts/browser-submission-processor.js";
|
||||
|
||||
const file = { type: "audio/wav", size: 64 };
|
||||
|
||||
test("disabled beta returns the original file without loading policy", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = () => { throw new Error("fetch must not run"); };
|
||||
try {
|
||||
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: false });
|
||||
assert.equal(processor.isEnabled(), false);
|
||||
assert.equal(processor.canProcess(file), false);
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("enabled shell checks current server policy and never claims processing occurred", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: true, version: 1 }) });
|
||||
try {
|
||||
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 });
|
||||
const result = await processor.prepare(file);
|
||||
assert.equal(result.file, file);
|
||||
assert.equal(result.metadata.browser_processing_used, false);
|
||||
assert.equal(result.metadata.browser_gate_result, "unavailable");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("admin-disabled policy and fetch failure both fall back to the original file", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 });
|
||||
try {
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: false, version: 1 }) });
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
globalThis.fetch = async () => { throw new Error("offline"); };
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
Binary file not shown.
@@ -1212,3 +1212,6 @@ msgstr "De classifier was niet bereikbaar of gaf ongeldige JSON terug."
|
||||
|
||||
msgid "Classification saved. This event remains Pending."
|
||||
msgstr "Classificatie opgeslagen. Deze melding blijft openstaan."
|
||||
|
||||
msgid "Preparing recording…"
|
||||
msgstr "Opname voorbereiden…"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --test frontend/tests/*.test.mjs",
|
||||
"dev": "concurrently --kill-others-on-fail --names django,vite --prefix-colors blue,magenta \"npm:django\" \"npm:vite\"",
|
||||
"django": "node scripts/dev-django.mjs",
|
||||
"vite": "vite",
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
/* empty css */import"./fireworks-home.js-D5iuyEAp.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"./fireworks-home.js-BF3PcmrX.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"./fireworks-home.js-DfXbE6JP.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"./fireworks-home.js-ij3dXXlf.js";import"./map.js-jpUFFpF3.js";import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"../../../theme-DXAi27ON.js";
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import"../../../manual-report-BLClvilD.js";import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";const r=document.querySelector(".upload-form"),n=document.querySelector("#drop-zone"),o=document.querySelector("#audio-file"),d=document.querySelector("#file-name"),a=document.querySelector("#upload-status"),s=e=>{d.textContent=e?e.name:"No file selected"};o.addEventListener("change",()=>s(o.files[0]));["dragenter","dragover"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.add("dragging")}));["dragleave","drop"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.remove("dragging")}));n.addEventListener("drop",e=>{const[t]=e.dataTransfer.files;t&&(o.files=e.dataTransfer.files,s(t))});r.addEventListener("htmx:beforeRequest",()=>{a.textContent="Analysing your recording…",r.setAttribute("aria-busy","true")});r.addEventListener("htmx:afterRequest",()=>{a.textContent="",r.removeAttribute("aria-busy")});r.addEventListener("htmx:responseError",()=>{a.textContent="Analysis could not be completed."});
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"../../../theme-DXAi27ON.js";const e=window.BOOMCAST_I18N||{},u=document.getElementById("event-map"),f=u.dataset.h3Resolution,t=L.map(u,{zoomControl:!1,scrollWheelZoom:!1}).setView([52.1326,5.2913],7);L.control.zoom({position:"bottomleft"}).addTo(t);const m=L.control({position:"topright"});m.onAdd=()=>{const o=L.DomUtil.create("div","map-compass");return o.setAttribute("role","img"),o.setAttribute("aria-label",e.mapCompass||"Map compass: north is up"),o.innerHTML='<span class="compass-n">N</span><span class="compass-e">E</span><span class="compass-s">S</span><span class="compass-w">W</span><span class="compass-needle">↑</span>',L.DomEvent.disableClickPropagation(o),o};m.addTo(t);L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png",{maxZoom:18,attribution:"© OpenStreetMap contributors"}).addTo(t);const y=JSON.parse(document.getElementById("h3-cells-data").textContent),M=JSON.parse(document.getElementById("map-events-data").textContent),d=L.latLngBounds([]);y.forEach(o=>{L.polygon(o.boundary,{color:"#f59e0b",weight:2,fillColor:"#f59e0b",fillOpacity:.25}).addTo(t).bindPopup('<span class="popup-title">H3 '+o.cell+'</span><span class="popup-meta">'+o.reports+" "+(o.reports===1?e.report||"report":e.reports||"reports")+" · "+o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+(e.resolution||"resolution")+" "+f+"</span>"),d.extend(L.latLngBounds(o.boundary))});function b(o){return["N","NE","E","SE","S","SW","W","NW"][Math.floor((o+22.5)%360/45)]}function v(o,n,s){const c=n*Math.PI/180,i=o[0]*Math.PI/180,h=o[1]*Math.PI/180,r=s/6378137,l=Math.asin(Math.sin(i)*Math.cos(r)+Math.cos(i)*Math.sin(r)*Math.cos(c)),g=h+Math.atan2(Math.sin(c)*Math.sin(r)*Math.cos(i),Math.cos(r)-Math.sin(i)*Math.sin(l));return[l*180/Math.PI,g*180/Math.PI]}const E=L.divIcon({className:"",html:'<div class="report-icon">✦</div>',iconSize:[37,37],iconAnchor:[19,19]});M.forEach(o=>{const n=o.visually_confirmed?e.visuallyConfirmed||"Visually confirmed":e.notVisuallyConfirmed||"Not visually confirmed";let s=o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+n+"<br>"+(e.reported||"Reported")+" "+o.reported_on;if(o.direction_degrees!==null&&(s+="<br>"+(e.compassDirection||"Compass direction")+" "+Math.round(o.direction_degrees)+"° ("+b(o.direction_degrees)+")",o.direction_accuracy_degrees!==null&&(s+=" (±"+Math.round(o.direction_accuracy_degrees)+"°)")),L.marker(o.center,{icon:E}).addTo(t).bindPopup('<span class="popup-title">'+(e.manualReport||"Manual report")+" · H3 "+o.cell+'</span><span class="popup-meta">'+s+"</span>"),o.direction_degrees!==null){const a=v(o.center,o.direction_degrees,900);L.polyline([o.center,a],{color:"#fff7e6",weight:9,opacity:.8}).addTo(t),L.polyline([o.center,a],{color:"#6d45a0",weight:5,opacity:1}).addTo(t);const c=L.divIcon({className:"",html:'<div class="direction-marker"><span style="transform:rotate('+o.direction_degrees+'deg)">↑</span></div>',iconSize:[56,56],iconAnchor:[28,28]});L.marker(a,{icon:c,interactive:!1}).addTo(t)}});d.isValid()&&t.fitBounds(d.pad(.18));const p=document.getElementById("range");p&&document.querySelectorAll("#from-date, #to-date").forEach(o=>{o.addEventListener("change",()=>{p.value="custom"})});
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-DXAi27ON.js";document.querySelector("#ntfy-url").addEventListener("input",()=>{document.querySelector("#ntfy-test-result").replaceChildren()});
|
||||
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;--theme-bg: #090e1d;--theme-ink: #eef3ff;--theme-muted: #aab9d8;--theme-surface: #172443;--theme-surface-raised: #111a31;--theme-line: #2b3d68;--theme-input: #0a1123}:root[data-theme=light]{color-scheme:light;--ink: #172033;--i: #172033;--muted: #536174;--m: #536174;--line: #c4cede;--l: #c4cede;--surface: #ffffff;--surface-2: #f2f6fc;--card: rgba(255, 255, 255, .94);--theme-bg: #f4f7fc;--theme-ink: #172033;--theme-muted: #536174;--theme-surface: #ffffff;--theme-surface-raised: #f2f6fc;--theme-line: #c4cede;--theme-input: #ffffff}:root[data-theme=light] body{color:var(--theme-ink)!important;background:radial-gradient(circle at 8% 0%,#dbeaff 0,transparent 31rem),radial-gradient(circle at 96% 100%,#eee2ff 0,transparent 29rem),var(--theme-bg)!important}:root[data-theme=light] .card,:root[data-theme=light] .welcome-card,:root[data-theme=light] .upload-card,:root[data-theme=light] .results-card,:root[data-theme=light] .panel,:root[data-theme=light] .map-panel{border-color:var(--theme-line)!important;background:var(--theme-surface)!important;box-shadow:0 1rem 3rem #20365c24!important}:root[data-theme=light] .topbar,:root[data-theme=light] .map-header,:root[data-theme=light] .nav,:root[data-theme=light] .filters,:root[data-theme=light] .result-group,:root[data-theme=light] .prediction,:root[data-theme=light] .event,:root[data-theme=light] .drop-zone{border-color:var(--theme-line)!important;color:var(--theme-ink);background:var(--theme-surface-raised)!important}:root[data-theme=light] .audio-upload--uploading .drop-zone,:root[data-theme=light] .audio-upload--processing .drop-zone{border-color:#7296d5!important;background:#e4ebff!important}:root[data-theme=light] input,:root[data-theme=light] select,:root[data-theme=light] textarea,:root[data-theme=light] .path{border-color:var(--theme-line)!important;color:var(--theme-ink)!important;background:var(--theme-input)!important}:root[data-theme=light] .intro,:root[data-theme=light] .lede,:root[data-theme=light] .subject,:root[data-theme=light] .message,:root[data-theme=light] .help,:root[data-theme=light] .empty,:root[data-theme=light] .meta,:root[data-theme=light] .popup-meta{color:var(--theme-muted)!important}.theme-toggle{position:fixed;top:1rem;left:1rem;z-index:1200;min-height:2.5rem;padding:.5rem .75rem;border:1px solid var(--theme-line);border-radius:999px;color:var(--theme-ink);font:700 .82rem/1 Inter,ui-sans-serif,system-ui,sans-serif;background:var(--theme-surface);box-shadow:0 .35rem 1.25rem #01030c3d;cursor:pointer}.theme-toggle:hover{filter:brightness(1.08)}.theme-toggle:focus-visible{outline:3px solid #8abaff;outline-offset:3px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{transition-duration:.01ms!important}}:root[data-theme=light] .shell h1{color:#172b50!important}:root[data-theme=light] .shell h2{color:#203b63!important}:root[data-theme=light] .shell h3{color:#31527f!important}:root[data-theme=light] .shell .kicker,:root[data-theme=light] .shell .eyebrow{color:#3f6fa9!important}:root[data-theme=light] .shell .map-header strong{color:#243e65!important}
|
||||
@@ -0,0 +1 @@
|
||||
const r="sound-signal-theme",s=new Set(["dark","light"]);function c(){try{const e=window.localStorage.getItem(r);return s.has(e)?e:"dark"}catch{return"dark"}}function d(e,t){if(document.documentElement.dataset.theme=e,!t)return;const n=e==="dark"?"light":"dark",a=window.BOOMCAST_I18N||{};t.textContent=n==="light"?"☀ "+(a.lightMode||"Light mode"):"☾ "+(a.darkMode||"Dark mode"),t.setAttribute("aria-label",n==="light"?a.switchToLight||"Switch to light mode":a.switchToDark||"Switch to dark mode"),t.setAttribute("aria-pressed",String(e==="light"))}function o(){const e=document.querySelector(".theme-toggle")??document.createElement("button");e.isConnected||(e.className="theme-toggle",e.type="button",document.body.append(e)),d(c(),e),e.addEventListener("click",()=>{const t=document.documentElement.dataset.theme==="dark"?"light":"dark";try{window.localStorage.setItem(r,t)}catch{}d(t,e)})}function i(){const e=document.querySelector(".fireworks-menu-toggle");if(!e)return;const t=()=>{e.setAttribute("aria-expanded","false"),e.setAttribute("aria-label",e.dataset.openLabel)};e.addEventListener("click",()=>{const n=e.getAttribute("aria-expanded")!=="true";e.setAttribute("aria-expanded",String(n)),e.setAttribute("aria-label",n?e.dataset.closeLabel:e.dataset.openLabel)}),document.addEventListener("keydown",n=>{n.key==="Escape"&&e.getAttribute("aria-expanded")==="true"&&(t(),e.focus())}),window.matchMedia("(min-width: 44.001rem)").addEventListener("change",t)}d(c());document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{o(),i()},{once:!0}):(o(),i());
|
||||
@@ -4,6 +4,12 @@ window.BOOMCAST_I18N = {
|
||||
noFile: "{% trans 'No file selected' as value %}{{ value|escapejs }}",
|
||||
analysing: "{% trans 'Analysing your recording…' as value %}{{ value|escapejs }}",
|
||||
analysisFailed: "{% trans 'Analysis could not be completed.' as value %}{{ value|escapejs }}",
|
||||
uploadingAudio: "{% trans 'Uploading audio…' as value %}{{ value|escapejs }}",
|
||||
preparingRecording: "{% trans 'Preparing recording…' as value %}{{ value|escapejs }}",
|
||||
uploadCompleteAnalysing: "{% trans 'Upload complete. Analysing audio…' as value %}{{ value|escapejs }}",
|
||||
analysisComplete: "{% trans 'Analysis complete.' as value %}{{ value|escapejs }}",
|
||||
uploadCancelled: "{% trans 'Upload cancelled.' as value %}{{ value|escapejs }}",
|
||||
uploadFailed: "{% trans 'Upload failed. Check your connection and try again.' as value %}{{ value|escapejs }}",
|
||||
accuracyUnavailable: "{% trans 'Accuracy unavailable' as value %}{{ value|escapejs }}",
|
||||
accuracy: "{% trans 'Accuracy' as value %}{{ value|escapejs }}",
|
||||
stopCapture: "{% trans 'Stop direction capture' as value %}{{ value|escapejs }}",
|
||||
|
||||
Reference in New Issue
Block a user