Compare commits
26
Commits
ff0d78ccba
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5999192888 | ||
|
|
2e624d902d | ||
|
|
a1662384dc | ||
|
|
686f536676 | ||
|
|
7d83caa27c | ||
|
|
c0c0bd7db8 | ||
|
|
d112028eb1 | ||
|
|
5820ea850a | ||
|
|
a54494c6a1 | ||
|
|
acb3b1f042 | ||
|
|
3c8bf956bf | ||
|
|
23b94b2b24 | ||
|
|
661bf3beaf | ||
|
|
c13a405d96 | ||
|
|
46ad514a70 | ||
|
|
1de4b8a0b3 | ||
|
|
c68e4b95ba | ||
|
|
beeb2b5e0e | ||
|
|
c93bead437 | ||
|
|
c047bd9843 | ||
|
|
13258e76c3 | ||
|
|
b676f35f0a | ||
|
|
66db97b6f7 | ||
|
|
884e2e8a11 | ||
|
|
a5dbbf3aed | ||
|
|
e572257f67 |
@@ -1,3 +1,10 @@
|
||||
vite_integration/static/vite/*
|
||||
!vite_integration/static/vite/.gitkeep
|
||||
node_modules/
|
||||
|
||||
# Local database and uploaded media
|
||||
/db.sqlite3
|
||||
/media/
|
||||
|
||||
# Local archives
|
||||
*.zip
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
# Ntfy blueprint for a Django tasks and health tracker
|
||||
|
||||
This is a portable version of this project's `/settings` integration. It gives each user a topic URL, a test button, an enable switch, and one function that task or health code can call. Replace `accounts` with the app that owns your user preferences. The examples assume an authenticated `/settings/` page and Django's standard CSRF and messages middleware.
|
||||
|
||||
## 1. Store preferences
|
||||
|
||||
In `accounts/models.py` (merge these fields into an existing per-user settings model if you have one):
|
||||
|
||||
```python
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
class NotificationSettings(models.Model):
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
```
|
||||
|
||||
Run `python manage.py makemigrations accounts` and `python manage.py migrate`.
|
||||
|
||||
## 2. Add the sender
|
||||
|
||||
Create `notifications/services.py` (and an empty `notifications/__init__.py` if needed):
|
||||
|
||||
```python
|
||||
import socket
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
class NotificationError(Exception):
|
||||
"""A delivery error safe to display to a user."""
|
||||
|
||||
def send_ntfy_notification(url, title, message, timeout=10):
|
||||
request = Request(
|
||||
url,
|
||||
data=message.encode("utf-8"),
|
||||
headers={"Content-Type": "text/plain; charset=utf-8", "Title": title},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=timeout) as response:
|
||||
status = response.getcode()
|
||||
except HTTPError as error:
|
||||
raise NotificationError(f"ntfy server responded with HTTP {error.code}.") from error
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise NotificationError("Connection to the ntfy server timed out.") from None
|
||||
except URLError as error:
|
||||
raise NotificationError("Could not connect to the ntfy server.") from error
|
||||
except OSError as error:
|
||||
raise NotificationError("Could not connect to the ntfy server.") from error
|
||||
if not 200 <= status < 300:
|
||||
raise NotificationError(f"ntfy server responded with HTTP {status}.")
|
||||
|
||||
def send_notification(user, title, message):
|
||||
from accounts.models import NotificationSettings
|
||||
preferences = NotificationSettings.objects.filter(user=user).first()
|
||||
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
|
||||
return False
|
||||
send_ntfy_notification(preferences.ntfy_url, title, message)
|
||||
return True
|
||||
```
|
||||
|
||||
The URL is a destination and may contain a private topic name. Keep it out of logs and error messages. A user supplied server URL also lets the server make outbound requests; restrict destinations or allow only your trusted ntfy host if your deployment needs that boundary. Add authentication headers if your ntfy server requires them; this example uses a topic URL only.
|
||||
|
||||
## 3. Form, views, and routes
|
||||
|
||||
In `accounts/forms.py`:
|
||||
|
||||
```python
|
||||
from django import forms
|
||||
from .models import NotificationSettings
|
||||
|
||||
class NotificationSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = NotificationSettings
|
||||
fields = ["ntfy_url", "ntfy_enabled"]
|
||||
widgets = {"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"})}
|
||||
|
||||
def clean_ntfy_url(self):
|
||||
return self.cleaned_data["ntfy_url"].strip()
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if data.get("ntfy_enabled") and not data.get("ntfy_url"):
|
||||
self.add_error("ntfy_url", "Enter a topic URL before enabling notifications.")
|
||||
return data
|
||||
```
|
||||
|
||||
In `accounts/views.py`:
|
||||
|
||||
```python
|
||||
from hashlib import sha256
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.shortcuts import redirect, render
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from notifications.services import NotificationError, send_ntfy_notification
|
||||
from .forms import NotificationSettingsForm
|
||||
from .models import NotificationSettings
|
||||
|
||||
def test_key(user):
|
||||
return f"ntfy_tested_url_fingerprint:{user.pk}"
|
||||
|
||||
def fingerprint(url):
|
||||
return sha256(url.encode("utf-8")).hexdigest()
|
||||
|
||||
@login_required
|
||||
def settings_page(request):
|
||||
preferences, _ = NotificationSettings.objects.get_or_create(user=request.user)
|
||||
old_url = preferences.ntfy_url
|
||||
form = NotificationSettingsForm(request.POST or None, instance=preferences)
|
||||
if request.method == "POST" and form.is_valid():
|
||||
url = form.cleaned_data["ntfy_url"]
|
||||
just_tested = bool(url) and request.session.get(test_key(request.user)) == fingerprint(url)
|
||||
previously_tested = url == old_url and preferences.ntfy_last_tested_at is not None
|
||||
if form.cleaned_data["ntfy_enabled"] and not (just_tested or previously_tested):
|
||||
form.add_error("ntfy_url", "Test this URL successfully before enabling notifications.")
|
||||
else:
|
||||
preferences = form.save(commit=False)
|
||||
if not url:
|
||||
preferences.ntfy_enabled = False
|
||||
preferences.ntfy_last_tested_at = None
|
||||
elif just_tested:
|
||||
preferences.ntfy_last_tested_at = timezone.now()
|
||||
elif url != old_url:
|
||||
preferences.ntfy_last_tested_at = None
|
||||
preferences.save()
|
||||
request.session.pop(test_key(request.user), None)
|
||||
messages.success(request, "Notification settings saved.")
|
||||
return redirect("settings_page")
|
||||
return render(request, "accounts/settings.html", {"form": form})
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def test_ntfy(request):
|
||||
url = request.POST.get("ntfy_url", "").strip()
|
||||
try:
|
||||
URLValidator(schemes=["http", "https"])(url)
|
||||
except ValidationError:
|
||||
return render(request, "accounts/ntfy_test_result.html", {"error": "Enter a valid HTTP or HTTPS topic URL."}, status=400)
|
||||
try:
|
||||
send_ntfy_notification(url, "Tasks & Health", "Test notification sent successfully.")
|
||||
except NotificationError as error:
|
||||
return render(request, "accounts/ntfy_test_result.html", {"error": str(error)}, status=502)
|
||||
request.session[test_key(request.user)] = fingerprint(url)
|
||||
return render(request, "accounts/ntfy_test_result.html", {"success": True})
|
||||
```
|
||||
|
||||
In `accounts/urls.py`, include these routes under `/settings/` in the project URLconf:
|
||||
|
||||
```python
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.settings_page, name="settings_page"),
|
||||
path("notifications/ntfy/test/", views.test_ntfy, name="ntfy_test"),
|
||||
]
|
||||
```
|
||||
|
||||
## 4. Settings UI
|
||||
|
||||
Put this section inside your existing `/settings/` template. It uses htmx for the inline test response; load htmx once in the page layout (or replace `hx-post` with a small `fetch` handler). Keep the CSRF input inside the form.
|
||||
|
||||
```html
|
||||
<form method="post" action="{% url 'settings_page' %}">
|
||||
{% csrf_token %}
|
||||
<section aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p>Use a topic URL from your ntfy server. Test it before enabling notifications.</p>
|
||||
<label for="ntfy-url">Topic URL</label>
|
||||
{{ form.ntfy_url }} {{ form.ntfy_url.errors }}
|
||||
<div class="check">
|
||||
{{ form.ntfy_enabled }}
|
||||
<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label>
|
||||
</div>
|
||||
<button type="button" hx-post="{% url 'ntfy_test' %}"
|
||||
hx-include="#ntfy-url, [name='csrfmiddlewaretoken']"
|
||||
hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
|
||||
<div id="ntfy-test-result" aria-live="polite"></div>
|
||||
</section>
|
||||
<button type="submit">Save settings</button>
|
||||
</form>
|
||||
<script>
|
||||
document.querySelector("#ntfy-url").addEventListener("input", () => {
|
||||
document.querySelector("#ntfy-test-result").replaceChildren();
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
`accounts/ntfy_test_result.html`:
|
||||
|
||||
```html
|
||||
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>
|
||||
{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
|
||||
```
|
||||
|
||||
Suggested CSS, scoped to your existing settings styles:
|
||||
|
||||
```css
|
||||
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
|
||||
.check { display: flex; gap: .6rem; align-items: center; }
|
||||
.check label { margin: 0; }
|
||||
.alert { margin-top: 1rem; padding: .75rem; border-radius: .55rem; }
|
||||
.alert--success { color: #d1fae5; background: #14532d; }
|
||||
.alert--error { color: #fee2e2; background: #7f1d1d; }
|
||||
```
|
||||
|
||||
## 5. Trigger from tasks or health events
|
||||
|
||||
Call the provider agnostic `send_notification` after a meaningful state change. Put delivery on a background worker for normal operation, since the HTTP call can take up to ten seconds. Queue the job after the database commit so it cannot announce a rolled back change.
|
||||
|
||||
```python
|
||||
from django.db import transaction
|
||||
|
||||
# After saving a task completion, missed deadline, check-in, or health alert:
|
||||
user_id = task.user_id
|
||||
task_id = task.pk
|
||||
transaction.on_commit(lambda: enqueue_task_event_notification(user_id, task_id))
|
||||
```
|
||||
|
||||
`enqueue_task_event_notification` is your existing Celery, RQ, or job queue entry point. In its worker, reload the user and task, confirm that the event still qualifies, then call `send_notification(user, "Task due", "Your task is due today.")`. Catch `NotificationError`, log a safe error without the topic URL, and retry according to your queue policy. Use an event ID or unique job key if duplicate delivery matters. If you have no worker yet, a management command run by cron can drain a small notification outbox instead.
|
||||
|
||||
Typical mapping for this app:
|
||||
|
||||
| App event | Suggested message | Trigger location |
|
||||
| --- | --- | --- |
|
||||
| Task due | “Your task is due today.” | Scheduled due-date job |
|
||||
| Task completed | “Task completed.” | Completion service, after commit |
|
||||
| Check-in missed | “Your daily check-in is still open.” | Scheduled reminder job |
|
||||
| Health threshold crossed | “A tracked value crossed your chosen threshold.” | Threshold evaluator, after commit |
|
||||
|
||||
Avoid including sensitive health measurements in the notification unless the user explicitly opts in. Define the event's recipient and idempotency rule in the app service, rather than in the ntfy sender.
|
||||
|
||||
## 6. Minimum verification
|
||||
|
||||
Test an invalid URL, a failed test, a successful test followed by save, a changed URL requiring a new test, and disabled settings suppressing sends. Mock `urlopen` or `send_ntfy_notification`; do not send real notifications in tests. Check one actual device delivery manually with a private topic before enabling event triggers.
|
||||
|
||||
Source implementation in this repo: `members/views.py`, `members/forms.py`, `members/models.py`, `members/templates/members/user_settings.html`, `notifications/services.py`, and `fireworks_detect/signals.py`. The source app groups Pending events by minute with `PendingNotificationBatch` and a scheduled command; use that pattern if your tracker needs digest notifications.
|
||||
@@ -105,3 +105,48 @@ python manage.py compilemessages
|
||||
```
|
||||
|
||||
The small amount of JavaScript UI text is translated by Django in `templates/js_translations.html` and read from `window.BOOMCAST_I18N`. After changing JavaScript, run `npm run build` and `python manage.py collectstatic --noinput` for production. Classifier class names, API keys, sensor tokens, H3 values and stored source/status values remain language-neutral.
|
||||
|
||||
## Browser Processing Beta
|
||||
|
||||
The administrator setting `browser_processing_beta_enabled` is off by default.
|
||||
When enabled, the upload form shows **Process recording in this browser (Beta)**,
|
||||
which also starts off. With the user toggle off, ordinary audio uses the
|
||||
existing server upload and classifier. With it on, selected audio is checked
|
||||
locally and selected video is converted to 16 kHz mono WAV before the local
|
||||
check. Files the user submits still run through the server classifier.
|
||||
Switching back to server mode cancels browser work and clears the local gate.
|
||||
The server upload endpoint currently accepts audio, so a video selected in
|
||||
server mode requires an audio file or browser mode.
|
||||
|
||||
Browser assets are loaded only after the user enables the toggle and selects a
|
||||
file. Regenerate the self-hosted model using [the YAMNet build guide](scripts/BROWSER_YAMNET.md),
|
||||
then run `npm run build` and `python manage.py collectstatic --noinput`.
|
||||
# Pending event notifications
|
||||
|
||||
Users can test and enable an ntfy topic in Settings. New Pending events are
|
||||
counted by source (manual or sensor) in one-minute batches per enabled user.
|
||||
Run `python manage.py send_pending_notifications` once per minute with the
|
||||
application's Python environment and working directory. For example, a cron
|
||||
entry can use `* * * * * cd /path/to/django && /path/to/python manage.py send_pending_notifications`.
|
||||
It sends completed minute batches,
|
||||
then removes them; failed deliveries remain queued for the next run.
|
||||
|
||||
For a systemd user timer on the laptop, install the units in
|
||||
[`deploy/systemd/`](deploy/systemd/) and start the timer:
|
||||
|
||||
```sh
|
||||
cd /home/jorenmartijn/python/django
|
||||
/usr/bin/python3 -m venv /home/jorenmartijn/python/.venv-notifications
|
||||
/home/jorenmartijn/python/.venv-notifications/bin/python -m pip install -r requirements.txt
|
||||
/home/jorenmartijn/python/.venv-notifications/bin/python manage.py check
|
||||
mkdir -p ~/.config/systemd/user
|
||||
cp deploy/systemd/send-pending-notifications.service deploy/systemd/send-pending-notifications.timer ~/.config/systemd/user/
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now send-pending-notifications.timer
|
||||
systemctl --user list-timers send-pending-notifications.timer
|
||||
```
|
||||
|
||||
The service runs `/home/jorenmartijn/python/.venv-notifications/bin/python` with this
|
||||
project as its working directory. To keep the user timer running after logout,
|
||||
run `sudo loginctl enable-linger jorenmartijn` once on the laptop. Check a run
|
||||
with `journalctl --user -u send-pending-notifications.service -n 30`.
|
||||
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Send batched Pending event ntfy notifications
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=/home/jorenmartijn/python/django
|
||||
ExecStart=/home/jorenmartijn/python/.venv-notifications/bin/python /home/jorenmartijn/python/django/manage.py send_pending_notifications
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Send Pending event ntfy summaries every minute
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:*:00
|
||||
AccuracySec=1s
|
||||
Persistent=true
|
||||
Unit=send-pending-notifications.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
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.
@@ -3,3 +3,6 @@ from django.apps import AppConfig
|
||||
|
||||
class FireworksDetectConfig(AppConfig):
|
||||
name = 'fireworks_detect'
|
||||
|
||||
def ready(self):
|
||||
from . import signals # noqa: F401
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""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
|
||||
|
||||
@@ -11,7 +14,10 @@ SPEECH_LABEL_TERMS = (
|
||||
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
|
||||
"speaking", "speech synthesizer",
|
||||
)
|
||||
GATE_RESULTS = {"whitelist_match", "no_match", "unavailable", "error"}
|
||||
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():
|
||||
@@ -31,15 +37,23 @@ def browser_policy():
|
||||
"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))
|
||||
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)
|
||||
]
|
||||
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
|
||||
|
||||
|
||||
@@ -64,4 +78,7 @@ def advisory_browser_metadata(post_data):
|
||||
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
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
from django.db.models import F
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.utils import timezone
|
||||
|
||||
from members.models import PendingNotificationBatch, UserSettings
|
||||
|
||||
from .models import PendingEvent
|
||||
|
||||
|
||||
@receiver(post_save, sender=PendingEvent)
|
||||
def count_new_pending_event(sender, instance, created, **kwargs):
|
||||
if not created:
|
||||
return
|
||||
minute = timezone.now().replace(second=0, microsecond=0)
|
||||
field = "manual_count" if instance.source_type == PendingEvent.SourceType.MANUAL else "sensor_count"
|
||||
for user_id in UserSettings.objects.filter(ntfy_enabled=True).exclude(ntfy_url="").values_list("user_id", flat=True):
|
||||
batch, _ = PendingNotificationBatch.objects.get_or_create(user_id=user_id, minute=minute)
|
||||
PendingNotificationBatch.objects.filter(pk=batch.pk).update(**{field: F(field) + 1})
|
||||
@@ -0,0 +1,3 @@
|
||||
google-yamnet-1
|
||||
source_revision=c651073789719ff39dcf51406733bbcaaafb43f2
|
||||
tensorflow=2.21.0
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,522 @@
|
||||
index,mid,display_name
|
||||
0,/m/09x0r,Speech
|
||||
1,/m/0ytgt,"Child speech, kid speaking"
|
||||
2,/m/01h8n0,Conversation
|
||||
3,/m/02qldy,"Narration, monologue"
|
||||
4,/m/0261r1,Babbling
|
||||
5,/m/0brhx,Speech synthesizer
|
||||
6,/m/07p6fty,Shout
|
||||
7,/m/07q4ntr,Bellow
|
||||
8,/m/07rwj3x,Whoop
|
||||
9,/m/07sr1lc,Yell
|
||||
10,/t/dd00135,Children shouting
|
||||
11,/m/03qc9zr,Screaming
|
||||
12,/m/02rtxlg,Whispering
|
||||
13,/m/01j3sz,Laughter
|
||||
14,/t/dd00001,Baby laughter
|
||||
15,/m/07r660_,Giggle
|
||||
16,/m/07s04w4,Snicker
|
||||
17,/m/07sq110,Belly laugh
|
||||
18,/m/07rgt08,"Chuckle, chortle"
|
||||
19,/m/0463cq4,"Crying, sobbing"
|
||||
20,/t/dd00002,"Baby cry, infant cry"
|
||||
21,/m/07qz6j3,Whimper
|
||||
22,/m/07qw_06,"Wail, moan"
|
||||
23,/m/07plz5l,Sigh
|
||||
24,/m/015lz1,Singing
|
||||
25,/m/0l14jd,Choir
|
||||
26,/m/01swy6,Yodeling
|
||||
27,/m/02bk07,Chant
|
||||
28,/m/01c194,Mantra
|
||||
29,/t/dd00005,Child singing
|
||||
30,/t/dd00006,Synthetic singing
|
||||
31,/m/06bxc,Rapping
|
||||
32,/m/02fxyj,Humming
|
||||
33,/m/07s2xch,Groan
|
||||
34,/m/07r4k75,Grunt
|
||||
35,/m/01w250,Whistling
|
||||
36,/m/0lyf6,Breathing
|
||||
37,/m/07mzm6,Wheeze
|
||||
38,/m/01d3sd,Snoring
|
||||
39,/m/07s0dtb,Gasp
|
||||
40,/m/07pyy8b,Pant
|
||||
41,/m/07q0yl5,Snort
|
||||
42,/m/01b_21,Cough
|
||||
43,/m/0dl9sf8,Throat clearing
|
||||
44,/m/01hsr_,Sneeze
|
||||
45,/m/07ppn3j,Sniff
|
||||
46,/m/06h7j,Run
|
||||
47,/m/07qv_x_,Shuffle
|
||||
48,/m/07pbtc8,"Walk, footsteps"
|
||||
49,/m/03cczk,"Chewing, mastication"
|
||||
50,/m/07pdhp0,Biting
|
||||
51,/m/0939n_,Gargling
|
||||
52,/m/01g90h,Stomach rumble
|
||||
53,/m/03q5_w,"Burping, eructation"
|
||||
54,/m/02p3nc,Hiccup
|
||||
55,/m/02_nn,Fart
|
||||
56,/m/0k65p,Hands
|
||||
57,/m/025_jnm,Finger snapping
|
||||
58,/m/0l15bq,Clapping
|
||||
59,/m/01jg02,"Heart sounds, heartbeat"
|
||||
60,/m/01jg1z,Heart murmur
|
||||
61,/m/053hz1,Cheering
|
||||
62,/m/028ght,Applause
|
||||
63,/m/07rkbfh,Chatter
|
||||
64,/m/03qtwd,Crowd
|
||||
65,/m/07qfr4h,"Hubbub, speech noise, speech babble"
|
||||
66,/t/dd00013,Children playing
|
||||
67,/m/0jbk,Animal
|
||||
68,/m/068hy,"Domestic animals, pets"
|
||||
69,/m/0bt9lr,Dog
|
||||
70,/m/05tny_,Bark
|
||||
71,/m/07r_k2n,Yip
|
||||
72,/m/07qf0zm,Howl
|
||||
73,/m/07rc7d9,Bow-wow
|
||||
74,/m/0ghcn6,Growling
|
||||
75,/t/dd00136,Whimper (dog)
|
||||
76,/m/01yrx,Cat
|
||||
77,/m/02yds9,Purr
|
||||
78,/m/07qrkrw,Meow
|
||||
79,/m/07rjwbb,Hiss
|
||||
80,/m/07r81j2,Caterwaul
|
||||
81,/m/0ch8v,"Livestock, farm animals, working animals"
|
||||
82,/m/03k3r,Horse
|
||||
83,/m/07rv9rh,Clip-clop
|
||||
84,/m/07q5rw0,"Neigh, whinny"
|
||||
85,/m/01xq0k1,"Cattle, bovinae"
|
||||
86,/m/07rpkh9,Moo
|
||||
87,/m/0239kh,Cowbell
|
||||
88,/m/068zj,Pig
|
||||
89,/t/dd00018,Oink
|
||||
90,/m/03fwl,Goat
|
||||
91,/m/07q0h5t,Bleat
|
||||
92,/m/07bgp,Sheep
|
||||
93,/m/025rv6n,Fowl
|
||||
94,/m/09b5t,"Chicken, rooster"
|
||||
95,/m/07st89h,Cluck
|
||||
96,/m/07qn5dc,"Crowing, cock-a-doodle-doo"
|
||||
97,/m/01rd7k,Turkey
|
||||
98,/m/07svc2k,Gobble
|
||||
99,/m/09ddx,Duck
|
||||
100,/m/07qdb04,Quack
|
||||
101,/m/0dbvp,Goose
|
||||
102,/m/07qwf61,Honk
|
||||
103,/m/01280g,Wild animals
|
||||
104,/m/0cdnk,"Roaring cats (lions, tigers)"
|
||||
105,/m/04cvmfc,Roar
|
||||
106,/m/015p6,Bird
|
||||
107,/m/020bb7,"Bird vocalization, bird call, bird song"
|
||||
108,/m/07pggtn,"Chirp, tweet"
|
||||
109,/m/07sx8x_,Squawk
|
||||
110,/m/0h0rv,"Pigeon, dove"
|
||||
111,/m/07r_25d,Coo
|
||||
112,/m/04s8yn,Crow
|
||||
113,/m/07r5c2p,Caw
|
||||
114,/m/09d5_,Owl
|
||||
115,/m/07r_80w,Hoot
|
||||
116,/m/05_wcq,"Bird flight, flapping wings"
|
||||
117,/m/01z5f,"Canidae, dogs, wolves"
|
||||
118,/m/06hps,"Rodents, rats, mice"
|
||||
119,/m/04rmv,Mouse
|
||||
120,/m/07r4gkf,Patter
|
||||
121,/m/03vt0,Insect
|
||||
122,/m/09xqv,Cricket
|
||||
123,/m/09f96,Mosquito
|
||||
124,/m/0h2mp,"Fly, housefly"
|
||||
125,/m/07pjwq1,Buzz
|
||||
126,/m/01h3n,"Bee, wasp, etc."
|
||||
127,/m/09ld4,Frog
|
||||
128,/m/07st88b,Croak
|
||||
129,/m/078jl,Snake
|
||||
130,/m/07qn4z3,Rattle
|
||||
131,/m/032n05,Whale vocalization
|
||||
132,/m/04rlf,Music
|
||||
133,/m/04szw,Musical instrument
|
||||
134,/m/0fx80y,Plucked string instrument
|
||||
135,/m/0342h,Guitar
|
||||
136,/m/02sgy,Electric guitar
|
||||
137,/m/018vs,Bass guitar
|
||||
138,/m/042v_gx,Acoustic guitar
|
||||
139,/m/06w87,"Steel guitar, slide guitar"
|
||||
140,/m/01glhc,Tapping (guitar technique)
|
||||
141,/m/07s0s5r,Strum
|
||||
142,/m/018j2,Banjo
|
||||
143,/m/0jtg0,Sitar
|
||||
144,/m/04rzd,Mandolin
|
||||
145,/m/01bns_,Zither
|
||||
146,/m/07xzm,Ukulele
|
||||
147,/m/05148p4,Keyboard (musical)
|
||||
148,/m/05r5c,Piano
|
||||
149,/m/01s0ps,Electric piano
|
||||
150,/m/013y1f,Organ
|
||||
151,/m/03xq_f,Electronic organ
|
||||
152,/m/03gvt,Hammond organ
|
||||
153,/m/0l14qv,Synthesizer
|
||||
154,/m/01v1d8,Sampler
|
||||
155,/m/03q5t,Harpsichord
|
||||
156,/m/0l14md,Percussion
|
||||
157,/m/02hnl,Drum kit
|
||||
158,/m/0cfdd,Drum machine
|
||||
159,/m/026t6,Drum
|
||||
160,/m/06rvn,Snare drum
|
||||
161,/m/03t3fj,Rimshot
|
||||
162,/m/02k_mr,Drum roll
|
||||
163,/m/0bm02,Bass drum
|
||||
164,/m/011k_j,Timpani
|
||||
165,/m/01p970,Tabla
|
||||
166,/m/01qbl,Cymbal
|
||||
167,/m/03qtq,Hi-hat
|
||||
168,/m/01sm1g,Wood block
|
||||
169,/m/07brj,Tambourine
|
||||
170,/m/05r5wn,Rattle (instrument)
|
||||
171,/m/0xzly,Maraca
|
||||
172,/m/0mbct,Gong
|
||||
173,/m/016622,Tubular bells
|
||||
174,/m/0j45pbj,Mallet percussion
|
||||
175,/m/0dwsp,"Marimba, xylophone"
|
||||
176,/m/0dwtp,Glockenspiel
|
||||
177,/m/0dwt5,Vibraphone
|
||||
178,/m/0l156b,Steelpan
|
||||
179,/m/05pd6,Orchestra
|
||||
180,/m/01kcd,Brass instrument
|
||||
181,/m/0319l,French horn
|
||||
182,/m/07gql,Trumpet
|
||||
183,/m/07c6l,Trombone
|
||||
184,/m/0l14_3,Bowed string instrument
|
||||
185,/m/02qmj0d,String section
|
||||
186,/m/07y_7,"Violin, fiddle"
|
||||
187,/m/0d8_n,Pizzicato
|
||||
188,/m/01xqw,Cello
|
||||
189,/m/02fsn,Double bass
|
||||
190,/m/085jw,"Wind instrument, woodwind instrument"
|
||||
191,/m/0l14j_,Flute
|
||||
192,/m/06ncr,Saxophone
|
||||
193,/m/01wy6,Clarinet
|
||||
194,/m/03m5k,Harp
|
||||
195,/m/0395lw,Bell
|
||||
196,/m/03w41f,Church bell
|
||||
197,/m/027m70_,Jingle bell
|
||||
198,/m/0gy1t2s,Bicycle bell
|
||||
199,/m/07n_g,Tuning fork
|
||||
200,/m/0f8s22,Chime
|
||||
201,/m/026fgl,Wind chime
|
||||
202,/m/0150b9,Change ringing (campanology)
|
||||
203,/m/03qjg,Harmonica
|
||||
204,/m/0mkg,Accordion
|
||||
205,/m/0192l,Bagpipes
|
||||
206,/m/02bxd,Didgeridoo
|
||||
207,/m/0l14l2,Shofar
|
||||
208,/m/07kc_,Theremin
|
||||
209,/m/0l14t7,Singing bowl
|
||||
210,/m/01hgjl,Scratching (performance technique)
|
||||
211,/m/064t9,Pop music
|
||||
212,/m/0glt670,Hip hop music
|
||||
213,/m/02cz_7,Beatboxing
|
||||
214,/m/06by7,Rock music
|
||||
215,/m/03lty,Heavy metal
|
||||
216,/m/05r6t,Punk rock
|
||||
217,/m/0dls3,Grunge
|
||||
218,/m/0dl5d,Progressive rock
|
||||
219,/m/07sbbz2,Rock and roll
|
||||
220,/m/05w3f,Psychedelic rock
|
||||
221,/m/06j6l,Rhythm and blues
|
||||
222,/m/0gywn,Soul music
|
||||
223,/m/06cqb,Reggae
|
||||
224,/m/01lyv,Country
|
||||
225,/m/015y_n,Swing music
|
||||
226,/m/0gg8l,Bluegrass
|
||||
227,/m/02x8m,Funk
|
||||
228,/m/02w4v,Folk music
|
||||
229,/m/06j64v,Middle Eastern music
|
||||
230,/m/03_d0,Jazz
|
||||
231,/m/026z9,Disco
|
||||
232,/m/0ggq0m,Classical music
|
||||
233,/m/05lls,Opera
|
||||
234,/m/02lkt,Electronic music
|
||||
235,/m/03mb9,House music
|
||||
236,/m/07gxw,Techno
|
||||
237,/m/07s72n,Dubstep
|
||||
238,/m/0283d,Drum and bass
|
||||
239,/m/0m0jc,Electronica
|
||||
240,/m/08cyft,Electronic dance music
|
||||
241,/m/0fd3y,Ambient music
|
||||
242,/m/07lnk,Trance music
|
||||
243,/m/0g293,Music of Latin America
|
||||
244,/m/0ln16,Salsa music
|
||||
245,/m/0326g,Flamenco
|
||||
246,/m/0155w,Blues
|
||||
247,/m/05fw6t,Music for children
|
||||
248,/m/02v2lh,New-age music
|
||||
249,/m/0y4f8,Vocal music
|
||||
250,/m/0z9c,A capella
|
||||
251,/m/0164x2,Music of Africa
|
||||
252,/m/0145m,Afrobeat
|
||||
253,/m/02mscn,Christian music
|
||||
254,/m/016cjb,Gospel music
|
||||
255,/m/028sqc,Music of Asia
|
||||
256,/m/015vgc,Carnatic music
|
||||
257,/m/0dq0md,Music of Bollywood
|
||||
258,/m/06rqw,Ska
|
||||
259,/m/02p0sh1,Traditional music
|
||||
260,/m/05rwpb,Independent music
|
||||
261,/m/074ft,Song
|
||||
262,/m/025td0t,Background music
|
||||
263,/m/02cjck,Theme music
|
||||
264,/m/03r5q_,Jingle (music)
|
||||
265,/m/0l14gg,Soundtrack music
|
||||
266,/m/07pkxdp,Lullaby
|
||||
267,/m/01z7dr,Video game music
|
||||
268,/m/0140xf,Christmas music
|
||||
269,/m/0ggx5q,Dance music
|
||||
270,/m/04wptg,Wedding music
|
||||
271,/t/dd00031,Happy music
|
||||
272,/t/dd00033,Sad music
|
||||
273,/t/dd00034,Tender music
|
||||
274,/t/dd00035,Exciting music
|
||||
275,/t/dd00036,Angry music
|
||||
276,/t/dd00037,Scary music
|
||||
277,/m/03m9d0z,Wind
|
||||
278,/m/09t49,Rustling leaves
|
||||
279,/t/dd00092,Wind noise (microphone)
|
||||
280,/m/0jb2l,Thunderstorm
|
||||
281,/m/0ngt1,Thunder
|
||||
282,/m/0838f,Water
|
||||
283,/m/06mb1,Rain
|
||||
284,/m/07r10fb,Raindrop
|
||||
285,/t/dd00038,Rain on surface
|
||||
286,/m/0j6m2,Stream
|
||||
287,/m/0j2kx,Waterfall
|
||||
288,/m/05kq4,Ocean
|
||||
289,/m/034srq,"Waves, surf"
|
||||
290,/m/06wzb,Steam
|
||||
291,/m/07swgks,Gurgling
|
||||
292,/m/02_41,Fire
|
||||
293,/m/07pzfmf,Crackle
|
||||
294,/m/07yv9,Vehicle
|
||||
295,/m/019jd,"Boat, Water vehicle"
|
||||
296,/m/0hsrw,"Sailboat, sailing ship"
|
||||
297,/m/056ks2,"Rowboat, canoe, kayak"
|
||||
298,/m/02rlv9,"Motorboat, speedboat"
|
||||
299,/m/06q74,Ship
|
||||
300,/m/012f08,Motor vehicle (road)
|
||||
301,/m/0k4j,Car
|
||||
302,/m/0912c9,"Vehicle horn, car horn, honking"
|
||||
303,/m/07qv_d5,Toot
|
||||
304,/m/02mfyn,Car alarm
|
||||
305,/m/04gxbd,"Power windows, electric windows"
|
||||
306,/m/07rknqz,Skidding
|
||||
307,/m/0h9mv,Tire squeal
|
||||
308,/t/dd00134,Car passing by
|
||||
309,/m/0ltv,"Race car, auto racing"
|
||||
310,/m/07r04,Truck
|
||||
311,/m/0gvgw0,Air brake
|
||||
312,/m/05x_td,"Air horn, truck horn"
|
||||
313,/m/02rhddq,Reversing beeps
|
||||
314,/m/03cl9h,"Ice cream truck, ice cream van"
|
||||
315,/m/01bjv,Bus
|
||||
316,/m/03j1ly,Emergency vehicle
|
||||
317,/m/04qvtq,Police car (siren)
|
||||
318,/m/012n7d,Ambulance (siren)
|
||||
319,/m/012ndj,"Fire engine, fire truck (siren)"
|
||||
320,/m/04_sv,Motorcycle
|
||||
321,/m/0btp2,"Traffic noise, roadway noise"
|
||||
322,/m/06d_3,Rail transport
|
||||
323,/m/07jdr,Train
|
||||
324,/m/04zmvq,Train whistle
|
||||
325,/m/0284vy3,Train horn
|
||||
326,/m/01g50p,"Railroad car, train wagon"
|
||||
327,/t/dd00048,Train wheels squealing
|
||||
328,/m/0195fx,"Subway, metro, underground"
|
||||
329,/m/0k5j,Aircraft
|
||||
330,/m/014yck,Aircraft engine
|
||||
331,/m/04229,Jet engine
|
||||
332,/m/02l6bg,"Propeller, airscrew"
|
||||
333,/m/09ct_,Helicopter
|
||||
334,/m/0cmf2,"Fixed-wing aircraft, airplane"
|
||||
335,/m/0199g,Bicycle
|
||||
336,/m/06_fw,Skateboard
|
||||
337,/m/02mk9,Engine
|
||||
338,/t/dd00065,Light engine (high frequency)
|
||||
339,/m/08j51y,"Dental drill, dentist's drill"
|
||||
340,/m/01yg9g,Lawn mower
|
||||
341,/m/01j4z9,Chainsaw
|
||||
342,/t/dd00066,Medium engine (mid frequency)
|
||||
343,/t/dd00067,Heavy engine (low frequency)
|
||||
344,/m/01h82_,Engine knocking
|
||||
345,/t/dd00130,Engine starting
|
||||
346,/m/07pb8fc,Idling
|
||||
347,/m/07q2z82,"Accelerating, revving, vroom"
|
||||
348,/m/02dgv,Door
|
||||
349,/m/03wwcy,Doorbell
|
||||
350,/m/07r67yg,Ding-dong
|
||||
351,/m/02y_763,Sliding door
|
||||
352,/m/07rjzl8,Slam
|
||||
353,/m/07r4wb8,Knock
|
||||
354,/m/07qcpgn,Tap
|
||||
355,/m/07q6cd_,Squeak
|
||||
356,/m/0642b4,Cupboard open or close
|
||||
357,/m/0fqfqc,Drawer open or close
|
||||
358,/m/04brg2,"Dishes, pots, and pans"
|
||||
359,/m/023pjk,"Cutlery, silverware"
|
||||
360,/m/07pn_8q,Chopping (food)
|
||||
361,/m/0dxrf,Frying (food)
|
||||
362,/m/0fx9l,Microwave oven
|
||||
363,/m/02pjr4,Blender
|
||||
364,/m/02jz0l,"Water tap, faucet"
|
||||
365,/m/0130jx,Sink (filling or washing)
|
||||
366,/m/03dnzn,Bathtub (filling or washing)
|
||||
367,/m/03wvsk,Hair dryer
|
||||
368,/m/01jt3m,Toilet flush
|
||||
369,/m/012xff,Toothbrush
|
||||
370,/m/04fgwm,Electric toothbrush
|
||||
371,/m/0d31p,Vacuum cleaner
|
||||
372,/m/01s0vc,Zipper (clothing)
|
||||
373,/m/03v3yw,Keys jangling
|
||||
374,/m/0242l,Coin (dropping)
|
||||
375,/m/01lsmm,Scissors
|
||||
376,/m/02g901,"Electric shaver, electric razor"
|
||||
377,/m/05rj2,Shuffling cards
|
||||
378,/m/0316dw,Typing
|
||||
379,/m/0c2wf,Typewriter
|
||||
380,/m/01m2v,Computer keyboard
|
||||
381,/m/081rb,Writing
|
||||
382,/m/07pp_mv,Alarm
|
||||
383,/m/07cx4,Telephone
|
||||
384,/m/07pp8cl,Telephone bell ringing
|
||||
385,/m/01hnzm,Ringtone
|
||||
386,/m/02c8p,"Telephone dialing, DTMF"
|
||||
387,/m/015jpf,Dial tone
|
||||
388,/m/01z47d,Busy signal
|
||||
389,/m/046dlr,Alarm clock
|
||||
390,/m/03kmc9,Siren
|
||||
391,/m/0dgbq,Civil defense siren
|
||||
392,/m/030rvx,Buzzer
|
||||
393,/m/01y3hg,"Smoke detector, smoke alarm"
|
||||
394,/m/0c3f7m,Fire alarm
|
||||
395,/m/04fq5q,Foghorn
|
||||
396,/m/0l156k,Whistle
|
||||
397,/m/06hck5,Steam whistle
|
||||
398,/t/dd00077,Mechanisms
|
||||
399,/m/02bm9n,"Ratchet, pawl"
|
||||
400,/m/01x3z,Clock
|
||||
401,/m/07qjznt,Tick
|
||||
402,/m/07qjznl,Tick-tock
|
||||
403,/m/0l7xg,Gears
|
||||
404,/m/05zc1,Pulleys
|
||||
405,/m/0llzx,Sewing machine
|
||||
406,/m/02x984l,Mechanical fan
|
||||
407,/m/025wky1,Air conditioning
|
||||
408,/m/024dl,Cash register
|
||||
409,/m/01m4t,Printer
|
||||
410,/m/0dv5r,Camera
|
||||
411,/m/07bjf,Single-lens reflex camera
|
||||
412,/m/07k1x,Tools
|
||||
413,/m/03l9g,Hammer
|
||||
414,/m/03p19w,Jackhammer
|
||||
415,/m/01b82r,Sawing
|
||||
416,/m/02p01q,Filing (rasp)
|
||||
417,/m/023vsd,Sanding
|
||||
418,/m/0_ksk,Power tool
|
||||
419,/m/01d380,Drill
|
||||
420,/m/014zdl,Explosion
|
||||
421,/m/032s66,"Gunshot, gunfire"
|
||||
422,/m/04zjc,Machine gun
|
||||
423,/m/02z32qm,Fusillade
|
||||
424,/m/0_1c,Artillery fire
|
||||
425,/m/073cg4,Cap gun
|
||||
426,/m/0g6b5,Fireworks
|
||||
427,/g/122z_qxw,Firecracker
|
||||
428,/m/07qsvvw,"Burst, pop"
|
||||
429,/m/07pxg6y,Eruption
|
||||
430,/m/07qqyl4,Boom
|
||||
431,/m/083vt,Wood
|
||||
432,/m/07pczhz,Chop
|
||||
433,/m/07pl1bw,Splinter
|
||||
434,/m/07qs1cx,Crack
|
||||
435,/m/039jq,Glass
|
||||
436,/m/07q7njn,"Chink, clink"
|
||||
437,/m/07rn7sz,Shatter
|
||||
438,/m/04k94,Liquid
|
||||
439,/m/07rrlb6,"Splash, splatter"
|
||||
440,/m/07p6mqd,Slosh
|
||||
441,/m/07qlwh6,Squish
|
||||
442,/m/07r5v4s,Drip
|
||||
443,/m/07prgkl,Pour
|
||||
444,/m/07pqc89,"Trickle, dribble"
|
||||
445,/t/dd00088,Gush
|
||||
446,/m/07p7b8y,Fill (with liquid)
|
||||
447,/m/07qlf79,Spray
|
||||
448,/m/07ptzwd,Pump (liquid)
|
||||
449,/m/07ptfmf,Stir
|
||||
450,/m/0dv3j,Boiling
|
||||
451,/m/0790c,Sonar
|
||||
452,/m/0dl83,Arrow
|
||||
453,/m/07rqsjt,"Whoosh, swoosh, swish"
|
||||
454,/m/07qnq_y,"Thump, thud"
|
||||
455,/m/07rrh0c,Thunk
|
||||
456,/m/0b_fwt,Electronic tuner
|
||||
457,/m/02rr_,Effects unit
|
||||
458,/m/07m2kt,Chorus effect
|
||||
459,/m/018w8,Basketball bounce
|
||||
460,/m/07pws3f,Bang
|
||||
461,/m/07ryjzk,"Slap, smack"
|
||||
462,/m/07rdhzs,"Whack, thwack"
|
||||
463,/m/07pjjrj,"Smash, crash"
|
||||
464,/m/07pc8lb,Breaking
|
||||
465,/m/07pqn27,Bouncing
|
||||
466,/m/07rbp7_,Whip
|
||||
467,/m/07pyf11,Flap
|
||||
468,/m/07qb_dv,Scratch
|
||||
469,/m/07qv4k0,Scrape
|
||||
470,/m/07pdjhy,Rub
|
||||
471,/m/07s8j8t,Roll
|
||||
472,/m/07plct2,Crushing
|
||||
473,/t/dd00112,"Crumpling, crinkling"
|
||||
474,/m/07qcx4z,Tearing
|
||||
475,/m/02fs_r,"Beep, bleep"
|
||||
476,/m/07qwdck,Ping
|
||||
477,/m/07phxs1,Ding
|
||||
478,/m/07rv4dm,Clang
|
||||
479,/m/07s02z0,Squeal
|
||||
480,/m/07qh7jl,Creak
|
||||
481,/m/07qwyj0,Rustle
|
||||
482,/m/07s34ls,Whir
|
||||
483,/m/07qmpdm,Clatter
|
||||
484,/m/07p9k1k,Sizzle
|
||||
485,/m/07qc9xj,Clicking
|
||||
486,/m/07rwm0c,Clickety-clack
|
||||
487,/m/07phhsh,Rumble
|
||||
488,/m/07qyrcz,Plop
|
||||
489,/m/07qfgpx,"Jingle, tinkle"
|
||||
490,/m/07rcgpl,Hum
|
||||
491,/m/07p78v5,Zing
|
||||
492,/t/dd00121,Boing
|
||||
493,/m/07s12q4,Crunch
|
||||
494,/m/028v0c,Silence
|
||||
495,/m/01v_m0,Sine wave
|
||||
496,/m/0b9m1,Harmonic
|
||||
497,/m/0hdsk,Chirp tone
|
||||
498,/m/0c1dj,Sound effect
|
||||
499,/m/07pt_g0,Pulse
|
||||
500,/t/dd00125,"Inside, small room"
|
||||
501,/t/dd00126,"Inside, large room or hall"
|
||||
502,/t/dd00127,"Inside, public space"
|
||||
503,/t/dd00128,"Outside, urban or manmade"
|
||||
504,/t/dd00129,"Outside, rural or natural"
|
||||
505,/m/01b9nn,Reverberation
|
||||
506,/m/01jnbd,Echo
|
||||
507,/m/096m7z,Noise
|
||||
508,/m/06_y0by,Environmental noise
|
||||
509,/m/07rgkc5,Static
|
||||
510,/m/06xkwv,Mains hum
|
||||
511,/m/0g12c5,Distortion
|
||||
512,/m/08p9q4,Sidetone
|
||||
513,/m/07szfh9,Cacophony
|
||||
514,/m/0chx_,White noise
|
||||
515,/m/0cj0r,Pink noise
|
||||
516,/m/07p_0gm,Throbbing
|
||||
517,/m/01jwx6,Vibration
|
||||
518,/m/07c52,Television
|
||||
519,/m/06bz3,Radio
|
||||
520,/m/07hvw1,Field recording
|
||||
|
File diff suppressed because one or more lines are too long
@@ -59,6 +59,11 @@
|
||||
{% 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,7 +3,7 @@
|
||||
<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">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>{% trans "Report fireworks · Sound Signal" %}</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<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{% if browser_processing_config.browserProcessingBeta %},video/*,.mp4,.mov,.m4v,.webm,.mkv,.avi{% endif %}" required>
|
||||
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
|
||||
<span>
|
||||
<span class="upload-icon" id="upload-progress-circle"><span class="upload-icon__content" id="upload-icon-content" aria-hidden="true">↑</span></span>
|
||||
<strong>{% trans "Drop an audio file here" %}</strong>
|
||||
@@ -10,11 +10,28 @@
|
||||
</span>
|
||||
<span class="file-name" id="file-name">{% trans "No file selected" %}</span>
|
||||
</label>
|
||||
{% if browser_processing_config.browserProcessingBeta %}
|
||||
<div class="browser-mode">
|
||||
<label class="browser-mode__label" for="browser-processing-toggle">
|
||||
<input id="browser-processing-toggle" type="checkbox">
|
||||
<span>{% trans "Process recording in this browser (Beta)" %}</span>
|
||||
</label>
|
||||
<p>{% trans "When enabled, BoomCast extracts and checks audio on this device before uploading it. When disabled, recordings are processed by the server as usual." %}</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="form-footer">
|
||||
<p class="file-note">{% trans "WAV, MP3, M4A, OGG and more · 25 MiB maximum" %}</p>
|
||||
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>{% trans "Analyse audio" %}</button>
|
||||
<button class="upload-cancel" type="button" hidden>{% trans "Cancel upload" %}</button>
|
||||
</div>
|
||||
<section class="browser-gate" id="browser-gate" hidden aria-live="polite">
|
||||
<strong id="browser-gate-title"></strong>
|
||||
<p id="browser-gate-message"></p>
|
||||
<div class="browser-gate-actions">
|
||||
<button type="button" id="browser-gate-choose">{% trans "Choose another recording" %}</button>
|
||||
<button type="button" id="browser-gate-override">{% trans "Submit for manual review anyway" %}</button>
|
||||
</div>
|
||||
</section>
|
||||
<section id="classification-results" aria-live="polite" aria-label="{% trans "Classification results" %}"></section>
|
||||
</form>
|
||||
<p id="upload-status" role="status" aria-live="polite"></p>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{% load i18n %}
|
||||
<div class="manual-direction-panel{% if measuring %} manual-direction-panel--open{% endif %}" id="manual-direction-panel" data-state="{% if measuring %}ready{% else %}idle{% endif %}">
|
||||
{% if measuring %}
|
||||
<div class="manual-direction-panel__topline">
|
||||
<strong class="manual-direction-panel__heading">{% trans "Capture direction" %}</strong>
|
||||
<button class="manual-direction-panel__close" type="button" hx-get="{% url 'fireworks_detect:manual_direction_panel' %}" hx-target="#manual-direction-panel" hx-swap="outerHTML" aria-label="{% trans 'Close direction capture' %}">×</button>
|
||||
</div>
|
||||
<p class="manual-direction-panel__copy">{% trans "Point the top of your phone toward the fireworks, then capture a single compass reading." %}</p>
|
||||
<div id="manual-direction-status" class="manual-direction-panel__status" aria-live="polite"></div>
|
||||
<button id="manual-capture-direction" class="manual-direction-panel__button" type="button">{% trans "Start measuring direction" %}</button>
|
||||
{% else %}
|
||||
<strong class="manual-direction-panel__heading">{% trans "Direction" %} <span>({% trans "optional" %})</span></strong>
|
||||
<p id="manual-direction-summary" class="manual-direction-panel__summary">{% trans "Not captured" %}</p>
|
||||
<button class="manual-direction-panel__open" type="button" hx-get="{% url 'fireworks_detect:manual_direction_panel' %}?mode=measure" hx-target="#manual-direction-panel" hx-swap="outerHTML">{% trans "Capture direction" %}</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -1,25 +1,46 @@
|
||||
{% load i18n %}
|
||||
<section class="manual-report" aria-labelledby="manual-report-title">
|
||||
<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">
|
||||
<header class="manual-report__header">
|
||||
<p class="eyebrow">{% trans "Quick report" %}</p>
|
||||
<div class="manual-report__heading-row"><span class="manual-report__fire" aria-hidden="true">🔥</span><h2 class="manual-report__title" id="manual-report-title">{% trans "Report fireworks now" %}</h2></div>
|
||||
<p class="manual-report__intro">{% trans "Did you hear a bang? Report what you heard in a few taps." %}</p>
|
||||
<div class="report-clock" role="group" aria-label="{% trans 'Report time' %}">
|
||||
<span class="report-clock__label" aria-hidden="true">{% trans "Report time" %}</span>
|
||||
<div class="report-clock__display">
|
||||
<time id="manual-report-time" class="report-clock__time" aria-label="{% trans 'Now' %}">
|
||||
<span id="report-clock-hours" aria-hidden="true">--</span><span class="report-clock__colon" aria-hidden="true">:</span><span id="report-clock-minutes" aria-hidden="true">--</span>
|
||||
</time>
|
||||
<span class="report-clock__now" aria-hidden="true"><span class="report-clock__dot"></span>{% trans "Now" %}</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<form id="manual-report-form" action="{% url "fireworks_detect:submit_manual_pending" %}" method="post" enctype="multipart/form-data">
|
||||
{% csrf_token %}
|
||||
<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">
|
||||
<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">
|
||||
<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>
|
||||
<button id="manual-increase" type="button" aria-label="{% trans 'Increase occurrences' %}">+</button>
|
||||
</div>
|
||||
<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>
|
||||
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
|
||||
</div>
|
||||
<section class="manual-report__supporting" data-state="off" aria-labelledby="manual-listening-title">
|
||||
<div class="manual-report__supporting-header">
|
||||
<span class="manual-report__microphone" aria-hidden="true">🎙</span>
|
||||
<div>
|
||||
<h3 id="manual-listening-title">{% trans "Automatic detection" %}</h3>
|
||||
<span id="burst-state" class="burst-listener__state" aria-live="polite">{% trans "Not listening" %}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="burst-listener" data-state="off">
|
||||
<button id="burst-start" class="burst-listener__button" type="button">{% trans "Start listening" %}</button>
|
||||
<div id="burst-panel" class="burst-listener__panel" hidden>
|
||||
<strong id="burst-heading" aria-live="polite"></strong>
|
||||
<canvas id="burst-waveform" width="600" height="90" aria-label="{% trans 'Live microphone waveform' %}"></canvas>
|
||||
@@ -33,6 +54,23 @@
|
||||
</div>
|
||||
<p id="burst-error" role="alert" hidden></p>
|
||||
</div>
|
||||
</section>
|
||||
<button id="manual-submit" class="manual-report__submit" type="button"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
|
||||
</form>
|
||||
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
|
||||
<div id="manual-compass-home">
|
||||
<div id="manual-compass" class="manual-compass" role="img" aria-label="{% trans 'Compass direction' %}" hidden>
|
||||
<div class="manual-compass__dial" aria-hidden="true">
|
||||
<div id="manual-compass-rose" class="manual-compass__rose">
|
||||
<span class="manual-compass__north">N</span>
|
||||
<span class="manual-compass__east">E</span>
|
||||
<span class="manual-compass__south">S</span>
|
||||
<span class="manual-compass__west">W</span>
|
||||
</div>
|
||||
<span class="manual-compass__pointer"></span>
|
||||
<span class="manual-compass__center"></span>
|
||||
</div>
|
||||
<span id="manual-compass-heading" class="manual-compass__heading"></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
<a href="{% url "fireworks_detect:fireworks" %}"{% if active_page == "analyse" %} aria-current="page"{% endif %}>{% trans "Analyse" %}</a>
|
||||
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>{% trans "Map" %}</a>
|
||||
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>{% trans "Events" %}</a>
|
||||
{% if request.user.is_authenticated %}
|
||||
<form action="{% url 'logout' %}" method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit">{% trans "Sign out" %}</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<a href="{% url 'login' %}">{% trans "Sign in" %}</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% if not request.user.is_authenticated %}
|
||||
<form class="public-language" action="{% url 'set_anonymous_language' %}" method="post" style="display:flex;align-items:center;gap:.3rem;color:var(--muted,#aab9d8);font-size:.78rem">
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
{% load i18n %}
|
||||
<div id="manual-submission" role="status">
|
||||
<div id="manual-submission" class="manual-submission{% if error %} manual-submission--error{% else %} manual-submission--success{% endif %}" role="status" data-result="{% if error %}error{% else %}success{% endif %}">
|
||||
{% if error %}
|
||||
<strong>{% trans "Could not report fireworks" %}</strong><p>{{ error }}</p>
|
||||
<span class="manual-submission__icon" aria-hidden="true">!</span>
|
||||
<strong>{% trans "Could not report fireworks" %}</strong>
|
||||
<p>{{ error }}</p>
|
||||
{% else %}
|
||||
<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>
|
||||
<span class="manual-submission__icon" aria-hidden="true">✓</span>
|
||||
<strong>{% trans "Report received!" %}</strong>
|
||||
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
|
||||
<p class="manual-submission__summary">
|
||||
{{ pending.created_at|date:"H:i" }} ·
|
||||
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
|
||||
{% if direction_label %} · {{ direction_label }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -37,12 +37,24 @@ class BrowserProcessingBetaTests(TestCase):
|
||||
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)
|
||||
@@ -53,8 +65,9 @@ class BrowserProcessingBetaTests(TestCase):
|
||||
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.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"])
|
||||
@@ -99,3 +112,50 @@ class BrowserProcessingBetaTests(TestCase):
|
||||
})
|
||||
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)
|
||||
|
||||
@@ -62,7 +62,9 @@ class ManualPendingEventTests(TestCase):
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Report sent to Pending")
|
||||
self.assertContains(response, "Report received!")
|
||||
self.assertContains(response, "4 occurrences")
|
||||
self.assertContains(response, 'data-result="success"')
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.original_filename, "Manual fireworks report")
|
||||
self.assertEqual(pending.source_type, PendingEvent.SourceType.MANUAL)
|
||||
@@ -83,6 +85,7 @@ class ManualPendingEventTests(TestCase):
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "Choose between 1 and 1,000 occurrences.", status_code=400)
|
||||
self.assertContains(response, 'data-result="error"', status_code=400)
|
||||
self.assertFalse(PendingEvent.objects.exists())
|
||||
|
||||
def test_manual_report_accepts_optional_wav_on_the_same_pending_event(self):
|
||||
@@ -157,9 +160,14 @@ class ManualPendingEventTests(TestCase):
|
||||
response = self.client.get(reverse("hello"))
|
||||
|
||||
self.assertContains(response, "Report fireworks now")
|
||||
self.assertContains(response, "I heard fireworks — send to Pending")
|
||||
self.assertContains(response, "I heard fireworks")
|
||||
self.assertContains(response, "Capture direction")
|
||||
self.assertContains(response, 'manual-direction-panel" hidden')
|
||||
self.assertContains(response, 'id="manual-decrease"')
|
||||
self.assertContains(response, 'id="manual-increase"')
|
||||
self.assertContains(response, 'id="manual-direction-panel"')
|
||||
self.assertContains(response, 'hx-get="/fireworks/manual-direction/?mode=measure"')
|
||||
self.assertContains(response, 'id="manual-compass"')
|
||||
self.assertContains(response, 'aria-label="Compass direction" hidden')
|
||||
self.assertContains(response, "htmx.min.js")
|
||||
self.assertContains(response, "/static/vite/")
|
||||
self.assertContains(response, 'type="module"')
|
||||
@@ -167,6 +175,29 @@ class ManualPendingEventTests(TestCase):
|
||||
self.assertContains(response, "Open map controls")
|
||||
self.assertContains(response, "Classify a recording")
|
||||
|
||||
def test_direction_subsection_opens_and_closes_with_htmx_fragments(self):
|
||||
url = reverse("fireworks_detect:manual_direction_panel")
|
||||
measuring = self.client.get(url, {"mode": "measure"}, HTTP_HX_REQUEST="true")
|
||||
self.assertContains(measuring, 'id="manual-capture-direction"')
|
||||
self.assertContains(measuring, 'hx-target="#manual-direction-panel"')
|
||||
|
||||
closed = self.client.get(url, HTTP_HX_REQUEST="true")
|
||||
self.assertContains(closed, 'id="manual-direction-summary"')
|
||||
self.assertNotContains(closed, 'id="manual-capture-direction"')
|
||||
|
||||
def test_dutch_report_labels_and_direction_are_translated(self):
|
||||
self.client.cookies["django_language"] = "nl"
|
||||
page = self.client.get(reverse("hello"))
|
||||
self.assertContains(page, "Hoe vaak hoorde je het?")
|
||||
self.assertContains(page, "Ik hoorde vuurwerk")
|
||||
self.assertContains(page, "Start luisteren")
|
||||
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "1", "direction_degrees": "192",
|
||||
})
|
||||
self.assertContains(response, "Melding ontvangen!")
|
||||
self.assertContains(response, "Zuid 192°")
|
||||
|
||||
def test_old_route_preserves_the_previous_landing_page(self):
|
||||
response = self.client.get(reverse("old_home"))
|
||||
|
||||
@@ -275,6 +306,9 @@ class ManualPendingEventTests(TestCase):
|
||||
"direction_accuracy_degrees": "8",
|
||||
})
|
||||
|
||||
self.assertContains(response, "2 occurrences")
|
||||
self.assertContains(response, "Southwest 237°")
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.direction_degrees, 237)
|
||||
|
||||
@@ -10,6 +10,7 @@ from .views import (
|
||||
fireworks_map_view,
|
||||
fireworks_view,
|
||||
pending_audio,
|
||||
manual_direction_panel,
|
||||
submit_manual_pending_event,
|
||||
submit_pending_event,
|
||||
sensor_heartbeat,
|
||||
@@ -27,6 +28,7 @@ urlpatterns = [
|
||||
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
|
||||
path("submit-pending/", submit_pending_event, name="submit_pending"),
|
||||
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
|
||||
path("manual-direction/", manual_direction_panel, name="manual_direction_panel"),
|
||||
path("events/", events_view, name="events"),
|
||||
path("events/list/", events_list, name="events_list"),
|
||||
path("admin-audio/pending/<int:event_id>/", pending_audio, name="pending_audio"),
|
||||
|
||||
@@ -22,7 +22,7 @@ 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
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
|
||||
@@ -286,6 +286,22 @@ def classify_upload(request):
|
||||
# Keep the raw payload in this request flow; this is the future hand-off point
|
||||
# for saving the upload and its classification to a database or queue.
|
||||
context = _classification_context(payload)
|
||||
override = (
|
||||
BrowserProcessingSettings.enabled()
|
||||
and metadata.get("browser_override") is True
|
||||
and metadata.get("browser_gate_result") in {"speech_only", "no_match"}
|
||||
)
|
||||
if override:
|
||||
# The browser gate is advisory. Always classify server-side first, then
|
||||
# force this explicit override into Pending Review regardless of scores.
|
||||
pending = PendingEvent.objects.create(
|
||||
audio_file=uploaded_file,
|
||||
original_filename=uploaded_file.name,
|
||||
classifier_response=payload,
|
||||
)
|
||||
context["pending"] = pending
|
||||
logger.info("Browser override sent to Pending Review: %s", pending.pk)
|
||||
else:
|
||||
context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification")
|
||||
return render(request, "fireworks_detect/classification_result.html", context)
|
||||
|
||||
@@ -347,6 +363,15 @@ def _manual_direction(request):
|
||||
accuracy = None
|
||||
return heading, accuracy
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
@never_cache
|
||||
def manual_direction_panel(request):
|
||||
return render(request, "fireworks_detect/includes/manual_direction_panel.html", {
|
||||
"measuring": request.GET.get("mode") == "measure",
|
||||
})
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@never_cache
|
||||
def submit_manual_pending_event(request):
|
||||
@@ -390,7 +415,14 @@ def submit_manual_pending_event(request):
|
||||
direction_accuracy_degrees=direction_accuracy_degrees,
|
||||
direction_source="device_compass" if direction_degrees is not None else "",
|
||||
)
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending})
|
||||
direction_names = {
|
||||
"N": _("North"), "NE": _("Northeast"), "E": _("East"), "SE": _("Southeast"),
|
||||
"S": _("South"), "SW": _("Southwest"), "W": _("West"), "NW": _("Northwest"),
|
||||
}
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {
|
||||
"pending": pending,
|
||||
"direction_label": direction_names.get(pending.direction_cardinal) if direction_degrees is not None else "",
|
||||
})
|
||||
|
||||
@never_cache
|
||||
def events_list(request):
|
||||
|
||||
@@ -3,6 +3,8 @@ import "../styles/pages/fireworks-home.css";
|
||||
import "../styles/pages/map.css";
|
||||
import "../styles/pages/dashboard.css";
|
||||
import "../styles/components/burst-listener.css";
|
||||
import "../styles/components/manual-compass.css";
|
||||
import "../styles/components/manual-report-structure.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/manual-report.js";
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import "../styles/pages/home.css";
|
||||
import "../styles/components/burst-listener.css";
|
||||
import "../styles/components/manual-compass.css";
|
||||
import "../styles/components/manual-report-structure.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/manual-report.js";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "../styles/pages/settings.css";
|
||||
import "../styles/components/fireworks-navigation.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/user-settings.js";
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
const RATE = 16000;
|
||||
|
||||
export class AudioPreprocessor {
|
||||
static async prepare(file, { signal } = {}) {
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
console.log("[BoomCast][YAMNet] Preparing local classification.");
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass || !(window.OfflineAudioContext || window.webkitOfflineAudioContext)) throw new Error("Browser audio decoding unavailable");
|
||||
const context = new AudioContextClass();
|
||||
try {
|
||||
const decoded = await context.decodeAudioData(await file.arrayBuffer());
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
if (!decoded.duration || !Number.isFinite(decoded.duration)) throw new Error("Invalid audio duration");
|
||||
const OfflineContextClass = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
||||
const offline = new OfflineContextClass(1, Math.ceil(decoded.duration * RATE), RATE);
|
||||
const source = offline.createBufferSource();
|
||||
source.buffer = decoded;
|
||||
source.connect(offline.destination);
|
||||
source.start();
|
||||
const rendered = await offline.startRendering();
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
const waveform = rendered.getChannelData(0).slice();
|
||||
console.log("[BoomCast][YAMNet] Waveform prepared.", {
|
||||
sampleRate: RATE, samples: waveform.length, durationSeconds: waveform.length / RATE,
|
||||
});
|
||||
return waveform;
|
||||
} finally {
|
||||
await context.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { BrowserSubmissionProcessor } from "./browser-submission-processor.js";
|
||||
|
||||
const form = document.querySelector(".upload-form");
|
||||
|
||||
if (form) {
|
||||
@@ -12,22 +10,56 @@ if (form) {
|
||||
const submit = form.querySelector('button[type="submit"]');
|
||||
const cancel = form.querySelector(".upload-cancel");
|
||||
const results = form.querySelector("#classification-results");
|
||||
const gatePanel = form.querySelector("#browser-gate");
|
||||
const gateTitle = form.querySelector("#browser-gate-title");
|
||||
const gateMessage = form.querySelector("#browser-gate-message");
|
||||
const gateChoose = form.querySelector("#browser-gate-choose");
|
||||
const gateOverride = form.querySelector("#browser-gate-override");
|
||||
const status = document.querySelector("#upload-status");
|
||||
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const browserToggle = form.querySelector("#browser-processing-toggle");
|
||||
const configElement = document.querySelector("#boomcast-browser-config");
|
||||
let browserConfig = { browserProcessingBeta: false };
|
||||
try { browserConfig = JSON.parse(configElement?.textContent || "{}"); }
|
||||
catch (error) { console.error("[BoomCast][BrowserBeta] Configuration unavailable:", error); }
|
||||
const browserAvailable = browserConfig.browserProcessingBeta === true && Boolean(browserToggle);
|
||||
if (browserToggle) browserToggle.checked = false;
|
||||
const audioAccept = fileInput.accept;
|
||||
const videoAccept = ",video/*,.mp4,.mov,.m4v,.webm,.mkv,.avi";
|
||||
const browserModeEnabled = () => browserAvailable && browserToggle.checked;
|
||||
const isVideoFile = (file) => Boolean(file) &&
|
||||
(file.type.startsWith("video/") || (!file.type && /\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name || "")));
|
||||
let browserProcessor = null;
|
||||
let browserProcessorPromise = null;
|
||||
let sourceFile = null;
|
||||
|
||||
async function getBrowserProcessor() {
|
||||
if (browserProcessor) return browserProcessor;
|
||||
browserProcessorPromise ||= import("./browser-submission-processor.js").then(({ BrowserSubmissionProcessor }) => {
|
||||
browserProcessor = new BrowserSubmissionProcessor(browserConfig);
|
||||
console.log("[BoomCast][BrowserBeta] Coordinator initialised.");
|
||||
return browserProcessor;
|
||||
}).catch((error) => {
|
||||
browserProcessorPromise = null;
|
||||
throw error;
|
||||
});
|
||||
return browserProcessorPromise;
|
||||
}
|
||||
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;
|
||||
let selectionId = 0;
|
||||
let selectionController = null;
|
||||
let selectedResult = null;
|
||||
let extractionPending = false;
|
||||
let extractionFailed = false;
|
||||
const browserProcessor = new BrowserSubmissionProcessor();
|
||||
if (!browserProcessor.isEnabled()) {
|
||||
console.log("[BoomCast][BrowserBeta] Feature disabled; using legacy submission flow.");
|
||||
let preparationPending = false;
|
||||
let preparationFailed = false;
|
||||
let gateBlocked = false;
|
||||
if (!browserAvailable) {
|
||||
console.log("[BoomCast][BrowserBeta] Feature disabled globally; using existing server flow.");
|
||||
} else {
|
||||
console.log("[BoomCast][BrowserBeta] Browser processing disabled by user; using existing server flow.");
|
||||
}
|
||||
|
||||
function setUploadState(state, { progress = null, message = "" } = {}) {
|
||||
@@ -36,6 +68,7 @@ if (form) {
|
||||
busy = active;
|
||||
submit.disabled = active;
|
||||
fileInput.disabled = active;
|
||||
if (browserToggle) browserToggle.disabled = active;
|
||||
cancel.hidden = !active;
|
||||
if (active) form.setAttribute("aria-busy", "true");
|
||||
else form.removeAttribute("aria-busy");
|
||||
@@ -128,47 +161,124 @@ if (form) {
|
||||
function selectFile(file) {
|
||||
selectionId += 1;
|
||||
selectionController?.abort();
|
||||
browserProcessor?.cancel();
|
||||
selectionController = null;
|
||||
selectedResult = null;
|
||||
extractionPending = false;
|
||||
extractionFailed = false;
|
||||
preparationPending = false;
|
||||
preparationFailed = false;
|
||||
gateBlocked = false;
|
||||
gatePanel.hidden = true;
|
||||
if (!busy) results.replaceChildren();
|
||||
showFile(file);
|
||||
if (!busy) { submit.disabled = false; cancel.hidden = true; }
|
||||
if (!file || !browserProcessor.isEnabled() || !BrowserSubmissionProcessor.isVideo(file)) return;
|
||||
if (!file) return;
|
||||
console.log("[BoomCast][BrowserBeta] File selected.", { mimeType: file.type, sizeBytes: file.size });
|
||||
if (!browserModeEnabled()) {
|
||||
console.log("[BoomCast][BrowserBeta] Server mode selected.");
|
||||
if (isVideoFile(file)) {
|
||||
preparationFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.serverAudioOnly || "Server processing currently accepts audio recordings. Choose an audio file or enable browser processing.";
|
||||
}
|
||||
return;
|
||||
}
|
||||
console.log("[BoomCast][BrowserBeta] Browser mode selected.");
|
||||
const id = selectionId;
|
||||
const controller = new AbortController();
|
||||
selectionController = controller;
|
||||
extractionPending = true;
|
||||
preparationPending = true;
|
||||
submit.disabled = true;
|
||||
cancel.hidden = false;
|
||||
status.textContent = t.extractingAudio || "Extracting audio from video…";
|
||||
browserProcessor.prepare(file, { signal: controller.signal, onState: (state) => {
|
||||
if (id === selectionId) console.log("[BoomCast][FFmpeg] State:", state);
|
||||
} }).then((result) => {
|
||||
if (id !== selectionId || controller.signal.aborted) return;
|
||||
selectedResult = result;
|
||||
extractionPending = false;
|
||||
submit.disabled = false;
|
||||
cancel.hidden = true;
|
||||
status.textContent = result.file === file
|
||||
? (t.videoExtractionUnavailable || "Video processing is unavailable. Please choose an audio recording.")
|
||||
: (t.onlyAudioSent || "Audio extracted on this device. Only audio will be sent to BoomCast.");
|
||||
extractionFailed = result.file === file;
|
||||
if (extractionFailed) submit.disabled = true;
|
||||
}).catch((error) => {
|
||||
status.textContent = isVideoFile(file)
|
||||
? (t.extractingAudio || "Extracting audio from video…")
|
||||
: (t.preparingRecording || "Preparing recording…");
|
||||
getBrowserProcessor().then((processor) => {
|
||||
if (id !== selectionId || controller.signal.aborted || !browserModeEnabled()) return null;
|
||||
processor.setEnabled(true);
|
||||
return processor.process(file, { signal: controller.signal, onState: (state) => {
|
||||
if (id !== selectionId) return;
|
||||
console.error("[BoomCast][FFmpeg] Falling back safely.", error);
|
||||
extractionPending = false;
|
||||
extractionFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = state === "checking" ? (t.checkingRecording || "Checking recording…")
|
||||
: (t.extractingAudio || "Extracting audio from video…");
|
||||
} });
|
||||
}).then((result) => {
|
||||
if (!result || id !== selectionId || controller.signal.aborted || !browserModeEnabled()) return;
|
||||
preparationPending = false;
|
||||
cancel.hidden = true;
|
||||
status.textContent = controller.signal.aborted
|
||||
? (t.extractionCancelled || "Audio extraction cancelled. Choose a recording to continue.")
|
||||
: (t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording.");
|
||||
if (isVideoFile(file) && result.file === file) {
|
||||
preparationFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording.";
|
||||
return;
|
||||
}
|
||||
selectedResult = result;
|
||||
gateBlocked = result.gate === "speech_only" || result.gate === "no_match";
|
||||
if (gateBlocked) {
|
||||
gateTitle.textContent = result.gate === "speech_only"
|
||||
? (t.speechGateTitle || "This recording appears to contain speech, but no relevant sound was detected.")
|
||||
: (t.irrelevantGateTitle || "No relevant sound was detected.");
|
||||
gateMessage.textContent = result.gate === "speech_only"
|
||||
? (t.speechGateMessage || "To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review.")
|
||||
: (t.irrelevantGateMessage || "BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review.");
|
||||
gatePanel.hidden = false;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.gateChooseMessage || "Recording checked. Choose another recording or submit for manual review.";
|
||||
} else {
|
||||
submit.disabled = false;
|
||||
status.textContent = result.gate === "unavailable"
|
||||
? (t.localUnavailable || "Local checking was unavailable. BoomCast will use normal server processing.")
|
||||
: isVideoFile(file)
|
||||
? (t.videoAudioOnly || "Video processed on this device. Only extracted audio will be sent if you submit.")
|
||||
: (t.readyToSubmit || "Ready to submit.");
|
||||
}
|
||||
}).catch((error) => {
|
||||
if (id !== selectionId || !browserModeEnabled()) return;
|
||||
console.error("[BoomCast][BrowserBeta] Unexpected browser pipeline error:", error);
|
||||
preparationPending = false;
|
||||
cancel.hidden = true;
|
||||
if (isVideoFile(file)) {
|
||||
preparationFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording.";
|
||||
} else {
|
||||
console.warn("[BoomCast][BrowserBeta] Browser pipeline unavailable; falling back to server.");
|
||||
selectedResult = { file, metadata: null, gate: "unavailable" };
|
||||
submit.disabled = false;
|
||||
status.textContent = t.localUnavailable || "Local checking was unavailable. BoomCast will use normal server processing.";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fileInput.addEventListener("change", () => selectFile(fileInput.files[0]));
|
||||
function restoreOriginalFile() {
|
||||
if (!sourceFile || fileInput.files[0] === sourceFile) return;
|
||||
try {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(sourceFile);
|
||||
fileInput.files = transfer.files;
|
||||
} catch (error) {
|
||||
console.error("[BoomCast][Cleanup] Could not restore original selection:", error);
|
||||
fileInput.value = "";
|
||||
sourceFile = null;
|
||||
}
|
||||
}
|
||||
|
||||
browserToggle?.addEventListener("change", () => {
|
||||
if (browserModeEnabled()) {
|
||||
console.log("[BoomCast][BrowserBeta] Browser processing enabled by user.");
|
||||
fileInput.accept = audioAccept + videoAccept;
|
||||
selectFile(sourceFile || fileInput.files[0]);
|
||||
} else {
|
||||
console.log("[BoomCast][BrowserBeta] Switching to server processing.");
|
||||
console.log("[BoomCast][Cleanup] Cancelling active browser processing job.");
|
||||
selectionController?.abort();
|
||||
browserProcessor?.setEnabled(false);
|
||||
browserProcessor?.cleanup();
|
||||
fileInput.accept = audioAccept;
|
||||
restoreOriginalFile();
|
||||
selectFile(sourceFile || fileInput.files[0]);
|
||||
}
|
||||
});
|
||||
|
||||
fileInput.addEventListener("change", () => { sourceFile = fileInput.files[0] || null; selectFile(sourceFile); });
|
||||
["dragenter", "dragover"].forEach((name) => dropZone.addEventListener(name, (event) => {
|
||||
event.preventDefault();
|
||||
if (!busy) dropZone.classList.add("dragging");
|
||||
@@ -180,10 +290,27 @@ if (form) {
|
||||
dropZone.addEventListener("drop", (event) => {
|
||||
if (busy || !event.dataTransfer.files.length) return;
|
||||
fileInput.files = event.dataTransfer.files;
|
||||
selectFile(fileInput.files[0]);
|
||||
sourceFile = fileInput.files[0] || null;
|
||||
selectFile(sourceFile);
|
||||
});
|
||||
|
||||
function startUpload(file, metadata = null) {
|
||||
// HTMX's later Pending action also reads the native file input. Replace a
|
||||
// video with its extracted WAV so no subsequent form action can send video.
|
||||
if (fileInput.files[0] !== file) {
|
||||
try {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(file);
|
||||
fileInput.files = transfer.files;
|
||||
if (fileInput.files[0] !== file) throw new Error("Prepared audio could not replace video in form");
|
||||
} catch (error) {
|
||||
console.error("[BoomCast][BrowserBeta] Could not secure native form upload:", error);
|
||||
preparationFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = (t.secureVideoFailed || "Could not prepare this video for upload. Please choose an audio recording.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const formData = new FormData(form);
|
||||
formData.set("audio", file);
|
||||
if (metadata) formData.set("browser_processing_metadata", JSON.stringify(metadata));
|
||||
@@ -226,69 +353,53 @@ if (form) {
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (busy || preparing || extractionPending || extractionFailed) return;
|
||||
if (busy || preparationPending || preparationFailed || gateBlocked) return;
|
||||
if (!form.reportValidity()) return;
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
if (selectedResult && BrowserSubmissionProcessor.isVideo(file)) {
|
||||
startUpload(selectedResult.file, selectedResult.metadata);
|
||||
return;
|
||||
}
|
||||
if (!browserProcessor.isEnabled()) {
|
||||
if (!browserModeEnabled()) { startUpload(file); return; }
|
||||
if (selectedResult) { startUpload(selectedResult.file, selectedResult.metadata); return; }
|
||||
// Unknown audio types retain the existing server flow.
|
||||
startUpload(file);
|
||||
return;
|
||||
}
|
||||
const id = selectionId;
|
||||
preparing = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.preparingRecording || "Preparing recording…";
|
||||
browserProcessor.prepare(file).then(({ file: preparedFile, metadata }) => {
|
||||
preparing = false;
|
||||
submit.disabled = false;
|
||||
if (fileInput.files[0] !== file || selectionId !== id) return;
|
||||
if (BrowserSubmissionProcessor.isVideo(file) && preparedFile === file) {
|
||||
extractionFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording.";
|
||||
return;
|
||||
}
|
||||
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;
|
||||
if (fileInput.files[0] !== file || selectionId !== id) return;
|
||||
if (BrowserSubmissionProcessor.isVideo(file)) {
|
||||
extractionFailed = true;
|
||||
submit.disabled = true;
|
||||
status.textContent = t.videoExtractionFailed || "Could not extract audio from this video. Please choose an audio recording.";
|
||||
return;
|
||||
}
|
||||
if (fileInput.files[0] === file && selectionId === id) startUpload(file);
|
||||
});
|
||||
}, true);
|
||||
|
||||
gateChoose.addEventListener("click", () => fileInput.click());
|
||||
gateOverride.addEventListener("click", () => {
|
||||
if (!browserModeEnabled() || !gateBlocked || !selectedResult || busy || preparationPending) return;
|
||||
console.warn("[BoomCast][Gate] User explicitly overrode local gate.");
|
||||
console.log("[BoomCast][Gate] Submission will enter manual review.");
|
||||
const metadata = { ...selectedResult.metadata, browser_override: true };
|
||||
selectedResult.metadata = metadata;
|
||||
gateBlocked = false;
|
||||
gatePanel.hidden = true;
|
||||
startUpload(selectedResult.file, metadata);
|
||||
});
|
||||
cancel.addEventListener("click", () => {
|
||||
if (extractionPending) {
|
||||
if (preparationPending) {
|
||||
selectionController?.abort();
|
||||
browserProcessor?.cancel();
|
||||
selectionId += 1;
|
||||
extractionPending = false;
|
||||
extractionFailed = true;
|
||||
preparationPending = false;
|
||||
preparationFailed = true;
|
||||
submit.disabled = true;
|
||||
cancel.hidden = true;
|
||||
status.textContent = t.extractionCancelled || "Audio extraction cancelled. Choose a recording to continue.";
|
||||
status.textContent = t.extractionCancelled || (t.preparationCancelled || "Preparation cancelled. Choose a recording to continue.");
|
||||
} else request?.abort();
|
||||
});
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) {
|
||||
request?.abort();
|
||||
selectionController?.abort();
|
||||
browserProcessor?.cancel();
|
||||
selectionId += 1;
|
||||
selectedResult = null;
|
||||
extractionPending = false;
|
||||
extractionFailed = false;
|
||||
sourceFile = null;
|
||||
if (browserToggle) { browserToggle.checked = false; fileInput.accept = audioAccept; }
|
||||
browserProcessor?.setEnabled(false);
|
||||
preparationPending = false;
|
||||
preparationFailed = false;
|
||||
gateBlocked = false;
|
||||
gatePanel.hidden = true;
|
||||
submit.disabled = false;
|
||||
fileInput.value = "";
|
||||
results.replaceChildren();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export class BrowserSubmissionGate {
|
||||
static evaluate(predictions, policy) {
|
||||
console.log("[BoomCast][Gate] Evaluating browser classification.");
|
||||
const relevant = new Set((policy.whitelist || []).map((name) => name.toLowerCase()));
|
||||
const speechNames = new Set((policy.privacy_sensitive_speech || []).map((name) => name.toLowerCase()));
|
||||
const matchThreshold = Number(policy.thresholds?.relevance ?? 0.5);
|
||||
const speechThreshold = Number(policy.thresholds?.speech ?? 0.5);
|
||||
const matches = predictions.filter((item) => relevant.has(item.class.toLowerCase()) && item.score >= matchThreshold);
|
||||
const speechDetected = predictions.some((item) => speechNames.has(item.class.toLowerCase()) && item.score >= speechThreshold);
|
||||
console.log("[BoomCast][Gate] Relevant whitelist matches:", matches);
|
||||
console.log("[BoomCast][Gate] Speech detected:", speechDetected);
|
||||
const result = matches.length ? "whitelist_match" : speechDetected ? "speech_only" : "no_match";
|
||||
console.log(`[BoomCast][Gate] Decision: ${result.toUpperCase()}`);
|
||||
if (result !== "whitelist_match") console.log("[BoomCast][Gate] Automatic upload suppressed.");
|
||||
return { result, speechDetected, matches };
|
||||
}
|
||||
}
|
||||
@@ -3,82 +3,137 @@ 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) {
|
||||
try { return JSON.parse(element.textContent); }
|
||||
catch (error) {
|
||||
console.error(`${PREFIX} Configuration unavailable:`, error);
|
||||
return { browserProcessingBeta: false };
|
||||
}
|
||||
}
|
||||
|
||||
export class BrowserSubmissionProcessor {
|
||||
constructor(config = readBrowserProcessingConfig(), extractVideo = null) {
|
||||
constructor(config = readBrowserProcessingConfig(), extractVideo = null, dependencies = {}) {
|
||||
this.config = config;
|
||||
this.extractVideo = extractVideo;
|
||||
this.dependencies = dependencies;
|
||||
this.userEnabled = false;
|
||||
this.activeController = null;
|
||||
}
|
||||
|
||||
isEnabled() {
|
||||
return this.config.browserProcessingBeta === true;
|
||||
isAvailable() { return this.config.browserProcessingBeta === true; }
|
||||
|
||||
isEnabled() { return this.isAvailable() && this.userEnabled; }
|
||||
|
||||
setEnabled(enabled) {
|
||||
if (!enabled) this.cancel();
|
||||
this.userEnabled = this.isAvailable() && enabled === true;
|
||||
console.log(`${PREFIX} ${this.userEnabled ? "Browser processing enabled by user." : "Browser processing disabled by user; using existing server flow."}`);
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.activeController?.abort();
|
||||
this.activeController = null;
|
||||
}
|
||||
|
||||
async process(file, { signal, onState } = {}) {
|
||||
this.cancel();
|
||||
const controller = new AbortController();
|
||||
this.activeController = controller;
|
||||
const abort = () => controller.abort();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
if (signal?.aborted) controller.abort();
|
||||
try {
|
||||
return await this.prepare(file, { signal: controller.signal, onState });
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
if (this.activeController === controller) this.activeController = null;
|
||||
}
|
||||
}
|
||||
|
||||
canProcess(file) {
|
||||
return this.isEnabled() && Boolean(file) && /^(audio|video)\//.test(file.type);
|
||||
return this.isEnabled() && Boolean(file) && (BrowserSubmissionProcessor.isAudio(file) || BrowserSubmissionProcessor.isVideo(file));
|
||||
}
|
||||
|
||||
static isAudio(file) {
|
||||
return Boolean(file) && (file.type.startsWith("audio/") || (!file.type && /\.(aac|aif|aiff|flac|m4a|mp3|ogg|opus|wav|weba)$/i.test(file.name || "")));
|
||||
}
|
||||
|
||||
static isVideo(file) {
|
||||
return Boolean(file) && (file.type.startsWith("video/") || (!file.type && /\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name || "")));
|
||||
}
|
||||
|
||||
async prepare(file, { signal, onState } = {}) {
|
||||
if (!this.isEnabled()) return { file, metadata: null };
|
||||
async prepare(file, { signal, onState = () => {} } = {}) {
|
||||
if (!this.canProcess(file)) return { file, metadata: null, gate: "unavailable" };
|
||||
console.log(`${PREFIX} Initialising beta submission pipeline.`);
|
||||
console.log(`${PREFIX} File selected:`, { type: file?.type || "", size: file?.size || 0 });
|
||||
if (!this.canProcess(file) && !BrowserSubmissionProcessor.isVideo(file)) {
|
||||
console.log(`${PREFIX} Browser preprocessing unavailable; falling back.`);
|
||||
return { file, metadata: null };
|
||||
}
|
||||
let policyTimeout;
|
||||
try {
|
||||
const video = BrowserSubmissionProcessor.isVideo(file);
|
||||
const controller = new AbortController();
|
||||
policyTimeout = setTimeout(() => controller.abort(), 5000);
|
||||
const abort = () => controller.abort();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
let policy;
|
||||
try {
|
||||
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();
|
||||
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 };
|
||||
return { file, metadata: null, gate: "unavailable" };
|
||||
}
|
||||
if (BrowserSubmissionProcessor.isVideo(file)) {
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw error;
|
||||
console.error(`${PREFIX} Policy unavailable:`, error);
|
||||
if (video) throw error;
|
||||
return { file, metadata: null, gate: "unavailable" };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
let preparedFile = file;
|
||||
if (video) {
|
||||
const extract = this.extractVideo || (await import("./ffmpeg-video-extractor.js")).extractVideoAudio;
|
||||
const wav = await extract(file, { signal, onState });
|
||||
return { file: wav, metadata: { browser_processing_used: true, browser_processing_version: policy.version, browser_gate_result: "unavailable", browser_override: false } };
|
||||
preparedFile = await extract(file, { signal, onState });
|
||||
}
|
||||
// Audio continues through the existing submission path.
|
||||
console.log(`${PREFIX} Browser processing shell ready; using original recording.`);
|
||||
return {
|
||||
file,
|
||||
metadata: {
|
||||
browser_processing_used: false,
|
||||
const metadata = {
|
||||
browser_processing_used: video,
|
||||
browser_processing_version: policy.version,
|
||||
browser_gate_result: "unavailable",
|
||||
browser_override: false,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`${PREFIX} Initialisation failed:`, error);
|
||||
this.cleanup();
|
||||
if (BrowserSubmissionProcessor.isVideo(file)) throw error;
|
||||
console.log(`${PREFIX} Restoring legacy submission flow.`);
|
||||
return { file, metadata: null };
|
||||
try {
|
||||
onState("checking");
|
||||
const prepareAudio = this.dependencies.prepareAudio || (await import("./audio-preprocessor.js")).AudioPreprocessor.prepare;
|
||||
let waveform = await prepareAudio(preparedFile, { signal });
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
try {
|
||||
const classify = this.dependencies.classify || (await import("./browser-yamnet-classifier.js")).BrowserYamnetClassifier.classify;
|
||||
const predictions = await classify(waveform, {
|
||||
modelUrl: policy.model_url, classMapUrl: policy.class_map_url, signal,
|
||||
});
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
const evaluate = this.dependencies.evaluate || (await import("./browser-submission-gate.js")).BrowserSubmissionGate.evaluate;
|
||||
const decision = evaluate(predictions, policy);
|
||||
metadata.browser_processing_used = true;
|
||||
metadata.browser_gate_result = decision.result;
|
||||
metadata.browser_speech_detected = decision.speechDetected;
|
||||
return { file: preparedFile, metadata, gate: decision.result, predictions: predictions.slice(0, 5) };
|
||||
} finally {
|
||||
clearTimeout(policyTimeout);
|
||||
waveform = null;
|
||||
console.log("[BoomCast][Cleanup] Releasing waveform buffers.");
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw error;
|
||||
console.error("[BoomCast][YAMNet] Local classification unavailable:", error);
|
||||
console.log("[BoomCast][Gate] Falling back to server classification.");
|
||||
metadata.browser_gate_result = "unavailable";
|
||||
return { file: preparedFile, metadata, gate: "unavailable" };
|
||||
}
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
// Future passes can release workers, object URLs, and model tensors here.
|
||||
this.cancel();
|
||||
console.log("[BoomCast][Cleanup] Browser beta resources released.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
const PREFIX = "[BoomCast][YAMNet]";
|
||||
|
||||
export class BrowserYamnetClassifier {
|
||||
static async classify(waveform, { modelUrl, classMapUrl, signal, loadTensorFlow } = {}) {
|
||||
let tf;
|
||||
let model;
|
||||
let input;
|
||||
let output;
|
||||
const started = performance.now();
|
||||
try {
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
console.log(`${PREFIX} Lazy-loading TensorFlow.js.`);
|
||||
tf = loadTensorFlow ? await loadTensorFlow() : await import("@tensorflow/tfjs");
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
console.log(`${PREFIX} TensorFlow.js loaded.`);
|
||||
await tf.ready();
|
||||
console.log(`${PREFIX} Backend:`, tf.getBackend());
|
||||
console.log(`${PREFIX} Loading model.`);
|
||||
const [loaded, mappingResponse] = await Promise.all([
|
||||
tf.loadGraphModel(modelUrl),
|
||||
fetch(classMapUrl, { cache: "force-cache", signal }),
|
||||
]);
|
||||
model = loaded;
|
||||
if (!mappingResponse.ok) throw new Error("YAMNet class map unavailable");
|
||||
const classMap = await mappingResponse.json();
|
||||
if (!Array.isArray(classMap) || classMap.length !== 521) throw new Error("Invalid YAMNet class map");
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
console.log(`${PREFIX} Model ready.`);
|
||||
// YAMNet needs at least one 0.96 s patch, including STFT padding.
|
||||
const samples = waveform.length < 15600 ? Float32Array.from({ length: 15600 }, (_, i) => waveform[i] || 0) : waveform;
|
||||
input = tf.tensor1d(samples, "float32");
|
||||
console.log(`${PREFIX} Starting inference.`);
|
||||
const result = await model.executeAsync(input);
|
||||
output = Array.isArray(result) ? result : [result];
|
||||
const scores = output.find((tensor) => tensor.shape.length === 2 && tensor.shape[1] === classMap.length);
|
||||
if (!scores) throw new Error("YAMNet score output unavailable");
|
||||
const values = await scores.data();
|
||||
if (signal?.aborted) throw new DOMException("Cancelled", "AbortError");
|
||||
const frames = scores.shape[0];
|
||||
const predictions = classMap.map((name, index) => {
|
||||
let score = -1;
|
||||
let frame = 0;
|
||||
for (let row = 0; row < frames; row += 1) {
|
||||
const value = values[row * classMap.length + index];
|
||||
if (value > score) { score = value; frame = row; }
|
||||
}
|
||||
return { class: name, score, frame, timeSeconds: Number((frame * 0.48).toFixed(2)) };
|
||||
});
|
||||
predictions.sort((a, b) => b.score - a.score);
|
||||
console.log(`${PREFIX} Inference completed in`, Math.round(performance.now() - started), "ms.");
|
||||
console.groupCollapsed(`${PREFIX} Top local predictions`);
|
||||
console.table(predictions.slice(0, 10));
|
||||
console.groupEnd();
|
||||
return predictions;
|
||||
} catch (error) {
|
||||
console.error(`${PREFIX} Local inference failed:`, error);
|
||||
throw error;
|
||||
} finally {
|
||||
if (tf) console.log(`${PREFIX} TensorFlow memory before cleanup:`, tf.memory());
|
||||
console.log("[BoomCast][Cleanup] Disposing YAMNet tensors.");
|
||||
input?.dispose();
|
||||
output?.forEach((tensor) => tensor?.dispose());
|
||||
console.log("[BoomCast][Cleanup] Disposing browser YAMNet model.");
|
||||
model?.dispose();
|
||||
console.log("[BoomCast][Cleanup] Releasing waveform buffers.");
|
||||
if (tf) console.log(`${PREFIX} TensorFlow memory after cleanup:`, tf.memory());
|
||||
console.log("[BoomCast][Cleanup] Browser classification cleanup complete.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
const form = document.querySelector("#manual-report-form");
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
|
||||
export function createBurstListener() {
|
||||
if (!form) return null;
|
||||
const start = document.querySelector("#burst-start");
|
||||
const container = start.closest(".burst-listener");
|
||||
const section = start.closest(".manual-report__supporting");
|
||||
const stateLabel = document.querySelector("#burst-state");
|
||||
const panel = document.querySelector("#burst-panel");
|
||||
const heading = document.querySelector("#burst-heading");
|
||||
const detail = document.querySelector("#burst-detail");
|
||||
@@ -42,11 +46,14 @@ export function createBurstListener() {
|
||||
|
||||
function setState(next) {
|
||||
state = next;
|
||||
if (container) container.dataset.state = next;
|
||||
if (section) section.dataset.state = next;
|
||||
if (stateLabel) stateLabel.textContent = next === "listening" ? (t.listeningNextBang || "Listening for the next bang") : next === "tail" ? (t.soundDetected || "Sound detected") : next === "captured" ? (t.soundCaptured || "Sound captured") : (t.notListening || "Not listening");
|
||||
start.hidden = next !== "off";
|
||||
panel.hidden = next === "off";
|
||||
resume.hidden = discard.hidden = next !== "captured";
|
||||
heading.textContent = next === "captured" ? "Sound captured" : next === "tail" ? "Sound detected — finishing clip…" : "Listening for the next sound…";
|
||||
detail.textContent = next === "listening" ? "Keeping the most recent ~10 seconds" : next === "captured" ? "Preview the clip or send your report." : "";
|
||||
heading.textContent = next === "captured" ? (t.soundCaptured || "Sound captured") : next === "tail" ? (t.soundDetectedFinishing || "Sound detected — finishing clip…") : (t.listeningNextSound || "Listening for the next sound…");
|
||||
detail.textContent = next === "listening" ? (t.keepingRecentAudio || "Keeping the most recent ~10 seconds") : next === "captured" ? (t.previewClipOrSend || "Preview the clip or send your report.") : "";
|
||||
}
|
||||
|
||||
function wav(samples, rate) {
|
||||
@@ -73,6 +80,9 @@ export function createBurstListener() {
|
||||
async function begin() {
|
||||
error.hidden = true;
|
||||
start.disabled = true;
|
||||
if (container) container.dataset.state = "starting";
|
||||
if (section) section.dataset.state = "starting";
|
||||
if (stateLabel) stateLabel.textContent = t.startingMicrophone || "Starting microphone…";
|
||||
try {
|
||||
if (!navigator.mediaDevices?.getUserMedia || !window.AudioWorkletNode) throw new Error("Microphone listening is unavailable in this browser or connection.");
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 }, video: false });
|
||||
@@ -111,7 +121,10 @@ export function createBurstListener() {
|
||||
setState("listening");
|
||||
} catch (cause) {
|
||||
await end();
|
||||
error.textContent = cause.name === "NotAllowedError" ? "Microphone permission was denied. Manual reporting is still available." : (cause.message || "Microphone capture failed.");
|
||||
if (container) container.dataset.state = "error";
|
||||
if (section) section.dataset.state = "error";
|
||||
if (stateLabel) stateLabel.textContent = t.microphoneUnavailable || "Microphone unavailable";
|
||||
error.textContent = cause.name === "NotAllowedError" ? (t.microphoneDenied || "Microphone permission was denied. Manual reporting is still available.") : (t.microphoneFailed || "Microphone capture failed.");
|
||||
error.hidden = false;
|
||||
} finally {
|
||||
start.disabled = false;
|
||||
|
||||
@@ -3,41 +3,135 @@
|
||||
|
||||
const manualForm = document.querySelector("#manual-report-form");
|
||||
const manualSubmit = document.querySelector("#manual-submit");
|
||||
const manualStatus = document.querySelector("#manual-submission");
|
||||
const submitLabel = document.querySelector("#manual-submit-label");
|
||||
const occurrences = document.querySelector("#manual-occurrences");
|
||||
const decrease = document.querySelector("#manual-decrease");
|
||||
const increase = document.querySelector("#manual-increase");
|
||||
const latitude = document.querySelector("#manual-latitude");
|
||||
const longitude = document.querySelector("#manual-longitude");
|
||||
const directionDegrees = document.querySelector("#manual-direction-degrees");
|
||||
const directionAccuracy = document.querySelector("#manual-direction-accuracy");
|
||||
const captureDirectionButton = document.querySelector("#manual-capture-direction");
|
||||
const directionStatus = document.querySelector("#manual-direction-status");
|
||||
const directionPanel = document.querySelector("#manual-direction-panel");
|
||||
const isMobileDevice = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/.test(navigator.userAgent)
|
||||
|| (navigator.userAgent.includes("Macintosh") && navigator.maxTouchPoints > 1);
|
||||
if (isMobileDevice) directionPanel.hidden = false;
|
||||
const captureDirectionButton = () => document.querySelector("#manual-capture-direction");
|
||||
const directionStatus = () => document.querySelector("#manual-direction-status");
|
||||
const directionPanel = () => document.querySelector("#manual-direction-panel");
|
||||
const compass = document.querySelector("#manual-compass");
|
||||
const compassHome = document.querySelector("#manual-compass-home");
|
||||
const compassRose = document.querySelector("#manual-compass-rose");
|
||||
const compassHeading = document.querySelector("#manual-compass-heading");
|
||||
const reportTime = document.querySelector("#manual-report-time");
|
||||
const reportHours = document.querySelector("#report-clock-hours");
|
||||
const reportMinutes = document.querySelector("#report-clock-minutes");
|
||||
let orientationListener;
|
||||
let compassUnavailableTimeout;
|
||||
let compassRotation = null;
|
||||
const burstListener = createBurstListener();
|
||||
|
||||
const isUsableNumber = (value) => Number.isFinite(value);
|
||||
const cardinalDirection = (heading) => ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][Math.floor(((heading + 22.5) % 360) / 45)];
|
||||
const cardinalDirection = (heading) => [
|
||||
t.north || "North", t.northeast || "Northeast", t.east || "East", t.southeast || "Southeast",
|
||||
t.south || "South", t.southwest || "Southwest", t.west || "West", t.northwest || "Northwest",
|
||||
][Math.floor(((heading + 22.5) % 360) / 45)];
|
||||
const displayDegrees = (value) => Number(value.toFixed(1)).toString();
|
||||
const updateReportTime = () => {
|
||||
if (!reportTime) return;
|
||||
const now = new Date();
|
||||
reportTime.dateTime = now.toISOString();
|
||||
const parts = new Intl.DateTimeFormat(document.documentElement.lang || undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now);
|
||||
const hours = parts.find((part) => part.type === "hour")?.value;
|
||||
const minutes = parts.find((part) => part.type === "minute")?.value;
|
||||
if (!hours || !minutes || !reportHours || !reportMinutes) return;
|
||||
reportHours.textContent = hours;
|
||||
reportMinutes.textContent = minutes;
|
||||
reportTime.setAttribute("aria-label", `${hours}:${minutes}`);
|
||||
};
|
||||
updateReportTime();
|
||||
if (reportTime) window.setInterval(updateReportTime, 60000);
|
||||
const idleSubmitLabel = submitLabel?.textContent || "I heard fireworks";
|
||||
|
||||
const setSubmissionState = (next, message = "") => {
|
||||
manualForm.dataset.state = next;
|
||||
manualSubmit.disabled = next === "submitting";
|
||||
if (submitLabel) submitLabel.textContent = next === "submitting" ? (t.sendingReport || "Sending…") : idleSubmitLabel;
|
||||
if (message) {
|
||||
const status = document.querySelector("#manual-submission");
|
||||
status.className = "manual-report__submission";
|
||||
status.textContent = message;
|
||||
}
|
||||
};
|
||||
|
||||
const showResponse = (html, successful) => {
|
||||
const parsed = new DOMParser().parseFromString(html, "text/html").querySelector("#manual-submission");
|
||||
if (!parsed) {
|
||||
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
||||
return false;
|
||||
}
|
||||
document.querySelector("#manual-submission").replaceWith(parsed);
|
||||
setSubmissionState(successful ? "submitted" : "error");
|
||||
return successful;
|
||||
};
|
||||
|
||||
const setCount = (value) => {
|
||||
const count = Number.parseInt(value, 10);
|
||||
occurrences.value = String(Math.min(1000, Math.max(1, Number.isFinite(count) ? count : 1)));
|
||||
decrease.disabled = occurrences.value === "1";
|
||||
increase.disabled = occurrences.value === "1000";
|
||||
};
|
||||
setCount(occurrences.value);
|
||||
decrease.addEventListener("click", () => setCount(Number(occurrences.value) - 1));
|
||||
increase.addEventListener("click", () => setCount(Number(occurrences.value) + 1));
|
||||
occurrences.addEventListener("change", () => setCount(occurrences.value));
|
||||
|
||||
const stopCompassReading = () => {
|
||||
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
orientationListener = null;
|
||||
compassUnavailableTimeout = null;
|
||||
compass.hidden = true;
|
||||
compassRotation = null;
|
||||
};
|
||||
|
||||
const updateCompass = (heading) => {
|
||||
const targetRotation = -heading;
|
||||
if (compassRotation === null) {
|
||||
compassRotation = targetRotation;
|
||||
compassRose.style.transition = "none";
|
||||
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
||||
// Restore the short rotation animation after the initial reading.
|
||||
compassRose.offsetWidth;
|
||||
compassRose.style.transition = "";
|
||||
} else {
|
||||
const change = ((targetRotation - compassRotation + 540) % 360) - 180;
|
||||
compassRotation += change;
|
||||
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
||||
}
|
||||
compassHeading.textContent = `${displayDegrees(heading)}° · ${cardinalDirection(heading)}`;
|
||||
compass.setAttribute("aria-label", `${t.compassDirection || "Compass direction"} ${displayDegrees(heading)}° ${cardinalDirection(heading)}`);
|
||||
compass.hidden = false;
|
||||
};
|
||||
|
||||
const showCapturedDirection = (heading, accuracy) => {
|
||||
const accuracyText = accuracy === null ? (t.accuracyUnavailable || "Accuracy unavailable") : (t.accuracy || "Accuracy") + ": ±" + displayDegrees(accuracy) + "°";
|
||||
directionStatus.innerHTML = "<strong>" + displayDegrees(heading) + "° · " + cardinalDirection(heading) + "</strong><br>" + accuracyText;
|
||||
captureDirectionButton.textContent = (t.stopCapture || "Stop direction capture");
|
||||
const status = directionStatus();
|
||||
if (status) {
|
||||
status.classList.toggle("manual-direction-panel__status--accuracy", accuracy !== null);
|
||||
if (accuracy === null) {
|
||||
status.textContent = t.accuracyUnavailable || "Accuracy unavailable";
|
||||
} else {
|
||||
const label = document.createElement("span");
|
||||
label.textContent = t.accuracy || "Accuracy";
|
||||
const value = document.createElement("strong");
|
||||
value.textContent = `±${displayDegrees(accuracy)}°`;
|
||||
status.replaceChildren(label, value);
|
||||
}
|
||||
}
|
||||
const button = captureDirectionButton();
|
||||
if (button) button.textContent = (t.stopCapture || "Stop measuring direction");
|
||||
};
|
||||
|
||||
const listenForCompassReading = () => {
|
||||
if (!directionStatus()) return;
|
||||
stopCompassReading();
|
||||
directionStatus.textContent = (t.pointPhone || "Point the top of your phone toward the sound — direction will update live.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "measuring";
|
||||
directionStatus().textContent = (t.pointPhone || "Point the top of your phone toward the sound — direction will update live.");
|
||||
orientationListener = (event) => {
|
||||
const isWebKitCompass = "webkitCompassHeading" in event;
|
||||
const heading = isUsableNumber(event.webkitCompassHeading)
|
||||
@@ -53,39 +147,49 @@
|
||||
directionDegrees.value = heading;
|
||||
directionAccuracy.value = accuracy === null ? "" : accuracy;
|
||||
showCapturedDirection(heading, accuracy);
|
||||
updateCompass(heading);
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
};
|
||||
window.addEventListener("deviceorientation", orientationListener);
|
||||
compassUnavailableTimeout = window.setTimeout(() => {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = (t.captureDirection || "Capture direction");
|
||||
directionStatus.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
const button = captureDirectionButton();
|
||||
const status = directionStatus();
|
||||
if (button) button.textContent = (t.captureDirection || "Start measuring direction");
|
||||
if (status) status.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
||||
}, 15000);
|
||||
};
|
||||
|
||||
const captureDirection = async () => {
|
||||
if (orientationListener) {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = (t.captureAgain || "Capture again");
|
||||
captureDirectionButton().textContent = (t.captureAgain || "Measure again");
|
||||
if (directionPanel()) directionPanel().dataset.state = directionDegrees.value ? "captured" : "ready";
|
||||
return;
|
||||
}
|
||||
directionStatus()?.classList.remove("manual-direction-panel__status--accuracy");
|
||||
if (!window.isSecureContext) {
|
||||
directionStatus.textContent = (t.secureCompass || "Compass capture requires a secure HTTPS connection.");
|
||||
directionStatus().textContent = (t.secureCompass || "Compass capture requires a secure HTTPS connection.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
||||
return;
|
||||
}
|
||||
if (typeof window.DeviceOrientationEvent === "undefined") {
|
||||
directionStatus.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
directionStatus().textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
||||
return;
|
||||
}
|
||||
if (typeof DeviceOrientationEvent.requestPermission === "function") {
|
||||
directionStatus.textContent = (t.compassPermission || "Requesting compass permission…");
|
||||
directionStatus().textContent = (t.compassPermission || "Requesting compass permission…");
|
||||
try {
|
||||
if (await DeviceOrientationEvent.requestPermission(true) !== "granted") {
|
||||
directionStatus.textContent = (t.compassDenied || "Compass permission denied.");
|
||||
if (directionStatus()) directionStatus().textContent = (t.compassDenied || "Compass permission denied.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
directionStatus.textContent = (t.compassDenied || "Compass permission denied.");
|
||||
if (directionStatus()) directionStatus().textContent = (t.compassDenied || "Compass permission denied.");
|
||||
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -93,8 +197,9 @@
|
||||
};
|
||||
|
||||
const submitManualReport = async () => {
|
||||
setCount(occurrences.value);
|
||||
stopCompassReading();
|
||||
manualSubmit.disabled = true;
|
||||
setSubmissionState("submitting", t.sendingReport || "Sending…");
|
||||
if (burstListener?.active) {
|
||||
try {
|
||||
const audio = await burstListener.clipForSubmission();
|
||||
@@ -102,33 +207,54 @@
|
||||
if (audio) data.append("audio", audio);
|
||||
const response = await fetch(manualForm.action, { method: "POST", body: data, credentials: "same-origin" });
|
||||
const html = await response.text();
|
||||
document.querySelector("#manual-submission").outerHTML = html;
|
||||
if (response.ok) burstListener.submissionSucceeded();
|
||||
if (showResponse(html, response.ok)) burstListener.submissionSucceeded();
|
||||
} catch (error) {
|
||||
document.querySelector("#manual-submission").textContent = "Could not send the report. Please try again.";
|
||||
} finally {
|
||||
manualSubmit.disabled = false;
|
||||
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (window.htmx) {
|
||||
try {
|
||||
htmx.ajax("POST", manualForm.action, {
|
||||
source: manualForm,
|
||||
target: "#manual-submission",
|
||||
swap: "outerHTML",
|
||||
});
|
||||
} catch (error) {
|
||||
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
||||
}
|
||||
} else {
|
||||
manualForm.submit();
|
||||
}
|
||||
};
|
||||
|
||||
captureDirectionButton.addEventListener("click", captureDirection);
|
||||
manualForm.addEventListener("click", (event) => {
|
||||
if (event.target.closest("#manual-capture-direction")) captureDirection();
|
||||
if (event.target.closest(".manual-direction-panel__close")) {
|
||||
stopCompassReading();
|
||||
if (compassHome) compassHome.append(compass);
|
||||
}
|
||||
});
|
||||
document.body.addEventListener("htmx:beforeSwap", (event) => {
|
||||
if (event.detail.target?.id === "manual-direction-panel" && compassHome) compassHome.append(compass);
|
||||
});
|
||||
document.body.addEventListener("htmx:afterSwap", (event) => {
|
||||
if (event.detail.target?.id !== "manual-direction-panel") return;
|
||||
if (captureDirectionButton()) directionPanel().querySelector(".manual-direction-panel__copy")?.after(compass);
|
||||
const summary = document.querySelector("#manual-direction-summary");
|
||||
if (summary && directionDegrees.value !== "") {
|
||||
const heading = Number(directionDegrees.value);
|
||||
summary.textContent = `${cardinalDirection(heading)} · ${displayDegrees(heading)}°`;
|
||||
directionPanel().dataset.state = "captured";
|
||||
}
|
||||
});
|
||||
manualSubmit.addEventListener("click", () => {
|
||||
if (manualSubmit.disabled) return;
|
||||
setSubmissionState("submitting", t.requestingLocation || "Requesting your optional location…");
|
||||
if (!navigator.geolocation) {
|
||||
submitManualReport();
|
||||
return;
|
||||
}
|
||||
manualStatus.textContent = (t.requestingLocation || "Requesting your optional location…");
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
latitude.value = position.coords.latitude;
|
||||
@@ -139,7 +265,22 @@
|
||||
{ enableHighAccuracy: false, maximumAge: 300000, timeout: 10000 },
|
||||
);
|
||||
});
|
||||
manualForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (!manualSubmit.disabled) manualSubmit.click();
|
||||
});
|
||||
document.body.addEventListener("htmx:afterRequest", (event) => {
|
||||
if (event.detail.elt === manualForm) manualSubmit.disabled = false;
|
||||
if (event.detail.elt !== manualForm) return;
|
||||
const response = event.detail.xhr;
|
||||
if (!response) {
|
||||
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
||||
} else if (response.status >= 400) {
|
||||
showResponse(response.responseText, false);
|
||||
} else {
|
||||
setSubmissionState("submitted");
|
||||
}
|
||||
});
|
||||
document.body.addEventListener("htmx:sendError", (event) => {
|
||||
if (event.detail.elt === manualForm) setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
||||
});
|
||||
|
||||
|
||||
@@ -1 +1,10 @@
|
||||
document.querySelector("#ntfy-url").addEventListener("input", () => { document.querySelector("#ntfy-test-result").replaceChildren(); });
|
||||
document.querySelector("#ntfy-url")?.addEventListener("input", () => {
|
||||
document.querySelector("#ntfy-test-result")?.replaceChildren();
|
||||
});
|
||||
|
||||
document.addEventListener("click", async (event) => {
|
||||
const button = event.target.closest("[data-copy-sensor-token]");
|
||||
if (!button) return;
|
||||
const token = document.querySelector("#sensor-token")?.textContent;
|
||||
if (token) await navigator.clipboard.writeText(token);
|
||||
});
|
||||
|
||||
@@ -1,9 +1,26 @@
|
||||
.burst-listener { width:min(100%,36rem); margin-top:1rem; }
|
||||
.burst-listener__button,.burst-listener__actions button { min-height:2.75rem; padding:.65rem 1rem; border:1px solid #ffd18c; border-radius:.7rem; color:#fff2df; font:inherit; font-weight:750; background:#39243a; cursor:pointer; }
|
||||
.burst-listener__panel { margin-top:.8rem; padding:1rem; border:1px solid #aa7294; border-radius:.8rem; background:#1b1730; color:#fff2df; }
|
||||
.burst-listener__panel canvas { display:block; width:100%; height:90px; margin:.8rem 0; background:#171225; border-radius:.4rem; }
|
||||
.burst-listener__panel p { margin:.5rem 0 1rem; color:#efc9dc; }
|
||||
.burst-listener__panel audio { width:100%; margin-bottom:1rem; }
|
||||
.burst-listener__actions { display:flex; flex-wrap:wrap; gap:.5rem; }
|
||||
.burst-listener [hidden] { display:none !important; }
|
||||
.burst-listener [role="alert"] { color:#ffd18c; }
|
||||
.manual-report__supporting { padding: 1rem; border: 1px solid #514282; border-radius: 1rem; background: #11152c; }
|
||||
.manual-report__supporting-header { display: flex; align-items: center; gap: .7rem; }
|
||||
.manual-report__microphone { display: grid; width: 2.5rem; height: 2.5rem; flex: none; place-items: center; border-radius: .7rem; background: #2a2051; font-size: 1.3rem; }
|
||||
.burst-listener__state { display: block; margin-top: .15rem; color: #b9addb; font-size: .84rem; }
|
||||
.manual-report__supporting[data-state="listening"] .burst-listener__state { color: #8fe5cc; }
|
||||
.manual-report__supporting[data-state="error"] .burst-listener__state { color: #ffbd9d; }
|
||||
.burst-listener { width: 100%; margin-top: .85rem; }
|
||||
.burst-listener__button, .burst-listener__actions button { min-height: 2.75rem; padding: .65rem 1rem; border: 1px solid #8d77d2; border-radius: .7rem; color: #e8dcff; font: inherit; font-weight: 750; background: #292148; cursor: pointer; }
|
||||
.burst-listener__button { width: 100%; }
|
||||
.burst-listener__panel { color: #f0eaff; }
|
||||
.burst-listener__panel strong { font-size: .92rem; }
|
||||
.burst-listener__panel canvas { display: block; width: 100%; height: 4rem; margin: .7rem 0 .35rem; border-radius: .5rem; background: linear-gradient(90deg, #191738, #241b44); }
|
||||
.burst-listener__panel p { margin: .35rem 0 .75rem; color: #b9addb; font-size: .82rem; }
|
||||
.burst-listener__panel audio { width: 100%; margin-bottom: .75rem; }
|
||||
.burst-listener__actions { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.burst-listener__actions button { flex: 1 1 10rem; }
|
||||
.burst-listener__actions #burst-stop { border-color: #fb9b72; color: #ffd8c4; background: #2e1b31; }
|
||||
.burst-listener [hidden] { display: none !important; }
|
||||
.burst-listener [role="alert"] { margin: .65rem 0 0; color: #ffd1b6; }
|
||||
.burst-listener button:focus-visible { outline: 3px solid #c9b4ff; outline-offset: 3px; }
|
||||
:root[data-theme="light"] .manual-report__supporting { border-color: #d9b4d8; background: #fff8fb; }
|
||||
:root[data-theme="light"] .manual-report__microphone { background: #ead2eb; }
|
||||
:root[data-theme="light"] .burst-listener__state, :root[data-theme="light"] .burst-listener__panel p { color: #694b68; }
|
||||
:root[data-theme="light"] .burst-listener__panel { color: #321d42; }
|
||||
:root[data-theme="light"] .burst-listener__button, :root[data-theme="light"] .burst-listener__actions button { border-color: #b68bb5; color: #321d42; background: #ead2eb; }
|
||||
:root[data-theme="light"] .burst-listener__actions #burst-stop { border-color: #cf7957; color: #71331d; background: #ffe9de; }
|
||||
|
||||
@@ -37,7 +37,8 @@
|
||||
background: #111a31d9;
|
||||
box-shadow: 0 .5rem 1.5rem #03071440;
|
||||
}
|
||||
.fireworks-nav a {
|
||||
.fireworks-nav a,
|
||||
.fireworks-nav button {
|
||||
padding: .5rem .75rem;
|
||||
border-radius: .5rem;
|
||||
color: var(--muted, var(--m, #aab9d8));
|
||||
@@ -45,7 +46,10 @@
|
||||
font-weight: 750;
|
||||
text-decoration: none;
|
||||
}
|
||||
.fireworks-nav a:hover { color: var(--ink, var(--i, #eef3ff)); background: #20345f; }
|
||||
.fireworks-nav form { display: flex; margin: 0; }
|
||||
.fireworks-nav button { border: 0; background: transparent; font: inherit; cursor: pointer; }
|
||||
.fireworks-nav a:hover,
|
||||
.fireworks-nav button:hover { color: var(--ink, var(--i, #eef3ff)); background: #20345f; }
|
||||
.fireworks-nav a[aria-current="page"] { color: var(--ink, var(--i, #eef3ff)); background: #2a3b67; }
|
||||
.theme-toggle--inline {
|
||||
position: static;
|
||||
@@ -59,8 +63,10 @@
|
||||
background: #edf4ff;
|
||||
box-shadow: 0 .45rem 1.25rem rgba(34, 68, 117, .12);
|
||||
}
|
||||
:root[data-theme="light"] .fireworks-nav a { color: #47617f; }
|
||||
:root[data-theme="light"] .fireworks-nav a:hover { color: #234a7b; background: #dceaff; }
|
||||
:root[data-theme="light"] .fireworks-nav a,
|
||||
:root[data-theme="light"] .fireworks-nav button { color: #47617f; }
|
||||
:root[data-theme="light"] .fireworks-nav a:hover,
|
||||
:root[data-theme="light"] .fireworks-nav button:hover { color: #234a7b; background: #dceaff; }
|
||||
:root[data-theme="light"] .fireworks-nav a[aria-current="page"] {
|
||||
color: #173d6a;
|
||||
background: #cfe3ff;
|
||||
@@ -89,6 +95,10 @@
|
||||
.fireworks-header__controls { display: none; flex-basis: 100%; width: 100%; flex-direction: column; align-items: stretch; }
|
||||
.fireworks-menu-toggle[aria-expanded="true"] ~ .fireworks-header__controls { display: flex; }
|
||||
.fireworks-nav { flex-direction: column; }
|
||||
.fireworks-nav a { padding: .75rem; }
|
||||
.fireworks-nav a,
|
||||
.fireworks-nav button { padding: .75rem; }
|
||||
.fireworks-nav form,
|
||||
.fireworks-nav button { width: 100%; }
|
||||
.fireworks-nav button { text-align: left; }
|
||||
.theme-toggle--inline { width: 100%; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
.manual-compass {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
width: 7rem;
|
||||
margin: .6rem 0 0 auto;
|
||||
color: #fff3d7;
|
||||
font-size: .78rem;
|
||||
font-weight: 850;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.manual-compass[hidden] { display: none; }
|
||||
.manual-compass__dial {
|
||||
position: relative;
|
||||
width: 5.75rem;
|
||||
aspect-ratio: 1;
|
||||
border: 2px solid #f2d7a8;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, #342441 0 28%, #211a32 75%);
|
||||
box-shadow: 0 .35rem 1rem #09061566, inset 0 0 0 .25rem #ffffff12;
|
||||
}
|
||||
.manual-compass__rose { position: absolute; inset: 0; transition: transform 120ms ease-out; }
|
||||
.manual-compass__rose span { position: absolute; line-height: 1; }
|
||||
.manual-compass__north { top: .38rem; left: 50%; color: #ff9e78; transform: translateX(-50%); }
|
||||
.manual-compass__east { right: .47rem; top: 50%; transform: translateY(-50%); }
|
||||
.manual-compass__south { bottom: .38rem; left: 50%; transform: translateX(-50%); }
|
||||
.manual-compass__west { left: .47rem; top: 50%; transform: translateY(-50%); }
|
||||
.manual-compass__pointer {
|
||||
position: absolute;
|
||||
top: -.55rem;
|
||||
left: 50%;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-right: .37rem solid transparent;
|
||||
border-bottom: .65rem solid #ffbd62;
|
||||
border-left: .37rem solid transparent;
|
||||
transform: translateX(-50%);
|
||||
filter: drop-shadow(0 .1rem .15rem #160d1b);
|
||||
}
|
||||
.manual-compass__center {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: .5rem;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
background: #ffbd62;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
.manual-compass__heading { margin-top: .5rem; white-space: nowrap; }
|
||||
:root[data-theme="light"] .manual-compass { color: #43243d; }
|
||||
:root[data-theme="light"] .manual-compass__dial { border-color: #996a9b; background: radial-gradient(circle, #f8ebf8 0 28%, #e8d7e9 75%); }
|
||||
:root[data-theme="light"] .manual-compass__east,
|
||||
:root[data-theme="light"] .manual-compass__south,
|
||||
:root[data-theme="light"] .manual-compass__west { color: #43243d; }
|
||||
@media (prefers-reduced-motion: reduce) { .manual-compass__rose { transition: none; } }
|
||||
@@ -0,0 +1,218 @@
|
||||
.manual-report__header {
|
||||
max-width: 42rem;
|
||||
}
|
||||
|
||||
.manual-report { --manual-report-section-gap: 1rem; }
|
||||
|
||||
.manual-report__primary {
|
||||
display: grid;
|
||||
gap: var(--manual-report-section-gap);
|
||||
max-width: 36rem;
|
||||
}
|
||||
|
||||
.manual-report__quantity {
|
||||
padding: 1rem;
|
||||
border: 1px solid #584891;
|
||||
border-radius: 1rem;
|
||||
background: #151932;
|
||||
}
|
||||
|
||||
.manual-report .manual-report__quantity #manual-occurrences {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 3.75rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: #f5f0ff;
|
||||
font-size: clamp(2.25rem, 8vw, 3.5rem);
|
||||
font-weight: 850;
|
||||
text-align: center;
|
||||
background: transparent;
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
.manual-report__quantity #manual-occurrences::-webkit-inner-spin-button,
|
||||
.manual-report__quantity #manual-occurrences::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
|
||||
.manual-report__stepper { display: grid; grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem; align-items: center; gap: .5rem; }
|
||||
.manual-report__stepper button { display: grid; place-items: center; width: 3.5rem; height: 3.5rem; min-height: 0; padding: 0; border: 1px solid #6d54ac; border-radius: 50%; color: #f5f0ff; font: inherit; font-size: 2rem; line-height: 1; background: #302553; cursor: pointer; }
|
||||
.manual-report__stepper button:disabled { opacity: .4; cursor: default; }
|
||||
|
||||
.manual-report .manual-report__primary .manual-direction-panel {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
border-radius: 1rem;
|
||||
background: #1a1739;
|
||||
}
|
||||
.manual-direction-panel[data-state="measuring"] { border-color: #a27cff; }
|
||||
.manual-direction-panel[data-state="captured"] { border-color: #68dba1; }
|
||||
.manual-direction-panel[data-state="unavailable"] { border-color: #d38b7a; }
|
||||
|
||||
.manual-direction-panel__topline { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
|
||||
.manual-direction-panel__summary { margin: .35rem 0 .8rem; color: #f5f0ff; font-weight: 700; }
|
||||
.manual-report .manual-direction-panel__status--accuracy { display: flex; align-items: center; justify-content: space-between; gap: .75rem; margin: .75rem 0; padding: .55rem .75rem; border: 1px solid #5d4d92; border-radius: .7rem; color: #d9cfee; background: #191630; font-size: .85rem; }
|
||||
.manual-direction-panel__status--accuracy strong { color: #f5edff; font-size: 1rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.manual-direction-panel__open, .manual-direction-panel__close { min-height: 2.75rem; border: 1px solid #8d77d2; border-radius: .7rem; color: #e8dcff; font: inherit; font-weight: 750; background: #302553; cursor: pointer; }
|
||||
.manual-direction-panel__open { padding: .5rem .85rem; }
|
||||
.manual-direction-panel__close { min-width: 2.75rem; font-size: 1.4rem; }
|
||||
|
||||
.manual-report #manual-submit {
|
||||
width: 100%;
|
||||
max-width: 36rem;
|
||||
min-height: 4.5rem;
|
||||
margin-top: var(--manual-report-section-gap);
|
||||
}
|
||||
|
||||
.manual-report__submit:disabled { cursor: wait; opacity: .72; }
|
||||
.manual-submission { display: grid; justify-items: center; gap: .5rem; max-width: 36rem; margin-top: 1rem; padding: 1.3rem; border: 1px solid #4caa82; border-radius: 1rem; color: #eafff2; text-align: center; background: #10352e; }
|
||||
.manual-submission__icon { display: grid; width: 3.5rem; height: 3.5rem; place-items: center; border: 2px solid #6ce4a8; border-radius: 50%; color: #eafff2; font-size: 2rem; background: #226c51; }
|
||||
.manual-submission strong { font-size: 1.35rem; }
|
||||
.manual-submission p { margin: 0; line-height: 1.45; }
|
||||
.manual-submission__summary { margin-top: .35rem !important; color: #b2e8cf; font-size: .9rem; }
|
||||
.manual-submission--error { border-color: #d37c6a; color: #fff0e8; background: #3a1c2b; }
|
||||
.manual-submission--error .manual-submission__icon { border-color: #ffac8c; background: #9b493a; }
|
||||
.manual-report__submission:empty { display: none; }
|
||||
|
||||
.manual-report button:focus-visible, .manual-report input:focus-visible { outline: 3px solid #c9b4ff; outline-offset: 3px; }
|
||||
|
||||
.manual-report__supporting {
|
||||
max-width: 36rem;
|
||||
margin-top: var(--manual-report-section-gap);
|
||||
padding-top: 1.25rem;
|
||||
border-top: 1px solid #584891;
|
||||
}
|
||||
|
||||
.manual-report__supporting h3 {
|
||||
margin: 0;
|
||||
color: #d8cffd;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.manual-report__supporting .burst-listener {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] .manual-report__quantity {
|
||||
border-color: #d9b4d8;
|
||||
background: #fff8fb;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] .manual-report__quantity #manual-occurrences { border: 0 !important; color: #321d42 !important; background: transparent !important; }
|
||||
:root[data-theme="light"] .manual-report__stepper button,
|
||||
:root[data-theme="light"] .manual-direction-panel__open,
|
||||
:root[data-theme="light"] .manual-direction-panel__close { color: #321d42; border-color: #b68bb5; background: #ead2eb; }
|
||||
:root[data-theme="light"] .manual-direction-panel__summary { color: #321d42; }
|
||||
:root[data-theme="light"] .manual-report .manual-direction-panel__status--accuracy { border-color: #cfaad1; color: #694b68; background: #fff8fb; }
|
||||
:root[data-theme="light"] .manual-direction-panel__status--accuracy strong { color: #321d42; }
|
||||
:root[data-theme="light"] .manual-submission { border-color: #54a67b; color: #164d34; background: #e8fff2; }
|
||||
:root[data-theme="light"] .manual-submission__icon { color: #fff; }
|
||||
:root[data-theme="light"] .manual-submission__summary { color: #2b6b48; }
|
||||
:root[data-theme="light"] .manual-submission--error { border-color: #ca7d65; color: #743520; background: #fff0e8; }
|
||||
|
||||
:root[data-theme="light"] .manual-report__supporting {
|
||||
border-color: #d9b4d8;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] .manual-report__supporting h3 {
|
||||
color: #492846;
|
||||
}
|
||||
|
||||
@media (max-width: 42rem) {
|
||||
.home-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
body:not(.dashboard-page) { padding: max(1rem, env(safe-area-inset-top, 0px)) max(.5rem, env(safe-area-inset-right, 0px)) max(1rem, env(safe-area-inset-bottom, 0px)) max(.5rem, env(safe-area-inset-left, 0px)); }
|
||||
.home-grid .manual-report, .dashboard-report, .dashboard-report .manual-report { overflow: visible; }
|
||||
.manual-report { padding: 1.25rem; }
|
||||
.dashboard-report .manual-report { padding: 0; }
|
||||
.manual-report__header { padding-right: 2.5rem; }
|
||||
.manual-report form { padding-bottom: calc(5rem + env(safe-area-inset-bottom, 0px)); }
|
||||
.manual-report #manual-submit {
|
||||
position: sticky;
|
||||
bottom: calc(.5rem + env(safe-area-inset-bottom, 0px));
|
||||
z-index: 10;
|
||||
box-shadow: 0 .7rem 1.6rem #070a18b3;
|
||||
}
|
||||
body:has(#manual-occurrences:focus) .manual-report #manual-submit { position: static; }
|
||||
.dashboard-intro { margin-bottom: 1rem; }
|
||||
.dashboard-intro h1 { font-size: clamp(2rem, 8vw, 2.8rem); }
|
||||
.dashboard-intro p:last-child { margin-top: .75rem; font-size: .95rem; line-height: 1.4; }
|
||||
.dashboard-section { margin-top: 1rem; }
|
||||
.dashboard-shell { padding-bottom: calc(2rem + env(safe-area-inset-bottom, 0px)); }
|
||||
.manual-report__stepper { grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem; }
|
||||
}
|
||||
|
||||
@media (max-width: 23.5rem) {
|
||||
.manual-report { padding: 1rem; }
|
||||
.manual-report__quantity { padding: .75rem; }
|
||||
.manual-report__stepper { grid-template-columns: 3rem minmax(0, 1fr) 3rem; gap: .25rem; }
|
||||
.manual-report__stepper button { width: 3rem; height: 3rem; }
|
||||
}
|
||||
|
||||
.manual-report__heading-row { display: flex; align-items: center; gap: .7rem; }
|
||||
.manual-report__fire { flex: none; font-size: clamp(1.8rem, 5vw, 2.5rem); filter: drop-shadow(0 .2rem .65rem #ff703b88); }
|
||||
.manual-report__intro, .dashboard-report .manual-report__intro { margin-bottom: .85rem; }
|
||||
.report-clock {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
max-width: 36rem;
|
||||
margin: 0 0 1rem;
|
||||
padding: .65rem .95rem .7rem;
|
||||
border: 1px solid #69539d;
|
||||
border-radius: .85rem;
|
||||
background: linear-gradient(115deg, #17162d, #10182c);
|
||||
box-shadow: inset 0 1px #ffffff0a;
|
||||
}
|
||||
.report-clock__label { color: #cbbce5; font-size: .66rem; font-weight: 750; letter-spacing: .13em; text-transform: uppercase; }
|
||||
.report-clock__display { display: flex; align-items: end; justify-content: space-between; gap: .75rem; }
|
||||
.report-clock__time {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
color: #ffbf72;
|
||||
font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
|
||||
font-size: clamp(2rem, 9vw, 2.45rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.1;
|
||||
letter-spacing: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-shadow: 0 0 .7rem #ff963b55;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.report-clock__time span { display: inline-block; }
|
||||
.report-clock__time #report-clock-hours, .report-clock__time #report-clock-minutes { width: 2ch; }
|
||||
.report-clock__colon { width: 1ch; flex: none; margin-inline: -.08em; line-height: 1; text-align: center; transform: translateY(-.06em); animation: report-clock-blink 2s steps(1, end) infinite; }
|
||||
.report-clock__now { display: inline-flex; align-items: center; gap: .4rem; flex: none; padding: .2rem .45rem; border: 1px solid #93634d; border-radius: 999px; color: #ffd2a2; font-size: .7rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.report-clock__dot { width: .4rem; height: .4rem; border-radius: 50%; background: #ffab5d; }
|
||||
@keyframes report-clock-blink { 50% { opacity: 0; } }
|
||||
.manual-direction-panel__open { width: 100%; text-align: left; }
|
||||
.manual-direction-panel--open .manual-compass { width: 100%; margin: .5rem auto 1rem; }
|
||||
.manual-direction-panel--open .manual-compass__dial { width: min(100%, 12rem); border-color: #8b67d4; background: radial-gradient(circle, #302054 0 20%, #17132d 70%); box-shadow: 0 0 0 .35rem #6640a228, 0 0 2rem #ac6aff35; }
|
||||
.manual-direction-panel--open .manual-compass__pointer { border-bottom-color: #ff925f; }
|
||||
.manual-direction-panel--open .manual-compass__heading { font-size: 1.1rem; }
|
||||
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit { transition: transform .15s ease, box-shadow .15s ease, filter .15s ease; }
|
||||
.manual-report__stepper button:not(:disabled):active, .manual-direction-panel__open:active, .manual-report__submit:not(:disabled):active { transform: scale(.97); }
|
||||
.manual-report__submit:not(:disabled):hover { filter: brightness(1.05); }
|
||||
.manual-submission--success .manual-submission__icon { animation: manual-confirm .35s ease-out both; }
|
||||
@keyframes manual-confirm { from { transform: scale(.75); opacity: .3; } to { transform: scale(1); opacity: 1; } }
|
||||
|
||||
:root[data-theme="dark"] .home-grid .manual-report,
|
||||
:root[data-theme="dark"] .dashboard-report { border-color: #7256ab; background: radial-gradient(circle at 88% 5%, #58254a55, transparent 13rem), linear-gradient(155deg, #151326, #0d1022 72%); box-shadow: 0 1rem 3rem #02041399; }
|
||||
:root[data-theme="dark"] .manual-report__title { color: #fff8f3; }
|
||||
:root[data-theme="dark"] .manual-report__intro { color: #d6cce4; }
|
||||
:root[data-theme="dark"] .manual-report__quantity { border-color: #514896; background: linear-gradient(145deg, #19183a, #121834); box-shadow: inset 0 0 0 1px #ffffff08; }
|
||||
:root[data-theme="dark"] .home-grid .manual-direction-panel,
|
||||
:root[data-theme="dark"] .dashboard-report .manual-direction-panel { border-color: #59499b; background: linear-gradient(145deg, #211945, #151835); }
|
||||
:root[data-theme="dark"] .manual-report__supporting { border-color: #493d7d; background: linear-gradient(145deg, #15142f, #10162d); }
|
||||
:root[data-theme="dark"] .manual-report__stepper button { box-shadow: 0 .25rem .7rem #07041655; }
|
||||
:root[data-theme="dark"] .manual-report__submit { background: linear-gradient(110deg, #ffc276, #ff7654); box-shadow: 0 .55rem 1.35rem #e2633a4d; }
|
||||
:root[data-theme="dark"] .manual-direction-panel[data-state="measuring"] { border-color: #a27cff; }
|
||||
:root[data-theme="dark"] .manual-direction-panel[data-state="captured"] { border-color: #68dba1; }
|
||||
:root[data-theme="dark"] .manual-direction-panel[data-state="unavailable"] { border-color: #d38b7a; }
|
||||
|
||||
:root[data-theme="light"] .report-clock { border-color: #8b6bab; background: linear-gradient(115deg, #221b37, #182039); }
|
||||
:root[data-theme="light"] .manual-direction-panel--open .manual-compass__dial { background: radial-gradient(circle, #f8ebf8 0 25%, #e8d7e9 75%); }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit { transition: none; }
|
||||
.manual-submission--success .manual-submission__icon { animation: none; }
|
||||
.report-clock__colon { animation: none; opacity: 1; }
|
||||
}
|
||||
@@ -509,3 +509,14 @@
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
.browser-gate { margin: 1rem 0; padding: 1rem; border: 1px solid #e5bb7a; border-radius: .75rem; background: #4d392950; }
|
||||
.browser-gate[hidden] { display: none; }
|
||||
.browser-gate p { margin: .45rem 0 1rem; }
|
||||
.browser-gate-actions { display: flex; gap: .65rem; flex-wrap: wrap; }
|
||||
.browser-gate-actions button { cursor: pointer; }
|
||||
|
||||
.browser-mode { margin: 1rem 0; }
|
||||
.browser-mode__label { display: inline-flex; align-items: center; gap: .55rem; font-weight: 700; cursor: pointer; }
|
||||
.browser-mode__label input { width: 1.1rem; height: 1.1rem; margin: 0; accent-color: #91baff; }
|
||||
.browser-mode p { margin: .35rem 0 0 1.65rem; font-size: .9rem; opacity: .85; }
|
||||
|
||||
@@ -1,11 +1,51 @@
|
||||
body{min-width:320px;margin:0;padding:2rem;color:#eef3ff;font-family:Inter,system-ui,sans-serif;background:#090e1d}.card{width:min(100%,42rem);margin:auto;padding:2rem;border:1px solid #2b3d68;border-radius:1rem;background:#172443}h1{margin-top:0}h2{margin:0}.intro,.help{color:#aab9d8;line-height:1.5}.section{margin-top:2rem;padding-top:1.5rem;border-top:1px solid #2b3d68}label{display:block;margin:.9rem 0 .35rem;font-weight:700}input[type=url]{width:100%;min-height:2.8rem;padding:.65rem;border:1px solid #526b9f;border-radius:.55rem;color:#eef3ff;font:inherit;background:#0a1123}.check{display:flex;gap:.6rem;align-items:center}.check label{margin:0}.button{min-height:2.8rem;margin-top:1rem;padding:.6rem 1rem;border:0;border-radius:.55rem;color:#17132b;font:inherit;font-weight:800;background:#a6ccff;cursor:pointer}.button--secondary{margin-right:.7rem;background:#d8c1fb}.alert,.errorlist{margin-top:1rem;padding:.75rem;border-radius:.55rem}.alert--success{color:#d1fae5;background:#14532d}.alert--error,.errorlist{color:#fee2e2;background:#7f1d1d}.messages{padding:0;list-style:none}@media(max-width:32rem){body{padding:1rem}.card{padding:1.4rem}}
|
||||
.sensor-card{margin:1rem 0;padding:1rem;border:1px solid var(--theme-line);border-radius:.7rem;background:var(--theme-surface-raised)}
|
||||
.sensor-card p{margin:.5rem 0;color:var(--theme-muted)}
|
||||
.sensor-card .button{display:inline-block;text-decoration:none}
|
||||
.sensor-status{display:inline-block;margin-left:.5rem;color:#ef4444;font-weight:700}
|
||||
.sensor-status--online{color:#22c55e}.sensor-status--delayed{color:#f59e0b}
|
||||
input[type=text]{box-sizing:border-box;width:100%;min-height:2.8rem;padding:.65rem;border:1px solid var(--theme-line);border-radius:.55rem;color:var(--theme-ink);font:inherit;background:var(--theme-input)}
|
||||
.token-once{margin:1rem 0;padding:1rem;border:1px solid #f59e0b;border-radius:.7rem;background:var(--theme-surface-raised)}
|
||||
.token-once code{display:block;overflow-wrap:anywhere;margin-top:.7rem;padding:.7rem;border-radius:.4rem;background:var(--theme-input);user-select:all}
|
||||
.button--danger{color:#fff;background:#991b1b}
|
||||
:root[data-theme=light] .sensor-status:not(.sensor-status--online):not(.sensor-status--delayed){color:#b91c1c}
|
||||
/* Settings cards follow the shared blue and violet theme. */
|
||||
*{box-sizing:border-box}
|
||||
body{min-height:100vh;padding:0;color:var(--theme-ink);background:var(--theme-bg)}
|
||||
.settings-shell{width:min(100% - 3.5rem,73.75rem);margin:auto;padding:4rem 0 5rem}
|
||||
.settings-content{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2.25rem 2rem;width:100%}
|
||||
.settings-heading,.messages{grid-column:1/-1}
|
||||
.settings-heading{margin-bottom:0}
|
||||
.eyebrow{margin:0 0 .7rem;color:#9fc5ff;font-size:.74rem;font-weight:800;letter-spacing:.1em;text-transform:uppercase}
|
||||
h1,h2{font-family:Georgia,ui-serif,serif;font-weight:700}
|
||||
h1{margin:0;font-size:clamp(2.3rem,4vw,3.5rem);letter-spacing:-.045em;line-height:1.12}
|
||||
h2{margin:0 0 .45rem;font-size:1.5rem;letter-spacing:-.02em}
|
||||
.intro,.help{margin:.45rem 0 0;color:var(--theme-muted);line-height:1.55}
|
||||
.card{min-width:0;width:100%;margin:0;padding:1.75rem;border:1px solid var(--theme-line);border-radius:1.125rem;background:var(--theme-surface);box-shadow:0 1.125rem 2.8rem #02071429}
|
||||
.settings-form{display:flex;flex-direction:column;gap:1rem}.settings-form h2+.field{margin-top:.4rem}
|
||||
.settings-form>.button[type=submit]{margin-top:auto}
|
||||
.field label{display:block;margin:0 0 .375rem;font-size:.85rem;font-weight:700}
|
||||
.field input,.field select{display:block;width:100%;min-height:2.625rem;padding:.55rem .625rem;border:1px solid var(--theme-line);border-radius:.56rem;color:var(--theme-ink);background:var(--theme-input);font:inherit}
|
||||
.field input:focus-visible,.field select:focus-visible,.button:focus-visible,.switch-control input:focus-visible+.switch-track{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.errorlist{margin:.5rem 0 0;padding:.7rem .9rem;border-radius:.55rem;color:#fee2e2;background:#7f1d1d}
|
||||
.button{display:inline-flex;align-items:center;justify-content:center;width:100%;min-height:2.875rem;margin:0;padding:.65rem 1.2rem;border:1px solid transparent;border-radius:999px;color:#111c30;background:#a6ccff;font:inherit;font-size:.9rem;font-weight:800;text-align:center;text-decoration:none;cursor:pointer;transition:transform .16s ease,box-shadow .16s ease,background .16s ease}
|
||||
.button:hover{transform:translateY(-1px);background:#c0ddff;box-shadow:0 .45rem 1rem #5899f733}
|
||||
.button--secondary{border-color:#6386bd;color:#d7e8ff;background:#223755}.button--secondary:hover{color:#111c30;background:#a6ccff}
|
||||
.switch-row{display:flex;align-items:center;justify-content:space-between;gap:1.125rem;min-height:4.375rem;padding:.8rem 1rem;border:1px solid #3d5879;border-radius:.94rem;background:#1a2a43;cursor:pointer}
|
||||
.switch-row:hover{border-color:#739ad0;background:#203554}.switch-copy{display:grid;gap:.2rem;min-width:0}.switch-copy strong{font-size:.92rem}.switch-copy small{color:var(--theme-muted);font-size:.77rem;line-height:1.35}
|
||||
.switch-control{position:relative;display:block;flex:0 0 3.1875rem;width:3.1875rem;height:1.9375rem}.switch-control input{position:absolute;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}.switch-track{display:block;width:100%;height:100%;border-radius:999px;background:#62758b;pointer-events:none;transition:background .16s ease}
|
||||
.switch-track::after{content:"";position:absolute;top:2px;left:2px;width:27px;height:27px;border-radius:50%;background:#fff;box-shadow:0 1px 4px #0004;transition:transform .16s ease}.switch-control input:checked+.switch-track{background:#34c76a}.switch-control input:checked+.switch-track::after{transform:translateX(20px)}
|
||||
.messages{margin:0;padding:0;list-style:none}.alert{margin:.5rem 0 0;padding:.75rem 1rem;border-radius:.65rem;line-height:1.45}#ntfy-test-result:empty{display:none}
|
||||
.sensor-list__intro{padding-bottom:1.25rem;border-bottom:1px solid var(--theme-line)}.sensor-list__intro .eyebrow{margin-bottom:.35rem}
|
||||
.sensor-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:1.5rem 0}.sensor-card{display:flex;flex-direction:column;min-width:0;margin:0;padding:1.3rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}
|
||||
.sensor-card__heading{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem 1rem}.sensor-card__heading h3{margin:0;font-family:Georgia,ui-serif,serif;font-size:1.25rem;overflow-wrap:anywhere}.sensor-card .sensor-status{display:inline-flex;padding:.32rem .65rem;border-radius:999px;background:var(--theme-input);font-size:.78rem;white-space:nowrap}
|
||||
.sensor-status{color:var(--theme-muted);font-weight:700}.sensor-status--online{color:#64dca0}.sensor-status--delayed{color:#f5c46b}.sensor-status--offline{color:#f49aa7}
|
||||
.sensor-access{align-self:flex-start;margin-top:.7rem;padding:.25rem .55rem;border:1px solid #3d806b;border-radius:999px;color:#8be0b9;font-size:.72rem;font-weight:800}.sensor-access--off{border-color:#806b75;color:#d4b9c5}
|
||||
.sensor-card__facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem 1rem;margin:1.3rem 0}.sensor-card__facts div{min-width:0}.sensor-card__facts dt{margin-bottom:.25rem;color:var(--theme-muted);font-size:.75rem;font-weight:700}.sensor-card__facts dd{margin:0;font-size:.88rem;font-weight:600;overflow-wrap:anywhere}.sensor-card__facts code{font:inherit}.sensor-card__facts div:last-child{grid-column:1/-1}
|
||||
.sensor-card .button{margin-top:auto}.sensor-empty{grid-column:1/-1;margin:0;padding:1.5rem;border:1px dashed var(--theme-line);border-radius:1rem;color:var(--theme-muted);text-align:center;line-height:1.5}
|
||||
.sensor-form{margin-top:1.5rem;padding:1.3rem;border:1px dashed #6386bd;border-radius:1rem;background:var(--theme-surface-raised)}.sensor-form h3{margin:0;font-family:Georgia,ui-serif,serif;font-size:1.2rem}.sensor-form .help{margin-top:.3rem}.sensor-form__controls{display:grid;grid-template-columns:minmax(0,1fr) 11rem;align-items:end;gap:1rem}
|
||||
.settings-content>#sensor-card{grid-column:1/-1}
|
||||
.sensor-detail__header{display:flex;align-items:start;justify-content:space-between;gap:1rem;padding-bottom:1.2rem;border-bottom:1px solid var(--theme-line)}.sensor-detail__header .eyebrow{margin-bottom:.35rem}.sensor-detail__header h2{margin:0;font-size:clamp(1.6rem,3vw,2rem);overflow-wrap:anywhere}.sensor-close{display:inline-flex;align-items:center;gap:.35rem;flex:none;padding:.45rem .85rem;border:1px solid var(--theme-line);border-radius:999px;color:var(--theme-ink);background:var(--theme-surface-raised);font-size:.85rem;font-weight:700;text-decoration:none}.sensor-close:hover{border-color:#86ade0;background:#2b4266}.sensor-close:focus-visible{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.sensor-detail__overview{margin:1.25rem 0 1.5rem;padding:1.2rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}.sensor-detail__overview>.sensor-status{display:inline-flex;margin:0 0 1rem;padding:.35rem .7rem;border-radius:999px;background:var(--theme-input);font-size:.85rem}
|
||||
.sensor-detail__facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem 1.5rem;margin:0}.sensor-detail__facts div{min-width:0}.sensor-detail__facts dt{margin:0 0 .3rem;color:var(--theme-muted);font-size:.78rem;font-weight:700}.sensor-detail__facts dd{margin:0;overflow-wrap:anywhere;font-size:.92rem;font-weight:600}.sensor-detail__facts code{font:inherit}
|
||||
.sensor-detail__actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.sensor-detail__section{display:flex;flex-direction:column;min-width:0;padding:1.2rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}.sensor-detail__section h3{margin:0 0 .35rem;font-family:Georgia,ui-serif,serif;font-size:1.15rem}.sensor-detail__section>.help{margin:0}.sensor-detail__section form{display:flex;flex:1;flex-direction:column;gap:.8rem;margin-top:1rem}.sensor-detail__section form .button{margin-top:auto}.sensor-detail__section .field{width:100%}.sensor-detail__section:last-child{border-color:#945f68;background:#392432}.sensor-detail__section:last-child .button--danger{border-color:#dc7b89;color:#fff;background:#a43c50}.sensor-detail__section:last-child .button--danger:hover{background:#bd4a60}
|
||||
.sensor-confirm{display:flex;align-items:start;gap:.6rem;line-height:1.4;font-size:.82rem;cursor:pointer}.sensor-confirm input{flex:none;width:1.1rem;height:1.1rem;margin:.15rem 0 0;accent-color:#84baff}.sensor-confirm input:focus-visible{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.sensor-messages{margin-top:1rem}.token-once{margin:1.25rem 0;padding:1rem;border:1px solid #e4ad55;border-radius:.8rem;background:var(--theme-surface-raised)}.token-once code{display:block;margin:.75rem 0;padding:.7rem;border-radius:.5rem;background:var(--theme-input);overflow-wrap:anywhere;user-select:all}
|
||||
.button--danger{color:#fff;background:#991b1b}.button--danger:hover{color:#fff;background:#b91c1c}
|
||||
:root[data-theme=light] .eyebrow{color:#23578d}:root[data-theme=light] .card{box-shadow:0 1.125rem 2.8rem #20365c1a}:root[data-theme=light] .button:not(.button--secondary):not(.button--danger){color:#fff;background:#245b96}:root[data-theme=light] .button:not(.button--secondary):not(.button--danger):hover{background:#174877}:root[data-theme=light] .button--secondary{border-color:#9cc0ed;color:#245b96;background:#edf4ff}:root[data-theme=light] .button--secondary:hover{color:#fff;background:#245b96}:root[data-theme=light] .switch-row{border-color:#d4e0ef;background:#f2f7fe}:root[data-theme=light] .switch-row:hover{border-color:#9cc0ed;background:#eaf3ff}:root[data-theme=light] .switch-track{background:#c1cbd8}:root[data-theme=light] .switch-control input:checked+.switch-track{background:#34c76a}
|
||||
:root[data-theme=light] .sensor-close:hover{background:#e4efff}:root[data-theme=light] .sensor-detail__section:last-child{border-color:#ecc6cb;background:#fff5f6}:root[data-theme=light] .sensor-detail__section:last-child .button--danger{color:#fff;background:#a43c50}
|
||||
:root[data-theme=light] .sensor-access{border-color:#b8dfca;color:#256147;background:#ecf8f0}:root[data-theme=light] .sensor-access--off{border-color:#dbcbd3;color:#80556a;background:#fbf4f7}:root[data-theme=light] .sensor-form{border-color:#9cc0ed}
|
||||
@media(max-width:48rem){.settings-content{grid-template-columns:minmax(0,1fr)}.settings-shell{width:min(100% - 2.25rem,73.75rem);padding:2.5rem 0 3rem}}
|
||||
@media(max-width:48rem){.sensor-detail__actions,.sensor-list{grid-template-columns:minmax(0,1fr)}}
|
||||
@media(max-width:30rem){.sensor-detail__facts{grid-template-columns:minmax(0,1fr)}.sensor-detail__header{align-items:start}.sensor-close span{display:none}}
|
||||
@media(max-width:35rem){.card{padding:1.25rem}.sensor-form__controls{grid-template-columns:minmax(0,1fr)}}
|
||||
@media(prefers-reduced-motion:reduce){.button,.switch-track,.switch-track::after{transition:none}.button:hover{transform:none}}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
function fixture() {
|
||||
const dom = new JSDOM(`<!doctype html><html><body>
|
||||
<script id="boomcast-browser-config" type="application/json">{"browserProcessingBeta":true,"policyUrl":"/policy","policyVersion":1}</script>
|
||||
<form class="upload-form" action="/classify">
|
||||
<label id="drop-zone"><input id="audio-file" name="audio" type="file" accept="audio/*,.wav" required><span id="upload-progress-circle"><span id="upload-icon-content"></span></span><span id="file-name"></span></label>
|
||||
<input id="browser-processing-toggle" type="checkbox">
|
||||
<button type="submit">Submit</button><button class="upload-cancel" type="button" hidden>Cancel</button>
|
||||
<section id="browser-gate" hidden><strong id="browser-gate-title"></strong><p id="browser-gate-message"></p><button id="browser-gate-choose" type="button"></button><button id="browser-gate-override" type="button"></button></section>
|
||||
<section id="classification-results"></section>
|
||||
</form><p id="upload-status"></p></body></html>`, { url: "https://example.test/" });
|
||||
const { window } = dom;
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
window.BOOMCAST_I18N = {};
|
||||
const requests = [];
|
||||
class MockXHR {
|
||||
upload = { addEventListener() {} };
|
||||
addEventListener() {}
|
||||
open() {}
|
||||
send(data) { requests.push(data); }
|
||||
}
|
||||
const originals = Object.fromEntries(["window", "document", "FormData", "XMLHttpRequest", "DOMParser", "fetch"].map((name) => [name, globalThis[name]]));
|
||||
Object.assign(globalThis, { window, document: window.document, FormData: window.FormData, XMLHttpRequest: MockXHR, DOMParser: window.DOMParser });
|
||||
const form = window.document.querySelector("form");
|
||||
form.reportValidity = () => true;
|
||||
const input = window.document.querySelector("#audio-file");
|
||||
const audio = new window.File(["audio"], "clip.wav", { type: "audio/wav" });
|
||||
Object.defineProperty(input, "files", { configurable: true, value: [audio] });
|
||||
const toggle = window.document.querySelector("#browser-processing-toggle");
|
||||
return { window, form, input, audio, toggle, requests, restore: () => {
|
||||
for (const [name, value] of Object.entries(originals)) {
|
||||
if (value === undefined) delete globalThis[name];
|
||||
else globalThis[name] = value;
|
||||
}
|
||||
dom.window.close();
|
||||
} };
|
||||
}
|
||||
|
||||
test("admin ON with user toggle OFF uploads the original audio without policy fetch", async () => {
|
||||
const ui = fixture();
|
||||
let fetches = 0;
|
||||
globalThis.fetch = () => { fetches += 1; throw new Error("browser policy must not load"); };
|
||||
try {
|
||||
await import("../src/scripts/audio-upload.js?mode=server");
|
||||
assert.equal(ui.toggle.checked, false);
|
||||
ui.input.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
|
||||
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, false);
|
||||
ui.form.dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
|
||||
assert.equal(fetches, 0);
|
||||
assert.equal(ui.requests.length, 1);
|
||||
assert.equal(ui.requests[0].get("audio").name, "clip.wav");
|
||||
assert.equal(ui.requests[0].has("browser_processing_metadata"), false);
|
||||
} finally { ui.restore(); }
|
||||
});
|
||||
|
||||
test("switching browser mode off invalidates a policy job and restores server submission", async () => {
|
||||
const ui = fixture();
|
||||
let resolveFetch;
|
||||
let fetches = 0;
|
||||
globalThis.fetch = () => { fetches += 1; return new Promise((resolve) => { resolveFetch = resolve; }); };
|
||||
try {
|
||||
await import("../src/scripts/audio-upload.js?mode=switch");
|
||||
ui.input.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
|
||||
ui.toggle.checked = true;
|
||||
ui.toggle.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
|
||||
for (let i = 0; i < 30 && !resolveFetch; i += 1) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
assert.equal(fetches, 1);
|
||||
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, true);
|
||||
ui.toggle.checked = false;
|
||||
ui.toggle.dispatchEvent(new ui.window.Event("change", { bubbles: true }));
|
||||
resolveFetch({ ok: true, json: async () => ({ browser_processing_beta_enabled: true, version: 1 }) });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.equal(ui.input.accept, "audio/*,.wav");
|
||||
assert.equal(ui.form.querySelector('button[type="submit"]').disabled, false);
|
||||
assert.equal(ui.window.document.querySelector("#browser-gate").hidden, true);
|
||||
ui.form.dispatchEvent(new ui.window.Event("submit", { bubbles: true, cancelable: true }));
|
||||
assert.equal(ui.requests.length, 1);
|
||||
assert.equal(ui.requests[0].get("audio").name, "clip.wav");
|
||||
assert.equal(ui.requests[0].has("browser_processing_metadata"), false);
|
||||
} finally { ui.restore(); }
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { BrowserSubmissionGate } from "../src/scripts/browser-submission-gate.js";
|
||||
import { BrowserSubmissionProcessor } from "../src/scripts/browser-submission-processor.js";
|
||||
|
||||
const policy = { whitelist: ["Fireworks"], privacy_sensitive_speech: ["Speech"], thresholds: { relevance: .5, speech: .5 } };
|
||||
|
||||
test("whitelist match allows normal submission even when speech is present", () => {
|
||||
const decision = BrowserSubmissionGate.evaluate([{ class: "Fireworks", score: .8 }, { class: "Speech", score: .9 }], policy);
|
||||
assert.equal(decision.result, "whitelist_match");
|
||||
assert.equal(decision.speechDetected, true);
|
||||
});
|
||||
|
||||
test("speech without relevance and irrelevant audio require explicit override", () => {
|
||||
assert.equal(BrowserSubmissionGate.evaluate([{ class: "Speech", score: .9 }], policy).result, "speech_only");
|
||||
assert.equal(BrowserSubmissionGate.evaluate([{ class: "Music", score: .9 }], policy).result, "no_match");
|
||||
});
|
||||
|
||||
test("audio and video-derived WAV use the same gate; audio never calls FFmpeg", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) });
|
||||
let extractionCalls = 0;
|
||||
let classificationCalls = 0;
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 },
|
||||
async () => { extractionCalls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); },
|
||||
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { classificationCalls += 1; return [{ class: "Speech", score: .9 }]; } },
|
||||
);
|
||||
processor.setEnabled(true);
|
||||
try {
|
||||
assert.equal((await processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }))).gate, "speech_only");
|
||||
assert.equal(extractionCalls, 0);
|
||||
assert.equal((await processor.prepare(new File(["video"], "clip.mp4", { type: "video/mp4" }))).gate, "speech_only");
|
||||
assert.equal(extractionCalls, 1);
|
||||
assert.equal(classificationCalls, 2);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
|
||||
test("local classifier failure restores ordinary server upload", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) });
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null,
|
||||
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { throw new Error("offline"); } },
|
||||
);
|
||||
const audio = new File(["audio"], "audio.wav", { type: "audio/wav" });
|
||||
processor.setEnabled(true);
|
||||
try {
|
||||
const result = await processor.prepare(audio);
|
||||
assert.equal(result.file, audio);
|
||||
assert.equal(result.gate, "unavailable");
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
|
||||
test("aborted classification never yields a gate decision", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) });
|
||||
const controller = new AbortController();
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null,
|
||||
{ prepareAudio: async () => new Float32Array(16000), classify: async () => { controller.abort(); return [{ class: "Fireworks", score: .9 }]; } },
|
||||
);
|
||||
processor.setEnabled(true);
|
||||
try {
|
||||
await assert.rejects(processor.prepare(new File(["audio"], "audio.wav", { type: "audio/wav" }), { signal: controller.signal }));
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
|
||||
test("replacing a classification cancels the old result and keeps the new file", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ ...policy, browser_processing_beta_enabled: true, version: 1 }) });
|
||||
let firstStarted;
|
||||
const started = new Promise((resolve) => { firstStarted = resolve; });
|
||||
let finishFirst;
|
||||
let calls = 0;
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 }, null,
|
||||
{ prepareAudio: async () => new Float32Array(16000), classify: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
firstStarted();
|
||||
return new Promise((resolve) => { finishFirst = resolve; });
|
||||
}
|
||||
return [{ class: "Fireworks", score: .9 }];
|
||||
} },
|
||||
);
|
||||
processor.setEnabled(true);
|
||||
const firstFile = new File(["a"], "first.wav", { type: "audio/wav" });
|
||||
const secondFile = new File(["b"], "second.wav", { type: "audio/wav" });
|
||||
try {
|
||||
const first = processor.process(firstFile);
|
||||
await started;
|
||||
const second = await processor.process(secondFile);
|
||||
assert.equal(second.file, secondFile);
|
||||
assert.equal(second.gate, "whitelist_match");
|
||||
finishFirst([{ class: "Speech", score: .9 }]);
|
||||
await assert.rejects(first);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
@@ -10,9 +10,10 @@ test("disabled beta returns the original file without loading policy", async ()
|
||||
globalThis.fetch = () => { throw new Error("fetch must not run"); };
|
||||
try {
|
||||
const processor = new BrowserSubmissionProcessor({ browserProcessingBeta: false });
|
||||
processor.setEnabled(true);
|
||||
assert.equal(processor.isEnabled(), false);
|
||||
assert.equal(processor.canProcess(file), false);
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
@@ -23,6 +24,7 @@ test("enabled shell checks current server policy and never claims processing occ
|
||||
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 });
|
||||
processor.setEnabled(true);
|
||||
const result = await processor.prepare(file);
|
||||
assert.equal(result.file, file);
|
||||
assert.equal(result.metadata.browser_processing_used, false);
|
||||
@@ -35,11 +37,12 @@ test("enabled shell checks current server policy and never claims processing occ
|
||||
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 });
|
||||
processor.setEnabled(true);
|
||||
try {
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({ browser_processing_beta_enabled: false, version: 1 }) });
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" });
|
||||
globalThis.fetch = async () => { throw new Error("offline"); };
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null });
|
||||
assert.deepEqual(await processor.prepare(file), { file, metadata: null, gate: "unavailable" });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
@@ -53,7 +56,9 @@ test("video routing is gated and audio never invokes FFmpeg", async () => {
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 },
|
||||
async () => { calls += 1; return new File(["wav"], "clip.wav", { type: "audio/wav" }); },
|
||||
{ prepareAudio: async () => new Float32Array(16000), classify: async () => [{ class: "Fireworks", score: .9 }] },
|
||||
);
|
||||
processor.setEnabled(true);
|
||||
await processor.prepare(file);
|
||||
assert.equal(calls, 0);
|
||||
const video = { type: "video/mp4", size: 123, name: "clip.mp4" };
|
||||
@@ -62,7 +67,7 @@ test("video routing is gated and audio never invokes FFmpeg", async () => {
|
||||
assert.equal(result.file.type, "audio/wav");
|
||||
assert.equal(result.metadata.browser_processing_used, true);
|
||||
const disabled = new BrowserSubmissionProcessor({ browserProcessingBeta: false }, async () => { throw new Error("must not run"); });
|
||||
assert.deepEqual(await disabled.prepare(video), { file: video, metadata: null });
|
||||
assert.deepEqual(await disabled.prepare(video), { file: video, metadata: null, gate: "unavailable" });
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
@@ -76,8 +81,32 @@ test("video conversion failure rejects instead of falling back to original video
|
||||
{ browserProcessingBeta: true, policyUrl: "/browser-policy/", policyVersion: 1 },
|
||||
async () => { throw new Error("decode failed"); },
|
||||
);
|
||||
processor.setEnabled(true);
|
||||
await assert.rejects(processor.prepare({ type: "video/mp4", name: "bad.mp4" }), /decode failed/);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test("admin ON and user toggle OFF bypasses policy, FFmpeg and TensorFlow", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = () => { throw new Error("policy must not load"); };
|
||||
const audio = new File(["audio"], "clip.wav", { type: "audio/wav" });
|
||||
const processor = new BrowserSubmissionProcessor(
|
||||
{ browserProcessingBeta: true, policyUrl: "/policy", policyVersion: 1 },
|
||||
async () => { throw new Error("FFmpeg must not load"); },
|
||||
{ prepareAudio: async () => { throw new Error("audio preparation must not run"); },
|
||||
classify: async () => { throw new Error("TensorFlow must not load"); } },
|
||||
);
|
||||
try {
|
||||
assert.equal(processor.isAvailable(), true);
|
||||
assert.equal(processor.isEnabled(), false);
|
||||
assert.deepEqual(await processor.process(audio), { file: audio, metadata: null, gate: "unavailable" });
|
||||
processor.setEnabled(true);
|
||||
assert.equal(processor.isEnabled(), true);
|
||||
processor.setEnabled(false);
|
||||
assert.equal(processor.isEnabled(), false);
|
||||
assert.deepEqual(await processor.process(audio), { file: audio, metadata: null, gate: "unavailable" });
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { BrowserYamnetClassifier } from "../src/scripts/browser-yamnet-classifier.js";
|
||||
|
||||
test("YAMNet peak scores are mapped and all owned resources are disposed", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const disposed = [];
|
||||
const values = new Float32Array(2 * 521);
|
||||
values[0] = .4;
|
||||
values[521] = .9;
|
||||
const output = { shape: [2, 521], data: async () => values, dispose: () => disposed.push("output") };
|
||||
const model = { executeAsync: async () => [output], dispose: () => disposed.push("model") };
|
||||
const tf = {
|
||||
ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }),
|
||||
loadGraphModel: async () => model,
|
||||
tensor1d: () => ({ dispose: () => disposed.push("input") }),
|
||||
};
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ["Fireworks", ...Array(520).fill("Other")] });
|
||||
try {
|
||||
const predictions = await BrowserYamnetClassifier.classify(new Float32Array(16000), {
|
||||
modelUrl: "/static/browser-yamnet/model.json", classMapUrl: "/static/browser-yamnet/yamnet_class_map.json",
|
||||
loadTensorFlow: async () => tf,
|
||||
});
|
||||
assert.equal(predictions[0].class, "Fireworks");
|
||||
assert.equal(predictions[0].score, values[521]);
|
||||
assert.equal(predictions[0].timeSeconds, .48);
|
||||
assert.deepEqual(disposed, ["input", "output", "model"]);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
|
||||
test("model failure still disposes the loaded model", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let disposed = false;
|
||||
const tf = {
|
||||
ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }),
|
||||
loadGraphModel: async () => ({ dispose: () => { disposed = true; } }),
|
||||
};
|
||||
globalThis.fetch = async () => ({ ok: false });
|
||||
try {
|
||||
await assert.rejects(BrowserYamnetClassifier.classify(new Float32Array(16000), {
|
||||
modelUrl: "/model.json", classMapUrl: "/map.json", loadTensorFlow: async () => tf,
|
||||
}));
|
||||
assert.equal(disposed, true);
|
||||
} finally { globalThis.fetch = originalFetch; }
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
test("compass stays hidden until permission and a heading, then rotates and hides when stopped", async () => {
|
||||
const dom = new JSDOM(`<!doctype html><html><body>
|
||||
<time id="manual-report-time"><span id="report-clock-hours">--</span><span class="report-clock__colon">:</span><span id="report-clock-minutes">--</span></time>
|
||||
<form id="manual-report-form" action="/submit">
|
||||
<input id="manual-latitude"><input id="manual-longitude">
|
||||
<input id="manual-direction-degrees"><input id="manual-direction-accuracy">
|
||||
<button id="manual-decrease" type="button"></button><input id="manual-occurrences" value="1"><button id="manual-increase" type="button"></button>
|
||||
<div id="manual-direction-panel" hidden><button id="manual-capture-direction" type="button"></button><div id="manual-direction-status"></div></div>
|
||||
<button id="manual-submit" type="button"></button>
|
||||
<button id="burst-start" type="button"></button><div id="burst-panel"></div><strong id="burst-heading"></strong>
|
||||
<div id="burst-detail"></div><canvas id="burst-waveform"></canvas><audio id="burst-preview"></audio>
|
||||
<button id="burst-resume" type="button"></button><button id="burst-discard" type="button"></button>
|
||||
<button id="burst-stop" type="button"></button><p id="burst-error"></p>
|
||||
</form>
|
||||
<div id="manual-submission"></div>
|
||||
<div id="manual-compass-home"><div id="manual-compass" hidden><div id="manual-compass-rose"></div><span id="manual-compass-heading"></span></div></div>
|
||||
</body></html>`, { url: "https://example.test/" });
|
||||
const { window } = dom;
|
||||
Object.defineProperty(window, "isSecureContext", { value: true });
|
||||
let resolvePermission;
|
||||
class MockOrientation {}
|
||||
MockOrientation.requestPermission = () => new Promise((resolve) => { resolvePermission = resolve; });
|
||||
window.DeviceOrientationEvent = MockOrientation;
|
||||
let submissions = 0;
|
||||
window.htmx = { ajax: () => { submissions++; } };
|
||||
const previous = Object.fromEntries(["window", "document", "navigator", "DeviceOrientationEvent", "htmx", "DOMParser"].map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
for (const [key, value] of Object.entries({ window, document: window.document, navigator: window.navigator, DeviceOrientationEvent: MockOrientation, htmx: window.htmx, DOMParser: window.DOMParser })) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
try {
|
||||
await import("../src/scripts/manual-report.js?compass=visual");
|
||||
const reportTime = window.document.querySelector("#manual-report-time");
|
||||
assert.match(reportTime.getAttribute("aria-label"), /^\d{2}:\d{2}$/);
|
||||
assert.equal(reportTime.querySelector(".report-clock__colon").textContent, ":");
|
||||
assert.match(reportTime.dateTime, /^\d{4}-\d{2}-\d{2}T/);
|
||||
const compass = window.document.querySelector("#manual-compass");
|
||||
const rose = window.document.querySelector("#manual-compass-rose");
|
||||
const button = window.document.querySelector("#manual-capture-direction");
|
||||
assert.equal(compass.hidden, true);
|
||||
button.click();
|
||||
assert.equal(compass.hidden, true);
|
||||
resolvePermission("granted");
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const reading = (heading, accuracy) => {
|
||||
const event = new window.Event("deviceorientation");
|
||||
Object.defineProperty(event, "webkitCompassHeading", { value: heading });
|
||||
if (accuracy !== undefined) Object.defineProperty(event, "webkitCompassAccuracy", { value: accuracy });
|
||||
window.dispatchEvent(event);
|
||||
};
|
||||
reading(359);
|
||||
assert.equal(compass.hidden, false);
|
||||
assert.equal(rose.style.transform, "rotate(-359deg)");
|
||||
reading(1, 14.8);
|
||||
assert.equal(rose.style.transform, "rotate(-361deg)");
|
||||
assert.equal(window.document.querySelector("#manual-direction-degrees").value, "1");
|
||||
assert.equal(window.document.querySelector("#manual-compass-heading").textContent, "1° · North");
|
||||
assert.equal(window.document.querySelector("#manual-direction-status").textContent, "Accuracy±14.8°");
|
||||
button.click();
|
||||
assert.equal(compass.hidden, true);
|
||||
window.document.querySelector("#manual-increase").click();
|
||||
assert.equal(window.document.querySelector("#manual-occurrences").value, "2");
|
||||
window.document.querySelector("#manual-decrease").click();
|
||||
assert.equal(window.document.querySelector("#manual-occurrences").value, "1");
|
||||
|
||||
window.document.querySelector("#manual-direction-panel").outerHTML = '<div id="manual-direction-panel"><p class="manual-direction-panel__copy"></p><button id="manual-capture-direction"></button><div id="manual-direction-status"></div></div>';
|
||||
const opened = window.document.querySelector("#manual-direction-panel");
|
||||
window.document.body.dispatchEvent(new window.CustomEvent("htmx:afterSwap", { detail: { target: opened } }));
|
||||
assert.equal(compass.parentElement.id, "manual-direction-panel");
|
||||
window.document.body.dispatchEvent(new window.CustomEvent("htmx:beforeSwap", { detail: { target: opened } }));
|
||||
assert.equal(compass.parentElement.id, "manual-compass-home");
|
||||
opened.outerHTML = '<div id="manual-direction-panel"><p id="manual-direction-summary">Not captured</p></div>';
|
||||
const closed = window.document.querySelector("#manual-direction-panel");
|
||||
window.document.body.dispatchEvent(new window.CustomEvent("htmx:afterSwap", { detail: { target: closed } }));
|
||||
assert.equal(window.document.querySelector("#manual-direction-summary").textContent, "North · 1°");
|
||||
|
||||
const submit = window.document.querySelector("#manual-submit");
|
||||
const form = window.document.querySelector("#manual-report-form");
|
||||
submit.click();
|
||||
submit.click();
|
||||
assert.equal(submissions, 1);
|
||||
assert.equal(submit.disabled, true);
|
||||
window.document.querySelector("#manual-submission").outerHTML = '<div id="manual-submission" data-result="success">Received</div>';
|
||||
window.document.body.dispatchEvent(new window.CustomEvent("htmx:afterRequest", { detail: { elt: form, xhr: { status: 200 } } }));
|
||||
assert.equal(submit.disabled, false);
|
||||
submit.click();
|
||||
assert.equal(submissions, 2);
|
||||
window.document.body.dispatchEvent(new window.CustomEvent("htmx:afterRequest", { detail: { elt: form, xhr: { status: 400, responseText: '<div id="manual-submission" data-result="error">Try again</div>' } } }));
|
||||
assert.equal(window.document.querySelector("#manual-submission").dataset.result, "error");
|
||||
assert.equal(submit.disabled, false);
|
||||
} finally {
|
||||
for (const [key, descriptor] of Object.entries(previous)) {
|
||||
if (descriptor === undefined) delete globalThis[key];
|
||||
else Object.defineProperty(globalThis, key, descriptor);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -3,7 +3,7 @@
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>{% trans "Welcome · 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/home.js" %}
|
||||
@@ -11,6 +11,7 @@
|
||||
<body>
|
||||
{% 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 %}
|
||||
<div class="home-grid">
|
||||
{% include "fireworks_detect/includes/manual_report_form.html" %}
|
||||
<main class="welcome-card">
|
||||
<div class="brand"><span class="brand-mark">✦</span> Sound Signal</div>
|
||||
<p class="eyebrow">{% trans "Control room" %}</p>
|
||||
@@ -24,7 +25,6 @@
|
||||
<span class="hint">{% trans "Audio analysis · Sensor map" %}</span>
|
||||
</div>
|
||||
</main>
|
||||
{% include "fireworks_detect/includes/manual_report_form.html" %}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Binary file not shown.
@@ -924,9 +924,20 @@ msgid "Notifications / ntfy"
|
||||
msgstr "Meldingen / ntfy"
|
||||
|
||||
#: members/templates/members/user_settings.html:30
|
||||
msgid ""
|
||||
"Use a topic URL from your ntfy server. Test the current URL before saving it."
|
||||
msgstr "Gebruik een onderwerp-URL van je ntfy-server. Test de URL voordat je hem opslaat."
|
||||
msgid "Use a topic URL from your ntfy server. Test the URL before enabling notifications."
|
||||
msgstr "Gebruik een onderwerp-URL van je ntfy-server. Test de URL voordat je meldingen inschakelt."
|
||||
|
||||
msgid "Pending events"
|
||||
msgstr "Wachtende meldingen"
|
||||
|
||||
msgid "%(count)d manual"
|
||||
msgstr "%(count)d handmatig"
|
||||
|
||||
msgid "%(count)d sensor"
|
||||
msgstr "%(count)d sensor"
|
||||
|
||||
msgid "%(count)d new Pending event(s): %(sources)s."
|
||||
msgstr "%(count)d nieuwe wachtende melding(en): %(sources)s."
|
||||
|
||||
#: members/templates/members/user_settings.html:31
|
||||
msgid "Topic URL"
|
||||
@@ -1215,3 +1226,180 @@ msgstr "Classificatie opgeslagen. Deze melding blijft openstaan."
|
||||
|
||||
msgid "Preparing recording…"
|
||||
msgstr "Opname voorbereiden…"
|
||||
|
||||
msgid "Checking recording…"
|
||||
msgstr "Opname controleren…"
|
||||
|
||||
msgid "Ready to submit."
|
||||
msgstr "Klaar om te verzenden."
|
||||
|
||||
msgid "Extracting audio from video…"
|
||||
msgstr "Audio uit video halen…"
|
||||
|
||||
msgid "Could not extract audio from this video. Please choose an audio recording."
|
||||
msgstr "Audio uit deze video halen is niet gelukt. Kies een audio-opname."
|
||||
|
||||
msgid "Preparation cancelled. Choose a recording to continue."
|
||||
msgstr "Voorbereiding geannuleerd. Kies een opname om verder te gaan."
|
||||
|
||||
msgid "Video processed on this device. Only extracted audio will be sent if you submit."
|
||||
msgstr "De video is op dit apparaat verwerkt. Alleen de audio wordt verzonden als je de opname indient."
|
||||
|
||||
msgid "This recording appears to contain speech, but no relevant sound was detected."
|
||||
msgstr "Deze opname lijkt spraak te bevatten, maar er is geen relevant geluid gevonden."
|
||||
|
||||
msgid "To protect people’s privacy, this recording will not be uploaded automatically. You can still submit it for manual review."
|
||||
msgstr "Om de privacy van mensen te beschermen, wordt deze opname niet automatisch geüpload. Je kunt de opname wel indienen voor handmatige beoordeling."
|
||||
|
||||
msgid "No relevant sound was detected."
|
||||
msgstr "Er is geen relevant geluid gevonden."
|
||||
|
||||
msgid "BoomCast could not identify a sound this service currently looks for. You can still submit it for manual review."
|
||||
msgstr "BoomCast kon geen geluid herkennen waar deze dienst momenteel naar zoekt. Je kunt de opname wel indienen voor handmatige beoordeling."
|
||||
|
||||
msgid "Recording checked. Choose another recording or submit for manual review."
|
||||
msgstr "Opname gecontroleerd. Kies een andere opname of dien deze in voor handmatige beoordeling."
|
||||
|
||||
msgid "Could not prepare this video for upload. Please choose an audio recording."
|
||||
msgstr "Deze video kon niet veilig worden voorbereid voor upload. Kies een audio-opname."
|
||||
|
||||
msgid "Choose another recording"
|
||||
msgstr "Kies een andere opname"
|
||||
|
||||
msgid "Submit for manual review anyway"
|
||||
msgstr "Toch indienen voor handmatige beoordeling"
|
||||
|
||||
msgid "Sent to Pending Review"
|
||||
msgstr "Verzonden voor beoordeling"
|
||||
|
||||
msgid "An administrator will review this recording."
|
||||
msgstr "Een beheerder beoordeelt deze opname."
|
||||
|
||||
msgid "Process recording in this browser (Beta)"
|
||||
msgstr "Opname in deze browser verwerken (bèta)"
|
||||
|
||||
msgid "When enabled, BoomCast extracts and checks audio on this device before uploading it. When disabled, recordings are processed by the server as usual."
|
||||
msgstr "Als dit aanstaat, haalt BoomCast de audio op dit apparaat uit de opname en controleert die vóór het uploaden. Als dit uitstaat, verwerkt de server de opname zoals gebruikelijk."
|
||||
|
||||
msgid "Server processing currently accepts audio recordings. Choose an audio file or enable browser processing."
|
||||
msgstr "De server verwerkt momenteel alleen audio-opnamen. Kies een audiobestand of schakel verwerking in de browser in."
|
||||
|
||||
msgid "Local checking was unavailable. BoomCast will use normal server processing."
|
||||
msgstr "Lokale controle was niet beschikbaar. BoomCast gebruikt de normale verwerking op de server."
|
||||
|
||||
msgid "Quick report"
|
||||
msgstr "Snelle melding"
|
||||
|
||||
msgid "Did you hear a bang? Report what you heard in a few taps."
|
||||
msgstr "Heb je een knal gehoord? Meld in een paar tikken wat je hoorde."
|
||||
|
||||
msgid "Now"
|
||||
msgstr "Nu"
|
||||
|
||||
msgid "Report time"
|
||||
msgstr "Tijdstip melding"
|
||||
|
||||
msgid "How many times did you hear it?"
|
||||
msgstr "Hoe vaak hoorde je het?"
|
||||
|
||||
msgid "Decrease occurrences"
|
||||
msgstr "Aantal verlagen"
|
||||
|
||||
msgid "Increase occurrences"
|
||||
msgstr "Aantal verhogen"
|
||||
|
||||
msgid "I heard fireworks"
|
||||
msgstr "Ik hoorde vuurwerk"
|
||||
|
||||
msgid "Automatic detection"
|
||||
msgstr "Automatische detectie"
|
||||
|
||||
msgid "Not listening"
|
||||
msgstr "Luistert niet"
|
||||
|
||||
msgid "Start listening"
|
||||
msgstr "Start luisteren"
|
||||
|
||||
msgid "Close direction capture"
|
||||
msgstr "Richtingmeting sluiten"
|
||||
|
||||
msgid "Start measuring direction"
|
||||
msgstr "Richting meten"
|
||||
|
||||
msgid "Not captured"
|
||||
msgstr "Niet vastgelegd"
|
||||
|
||||
msgid "Report received!"
|
||||
msgstr "Melding ontvangen!"
|
||||
|
||||
msgid "Thank you. Your report helps map fireworks nearby."
|
||||
msgstr "Bedankt voor je bijdrage. Je melding helpt om vuurwerk in de buurt in kaart te brengen."
|
||||
|
||||
msgid "Stop measuring direction"
|
||||
msgstr "Stop richting meten"
|
||||
|
||||
msgid "Measure again"
|
||||
msgstr "Opnieuw meten"
|
||||
|
||||
msgid "Sending…"
|
||||
msgstr "Versturen…"
|
||||
|
||||
msgid "Could not send the report. Please try again."
|
||||
msgstr "De melding kon niet worden verzonden. Probeer het opnieuw."
|
||||
|
||||
msgid "North"
|
||||
msgstr "Noord"
|
||||
|
||||
msgid "Northeast"
|
||||
msgstr "Noordoost"
|
||||
|
||||
msgid "East"
|
||||
msgstr "Oost"
|
||||
|
||||
msgid "Southeast"
|
||||
msgstr "Zuidoost"
|
||||
|
||||
msgid "South"
|
||||
msgstr "Zuid"
|
||||
|
||||
msgid "Southwest"
|
||||
msgstr "Zuidwest"
|
||||
|
||||
msgid "West"
|
||||
msgstr "West"
|
||||
|
||||
msgid "Northwest"
|
||||
msgstr "Noordwest"
|
||||
|
||||
msgid "Listening for the next bang"
|
||||
msgstr "Luistert naar de volgende knal"
|
||||
|
||||
msgid "Sound detected"
|
||||
msgstr "Geluid gedetecteerd"
|
||||
|
||||
msgid "Sound captured"
|
||||
msgstr "Geluid vastgelegd"
|
||||
|
||||
msgid "Sound detected — finishing clip…"
|
||||
msgstr "Geluid gedetecteerd — opname afronden…"
|
||||
|
||||
msgid "Listening for the next sound…"
|
||||
msgstr "Luistert naar het volgende geluid…"
|
||||
|
||||
msgid "Keeping the most recent ~10 seconds"
|
||||
msgstr "Bewaart de laatste ~10 seconden"
|
||||
|
||||
msgid "Preview the clip or send your report."
|
||||
msgstr "Luister de opname terug of dien je melding in."
|
||||
|
||||
msgid "Starting microphone…"
|
||||
msgstr "Microfoon starten…"
|
||||
|
||||
msgid "Microphone unavailable"
|
||||
msgstr "Microfoon niet beschikbaar"
|
||||
|
||||
msgid "Microphone permission was denied. Manual reporting is still available."
|
||||
msgstr "Toegang tot de microfoon is geweigerd. Je kunt nog steeds handmatig melden."
|
||||
|
||||
msgid "Microphone capture failed."
|
||||
msgstr "Opnemen met de microfoon is mislukt."
|
||||
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
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.
@@ -1 +0,0 @@
|
||||
RIFF0000WAVEdata
|
||||
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.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user