added translations
This commit is contained in:
@@ -91,3 +91,17 @@ Django settings override environment variables with the same names. `VITE_BASE_U
|
||||
- **Browser cannot reach HMR:** set `VITE_DEV_SERVER_URL` to the browser-reachable Vite address, and use matching `VITE_HOST`/`VITE_PORT`. For containers or remote browsers this is often `0.0.0.0` for the host plus a public hostname for the URL.
|
||||
- **A page fails in development:** set `VITE_USE_DEV_SERVER=true` only while `npm run vite` or `npm run dev` is running.
|
||||
- **Assets return 404 after deployment:** rerun both the build and `collectstatic`; ensure the web server serves `STATIC_ROOT` at `STATIC_URL`.
|
||||
|
||||
## Interface translations
|
||||
|
||||
English text in templates and Python is the source language. Dutch translations live in `locale/nl/LC_MESSAGES/django.po`; the compiled `django.mo` is used at runtime. Logged-in users choose their language at `/settings/`. Visitors use the language switcher in the public navigation, which saves Django's standard language cookie. URLs and stored status or source codes do not change with the language.
|
||||
|
||||
Update translations after changing user-facing source text:
|
||||
|
||||
```bash
|
||||
python manage.py makemessages -l nl --ignore=node_modules --ignore=staticfiles --ignore='*.orig'
|
||||
# Edit locale/nl/LC_MESSAGES/django.po
|
||||
python manage.py compilemessages
|
||||
```
|
||||
|
||||
The small amount of JavaScript UI text is translated by Django in `templates/js_translations.html` and read from `window.BOOMCAST_I18N`. After changing JavaScript, run `npm run build` and `python manage.py collectstatic --noinput` for production. Classifier class names, API keys, sensor tokens, H3 values and stored source/status values remain language-neutral.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+18
-17
@@ -3,6 +3,7 @@ import json
|
||||
from django.contrib import admin, messages
|
||||
from django.utils import timezone
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext as _, gettext_lazy, ngettext
|
||||
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
@@ -22,11 +23,11 @@ class ClassificationAdmin(admin.ModelAdmin):
|
||||
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
|
||||
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
|
||||
|
||||
@admin.display(description="Direction")
|
||||
@admin.display(description=gettext_lazy("Direction"))
|
||||
def direction_display(self, obj):
|
||||
return obj.direction_display
|
||||
|
||||
@admin.display(description="Classifier response")
|
||||
@admin.display(description=gettext_lazy("Classifier response"))
|
||||
def pretty_classifier_response(self, obj):
|
||||
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
|
||||
|
||||
@@ -38,21 +39,21 @@ class PendingEventAdmin(ClassificationAdmin):
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
|
||||
@admin.action(description="Approve selected samples and move them to Events")
|
||||
@admin.action(description=gettext_lazy("Approve selected samples and move them to Events"))
|
||||
def approve_selected(self, request, queryset):
|
||||
approved = 0
|
||||
for pending in queryset:
|
||||
pending.approve()
|
||||
approved += 1
|
||||
self.message_user(request, f"{approved} sample(s) approved and moved to Events.", messages.SUCCESS)
|
||||
self.message_user(request, ngettext("%(count)d sample approved and moved to Events.", "%(count)d samples approved and moved to Events.", approved) % {"count": approved}, messages.SUCCESS)
|
||||
|
||||
@admin.action(description="Deny selected samples and delete their uploaded audio")
|
||||
@admin.action(description=gettext_lazy("Deny selected samples and delete their uploaded audio"))
|
||||
def deny_selected(self, request, queryset):
|
||||
denied = 0
|
||||
for pending in queryset:
|
||||
pending.deny()
|
||||
denied += 1
|
||||
self.message_user(request, f"{denied} sample(s) denied and removed.", messages.WARNING)
|
||||
self.message_user(request, ngettext("%(count)d sample denied and removed.", "%(count)d samples denied and removed.", denied) % {"count": denied}, messages.WARNING)
|
||||
|
||||
|
||||
@admin.register(Event)
|
||||
@@ -72,30 +73,30 @@ class SensorAdmin(admin.ModelAdmin):
|
||||
readonly_fields = ("token_prefix", "last_heartbeat", "last_submission", "created_at")
|
||||
actions = ("issue_api_token",)
|
||||
fieldsets = (
|
||||
("Sensor", {"fields": ("name", "is_active", "created_at")}),
|
||||
("API token", {"fields": ("token_prefix",), "description": "Save the sensor first, select it in the list, then choose ‘Issue or rotate API token’. The complete token is shown once only; its salted hash is the only value stored."}),
|
||||
("Heartbeat", {"fields": ("last_heartbeat", "last_submission"), "description": "Devices should POST to /fireworks/heartbeat/ with Authorization: Bearer <token>. Green means seen within 5 minutes; amber within 15; red is older or never seen."}),
|
||||
(gettext_lazy("Sensor"), {"fields": ("name", "is_active", "created_at")}),
|
||||
(gettext_lazy("API token"), {"fields": ("token_prefix",), "description": gettext_lazy("Save the sensor first, select it in the list, then choose ‘Issue or rotate API token’. The complete token is shown once only; its salted hash is the only value stored.")}),
|
||||
(gettext_lazy("Heartbeat"), {"fields": ("last_heartbeat", "last_submission"), "description": gettext_lazy("Devices should POST to /fireworks/heartbeat/ with Authorization: Bearer <token>. Green means seen within 5 minutes; amber within 15; red is older or never seen.")}),
|
||||
)
|
||||
|
||||
@admin.display(description="Heartbeat")
|
||||
@admin.display(description=gettext_lazy("Heartbeat"))
|
||||
def heartbeat_light(self, obj):
|
||||
if not obj.last_heartbeat:
|
||||
colour, label = "#ef4444", "Never seen"
|
||||
colour, label = "#ef4444", _("Never seen")
|
||||
else:
|
||||
age = timezone.now() - obj.last_heartbeat
|
||||
if age.total_seconds() <= 300:
|
||||
colour, label = "#22c55e", "Online"
|
||||
colour, label = "#22c55e", _("Online")
|
||||
elif age.total_seconds() <= 900:
|
||||
colour, label = "#f59e0b", "Delayed"
|
||||
colour, label = "#f59e0b", _("Delayed")
|
||||
else:
|
||||
colour, label = "#ef4444", "Offline"
|
||||
colour, label = "#ef4444", _("Offline")
|
||||
return format_html('<span style="display:inline-flex;align-items:center;gap:6px"><span style="width:10px;height:10px;border-radius:50%;background:{}"></span>{}</span>', colour, label)
|
||||
|
||||
@admin.action(description="Issue or rotate API token (shown once)")
|
||||
@admin.action(description=gettext_lazy("Issue or rotate API token (shown once)"))
|
||||
def issue_api_token(self, request, queryset):
|
||||
if queryset.count() != 1:
|
||||
self.message_user(request, "Select exactly one sensor to issue a token.", messages.ERROR)
|
||||
self.message_user(request, _("Select exactly one sensor to issue a token."), messages.ERROR)
|
||||
return
|
||||
sensor = queryset.get()
|
||||
token = sensor.issue_token()
|
||||
self.message_user(request, format_html('Copy this token now; it is not stored and will not be shown again: <code>{}</code>', token), messages.WARNING)
|
||||
self.message_user(request, format_html(_("Copy this token now; it is not stored and will not be shown again: <code>{}</code>"), token), messages.WARNING)
|
||||
|
||||
+13
-12
@@ -6,12 +6,13 @@ from django.core.exceptions import ValidationError
|
||||
from django.core.files.storage import default_storage
|
||||
from django.db import models, transaction
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class Sensor(models.Model):
|
||||
"""A physical recorder authorised to submit audio to the device API."""
|
||||
|
||||
name = models.CharField(max_length=100, unique=True, help_text="A recognisable device name, e.g. Garden ESP32.")
|
||||
name = models.CharField(max_length=100, unique=True, help_text=_("A recognisable device name, e.g. Garden ESP32."))
|
||||
is_active = models.BooleanField(default=True)
|
||||
token_prefix = models.CharField(max_length=15, blank=True, editable=False)
|
||||
token_hash = models.CharField(max_length=256, blank=True, editable=False)
|
||||
@@ -50,8 +51,8 @@ class ClassificationRule(models.Model):
|
||||
"""A configurable inclusion or exclusion rule for a classification label."""
|
||||
|
||||
class RuleType(models.TextChoices):
|
||||
WHITELIST = "whitelist", "Whitelist"
|
||||
BLACKLIST = "blacklist", "Blacklist"
|
||||
WHITELIST = "whitelist", _("Whitelist")
|
||||
BLACKLIST = "blacklist", _("Blacklist")
|
||||
|
||||
value = models.CharField(max_length=255)
|
||||
rule_type = models.CharField(max_length=10, choices=RuleType.choices)
|
||||
@@ -71,8 +72,8 @@ class ClassifiedAudio(models.Model):
|
||||
"""Shared fields for a classifier response and its original audio upload."""
|
||||
|
||||
class SourceType(models.TextChoices):
|
||||
SENSOR = "sensor", "Sensor"
|
||||
MANUAL = "manual", "Manual report"
|
||||
SENSOR = "sensor", _("Sensor")
|
||||
MANUAL = "manual", _("Manual report")
|
||||
|
||||
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d", blank=True)
|
||||
sensor = models.ForeignKey(Sensor, null=True, blank=True, on_delete=models.SET_NULL, related_name="%(class)s_records")
|
||||
@@ -103,11 +104,11 @@ class ClassifiedAudio(models.Model):
|
||||
if self.direction_degrees is not None and (
|
||||
not math.isfinite(self.direction_degrees) or not 0 <= self.direction_degrees < 360
|
||||
):
|
||||
errors["direction_degrees"] = "Direction must be a finite value from 0 up to, but not including, 360 degrees."
|
||||
errors["direction_degrees"] = _("Direction must be a finite value from 0 up to, but not including, 360 degrees.")
|
||||
if self.direction_accuracy_degrees is not None and (
|
||||
not math.isfinite(self.direction_accuracy_degrees) or self.direction_accuracy_degrees < 0
|
||||
):
|
||||
errors["direction_accuracy_degrees"] = "Compass accuracy must be a finite, non-negative value."
|
||||
errors["direction_accuracy_degrees"] = _("Compass accuracy must be a finite, non-negative value.")
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
@@ -138,7 +139,7 @@ class ClassifiedAudio(models.Model):
|
||||
|
||||
@property
|
||||
def primary_label(self):
|
||||
return self.primary_prediction.get("class", "No prediction")
|
||||
return self.primary_prediction.get("class", _("No prediction"))
|
||||
|
||||
@property
|
||||
def primary_score(self):
|
||||
@@ -177,8 +178,8 @@ class PendingEvent(ClassifiedAudio):
|
||||
"""A submitted classification awaiting a human review in Django admin."""
|
||||
|
||||
class Meta(ClassifiedAudio.Meta):
|
||||
verbose_name = "Pending event"
|
||||
verbose_name_plural = "Pending"
|
||||
verbose_name = _("Pending event")
|
||||
verbose_name_plural = _("Pending")
|
||||
|
||||
@transaction.atomic
|
||||
def approve(self):
|
||||
@@ -214,5 +215,5 @@ class Event(ClassifiedAudio):
|
||||
approved_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta(ClassifiedAudio.Meta):
|
||||
verbose_name = "Event"
|
||||
verbose_name_plural = "Events"
|
||||
verbose_name = _("Event")
|
||||
verbose_name_plural = _("Events")
|
||||
|
||||
@@ -1,32 +1,33 @@
|
||||
{% load i18n %}
|
||||
{% if error %}
|
||||
<section class="results-card error-card" role="alert">
|
||||
<h2>Analysis unavailable</h2>
|
||||
<h2>{% trans "Analysis unavailable" %}</h2>
|
||||
<p>{{ error }}</p>
|
||||
</section>
|
||||
{% else %}
|
||||
<section class="results-card" tabindex="-1">
|
||||
<div class="result-heading">
|
||||
<div>
|
||||
<h2>Analysis complete</h2>
|
||||
<h2>{% trans "Analysis complete" %}</h2>
|
||||
<p>{{ result.filename|default:"Audio file" }}</p>
|
||||
</div>
|
||||
<span class="result-status">Ready</span>
|
||||
<span class="result-status">{% trans "Ready" %}</span>
|
||||
</div>
|
||||
|
||||
<div class="meta">
|
||||
<span>{{ result.duration_seconds|default:"—" }} seconds</span>
|
||||
<span>{{ result.frames_analysed|default:"—" }} frames analysed</span>
|
||||
<span>{{ result.yamnet_sample_rate|default:"—" }} Hz model rate</span>
|
||||
<span>{% blocktrans with duration=result.duration_seconds|default:"—" %}{{ duration }} seconds{% endblocktrans %}</span>
|
||||
<span>{% blocktrans with frames=result.frames_analysed|default:"—" %}{{ frames }} frames analysed{% endblocktrans %}</span>
|
||||
<span>{% blocktrans with rate=result.yamnet_sample_rate|default:"—" %}{{ rate }} Hz model rate{% endblocktrans %}</span>
|
||||
</div>
|
||||
|
||||
<div class="legend" aria-label="Result legend">
|
||||
{% if firework_count %}<span class="firework">✦ {{ firework_count }} firework-related signal{{ firework_count|pluralize }}</span>{% endif %}
|
||||
{% if speech_count %}<span class="speech">● {{ speech_count }} speech/privacy signal{{ speech_count|pluralize }}</span>{% endif %}
|
||||
<div class="legend" aria-label="{% trans "Result legend" %}">
|
||||
{% if firework_count %}<span class="firework">✦ {% blocktrans count count=firework_count %}{{ count }} firework-related signal{% plural %}{{ count }} firework-related signals{% endblocktrans %}</span>{% endif %}
|
||||
{% if speech_count %}<span class="speech">● {% blocktrans count count=speech_count %}{{ count }} speech/privacy signal{% plural %}{{ count }} speech/privacy signals{% endblocktrans %}</span>{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="result-grid">
|
||||
<section class="result-group" aria-labelledby="top-predictions">
|
||||
<h3 id="top-predictions">Top sound classes</h3>
|
||||
<h3 id="top-predictions">{% trans "Top sound classes" %}</h3>
|
||||
{% if predictions %}
|
||||
<ul class="prediction-list">
|
||||
{% for prediction in predictions %}
|
||||
@@ -37,11 +38,11 @@
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}<p class="empty">No overall predictions were returned.</p>{% endif %}
|
||||
{% else %}<p class="empty">{% trans "No overall predictions were returned." %}</p>{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="result-group" aria-labelledby="peak-predictions">
|
||||
<h3 id="peak-predictions">Notable moments</h3>
|
||||
<h3 id="peak-predictions">{% trans "Notable moments" %}</h3>
|
||||
{% if peak_predictions %}
|
||||
<div class="peak-list">
|
||||
{% for prediction in peak_predictions %}
|
||||
@@ -55,14 +56,14 @@
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}<p class="empty">No peak events were returned.</p>{% endif %}
|
||||
{% else %}<p class="empty">{% trans "No peak events were returned." %}</p>{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
{% if submission_token %}
|
||||
<div class="review-submission" id="review-submission">
|
||||
<input type="hidden" name="classification_token" value="{{ submission_token }}">
|
||||
<div><strong>Submit this sample for review</strong><p>The audio and signed classifier response will be added to Pending.</p></div>
|
||||
<button type="button" hx-post="{% url 'fireworks_detect:submit_pending' %}" hx-target="#review-submission" hx-swap="outerHTML" hx-encoding="multipart/form-data">Send to Pending →</button>
|
||||
<div><strong>{% trans "Submit this sample for review" %}</strong><p>{% trans "The audio and signed classifier response will be added to Pending." %}</p></div>
|
||||
<button type="button" hx-post="{% url 'fireworks_detect:submit_pending' %}" hx-target="#review-submission" hx-swap="outerHTML" hx-encoding="multipart/form-data">{% trans "Send to Pending →" %}</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!doctype html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Report fireworks · Sound Signal</title>
|
||||
<title>{% trans "Report fireworks · Sound Signal" %}</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
{% vite_asset "frontend/src/entries/dashboard.js" %}
|
||||
{% include "js_translations.html" %}
|
||||
</head>
|
||||
<body class="dashboard-page">
|
||||
{% if user.is_authenticated %}<a class="profile-circle" href="{% url "user_settings" %}" aria-label="Open settings for {{ user.get_username }}" title="Settings">{{ user.get_username|first|upper }}</a>{% endif %}
|
||||
{% if user.is_authenticated %}<a class="profile-circle" href="{% url "user_settings" %}" aria-label="{% blocktrans with username=user.get_username %}Open settings for {{ username }}{% endblocktrans %}" title="{% trans "Settings" %}">{{ user.get_username|first|upper }}</a>{% endif %}
|
||||
<main class="dashboard-shell">
|
||||
{% include "fireworks_detect/includes/navigation.html" %}
|
||||
|
||||
<section class="dashboard-intro" aria-labelledby="dashboard-title">
|
||||
<p class="dashboard-kicker">Community reporting</p>
|
||||
<h1 id="dashboard-title">Report what you heard.</h1>
|
||||
<p>Quickly log fireworks when they happen. Your optional location is represented as an H3 cell on the map, rather than as precise coordinates.</p>
|
||||
<p class="dashboard-kicker">{% trans "Community reporting" %}</p>
|
||||
<h1 id="dashboard-title">{% trans "Report what you heard." %}</h1>
|
||||
<p>{% trans "Quickly log fireworks when they happen. Your optional location is represented as an H3 cell on the map, rather than as precise coordinates." %}</p>
|
||||
</section>
|
||||
|
||||
<section class="dashboard-section" aria-label="Quick fireworks report">
|
||||
<section class="dashboard-section" aria-label="{% trans "Quick fireworks report" %}">
|
||||
<div class="dashboard-report">
|
||||
{% include "fireworks_detect/includes/manual_report_form.html" %}
|
||||
</div>
|
||||
@@ -28,15 +29,15 @@
|
||||
|
||||
<section class="dashboard-section dashboard-map" aria-labelledby="dashboard-map-title">
|
||||
<header class="dashboard-section__header">
|
||||
<div><p class="dashboard-kicker">Recent reports</p><h2 id="dashboard-map-title">Activity map</h2></div>
|
||||
<a class="dashboard-link" href="{% url "fireworks_detect:map" %}">Open map controls <span aria-hidden="true">→</span></a>
|
||||
<div><p class="dashboard-kicker">{% trans "Recent reports" %}</p><h2 id="dashboard-map-title">{% trans "Activity map" %}</h2></div>
|
||||
<a class="dashboard-link" href="{% url "fireworks_detect:map" %}">{% trans "Open map controls" %} <span aria-hidden="true">→</span></a>
|
||||
</header>
|
||||
{% include "fireworks_detect/includes/map_panel.html" %}
|
||||
</section>
|
||||
|
||||
<section class="dashboard-section" aria-labelledby="dashboard-audio-title">
|
||||
<header class="dashboard-section__header">
|
||||
<div><p class="dashboard-kicker">Audio analysis</p><h2 id="dashboard-audio-title">Classify a recording</h2></div>
|
||||
<div><p class="dashboard-kicker">{% trans "Audio analysis" %}</p><h2 id="dashboard-audio-title">{% trans "Classify a recording" %}</h2></div>
|
||||
</header>
|
||||
<div class="upload-card dashboard-upload">
|
||||
{% include "fireworks_detect/includes/audio_upload_form.html" %}
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
{% load i18n %}
|
||||
{% if event.source_type == "manual" %}
|
||||
<h2>Manual fireworks report</h2>
|
||||
<p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · Reported manually</p>
|
||||
<h3>Report details</h3>
|
||||
<div class="prediction prediction--firework"><strong>Occurrences</strong><span>{{ event.occurrences }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Location</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Captured location</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Direction</strong><span>{{ event.direction_display }}</span></div>
|
||||
{% if event.direction_accuracy_degrees is not None %}<div class="prediction prediction--firework"><strong>Compass accuracy</strong><span>±{{ event.direction_accuracy_degrees|floatformat:"-1" }}°</span></div>{% endif %}
|
||||
<div class="prediction prediction--firework"><strong>Visually confirmed</strong><span>{% if event.visually_confirmed %}Yes{% else %}No{% endif %}</span></div>
|
||||
<p class="empty">This was a manual report; there is no audio classification attached.</p>
|
||||
<h2>{% trans "Manual fireworks report" %}</h2>
|
||||
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" %}Approved {{ date }} · Reported manually{% endblocktrans %}</p>
|
||||
<h3>{% trans "Report details" %}</h3>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Occurrences" %}</strong><span>{{ event.occurrences }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Location" %}</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Captured location" %}</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Direction" %}</strong><span>{{ event.direction_display }}</span></div>
|
||||
{% if event.direction_accuracy_degrees is not None %}<div class="prediction prediction--firework"><strong>{% trans "Compass accuracy" %}</strong><span>±{{ event.direction_accuracy_degrees|floatformat:"-1" }}°</span></div>{% endif %}
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Visually confirmed" %}</strong><span>{% if event.visually_confirmed %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</span></div>
|
||||
<p class="empty">{% trans "This was a manual report; there is no audio classification attached." %}</p>
|
||||
{% else %}
|
||||
<h2>{{ event.original_filename }}</h2>
|
||||
<p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · {{ result.duration_seconds|default:"—" }} seconds · {{ result.frames_analysed|default:"—" }} frames</p>
|
||||
<h3>Top sound classes</h3>
|
||||
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" duration=result.duration_seconds|default:"—" frames=result.frames_analysed|default:"—" %}Approved {{ date }} · {{ duration }} seconds · {{ frames }} frames{% endblocktrans %}</p>
|
||||
<h3>{% trans "Top sound classes" %}</h3>
|
||||
{% for prediction in predictions %}
|
||||
<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>
|
||||
{% empty %}
|
||||
<p class="empty">No predictions returned.</p>
|
||||
<p class="empty">{% trans "No predictions returned." %}</p>
|
||||
{% endfor %}
|
||||
<h3>Notable moments</h3>
|
||||
<h3>{% trans "Notable moments" %}</h3>
|
||||
{% for prediction in peak_predictions %}
|
||||
<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>
|
||||
{% empty %}
|
||||
<p class="empty">No peak events returned.</p>
|
||||
<p class="empty">{% trans "No peak events returned." %}</p>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
{% load vite %}
|
||||
<!doctype html><html lang="en" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Events · Sound Signal</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" with active_page="events" %}<p class="eyebrow">Reviewed signal archive</p><h1>Approved events.</h1><p class="lede">This feed refreshes automatically every three seconds after a pending sample is approved in admin.</p><div class="grid"><section class="panel"><h2>Latest events</h2><div id="events-feed" hx-get="{% url 'fireworks_detect:events_list' %}" hx-trigger="load, every 3s" hx-swap="innerHTML"><p class="empty">Loading events…</p></div></section><section class="panel detail" id="event-detail"><h2>Select an event</h2><p class="empty">Choose an approved event to inspect its classification details.</p></section></div></main></body></html>
|
||||
{% load i18n vite %}
|
||||
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Events · Sound Signal" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}{% include "js_translations.html" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" with active_page="events" %}<p class="eyebrow">{% trans "Reviewed signal archive" %}</p><h1>{% trans "Approved events." %}</h1><p class="lede">{% trans "This feed refreshes automatically every three seconds after a pending sample is approved in admin." %}</p><div class="grid"><section class="panel"><h2>{% trans "Latest events" %}</h2><div id="events-feed" hx-get="{% url 'fireworks_detect:events_list' %}" hx-trigger="load, every 3s" hx-swap="innerHTML"><p class="empty">{% trans "Loading events…" %}</p></div></section><section class="panel detail" id="event-detail"><h2>{% trans "Select an event" %}</h2><p class="empty">{% trans "Choose an approved event to inspect its classification details." %}</p></section></div></main></body></html>
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
{% load i18n %}
|
||||
{% if events %}
|
||||
{% for event in events %}
|
||||
<button class="event {% if event.source_type == "manual" %}event--manual{% else %}event--sensor{% endif %}" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
|
||||
<span class="event__content">
|
||||
{% if event.source_type == "manual" %}
|
||||
<span class="event__source">Manual report</span>
|
||||
<strong>Manual fireworks report</strong><br>
|
||||
<small>{{ event.occurrences }} occurrence{{ event.occurrences|pluralize }}{% if event.location %} · {{ event.location }}{% endif %}</small>
|
||||
<span class="event__source">{% trans "Manual report" %}</span>
|
||||
<strong>{% trans "Manual fireworks report" %}</strong><br>
|
||||
<small>{% blocktrans count count=event.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}{% if event.location %} · {{ event.location }}{% endif %}</small>
|
||||
{% else %}
|
||||
<span class="event__source">Sensor classification</span>
|
||||
<span class="event__source">{% trans "Sensor classification" %}</span>
|
||||
<strong>{{ event.primary_label }}</strong><br>
|
||||
<small>{{ event.original_filename }} · {{ event.duration }}s</small>
|
||||
{% endif %}
|
||||
</span>
|
||||
<span class="badge">{% if event.source_type == "manual" %}Manual →{% else %}{{ event.primary_score }} →{% endif %}</span>
|
||||
<span class="badge">{% if event.source_type == "manual" %}{% trans "Manual" %} →{% else %}{{ event.primary_score }} →{% endif %}</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>
|
||||
<p class="empty">{% trans "No approved events yet. Submit a classification, then approve it from the Pending page in admin." %}</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sound Signal · Fireworks detection</title>
|
||||
<title>{% trans "Sound Signal · Fireworks detection" %}</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
{% vite_asset "frontend/src/entries/fireworks-home.js" %}
|
||||
{% include "js_translations.html" %}
|
||||
</head>
|
||||
|
||||
<body>
|
||||
@@ -16,16 +17,14 @@
|
||||
|
||||
|
||||
<section class="intro" aria-labelledby="page-title">
|
||||
<p class="kicker">Audio event analysis</p>
|
||||
<h1 id="page-title">See what your audio heard.</h1>
|
||||
<p class="lede">Drop a recording to identify its most likely sounds. Firework-related signals are
|
||||
highlighted in amber; speech-related signals are marked in red for future privacy filtering.</p>
|
||||
<a href="https://pixabay.com/sound-effects/search/fireworks/" class="button" target="_blank">Here's some
|
||||
samples to test with</a>
|
||||
<p class="kicker">{% trans "Audio event analysis" %}</p>
|
||||
<h1 id="page-title">{% trans "See what your audio heard." %}</h1>
|
||||
<p class="lede">{% blocktrans trimmed %}Drop a recording to identify its most likely sounds. Firework-related signals are highlighted in amber; speech-related signals are marked in red for future privacy filtering.{% endblocktrans %}</p>
|
||||
<a href="https://pixabay.com/sound-effects/search/fireworks/" class="button" target="_blank">{% trans "Here are some samples to test with" %}</a>
|
||||
<br /><br />
|
||||
</section>
|
||||
|
||||
<section class="upload-card" aria-label="Upload audio for classification">
|
||||
<section class="upload-card" aria-label="{% trans "Upload audio for classification" %}">
|
||||
{% include "fireworks_detect/includes/audio_upload_form.html" %}
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
{% load i18n %}
|
||||
<form class="upload-form" action="{% url "fireworks_detect:classify_upload" %}" method="post" enctype="multipart/form-data" hx-post="{% url "fireworks_detect:classify_upload" %}" hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-indicator="#upload-indicator">
|
||||
{% csrf_token %}
|
||||
<label class="drop-zone" id="drop-zone">
|
||||
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
|
||||
<span>
|
||||
<span class="upload-icon">↑</span>
|
||||
<strong>Drop an audio file here</strong>
|
||||
<span>or click to browse your device</span>
|
||||
<strong>{% trans "Drop an audio file here" %}</strong>
|
||||
<span>{% trans "or click to browse your device" %}</span>
|
||||
</span>
|
||||
<span class="file-name" id="file-name">No file selected</span>
|
||||
<span class="file-name" id="file-name">{% trans "No file selected" %}</span>
|
||||
</label>
|
||||
<div class="form-footer">
|
||||
<p class="file-note">WAV, MP3, M4A, OGG and more · 25 MiB maximum</p>
|
||||
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>Analyse audio</button>
|
||||
<p class="file-note">{% trans "WAV, MP3, M4A, OGG and more · 25 MiB maximum" %}</p>
|
||||
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>{% trans "Analyse audio" %}</button>
|
||||
</div>
|
||||
<section id="classification-results" aria-live="polite" aria-label="Classification results"></section>
|
||||
<section id="classification-results" aria-live="polite" aria-label="{% trans "Classification results" %}"></section>
|
||||
</form>
|
||||
<p id="upload-status" role="status" aria-live="polite"></p>
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
{% load i18n %}
|
||||
<section class="manual-report" aria-labelledby="manual-report-title">
|
||||
<p class="eyebrow">No recording needed</p>
|
||||
<h2 class="manual-report__title" id="manual-report-title">Report fireworks now</h2>
|
||||
<p class="manual-report__intro">Choose how many times you heard fireworks, then send it straight to Pending. The report is timestamped now.</p>
|
||||
<p class="eyebrow">{% trans "No recording needed" %}</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" hx-post="{% url "fireworks_detect:submit_manual_pending" %}" hx-target="#manual-submission" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<label class="manual-report__label" for="manual-occurrences">Number of occurrences</label>
|
||||
<label class="manual-report__label" for="manual-occurrences">{% trans "Number of occurrences" %}</label>
|
||||
<input id="manual-latitude" name="latitude" type="hidden">
|
||||
<input id="manual-longitude" name="longitude" type="hidden">
|
||||
<input id="manual-direction-degrees" name="direction_degrees" type="hidden">
|
||||
<input id="manual-direction-accuracy" name="direction_accuracy_degrees" type="hidden">
|
||||
<input id="manual-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">Direction <span>(optional)</span></strong>
|
||||
<p class="manual-direction-panel__copy">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">Capture direction</button>
|
||||
<strong class="manual-direction-panel__heading">{% trans "Direction" %} <span>({% trans "optional" %})</span></strong>
|
||||
<p class="manual-direction-panel__copy">{% trans "Point the top of your phone toward the fireworks, then capture a single compass reading." %}</p>
|
||||
<button id="manual-capture-direction" class="manual-direction-panel__button" type="button">{% trans "Capture direction" %}</button>
|
||||
<div id="manual-direction-status" class="manual-direction-panel__status" aria-live="polite"></div>
|
||||
</div>
|
||||
<button id="manual-submit" class="manual-report__submit" type="button">I heard fireworks — send to Pending</button>
|
||||
<button id="manual-submit" class="manual-report__submit" type="button">{% trans "I heard fireworks — send to Pending" %}</button>
|
||||
</form>
|
||||
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
|
||||
</section>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<section class="map-panel" aria-label="Manual fireworks report map">
|
||||
<div class="map-header"><strong>Manual reports · privacy-preserving H3 cells</strong><span class="live"><i></i> H3 resolution {{ h3_resolution }} · sensor layer disabled</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="Interactive map of manual fireworks reports"></div>
|
||||
<aside class="legend" aria-label="Map legend"><h2>Manual reports</h2><div><span class="legend-dot"></span> Report marker at H3-cell centre</div><div><span class="legend-ring"></span> H3 cell (resolution {{ h3_resolution }})</div><div><span class="legend-line"></span> Saved compass direction</div></aside>
|
||||
{% load i18n %}
|
||||
<section class="map-panel" aria-label="{% trans "Manual fireworks report map" %}">
|
||||
<div class="map-header"><strong>{% trans "Manual reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }} · sensor layer disabled{% endblocktrans %}</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of manual fireworks reports" %}"></div>
|
||||
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Manual reports" %}</h2><div><span class="legend-dot"></span> {% trans "Report marker at H3-cell centre" %}</div><div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div><div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div></aside>
|
||||
</div>
|
||||
</section>
|
||||
{{ h3_cells|json_script:"h3-cells-data" }}
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
{% load i18n %}
|
||||
<header class="fireworks-header">
|
||||
<a class="fireworks-brand" href="{% url "fireworks_detect:fireworks" %}"><span class="brand-mark">✦</span> Sound Signal</a>
|
||||
<div class="fireworks-header__controls">
|
||||
<nav class="fireworks-nav" aria-label="Fireworks navigation">
|
||||
<a href="{% url "fireworks_detect:fireworks" %}"{% if active_page == "analyse" %} aria-current="page"{% endif %}>Analyse</a>
|
||||
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>Map</a>
|
||||
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>Events</a>
|
||||
<nav class="fireworks-nav" aria-label="{% trans "Fireworks navigation" %}">
|
||||
<a href="{% url "fireworks_detect:fireworks" %}"{% if active_page == "analyse" %} aria-current="page"{% endif %}>{% trans "Analyse" %}</a>
|
||||
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>{% trans "Map" %}</a>
|
||||
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>{% trans "Events" %}</a>
|
||||
</nav>
|
||||
<button class="theme-toggle theme-toggle--inline" type="button" aria-label="Switch theme"></button>
|
||||
{% if not request.user.is_authenticated %}
|
||||
<form class="public-language" action="{% url 'set_anonymous_language' %}" method="post" style="display:flex;align-items:center;gap:.3rem;color:var(--muted,#aab9d8);font-size:.78rem">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="next" value="{{ request.get_full_path }}">
|
||||
<label for="public-language-choice">{% trans "Language" %}</label>
|
||||
<select id="public-language-choice" name="language" style="border:1px solid var(--line,#2b3d68);border-radius:.5rem;padding:.4rem;color:inherit;background:transparent;font:inherit">
|
||||
<option value="nl"{% if request.LANGUAGE_CODE == 'nl' %} selected{% endif %}>Nederlands</option>
|
||||
<option value="en"{% if request.LANGUAGE_CODE == 'en' %} selected{% endif %}>English</option>
|
||||
</select>
|
||||
<button type="submit" style="border:1px solid var(--line,#2b3d68);border-radius:.5rem;padding:.4rem;color:inherit;background:transparent;font:inherit;cursor:pointer">OK</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
<button class="theme-toggle theme-toggle--inline" type="button" aria-label="{% trans "Switch theme" %}"></button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{% load i18n %}
|
||||
<div id="manual-submission" role="status">
|
||||
{% if error %}
|
||||
<strong>Could not report fireworks</strong><p>{{ error }}</p>
|
||||
<strong>{% trans "Could not report fireworks" %}</strong><p>{{ error }}</p>
|
||||
{% else %}
|
||||
<strong>Report sent to Pending</strong><p>{{ pending.occurrences }} occurrence{{ pending.occurrences|pluralize }} reported at {{ pending.created_at|date:"H:i" }}.</p>
|
||||
<strong>{% trans "Report sent to Pending" %}</strong><p>{% blocktrans count count=pending.occurrences with time=pending.created_at|date:"H:i" %}{{ count }} occurrence reported at {{ time }}.{% plural %}{{ count }} occurrences reported at {{ time }}.{% endblocktrans %}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Signal map · Sound Signal</title>
|
||||
<title>{% trans "Signal map · Sound Signal" %}</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
||||
{% vite_asset "frontend/src/entries/map.js" %}
|
||||
{% include "js_translations.html" %}
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
|
||||
|
||||
<section class="headline" aria-labelledby="map-title">
|
||||
<div><p class="kicker">Manual report intelligence</p><h1 id="map-title">Sound activity map.</h1></div>
|
||||
<p>Reviewed manual reports with a captured location appear as their H3 cell, not their precise coordinates. Saved phone compass readings show the reported direction of the sound.</p>
|
||||
<div><p class="kicker">{% trans "Manual report intelligence" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
|
||||
<p>{% trans "Reviewed manual reports with a captured location appear as their H3 cell, not their precise coordinates. Saved phone compass readings show the reported direction of the sound." %}</p>
|
||||
</section>
|
||||
|
||||
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="Map filters">
|
||||
<div class="filter"><label for="event-source">Source</label><select id="event-source" disabled><option selected>Manual reports</option><option>Sensor events — coming soon</option></select></div>
|
||||
<div class="filter"><label for="range">Period</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>Last 7 days</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>Last 2 weeks</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>Last 30 days</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>All time</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>Custom range</option></select></div>
|
||||
<div class="filter"><label for="from-date">From</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
|
||||
<div class="filter"><label for="to-date">To</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
|
||||
<div class="filter"><label for="visual">Visual confirmation</label><select id="visual" name="visual"><option value="all" {% if map_filters.visual == "all" %}selected{% endif %}>Any report</option><option value="yes" {% if map_filters.visual == "yes" %}selected{% endif %}>Visually confirmed</option><option value="no" {% if map_filters.visual == "no" %}selected{% endif %}>Not visually confirmed</option></select></div>
|
||||
<button class="filter-submit" type="submit">Apply filters</button>
|
||||
<span class="map-tag">{{ mapped_event_count }} report{{ mapped_event_count|pluralize }}</span>
|
||||
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="{% trans "Map filters" %}">
|
||||
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" disabled><option selected>{% trans "Manual reports" %}</option><option>{% trans "Sensor events — coming soon" %}</option></select></div>
|
||||
<div class="filter"><label for="range">{% trans "Period" %}</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>{% trans "Last 7 days" %}</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>{% trans "Last 2 weeks" %}</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>{% trans "Last 30 days" %}</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>{% trans "All time" %}</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>{% trans "Custom range" %}</option></select></div>
|
||||
<div class="filter"><label for="from-date">{% trans "From" %}</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
|
||||
<div class="filter"><label for="to-date">{% trans "To" %}</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
|
||||
<div class="filter"><label for="visual">{% trans "Visual confirmation" %}</label><select id="visual" name="visual"><option value="all" {% if map_filters.visual == "all" %}selected{% endif %}>{% trans "Any report" %}</option><option value="yes" {% if map_filters.visual == "yes" %}selected{% endif %}>{% trans "Visually confirmed" %}</option><option value="no" {% if map_filters.visual == "no" %}selected{% endif %}>{% trans "Not visually confirmed" %}</option></select></div>
|
||||
<button class="filter-submit" type="submit">{% trans "Apply filters" %}</button>
|
||||
<span class="map-tag">{% blocktrans count count=mapped_event_count %}{{ count }} report{% plural %}{{ count }} reports{% endblocktrans %}</span>
|
||||
</form>
|
||||
|
||||
{% include "fireworks_detect/includes/map_panel.html" %}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
{% load i18n %}
|
||||
<div class="review-submission" id="review-submission" role="status">
|
||||
{% if error %}<div><strong>Could not submit this sample</strong><p>{{ error }}</p></div>{% else %}<div><strong>Sent to Pending</strong><p>{{ pending.original_filename }} is ready for administrator review.</p></div><a href="{% url 'fireworks_detect:events' %}">View events</a>{% endif %}
|
||||
{% if error %}<div><strong>{% trans "Could not submit this sample" %}</strong><p>{{ error }}</p></div>{% else %}<div><strong>{% trans "Sent to Pending" %}</strong><p>{% blocktrans with filename=pending.original_filename %}{{ filename }} is ready for administrator review.{% endblocktrans %}</p></div><a href="{% url 'fireworks_detect:events' %}">{% trans "View events" %}</a>{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sound Signal · Fireworks detection</title>
|
||||
<title>{% trans "Sound Signal · Fireworks detection" %}</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
{% vite_asset "frontend/src/entries/legacy-fireworks-home.js" %}
|
||||
</head>
|
||||
@@ -12,32 +12,32 @@
|
||||
<main class="shell">
|
||||
<div class="brand"><span class="brand-mark">✦</span> Sound Signal</div>
|
||||
<section class="intro" aria-labelledby="page-title">
|
||||
<p class="kicker">Audio event analysis</p>
|
||||
<h1 id="page-title">See what your audio heard.</h1>
|
||||
<p class="lede">Drop a recording to identify its most likely sounds. Firework-related signals are highlighted in amber; speech-related signals are marked in red for future privacy filtering.</p>
|
||||
<p class="kicker">{% trans "Audio event analysis" %}</p>
|
||||
<h1 id="page-title">{% trans "See what your audio heard." %}</h1>
|
||||
<p class="lede">{% trans "Drop a recording to identify its most likely sounds. Firework-related signals are highlighted in amber; speech-related signals are marked in red for future privacy filtering." %}</p>
|
||||
</section>
|
||||
|
||||
<section class="upload-card" aria-label="Upload audio for classification">
|
||||
<section class="upload-card" aria-label="{% trans "Upload audio for classification" %}">
|
||||
<form class="upload-form" action="{% url 'fireworks_detect:classify' %}" method="post" enctype="multipart/form-data" hx-post="{% url 'fireworks_detect:classify' %}" hx-target="#classification-results" hx-swap="innerHTML" hx-encoding="multipart/form-data" hx-indicator="#upload-indicator">
|
||||
{% csrf_token %}
|
||||
<label class="drop-zone" id="drop-zone">
|
||||
<input class="file-input" id="audio-file" type="file" name="audio" accept="audio/*,.wav,.mp3,.m4a,.ogg,.flac,.aac,.opus" required>
|
||||
<span>
|
||||
<span class="upload-icon">↑</span>
|
||||
<strong>Drop an audio file here</strong>
|
||||
<span>or click to browse your device</span>
|
||||
<strong>{% trans "Drop an audio file here" %}</strong>
|
||||
<span>{% trans "or click to browse your device" %}</span>
|
||||
</span>
|
||||
<span class="file-name" id="file-name">No file selected</span>
|
||||
<span class="file-name" id="file-name">{% trans "No file selected" %}</span>
|
||||
</label>
|
||||
<div class="form-footer">
|
||||
<p class="file-note">WAV, MP3, M4A, OGG and more · 25 MiB maximum</p>
|
||||
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>Analyse audio</button>
|
||||
<p class="file-note">{% trans "WAV, MP3, M4A, OGG and more · 25 MiB maximum" %}</p>
|
||||
<button type="submit"><span class="spinner htmx-indicator" id="upload-indicator" aria-hidden="true"></span>{% trans "Analyse audio" %}</button>
|
||||
</div>
|
||||
</form>
|
||||
<p id="upload-status" role="status" aria-live="polite"></p>
|
||||
</section>
|
||||
|
||||
<section id="classification-results" aria-live="polite" aria-label="Classification results"></section>
|
||||
<section id="classification-results" aria-live="polite" aria-label="{% trans "Classification results" %}"></section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -45,6 +45,9 @@ class ClassificationRuleApiTests(TestCase):
|
||||
|
||||
|
||||
class ManualPendingEventTests(TestCase):
|
||||
def setUp(self):
|
||||
self.client.cookies["django_language"] = "en"
|
||||
|
||||
def test_manual_report_creates_a_timestamped_pending_event(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "4",
|
||||
@@ -128,8 +131,8 @@ class ManualPendingEventTests(TestCase):
|
||||
response = self.client.get(reverse("old_home"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Welkom Joren")
|
||||
self.assertContains(response, "Open vuurwerk detector")
|
||||
self.assertContains(response, "Welcome Joren")
|
||||
self.assertContains(response, "Open fireworks detector")
|
||||
|
||||
def test_manual_event_appears_in_the_normal_event_list_with_its_details(self):
|
||||
event = Event.objects.create(
|
||||
|
||||
+14
-13
@@ -14,6 +14,7 @@ from django.core import signing
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
@@ -239,13 +240,13 @@ def classify_upload(request):
|
||||
|
||||
uploaded_file = request.FILES.get("audio")
|
||||
if not uploaded_file:
|
||||
return _render_error(request, "Choose an audio file before starting the analysis.")
|
||||
return _render_error(request, _("Choose an audio file before starting the analysis."))
|
||||
|
||||
extension = Path(uploaded_file.name).suffix.lower()
|
||||
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
|
||||
return _render_error(request, "Please upload a supported audio file (such as WAV, MP3, M4A, or OGG).")
|
||||
return _render_error(request, _("Please upload a supported audio file (such as WAV, MP3, M4A, or OGG)."))
|
||||
if uploaded_file.size > MAX_AUDIO_SIZE:
|
||||
return _render_error(request, "This demo accepts audio files up to 25 MiB.")
|
||||
return _render_error(request, _("This demo accepts audio files up to 25 MiB."))
|
||||
|
||||
body, content_type = _encode_audio_multipart(uploaded_file)
|
||||
classifier_request = Request(
|
||||
@@ -259,14 +260,14 @@ def classify_upload(request):
|
||||
with urlopen(classifier_request, timeout=60) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
except HTTPError as error:
|
||||
return _render_error(request, f"The classifier returned an error (HTTP {error.code}).", status=502)
|
||||
return _render_error(request, _("The classifier returned an error (HTTP %(code)s).") % {"code": error.code}, status=502)
|
||||
except (URLError, TimeoutError):
|
||||
return _render_error(request, "The classifier could not be reached. Please try again shortly.", status=502)
|
||||
return _render_error(request, _("The classifier could not be reached. Please try again shortly."), status=502)
|
||||
except json.JSONDecodeError:
|
||||
return _render_error(request, "The classifier returned an unreadable response.", status=502)
|
||||
return _render_error(request, _("The classifier returned an unreadable response."), status=502)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return _render_error(request, "The classifier returned an unexpected response.", status=502)
|
||||
return _render_error(request, _("The classifier returned an unexpected response."), status=502)
|
||||
|
||||
# Keep the raw payload in this request flow; this is the future hand-off point
|
||||
# for saving the upload and its classification to a database or queue.
|
||||
@@ -281,17 +282,17 @@ def submit_pending_event(request):
|
||||
uploaded_file = request.FILES.get("audio")
|
||||
token = request.POST.get("classification_token")
|
||||
if not uploaded_file:
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": "Keep the analysed audio file selected before submitting it for review."}, status=400)
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": _("Keep the analysed audio file selected before submitting it for review.")}, status=400)
|
||||
if not token:
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": "Analyse the file before submitting it for review."}, status=400)
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": _("Analyse the file before submitting it for review.")}, status=400)
|
||||
|
||||
try:
|
||||
payload = signing.loads(token, salt="fireworks_detect.classification", max_age=60 * 60)
|
||||
except signing.BadSignature:
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": "This analysis has expired. Please analyse the audio again."}, status=400)
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": _("This analysis has expired. Please analyse the audio again.")}, status=400)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": "The saved analysis is not valid."}, status=400)
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"error": _("The saved analysis is not valid.")}, status=400)
|
||||
|
||||
pending = PendingEvent.objects.create(
|
||||
audio_file=uploaded_file,
|
||||
@@ -341,7 +342,7 @@ def submit_manual_pending_event(request):
|
||||
return render(
|
||||
request,
|
||||
"fireworks_detect/manual_pending_submission.html",
|
||||
{"error": "Choose between 1 and 1,000 occurrences."},
|
||||
{"error": _("Choose between 1 and 1,000 occurrences.")},
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -379,7 +380,7 @@ def event_detail(request, event_id):
|
||||
|
||||
def _audio_response(record):
|
||||
if not record.audio_file:
|
||||
raise Http404("No audio is attached to this record.")
|
||||
raise Http404(_("No audio is attached to this record."))
|
||||
content_type = mimetypes.guess_type(record.audio_file.name)[0] or "application/octet-stream"
|
||||
return FileResponse(record.audio_file.open("rb"), content_type=content_type)
|
||||
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
document.querySelectorAll('.audio-preview').forEach(function(box){var button=box.querySelector('.audio-play'),audio=box.querySelector('audio'),label=box.querySelector('.audio-play__label'),status=box.querySelector('.audio-status');button.addEventListener('click',function(){if(!audio.src){audio.src=button.dataset.audioUrl;button.classList.add('is-loading');status.textContent='Loading recording…';}if(audio.paused){audio.play().catch(function(){button.classList.remove('is-loading');status.textContent='Could not play this recording.';});}else{audio.pause();}});audio.addEventListener('playing',function(){button.classList.remove('is-loading');label.textContent='Pause recording';status.textContent='Playing now';});audio.addEventListener('pause',function(){if(!audio.ended){label.textContent='Resume recording';status.textContent='Paused';}});audio.addEventListener('ended',function(){label.textContent='Replay recording';status.textContent='Finished';});audio.addEventListener('waiting',function(){button.classList.add('is-loading');status.textContent='Buffering…';});audio.addEventListener('canplay',function(){button.classList.remove('is-loading');});audio.addEventListener('error',function(){button.classList.remove('is-loading');status.textContent='Could not load this recording.';});});
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
document.querySelectorAll('.audio-preview').forEach(function(box){var button=box.querySelector('.audio-play'),audio=box.querySelector('audio'),label=box.querySelector('.audio-play__label'),status=box.querySelector('.audio-status');button.addEventListener('click',function(){if(!audio.src){audio.src=button.dataset.audioUrl;button.classList.add('is-loading');status.textContent=(t.loadingRecording || 'Loading recording…');}if(audio.paused){audio.play().catch(function(){button.classList.remove('is-loading');status.textContent=(t.couldNotPlay || 'Could not play this recording.');});}else{audio.pause();}});audio.addEventListener('playing',function(){button.classList.remove('is-loading');label.textContent=(t.pauseRecording || 'Pause recording');status.textContent=(t.playingNow || 'Playing now');});audio.addEventListener('pause',function(){if(!audio.ended){label.textContent=(t.resumeRecording || 'Resume recording');status.textContent=(t.paused || 'Paused');}});audio.addEventListener('ended',function(){label.textContent=(t.replayRecording || 'Replay recording');status.textContent=(t.finished || 'Finished');});audio.addEventListener('waiting',function(){button.classList.add('is-loading');status.textContent=(t.buffering || 'Buffering…');});audio.addEventListener('canplay',function(){button.classList.remove('is-loading');});audio.addEventListener('error',function(){button.classList.remove('is-loading');status.textContent=(t.couldNotLoad || 'Could not load this recording.');});});
|
||||
@@ -1,18 +1,19 @@
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
|
||||
const form = document.querySelector('.upload-form');
|
||||
const dropZone = document.querySelector('#drop-zone');
|
||||
const fileInput = document.querySelector('#audio-file');
|
||||
const fileName = document.querySelector('#file-name');
|
||||
const status = document.querySelector('#upload-status');
|
||||
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
|
||||
const showFile = (file) => { fileName.textContent = file ? file.name : (t.noFile || 'No file selected'); };
|
||||
|
||||
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
|
||||
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
|
||||
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
|
||||
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
|
||||
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
|
||||
form.addEventListener('htmx:beforeRequest', () => { status.textContent = (t.analysing || 'Analysing your recording…'); form.setAttribute('aria-busy', 'true'); });
|
||||
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
|
||||
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
|
||||
form.addEventListener('htmx:responseError', () => { status.textContent = (t.analysisFailed || 'Analysis could not be completed.'); });
|
||||
document.body.addEventListener('htmx:beforeSwap', (event) => {
|
||||
if (event.detail.xhr.status >= 400) {
|
||||
event.detail.shouldSwap = true;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
|
||||
const mapElement = document.getElementById("event-map");
|
||||
const h3Resolution = mapElement.dataset.h3Resolution;
|
||||
@@ -7,7 +8,7 @@
|
||||
compassControl.onAdd = () => {
|
||||
const compass = L.DomUtil.create("div", "map-compass");
|
||||
compass.setAttribute("role", "img");
|
||||
compass.setAttribute("aria-label", "Map compass: north is up");
|
||||
compass.setAttribute("aria-label", (t.mapCompass || "Map compass: north is up"));
|
||||
compass.innerHTML = "<span class=\"compass-n\">N</span><span class=\"compass-e\">E</span><span class=\"compass-s\">S</span><span class=\"compass-w\">W</span><span class=\"compass-needle\">↑</span>";
|
||||
L.DomEvent.disableClickPropagation(compass);
|
||||
return compass;
|
||||
@@ -28,8 +29,8 @@
|
||||
}).addTo(map);
|
||||
polygon.bindPopup(
|
||||
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
|
||||
"<span class=\"popup-meta\">" + cell.reports + " reports · " + cell.occurrences +
|
||||
" occurrences · resolution " + h3Resolution + "</span>"
|
||||
"<span class=\"popup-meta\">" + cell.reports + " " + (cell.reports === 1 ? (t.report || "report") : (t.reports || "reports")) + " · " + cell.occurrences +
|
||||
" " + (cell.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) + " · " + (t.resolution || "resolution") + " " + h3Resolution + "</span>"
|
||||
);
|
||||
bounds.extend(L.latLngBounds(cell.boundary));
|
||||
});
|
||||
@@ -60,17 +61,17 @@
|
||||
className: "", html: "<div class=\"report-icon\">✦</div>", iconSize: [37, 37], iconAnchor: [19, 19],
|
||||
});
|
||||
reports.forEach((report) => {
|
||||
const visualStatus = report.visually_confirmed ? "Visually confirmed" : "Not visually confirmed";
|
||||
let detail = report.occurrences + " occurrence" + (report.occurrences === 1 ? "" : "s") +
|
||||
" · " + visualStatus + "<br>Reported " + report.reported_on;
|
||||
const visualStatus = report.visually_confirmed ? (t.visuallyConfirmed || "Visually confirmed") : (t.notVisuallyConfirmed || "Not visually confirmed");
|
||||
let detail = report.occurrences + " " + (report.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) +
|
||||
" · " + visualStatus + "<br>" + (t.reported || "Reported") + " " + report.reported_on;
|
||||
if (report.direction_degrees !== null) {
|
||||
detail += "<br>Compass direction " + Math.round(report.direction_degrees) + "° (" + cardinalDirection(report.direction_degrees) + ")";
|
||||
detail += "<br>" + (t.compassDirection || "Compass direction") + " " + Math.round(report.direction_degrees) + "° (" + cardinalDirection(report.direction_degrees) + ")";
|
||||
if (report.direction_accuracy_degrees !== null) {
|
||||
detail += " (±" + Math.round(report.direction_accuracy_degrees) + "°)";
|
||||
}
|
||||
}
|
||||
L.marker(report.center, { icon: reportIcon }).addTo(map).bindPopup(
|
||||
"<span class=\"popup-title\">Manual report · H3 " + report.cell + "</span>" +
|
||||
"<span class=\"popup-title\">" + (t.manualReport || "Manual report") + " · H3 " + report.cell + "</span>" +
|
||||
"<span class=\"popup-meta\">" + detail + "</span>"
|
||||
);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
|
||||
const manualForm = document.querySelector("#manual-report-form");
|
||||
const manualSubmit = document.querySelector("#manual-submit");
|
||||
@@ -27,14 +28,14 @@
|
||||
};
|
||||
|
||||
const showCapturedDirection = (heading, accuracy) => {
|
||||
const accuracyText = accuracy === null ? "Accuracy unavailable" : "Accuracy: ±" + displayDegrees(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 = "Stop direction capture";
|
||||
captureDirectionButton.textContent = (t.stopCapture || "Stop direction capture");
|
||||
};
|
||||
|
||||
const listenForCompassReading = () => {
|
||||
stopCompassReading();
|
||||
directionStatus.textContent = "Point the top of your phone toward the sound — direction will update live.";
|
||||
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)
|
||||
@@ -55,34 +56,34 @@
|
||||
window.addEventListener("deviceorientation", orientationListener);
|
||||
compassUnavailableTimeout = window.setTimeout(() => {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = "Capture direction";
|
||||
directionStatus.textContent = "Compass unavailable on this device.";
|
||||
captureDirectionButton.textContent = (t.captureDirection || "Capture direction");
|
||||
directionStatus.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
}, 15000);
|
||||
};
|
||||
|
||||
const captureDirection = async () => {
|
||||
if (orientationListener) {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = "Capture again";
|
||||
captureDirectionButton.textContent = (t.captureAgain || "Capture again");
|
||||
return;
|
||||
}
|
||||
if (!window.isSecureContext) {
|
||||
directionStatus.textContent = "Compass capture requires a secure HTTPS connection.";
|
||||
directionStatus.textContent = (t.secureCompass || "Compass capture requires a secure HTTPS connection.");
|
||||
return;
|
||||
}
|
||||
if (typeof window.DeviceOrientationEvent === "undefined") {
|
||||
directionStatus.textContent = "Compass unavailable on this device.";
|
||||
directionStatus.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
||||
return;
|
||||
}
|
||||
if (typeof DeviceOrientationEvent.requestPermission === "function") {
|
||||
directionStatus.textContent = "Requesting compass permission…";
|
||||
directionStatus.textContent = (t.compassPermission || "Requesting compass permission…");
|
||||
try {
|
||||
if (await DeviceOrientationEvent.requestPermission(true) !== "granted") {
|
||||
directionStatus.textContent = "Compass permission denied.";
|
||||
directionStatus.textContent = (t.compassDenied || "Compass permission denied.");
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
directionStatus.textContent = "Compass permission denied.";
|
||||
directionStatus.textContent = (t.compassDenied || "Compass permission denied.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -109,7 +110,7 @@
|
||||
submitManualReport();
|
||||
return;
|
||||
}
|
||||
manualStatus.textContent = "Requesting your optional location…";
|
||||
manualStatus.textContent = (t.requestingLocation || "Requesting your optional location…");
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
latitude.value = position.coords.latitude;
|
||||
|
||||
@@ -14,8 +14,9 @@ function applyTheme(theme, button) {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
if (!button) return;
|
||||
const nextTheme = theme === "dark" ? "light" : "dark";
|
||||
button.textContent = nextTheme === "light" ? "☀ Light mode" : "☾ Dark mode";
|
||||
button.setAttribute("aria-label", "Switch to " + nextTheme + " mode");
|
||||
const t = window.BOOMCAST_I18N || {};
|
||||
button.textContent = nextTheme === "light" ? "☀ " + (t.lightMode || "Light mode") : "☾ " + (t.darkMode || "Dark mode");
|
||||
button.setAttribute("aria-label", nextTheme === "light" ? (t.switchToLight || "Switch to light mode") : (t.switchToDark || "Switch to dark mode"));
|
||||
button.setAttribute("aria-pressed", String(theme === "light"));
|
||||
}
|
||||
|
||||
|
||||
+13
-13
@@ -1,27 +1,27 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Welkom · Sound Signal</title>
|
||||
<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" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
{% if user.is_authenticated %}<a class="profile-circle" href="{% url 'user_settings' %}" aria-label="Open settings for {{ user.get_username }}" title="Settings">{{ user.get_username|first|upper }}</a>{% endif %}
|
||||
{% 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">
|
||||
<main class="welcome-card">
|
||||
<div class="brand"><span class="brand-mark">✦</span> Sound Signal</div>
|
||||
<p class="eyebrow">Control room</p>
|
||||
<h1>Welkom {{ naam }}</h1>
|
||||
<p class="subject"><span class="sparkle">✦</span> Je leert <strong>{{ vak }}</strong>. Explore the prototype for live audio classification and future sensor mapping.</p>
|
||||
<p class="eyebrow">{% trans "Control room" %}</p>
|
||||
<h1>{% blocktrans %}Welcome {{ naam }}{% endblocktrans %}</h1>
|
||||
<p class="subject"><span class="sparkle">✦</span> {% blocktrans %}You are learning {{ vak }}. Explore the prototype for live audio classification and future sensor mapping.{% endblocktrans %}</p>
|
||||
<div class="actions">
|
||||
<a href="{% url 'fireworks_detect:fireworks' %}" class="button">Open vuurwerk detector <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:map' %}" class="button">Open kaart concept <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_create' %}" class="button">Open formulier <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:events' %}" class="button">Open gebeurtenissen <span aria-hidden="true">→</span></a>
|
||||
<span class="hint">Audio analysis · Sensor map</span>
|
||||
<a href="{% url 'fireworks_detect:fireworks' %}" class="button">{% trans "Open fireworks detector" %} <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:map' %}" class="button">{% trans "Open map concept" %} <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_create' %}" class="button">{% trans "Open form" %} <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:events' %}" class="button">{% trans "Open events" %} <span aria-hidden="true">→</span></a>
|
||||
<span class="hint">{% trans "Audio analysis · Sensor map" %}</span>
|
||||
</div>
|
||||
</main>
|
||||
{% include "fireworks_detect/includes/manual_report_form.html" %}
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -18,3 +18,9 @@ class UserSettingsForm(forms.ModelForm):
|
||||
|
||||
def clean_ntfy_url(self):
|
||||
return self.cleaned_data["ntfy_url"].strip()
|
||||
|
||||
|
||||
class LanguageSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ["preferred_language"]
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponseBadRequest, HttpResponseForbidden
|
||||
from django.views.i18n import set_language
|
||||
|
||||
|
||||
def set_anonymous_language(request):
|
||||
if request.user.is_authenticated:
|
||||
return HttpResponseForbidden()
|
||||
if request.method != "POST" or request.POST.get("language") not in dict(settings.LANGUAGES):
|
||||
return HttpResponseBadRequest()
|
||||
return set_language(request)
|
||||
@@ -0,0 +1,24 @@
|
||||
from django.conf import settings
|
||||
from django.utils import translation
|
||||
|
||||
from .models import UserSettings
|
||||
|
||||
|
||||
class UserLanguageMiddleware:
|
||||
"""Give an authenticated user's saved choice precedence over request negotiation."""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
if request.user.is_authenticated:
|
||||
language = UserSettings.objects.filter(user=request.user).values_list(
|
||||
"preferred_language", flat=True
|
||||
).first()
|
||||
language = language if language in dict(settings.LANGUAGES) else settings.LANGUAGE_CODE
|
||||
else:
|
||||
cookie_language = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
|
||||
language = cookie_language if cookie_language in dict(settings.LANGUAGES) else settings.LANGUAGE_CODE
|
||||
with translation.override(language):
|
||||
request.LANGUAGE_CODE = language
|
||||
return self.get_response(request)
|
||||
@@ -0,0 +1,13 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('members', '0002_usersettings')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='usersettings',
|
||||
name='preferred_language',
|
||||
field=models.CharField(choices=[('nl', 'Nederlands'), ('en', 'English')], default='nl', max_length=2),
|
||||
),
|
||||
]
|
||||
Binary file not shown.
+8
-4
@@ -1,5 +1,6 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
# Create your models here.
|
||||
class Member(models.Model):
|
||||
@@ -12,16 +13,19 @@ class Member(models.Model):
|
||||
return f"{self.first_name} {self.last_name}"
|
||||
|
||||
class UserSettings(models.Model):
|
||||
"""Per-user configuration for optional notification providers."""
|
||||
"""Per-user application preferences."""
|
||||
|
||||
LANGUAGE_CHOICES = [("nl", "Nederlands"), ("en", "English")]
|
||||
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_settings")
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
preferred_language = models.CharField(max_length=2, choices=LANGUAGE_CHOICES, default="nl")
|
||||
|
||||
class Meta:
|
||||
verbose_name = "User settings"
|
||||
verbose_name_plural = "User settings"
|
||||
verbose_name = _("User settings")
|
||||
verbose_name_plural = _("User settings")
|
||||
|
||||
def __str__(self):
|
||||
return f"Notification settings for {self.user}"
|
||||
return _("Settings for %(user)s") % {"user": self.user}
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Hello</title>
|
||||
<title>{% trans "Hello" %}</title>
|
||||
{% vite_asset "frontend/src/entries/member-form.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<p class="eyebrow"><span class="sparkle">✦</span> A warm welcome</p>
|
||||
<h1>What’s your name?</h1>
|
||||
<p class="intro">Enter your name below and we’ll say hello.</p>
|
||||
<p class="eyebrow"><span class="sparkle">✦</span> {% trans "A warm welcome" %}</p>
|
||||
<h1>{% trans "What’s your name?" %}</h1>
|
||||
<p class="intro">{% trans "Enter your name below and we’ll say hello." %}</p>
|
||||
|
||||
<form method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{{ form.as_p }}
|
||||
<button type="submit">Save</button>
|
||||
<button type="submit">{% trans "Save" %}</button>
|
||||
</form>
|
||||
|
||||
{% if message %}
|
||||
<p class="result" role="status">{{ message }}</p>
|
||||
{% endif %}
|
||||
<br/>
|
||||
<a href="{% url 'member_list' %}" class="button">Toon leden <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_list' %}" class="button">{% trans "Show members" %} <span aria-hidden="true">→</span></a>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Members</title>
|
||||
<title>{% trans "Members" %}</title>
|
||||
{% vite_asset "frontend/src/entries/member-list.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="page">
|
||||
<section class="card">
|
||||
@@ -14,13 +14,13 @@
|
||||
<div>
|
||||
<p class="eyebrow">
|
||||
<span class="sparkle">✦</span>
|
||||
Member directory
|
||||
{% trans "Member directory" %}
|
||||
</p>
|
||||
<h1>All members</h1>
|
||||
<p class="intro">A complete overview of everyone currently registered in the database.</p>
|
||||
<h1>{% trans "All members" %}</h1>
|
||||
<p class="intro">{% trans "A complete overview of everyone currently registered in the database." %}</p>
|
||||
</div>
|
||||
|
||||
<p class="count">{{ members|length }} member{{ members|length|pluralize }}</p>
|
||||
<p class="count">{% blocktrans count count=members|length %}{{ count }} member{% plural %}{{ count }} members{% endblocktrans %}</p>
|
||||
|
||||
</header>
|
||||
|
||||
@@ -30,9 +30,9 @@
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Member</th>
|
||||
<th scope="col">Phone number</th>
|
||||
<th scope="col">Joined</th>
|
||||
<th scope="col">{% trans "Member" %}</th>
|
||||
<th scope="col">{% trans "Phone number" %}</th>
|
||||
<th scope="col">{% trans "Joined" %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -56,15 +56,15 @@
|
||||
{% else %}
|
||||
<div class="empty">
|
||||
<div class="empty-icon">◎</div>
|
||||
<h2>No members yet</h2>
|
||||
<p>Add the first member to see them here.</p>
|
||||
<h2>{% trans "No members yet" %}</h2>
|
||||
<p>{% trans "Add the first member to see them here." %}</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
</section>
|
||||
<br/>
|
||||
<a href="{% url 'member_create' %}" class="button">Open nog een formulier <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_create' %}" class="button">{% trans "Open another form" %} <span aria-hidden="true">→</span></a>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!doctype html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Sign in · Sound Signal</title>
|
||||
<title>{% trans "Sign in · Sound Signal" %}</title>
|
||||
{% vite_asset "frontend/src/entries/login.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<p>✦ Sound Signal</p>
|
||||
<h1>Sign in</h1>
|
||||
<p class="intro">Sign in to manage your notification settings.</p>
|
||||
<h1>{% trans "Sign in" %}</h1>
|
||||
<p class="intro">{% trans "Sign in to manage your notification settings." %}</p>
|
||||
{% if form.errors %}
|
||||
<div class="error">Your username and password did not match. Please try again.</div>
|
||||
<div class="error">{% trans "Your username and password did not match. Please try again." %}</div>
|
||||
{% endif %}
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<label for="{{ form.username.id_for_label }}">Username</label>
|
||||
<label for="{{ form.username.id_for_label }}">{% trans "Username" %}</label>
|
||||
{{ form.username }}
|
||||
<label for="{{ form.password.id_for_label }}">Password</label>
|
||||
<label for="{{ form.password.id_for_label }}">{% trans "Password" %}</label>
|
||||
{{ form.password }}
|
||||
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
|
||||
<button type="submit">Sign in</button>
|
||||
<button type="submit">{% trans "Sign in" %}</button>
|
||||
</form>
|
||||
<p class="intro">You will return to the page you requested.</p>
|
||||
<p class="intro">{% trans "You will return to the page you requested." %}</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
{% 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 %}
|
||||
{% load i18n %}
|
||||
{% if success %}<div class="alert alert--success">✓ {% trans "Test notification sent successfully." %}</div>{% else %}<div class="alert alert--error">{% blocktrans %}Could not send the test notification:{% endblocktrans %} {{ error }}</div>{% endif %}
|
||||
|
||||
@@ -1,31 +1,41 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!doctype html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Settings · Sound Signal</title>
|
||||
<title>{% trans "Settings · 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/settings.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Settings</h1>
|
||||
<p class="intro">Manage personal notification preferences.</p>
|
||||
<h1>{% trans "Settings" %}</h1>
|
||||
<p class="intro">{% trans "Manage your personal preferences." %}</p>
|
||||
{% if messages %}<ul class="messages">{% for message in messages %}<li class="alert alert--success">{{ message }}</li>{% endfor %}</ul>{% endif %}
|
||||
<form method="post" action="{% url 'user_settings' %}">
|
||||
{% csrf_token %}
|
||||
<section class="section" aria-labelledby="language-title">
|
||||
<h2 id="language-title">{% trans "Language" %}</h2>
|
||||
<label for="{{ language_form.preferred_language.id_for_label }}">{% trans "Preferred language" %}</label>
|
||||
{{ language_form.preferred_language }}
|
||||
{{ language_form.preferred_language.errors }}
|
||||
</section>
|
||||
<button class="button" type="submit" name="save_language" value="1">{% trans "Save language" %}</button>
|
||||
</form>
|
||||
<form method="post" action="{% url 'user_settings' %}">
|
||||
{% csrf_token %}
|
||||
<section class="section" aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p class="help">Use a topic URL from your ntfy server. Test the current URL before saving it.</p>
|
||||
<label for="ntfy-url">Topic URL</label>
|
||||
<h2 id="ntfy-title">{% trans "Notifications / ntfy" %}</h2>
|
||||
<p class="help">{% trans "Use a topic URL from your ntfy server. Test the current URL before saving it." %}</p>
|
||||
<label for="ntfy-url">{% trans "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 class="button button--secondary" type="button" hx-post="{% url 'ntfy_test_notification' %}" hx-include="#ntfy-url, [name='csrfmiddlewaretoken']" hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
|
||||
<div class="check">{{ form.ntfy_enabled }}<label for="{{ form.ntfy_enabled.id_for_label }}">{% trans "Enable ntfy notifications" %}</label></div>
|
||||
<button class="button button--secondary" type="button" hx-post="{% url 'ntfy_test_notification' %}" hx-include="#ntfy-url, [name='csrfmiddlewaretoken']" hx-target="#ntfy-test-result" hx-swap="innerHTML">{% trans "Test notification" %}</button>
|
||||
<div id="ntfy-test-result" aria-live="polite"></div>
|
||||
</section>
|
||||
<button class="button" type="submit">Save settings</button>
|
||||
<button class="button" type="submit">{% trans "Save settings" %}</button>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Hello</title>
|
||||
<title>{% trans "Hello" %}</title>
|
||||
{% vite_asset "frontend/src/entries/member-success.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<p class="eyebrow"><span class="sparkle">✦</span> A warm welcome</p>
|
||||
<h1>What’s your name?</h1>
|
||||
<p class="intro">Toegevoegt aan de database.</p>
|
||||
<p class="eyebrow"><span class="sparkle">✦</span> {% trans "A warm welcome" %}</p>
|
||||
<h1>{% trans "What’s your name?" %}</h1>
|
||||
<p class="intro">{% trans "Added to the database." %}</p>
|
||||
|
||||
|
||||
{% if message %}
|
||||
<p class="result" role="status">{{ message }}</p>
|
||||
{% endif %}
|
||||
<a href="{% url 'member_create' %}" class="button">Open nog een formulier <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_list' %}" class="button">Toon leden <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_create' %}" class="button">{% trans "Open another form" %} <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_list' %}" class="button">{% trans "Show members" %} <span aria-hidden="true">→</span></a>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
+113
-7
@@ -3,8 +3,10 @@ from unittest.mock import MagicMock, patch
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.conf import settings
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
from django.utils import translation
|
||||
|
||||
from notifications.services import NotificationError, send_notification, send_ntfy_notification
|
||||
|
||||
@@ -57,7 +59,7 @@ class UserSettingsNtfyTests(TestCase):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": "not a URL"})
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "valid HTTP or HTTPS", status_code=400)
|
||||
self.assertContains(response, "geldige HTTP- of HTTPS-URL", status_code=400)
|
||||
mock_send.assert_not_called()
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
@@ -65,11 +67,11 @@ class UserSettingsNtfyTests(TestCase):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test notification sent successfully")
|
||||
self.assertContains(response, "Testmelding verzonden")
|
||||
mock_send.assert_called_once_with(
|
||||
self.url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
title="Vuurwerkdetector",
|
||||
message="ntfy-meldingen zijn goed ingesteld.",
|
||||
)
|
||||
|
||||
@patch("members.views.send_ntfy_notification", side_effect=NotificationError("Connection to the ntfy server timed out."))
|
||||
@@ -83,7 +85,7 @@ class UserSettingsNtfyTests(TestCase):
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
self.assertContains(response, "Test deze URL")
|
||||
settings = UserSettings.objects.get(user=self.user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
self.assertEqual(settings.ntfy_url, "")
|
||||
@@ -109,7 +111,7 @@ class UserSettingsNtfyTests(TestCase):
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": changed_url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
self.assertContains(response, "Test deze URL")
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).ntfy_url, self.url)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
@@ -120,7 +122,7 @@ class UserSettingsNtfyTests(TestCase):
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
self.assertContains(response, "Test deze URL")
|
||||
settings = UserSettings.objects.get(user=self.other_user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
|
||||
@@ -135,6 +137,7 @@ class UserSettingsNtfyTests(TestCase):
|
||||
|
||||
class FrontendAuthenticationTests(TestCase):
|
||||
def setUp(self):
|
||||
self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
|
||||
self.user = get_user_model().objects.create_user(username="profile-user", password="secret")
|
||||
|
||||
def test_frontend_login_page_is_available(self):
|
||||
@@ -162,3 +165,106 @@ class FrontendAuthenticationTests(TestCase):
|
||||
authenticated_response = self.client.get(reverse("hello"))
|
||||
self.assertContains(authenticated_response, "class=\"profile-circle\"")
|
||||
self.assertContains(authenticated_response, reverse("user_settings"))
|
||||
|
||||
|
||||
class LanguageSettingsTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="language-user", password="secret")
|
||||
self.client.force_login(self.user)
|
||||
|
||||
def test_missing_settings_row_uses_dutch_and_page_displays_it(self):
|
||||
response = self.client.get(reverse("user_settings"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, '<option value="nl" selected>')
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).preferred_language, "nl")
|
||||
|
||||
def test_language_can_switch_and_persists_between_requests(self):
|
||||
for language in ("en", "nl"):
|
||||
response = self.client.post(reverse("user_settings"), {
|
||||
"save_language": "1", "preferred_language": language,
|
||||
})
|
||||
self.assertRedirects(response, reverse("user_settings"))
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).preferred_language, language)
|
||||
response = self.client.get(reverse("user_settings"), HTTP_ACCEPT_LANGUAGE="en")
|
||||
self.assertEqual(response.wsgi_request.LANGUAGE_CODE, language)
|
||||
self.assertContains(response, f'<option value="{language}" selected>')
|
||||
|
||||
def test_invalid_language_is_rejected(self):
|
||||
self.client.post(reverse("user_settings"), {"save_language": "1", "preferred_language": "en"})
|
||||
response = self.client.post(reverse("user_settings"), {
|
||||
"save_language": "1", "preferred_language": "fr",
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Select a valid choice")
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).preferred_language, "en")
|
||||
|
||||
def test_anonymous_request_still_works(self):
|
||||
self.client.logout()
|
||||
response = self.client.get(reverse("hello"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_public_switcher_only_appears_for_anonymous_visitors(self):
|
||||
self.client.logout()
|
||||
self.assertContains(self.client.get(reverse("hello")), 'id="public-language-choice"')
|
||||
self.client.force_login(self.user)
|
||||
self.assertNotContains(self.client.get(reverse("hello")), 'id="public-language-choice"')
|
||||
|
||||
def test_anonymous_language_defaults_to_dutch_without_valid_cookie(self):
|
||||
self.client.logout()
|
||||
self.assertEqual(self.client.get(reverse("hello"), HTTP_ACCEPT_LANGUAGE="en").wsgi_request.LANGUAGE_CODE, "nl")
|
||||
self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "fr"
|
||||
self.assertEqual(self.client.get(reverse("hello")).wsgi_request.LANGUAGE_CODE, "nl")
|
||||
|
||||
def test_dashboard_uses_dutch_catalogue_and_english_source(self):
|
||||
self.client.logout()
|
||||
self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "nl"
|
||||
response = self.client.get(reverse("hello"))
|
||||
self.assertContains(response, "Meld wat je hebt gehoord.")
|
||||
self.assertContains(response, 'lang="nl"')
|
||||
self.client.cookies[settings.LANGUAGE_COOKIE_NAME] = "en"
|
||||
response = self.client.get(reverse("hello"))
|
||||
self.assertContains(response, "Report what you heard.")
|
||||
self.assertContains(response, 'lang="en"')
|
||||
|
||||
def test_translated_choice_label_keeps_stored_value_and_urls(self):
|
||||
from fireworks_detect.models import PendingEvent
|
||||
|
||||
with translation.override("nl"):
|
||||
self.assertEqual(str(PendingEvent.SourceType.MANUAL.label), "Handmatige melding")
|
||||
self.assertEqual(PendingEvent.SourceType.MANUAL.value, "manual")
|
||||
self.assertEqual(reverse("fireworks_detect:map"), "/fireworks/map/")
|
||||
|
||||
def test_anonymous_language_cookie_persists_and_controls_next_request(self):
|
||||
self.client.logout()
|
||||
for language in ("en", "nl"):
|
||||
response = self.client.post(reverse("set_anonymous_language"), {
|
||||
"language": language, "next": reverse("hello"),
|
||||
})
|
||||
self.assertRedirects(response, reverse("hello"))
|
||||
cookie = response.cookies[settings.LANGUAGE_COOKIE_NAME]
|
||||
self.assertEqual(cookie.value, language)
|
||||
self.assertGreater(int(cookie["max-age"]), 0)
|
||||
self.assertEqual(self.client.get(reverse("hello")).wsgi_request.LANGUAGE_CODE, language)
|
||||
|
||||
def test_invalid_language_and_unsafe_redirect_are_rejected(self):
|
||||
self.client.logout()
|
||||
response = self.client.post(reverse("set_anonymous_language"), {
|
||||
"language": "fr", "next": reverse("hello"),
|
||||
})
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertNotIn(settings.LANGUAGE_COOKIE_NAME, response.cookies)
|
||||
response = self.client.post(reverse("set_anonymous_language"), {
|
||||
"language": "en", "next": "https://evil.example/",
|
||||
})
|
||||
self.assertNotEqual(response.get("Location"), "https://evil.example/")
|
||||
|
||||
def test_account_preference_wins_over_anonymous_cookie_on_login(self):
|
||||
self.client.logout()
|
||||
self.client.post(reverse("set_anonymous_language"), {
|
||||
"language": "en", "next": reverse("hello"),
|
||||
})
|
||||
UserSettings.objects.update_or_create(user=self.user, defaults={"preferred_language": "nl"})
|
||||
self.client.post(reverse("login"), {"username": "language-user", "password": "secret"})
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).preferred_language, "nl")
|
||||
self.assertEqual(self.client.get(reverse("hello")).wsgi_request.LANGUAGE_CODE, "nl")
|
||||
self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "en")
|
||||
|
||||
+21
-11
@@ -6,10 +6,11 @@ from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.shortcuts import render, redirect
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from notifications.services import NotificationError, send_ntfy_notification
|
||||
from .forms import MemberForm, UserSettingsForm
|
||||
from .forms import LanguageSettingsForm, MemberForm, UserSettingsForm
|
||||
from .models import Member, UserSettings
|
||||
|
||||
def member_create(request):
|
||||
@@ -38,9 +39,9 @@ def hello_form(request):
|
||||
name = request.POST.get("name", "").strip()
|
||||
|
||||
if name:
|
||||
message = f"Hello, {name}!"
|
||||
message = _("Hello, %(name)s!") % {"name": name}
|
||||
else:
|
||||
message = "Please enter your name."
|
||||
message = _("Please enter your name.")
|
||||
|
||||
return render(request, "hello-form.html", {"message": message})
|
||||
|
||||
@@ -50,7 +51,7 @@ NTFY_TEST_SESSION_PREFIX = "ntfy_tested_url_fingerprint"
|
||||
def _validated_ntfy_url(value):
|
||||
url = value.strip()
|
||||
if not url:
|
||||
raise ValidationError("Enter an ntfy topic URL.")
|
||||
raise ValidationError(_("Enter an ntfy topic URL."))
|
||||
URLValidator(schemes=["http", "https"])(url)
|
||||
return url
|
||||
|
||||
@@ -65,7 +66,16 @@ def _url_fingerprint(url):
|
||||
|
||||
@login_required
|
||||
def user_settings(request):
|
||||
settings, _ = UserSettings.objects.get_or_create(user=request.user)
|
||||
settings, created = UserSettings.objects.get_or_create(user=request.user)
|
||||
language_form = LanguageSettingsForm(instance=settings)
|
||||
if request.method == "POST" and "save_language" in request.POST:
|
||||
language_form = LanguageSettingsForm(request.POST, instance=settings)
|
||||
if language_form.is_valid():
|
||||
language_form.save()
|
||||
messages.success(request, _("Language preference saved."))
|
||||
return redirect("user_settings")
|
||||
form = UserSettingsForm(instance=settings)
|
||||
return render(request, "members/user_settings.html", {"form": form, "language_form": language_form})
|
||||
saved_ntfy_url = settings.ntfy_url
|
||||
if request.method == "POST":
|
||||
form = UserSettingsForm(request.POST, instance=settings)
|
||||
@@ -74,7 +84,7 @@ def user_settings(request):
|
||||
tested_fingerprint = request.session.get(_ntfy_test_session_key(request.user))
|
||||
was_previously_tested = saved_ntfy_url == url and settings.ntfy_last_tested_at is not None
|
||||
if url and tested_fingerprint != _url_fingerprint(url) and not was_previously_tested:
|
||||
form.add_error("ntfy_url", "Test this URL successfully before saving notification settings.")
|
||||
form.add_error("ntfy_url", _("Test this URL successfully before saving notification settings."))
|
||||
else:
|
||||
settings = form.save(commit=False)
|
||||
if not url:
|
||||
@@ -84,11 +94,11 @@ def user_settings(request):
|
||||
settings.ntfy_last_tested_at = timezone.now()
|
||||
settings.save()
|
||||
request.session.pop(_ntfy_test_session_key(request.user), None)
|
||||
messages.success(request, "Notification settings saved.")
|
||||
messages.success(request, _("Notification settings saved."))
|
||||
return redirect("user_settings")
|
||||
else:
|
||||
form = UserSettingsForm(instance=settings)
|
||||
return render(request, "members/user_settings.html", {"form": form})
|
||||
return render(request, "members/user_settings.html", {"form": form, "language_form": language_form})
|
||||
|
||||
|
||||
@login_required
|
||||
@@ -100,15 +110,15 @@ def test_ntfy_notification(request):
|
||||
return render(
|
||||
request,
|
||||
"members/ntfy_test_result.html",
|
||||
{"error": "Enter a valid HTTP or HTTPS ntfy topic URL."},
|
||||
{"error": _("Enter a valid HTTP or HTTPS ntfy topic URL.")},
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
send_ntfy_notification(
|
||||
url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
title=_("Fireworks Detector"),
|
||||
message=_("ntfy notifications are configured correctly."),
|
||||
)
|
||||
except NotificationError as error:
|
||||
return render(request, "members/ntfy_test_result.html", {"error": str(error)}, status=502)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -54,9 +54,11 @@ INSTALLED_APPS = [
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.locale.LocaleMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'members.middleware.UserLanguageMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
@@ -114,7 +116,10 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/6.1/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
LANGUAGE_CODE = 'nl'
|
||||
LANGUAGES = [('nl', 'Nederlands'), ('en', 'English')]
|
||||
LANGUAGE_COOKIE_AGE = 365 * 24 * 60 * 60
|
||||
LOCALE_PATHS = [BASE_DIR / 'locale']
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
|
||||
@@ -8,8 +8,10 @@ from django.views.static import serve
|
||||
|
||||
from fireworks_detect.views import dashboard_view
|
||||
from hello.views import hello_view
|
||||
from members.language_views import set_anonymous_language
|
||||
|
||||
urlpatterns = [
|
||||
path("language/", set_anonymous_language, name="set_anonymous_language"),
|
||||
path("admin/", admin.site.urls),
|
||||
path("login/", auth_views.LoginView.as_view(template_name="members/login.html"), name="login"),
|
||||
path("classifications/", include("fireworks_detect.classification_urls")),
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
const t=window.BOOMCAST_I18N||{};document.querySelectorAll(".audio-preview").forEach(function(o){var n=o.querySelector(".audio-play"),e=o.querySelector("audio"),a=o.querySelector(".audio-play__label"),i=o.querySelector(".audio-status");n.addEventListener("click",function(){e.src||(e.src=n.dataset.audioUrl,n.classList.add("is-loading"),i.textContent=t.loadingRecording||"Loading recording…"),e.paused?e.play().catch(function(){n.classList.remove("is-loading"),i.textContent=t.couldNotPlay||"Could not play this recording."}):e.pause()}),e.addEventListener("playing",function(){n.classList.remove("is-loading"),a.textContent=t.pauseRecording||"Pause recording",i.textContent=t.playingNow||"Playing now"}),e.addEventListener("pause",function(){e.ended||(a.textContent=t.resumeRecording||"Resume recording",i.textContent=t.paused||"Paused")}),e.addEventListener("ended",function(){a.textContent=t.replayRecording||"Replay recording",i.textContent=t.finished||"Finished"}),e.addEventListener("waiting",function(){n.classList.add("is-loading"),i.textContent=t.buffering||"Buffering…"}),e.addEventListener("canplay",function(){n.classList.remove("is-loading")}),e.addEventListener("error",function(){n.classList.remove("is-loading"),i.textContent=t.couldNotLoad||"Could not load this recording."})});
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"./fireworks-home.js-CmXgGYKn.js";import"./map.js-3a1Gpit5.js";import"../../../theme-C3M4iSOd.js";import"../../../manual-report-CpWI_VWJ.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"../../../theme-C3M4iSOd.js";const s=window.BOOMCAST_I18N||{},r=document.querySelector(".upload-form"),n=document.querySelector("#drop-zone"),o=document.querySelector("#audio-file"),i=document.querySelector("#file-name"),a=document.querySelector("#upload-status"),d=e=>{i.textContent=e?e.name:s.noFile||"No file selected"};o.addEventListener("change",()=>d(o.files[0]));["dragenter","dragover"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.add("dragging")}));["dragleave","drop"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.remove("dragging")}));n.addEventListener("drop",e=>{const[t]=e.dataTransfer.files;t&&(o.files=e.dataTransfer.files,d(t))});r.addEventListener("htmx:beforeRequest",()=>{a.textContent=s.analysing||"Analysing your recording…",r.setAttribute("aria-busy","true")});r.addEventListener("htmx:afterRequest",()=>{a.textContent="",r.removeAttribute("aria-busy")});r.addEventListener("htmx:responseError",()=>{a.textContent=s.analysisFailed||"Analysis could not be completed."});document.body.addEventListener("htmx:beforeSwap",e=>{e.detail.xhr.status>=400&&(e.detail.shouldSwap=!0,e.detail.isError=!1)});window.addEventListener("pageshow",e=>{e.persisted&&(o.value="",d(),a.textContent="",document.querySelector("#classification-results").replaceChildren())});
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";import"../../../manual-report-CpWI_VWJ.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";const r=document.querySelector(".upload-form"),n=document.querySelector("#drop-zone"),o=document.querySelector("#audio-file"),d=document.querySelector("#file-name"),a=document.querySelector("#upload-status"),s=e=>{d.textContent=e?e.name:"No file selected"};o.addEventListener("change",()=>s(o.files[0]));["dragenter","dragover"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.add("dragging")}));["dragleave","drop"].forEach(e=>n.addEventListener(e,t=>{t.preventDefault(),n.classList.remove("dragging")}));n.addEventListener("drop",e=>{const[t]=e.dataTransfer.files;t&&(o.files=e.dataTransfer.files,s(t))});r.addEventListener("htmx:beforeRequest",()=>{a.textContent="Analysing your recording…",r.setAttribute("aria-busy","true")});r.addEventListener("htmx:afterRequest",()=>{a.textContent="",r.removeAttribute("aria-busy")});r.addEventListener("htmx:responseError",()=>{a.textContent="Analysis could not be completed."});
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
/* empty css */import"../../../theme-C3M4iSOd.js";const e=window.BOOMCAST_I18N||{},u=document.getElementById("event-map"),f=u.dataset.h3Resolution,t=L.map(u,{zoomControl:!1,scrollWheelZoom:!1}).setView([52.1326,5.2913],7);L.control.zoom({position:"bottomleft"}).addTo(t);const m=L.control({position:"topright"});m.onAdd=()=>{const o=L.DomUtil.create("div","map-compass");return o.setAttribute("role","img"),o.setAttribute("aria-label",e.mapCompass||"Map compass: north is up"),o.innerHTML='<span class="compass-n">N</span><span class="compass-e">E</span><span class="compass-s">S</span><span class="compass-w">W</span><span class="compass-needle">↑</span>',L.DomEvent.disableClickPropagation(o),o};m.addTo(t);L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png",{maxZoom:18,attribution:"© OpenStreetMap contributors"}).addTo(t);const y=JSON.parse(document.getElementById("h3-cells-data").textContent),M=JSON.parse(document.getElementById("map-events-data").textContent),d=L.latLngBounds([]);y.forEach(o=>{L.polygon(o.boundary,{color:"#f59e0b",weight:2,fillColor:"#f59e0b",fillOpacity:.25}).addTo(t).bindPopup('<span class="popup-title">H3 '+o.cell+'</span><span class="popup-meta">'+o.reports+" "+(o.reports===1?e.report||"report":e.reports||"reports")+" · "+o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+(e.resolution||"resolution")+" "+f+"</span>"),d.extend(L.latLngBounds(o.boundary))});function b(o){return["N","NE","E","SE","S","SW","W","NW"][Math.floor((o+22.5)%360/45)]}function v(o,n,s){const c=n*Math.PI/180,i=o[0]*Math.PI/180,h=o[1]*Math.PI/180,r=s/6378137,l=Math.asin(Math.sin(i)*Math.cos(r)+Math.cos(i)*Math.sin(r)*Math.cos(c)),g=h+Math.atan2(Math.sin(c)*Math.sin(r)*Math.cos(i),Math.cos(r)-Math.sin(i)*Math.sin(l));return[l*180/Math.PI,g*180/Math.PI]}const E=L.divIcon({className:"",html:'<div class="report-icon">✦</div>',iconSize:[37,37],iconAnchor:[19,19]});M.forEach(o=>{const n=o.visually_confirmed?e.visuallyConfirmed||"Visually confirmed":e.notVisuallyConfirmed||"Not visually confirmed";let s=o.occurrences+" "+(o.occurrences===1?e.occurrence||"occurrence":e.occurrences||"occurrences")+" · "+n+"<br>"+(e.reported||"Reported")+" "+o.reported_on;if(o.direction_degrees!==null&&(s+="<br>"+(e.compassDirection||"Compass direction")+" "+Math.round(o.direction_degrees)+"° ("+b(o.direction_degrees)+")",o.direction_accuracy_degrees!==null&&(s+=" (±"+Math.round(o.direction_accuracy_degrees)+"°)")),L.marker(o.center,{icon:E}).addTo(t).bindPopup('<span class="popup-title">'+(e.manualReport||"Manual report")+" · H3 "+o.cell+'</span><span class="popup-meta">'+s+"</span>"),o.direction_degrees!==null){const a=v(o.center,o.direction_degrees,900);L.polyline([o.center,a],{color:"#fff7e6",weight:9,opacity:.8}).addTo(t),L.polyline([o.center,a],{color:"#6d45a0",weight:5,opacity:1}).addTo(t);const c=L.divIcon({className:"",html:'<div class="direction-marker"><span style="transform:rotate('+o.direction_degrees+'deg)">↑</span></div>',iconSize:[56,56],iconAnchor:[28,28]});L.marker(a,{icon:c,interactive:!1}).addTo(t)}});d.isValid()&&t.fitBounds(d.pad(.18));const p=document.getElementById("range");p&&document.querySelectorAll("#from-date, #to-date").forEach(o=>{o.addEventListener("change",()=>{p.value="custom"})});
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";
|
||||
@@ -0,0 +1 @@
|
||||
import"../../../theme-C3M4iSOd.js";document.querySelector("#ntfy-url").addEventListener("input",()=>{document.querySelector("#ntfy-test-result").replaceChildren()});
|
||||
@@ -0,0 +1 @@
|
||||
const t=window.BOOMCAST_I18N||{},r=document.querySelector("#manual-report-form"),p=document.querySelector("#manual-submit"),C=document.querySelector("#manual-submission"),b=document.querySelector("#manual-latitude"),w=document.querySelector("#manual-longitude"),y=document.querySelector("#manual-direction-degrees"),v=document.querySelector("#manual-direction-accuracy"),u=document.querySelector("#manual-capture-direction"),n=document.querySelector("#manual-direction-status"),f=document.querySelector("#manual-direction-panel"),S=/Android|iPhone|iPad|iPod|IEMobile|Opera Mini/.test(navigator.userAgent)||navigator.userAgent.includes("Macintosh")&&navigator.maxTouchPoints>1;S&&(f.hidden=!1);let i,s;const d=e=>Number.isFinite(e),x=e=>["N","NE","E","SE","S","SW","W","NW"][Math.floor((e+22.5)%360/45)],g=e=>Number(e.toFixed(1)).toString(),c=()=>{i&&window.removeEventListener("deviceorientation",i),window.clearTimeout(s),i=null,s=null},h=(e,a)=>{const o=a===null?t.accuracyUnavailable||"Accuracy unavailable":(t.accuracy||"Accuracy")+": ±"+g(a)+"°";n.innerHTML="<strong>"+g(e)+"° · "+x(e)+"</strong><br>"+o,u.textContent=t.stopCapture||"Stop direction capture"},q=()=>{c(),n.textContent=t.pointPhone||"Point the top of your phone toward the sound — direction will update live.",i=e=>{const a="webkitCompassHeading"in e,o=d(e.webkitCompassHeading)?e.webkitCompassHeading:!a&&e.absolute&&d(e.alpha)?(360-e.alpha)%360:null;if(o===null||o<0||o>=360)return;const l=d(e.webkitCompassAccuracy)&&e.webkitCompassAccuracy>=0?e.webkitCompassAccuracy:null;y.value=o,v.value=l===null?"":l,h(o,l),window.clearTimeout(s)},window.addEventListener("deviceorientation",i),s=window.setTimeout(()=>{c(),u.textContent=t.captureDirection||"Capture direction",n.textContent=t.compassUnavailable||"Compass unavailable on this device."},15e3)},A=async()=>{if(i){c(),u.textContent=t.captureAgain||"Capture again";return}if(!window.isSecureContext){n.textContent=t.secureCompass||"Compass capture requires a secure HTTPS connection.";return}if(typeof window.DeviceOrientationEvent>"u"){n.textContent=t.compassUnavailable||"Compass unavailable on this device.";return}if(typeof DeviceOrientationEvent.requestPermission=="function"){n.textContent=t.compassPermission||"Requesting compass permission…";try{if(await DeviceOrientationEvent.requestPermission(!0)!=="granted"){n.textContent=t.compassDenied||"Compass permission denied.";return}}catch{n.textContent=t.compassDenied||"Compass permission denied.";return}}q()},m=()=>{c(),p.disabled=!0,window.htmx?htmx.ajax("POST",r.action,{source:r,target:"#manual-submission",swap:"outerHTML"}):r.submit()};u.addEventListener("click",A);p.addEventListener("click",()=>{if(!navigator.geolocation){m();return}C.textContent=t.requestingLocation||"Requesting your optional location…",navigator.geolocation.getCurrentPosition(e=>{b.value=e.coords.latitude,w.value=e.coords.longitude,m()},()=>m(),{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})});document.body.addEventListener("htmx:afterRequest",e=>{e.detail.elt===r&&(p.disabled=!1)});
|
||||
@@ -0,0 +1 @@
|
||||
const c="sound-signal-theme",r=new Set(["dark","light"]);function i(){try{const e=window.localStorage.getItem(c);return r.has(e)?e:"dark"}catch{return"dark"}}function o(e,t){if(document.documentElement.dataset.theme=e,!t)return;const a=e==="dark"?"light":"dark",n=window.BOOMCAST_I18N||{};t.textContent=a==="light"?"☀ "+(n.lightMode||"Light mode"):"☾ "+(n.darkMode||"Dark mode"),t.setAttribute("aria-label",a==="light"?n.switchToLight||"Switch to light mode":n.switchToDark||"Switch to dark mode"),t.setAttribute("aria-pressed",String(e==="light"))}function d(){const e=document.querySelector(".theme-toggle")??document.createElement("button");e.isConnected||(e.className="theme-toggle",e.type="button",document.body.append(e)),o(i(),e),e.addEventListener("click",()=>{const t=document.documentElement.dataset.theme==="dark"?"light":"dark";try{window.localStorage.setItem(c,t)}catch{}o(t,e)})}o(i());document.readyState==="loading"?document.addEventListener("DOMContentLoaded",d,{once:!0}):d();
|
||||
+9
-9
@@ -1,22 +1,22 @@
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Page not found · Sound Signal</title>
|
||||
<title>{% trans "Page not found · Sound Signal" %}</title>
|
||||
{% vite_asset "frontend/src/entries/not-found.js" %}
|
||||
</head>
|
||||
{% include "js_translations.html" %}</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<div class="mark"><span>⌁</span></div>
|
||||
<p class="code"><strong>404</strong> · Signal lost</p>
|
||||
<h1 class="title">This page wandered off.</h1>
|
||||
<p class="message">The address does not point to anything in this corner of Sound Signal. Try one of the routes below instead.</p>
|
||||
<p class="code"><strong>404</strong> · {% trans "Signal lost" %}</p>
|
||||
<h1 class="title">{% trans "This page wandered off." %}</h1>
|
||||
<p class="message">{% trans "The address does not point to anything in this corner of Sound Signal. Try one of the routes below instead." %}</p>
|
||||
{% if request_path %}<span class="path">{{ request_path }}</span>{% endif %}
|
||||
<div class="actions">
|
||||
<a class="button button-primary" href="/">Go home</a>
|
||||
<a class="button" href="/fireworks/">Open Sound Signal</a>
|
||||
<a class="button button-primary" href="/">{% trans "Go home" %}</a>
|
||||
<a class="button" href="/fireworks/">{% trans "Open Sound Signal" %}</a>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
@@ -1 +1 @@
|
||||
{% extends "admin/base.html" %}{% load static %}{% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static 'project_admin/admin.css' %}">{% endblock %}{% block branding %}<h1 id="site-name"><a href="{% url 'admin:index' %}">✦ Sound Signal <span>Administration</span></a></h1>{% endblock %}
|
||||
{% extends "admin/base.html" %}{% load i18n static %}{% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static 'project_admin/admin.css' %}">{% endblock %}{% block branding %}<h1 id="site-name"><a href="{% url 'admin:index' %}">✦ Sound Signal <span>{% trans "Administration" %}</span></a></h1>{% endblock %}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
{% extends "admin/fireworks_detect/classification_change_form.html" %}
|
||||
{% load vite %}
|
||||
{% load i18n vite %}
|
||||
|
||||
{% block extrahead %}
|
||||
{{ block.super }}
|
||||
{% vite_asset "frontend/src/entries/admin-audio-preview.js" %}
|
||||
{% include "js_translations.html" %}
|
||||
{% endblock %}
|
||||
|
||||
{% block after_field_sets %}
|
||||
@@ -11,9 +12,9 @@
|
||||
{% if original.audio_file %}
|
||||
<section class="audio-preview">
|
||||
<button class="audio-play" type="button" data-audio-url="{% url original.admin_audio_route original.pk %}">
|
||||
<span class="audio-play__icon">▶</span><span class="audio-play__label">Play recording</span>
|
||||
<span class="audio-play__icon">▶</span><span class="audio-play__label">{% trans "Play recording" %}</span>
|
||||
</button>
|
||||
<span class="audio-status" aria-live="polite">Loads only when played</span>
|
||||
<span class="audio-status" aria-live="polite">{% trans "Loads only when played" %}</span>
|
||||
<audio preload="none"></audio>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
{% extends "admin/change_form.html" %}{% block after_field_sets %}{{ block.super }}{% if original %}<section class="classification-preview"><h2>Classification preview</h2><p class="preview-meta">{{ original.duration }} seconds · {{ original.classifier_response.frames_analysed|default:"—" }} frames analysed</p><div class="preview-grid"><div><h3>Top sound classes</h3>{% for prediction in original.admin_predictions %}<div class="preview-row preview-row--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>{% empty %}<p>No predictions returned.</p>{% endfor %}</div><div><h3>Notable moments</h3>{% for prediction in original.admin_peaks %}<div class="preview-row preview-row--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>{% empty %}<p>No peak events returned.</p>{% endfor %}</div></div><details class="raw-json"><summary>Show raw classifier JSON</summary><pre>{{ original.classifier_response|pprint }}</pre></details></section>{% endif %}{% endblock %}
|
||||
{% load i18n %}
|
||||
{% extends "admin/change_form.html" %}{% block after_field_sets %}{{ block.super }}{% if original %}<section class="classification-preview"><h2>{% trans "Classification preview" %}</h2><p class="preview-meta">{{ original.duration }} seconds · {{ original.classifier_response.frames_analysed|default:"—" }} frames analysed</p><div class="preview-grid"><div><h3>{% trans "Top sound classes" %}</h3>{% for prediction in original.admin_predictions %}<div class="preview-row preview-row--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>{% empty %}<p>{% trans "No predictions returned." %}</p>{% endfor %}</div><div><h3>{% trans "Notable moments" %}</h3>{% for prediction in original.admin_peaks %}<div class="preview-row preview-row--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>{% empty %}<p>{% trans "No peak events returned." %}</p>{% endfor %}</div></div><details class="raw-json"><summary>{% trans "Show raw classifier JSON" %}</summary><pre>{{ original.classifier_response|pprint }}</pre></details></section>{% endif %}{% endblock %}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{% load i18n vite %}<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% translate 'Log in' %} · Sound Signal</title>{% vite_asset "frontend/src/entries/admin-login.js" %}</head><body><main class="card"><div class="brand"><span class="mark">✦</span> Sound Signal</div><p class="eyebrow">Secure access</p><h1>Welcome back.</h1><p class="intro">Sign in to review pending audio samples and manage approved events.</p>{% if form.errors %}<div class="error">{% translate 'Your username and password did not match. Please try again.' %}</div>{% endif %}{% if user.is_authenticated %}<div class="error">{% blocktranslate trimmed %}You are authenticated as {{ username }}, but are not authorized to access this page. Would you like to log in to a different account?{% endblocktranslate %}</div>{% endif %}<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}<label for="{{ form.username.id_for_label }}">{% translate 'Username' %}</label>{{ form.username }}<label for="{{ form.password.id_for_label }}">{% translate 'Password' %}</label>{{ form.password }}{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}<button type="submit">{% translate 'Sign in' %} <span aria-hidden="true">→</span></button></form><p class="foot">Sound Signal administration</p></main></body></html>
|
||||
{% load i18n vite %}<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% translate 'Log in' %} · Sound Signal</title>{% vite_asset "frontend/src/entries/admin-login.js" %}</head><body><main class="card"><div class="brand"><span class="mark">✦</span> Sound Signal</div><p class="eyebrow">{% trans "Secure access" %}</p><h1>{% trans "Welcome back." %}</h1><p class="intro">{% trans "Sign in to review pending audio samples and manage approved events." %}</p>{% if form.errors %}<div class="error">{% translate 'Your username and password did not match. Please try again.' %}</div>{% endif %}{% if user.is_authenticated %}<div class="error">{% blocktranslate trimmed %}You are authenticated as {{ username }}, but are not authorized to access this page. Would you like to log in to a different account?{% endblocktranslate %}</div>{% endif %}<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}<label for="{{ form.username.id_for_label }}">{% translate 'Username' %}</label>{{ form.username }}<label for="{{ form.password.id_for_label }}">{% translate 'Password' %}</label>{{ form.password }}{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}<button type="submit">{% translate 'Sign in' %} <span aria-hidden="true">→</span></button></form><p class="foot">{% trans "Sound Signal administration" %}</p></main></body></html>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
{% load i18n %}
|
||||
<script>
|
||||
window.BOOMCAST_I18N = {
|
||||
noFile: "{% trans 'No file selected' as value %}{{ value|escapejs }}",
|
||||
analysing: "{% trans 'Analysing your recording…' as value %}{{ value|escapejs }}",
|
||||
analysisFailed: "{% trans 'Analysis could not be completed.' as value %}{{ value|escapejs }}",
|
||||
accuracyUnavailable: "{% trans 'Accuracy unavailable' as value %}{{ value|escapejs }}",
|
||||
accuracy: "{% trans 'Accuracy' as value %}{{ value|escapejs }}",
|
||||
stopCapture: "{% trans 'Stop direction capture' as value %}{{ value|escapejs }}",
|
||||
pointPhone: "{% trans 'Point the top of your phone toward the sound — direction will update live.' as value %}{{ value|escapejs }}",
|
||||
captureDirection: "{% trans 'Capture direction' as value %}{{ value|escapejs }}",
|
||||
captureAgain: "{% trans 'Capture again' as value %}{{ value|escapejs }}",
|
||||
compassUnavailable: "{% trans 'Compass unavailable on this device.' as value %}{{ value|escapejs }}",
|
||||
secureCompass: "{% trans 'Compass capture requires a secure HTTPS connection.' as value %}{{ value|escapejs }}",
|
||||
compassPermission: "{% trans 'Requesting compass permission…' as value %}{{ value|escapejs }}",
|
||||
compassDenied: "{% trans 'Compass permission denied.' as value %}{{ value|escapejs }}",
|
||||
requestingLocation: "{% trans 'Requesting your optional location…' as value %}{{ value|escapejs }}",
|
||||
mapCompass: "{% trans 'Map compass: north is up' as value %}{{ value|escapejs }}",
|
||||
reports: "{% trans 'reports' as value %}{{ value|escapejs }}",
|
||||
occurrences: "{% trans 'occurrences' as value %}{{ value|escapejs }}",
|
||||
resolution: "{% trans 'resolution' as value %}{{ value|escapejs }}",
|
||||
visuallyConfirmed: "{% trans 'Visually confirmed' as value %}{{ value|escapejs }}",
|
||||
notVisuallyConfirmed: "{% trans 'Not visually confirmed' as value %}{{ value|escapejs }}",
|
||||
reported: "{% trans 'Reported' as value %}{{ value|escapejs }}",
|
||||
compassDirection: "{% trans 'Compass direction' as value %}{{ value|escapejs }}",
|
||||
report: "{% trans 'report' as value %}{{ value|escapejs }}",
|
||||
occurrence: "{% trans 'occurrence' as value %}{{ value|escapejs }}",
|
||||
lightMode: "{% trans 'Light mode' as value %}{{ value|escapejs }}",
|
||||
darkMode: "{% trans 'Dark mode' as value %}{{ value|escapejs }}",
|
||||
switchToLight: "{% trans 'Switch to light mode' as value %}{{ value|escapejs }}",
|
||||
switchToDark: "{% trans 'Switch to dark mode' as value %}{{ value|escapejs }}",
|
||||
loadingRecording: "{% trans 'Loading recording…' as value %}{{ value|escapejs }}",
|
||||
couldNotPlay: "{% trans 'Could not play this recording.' as value %}{{ value|escapejs }}",
|
||||
pauseRecording: "{% trans 'Pause recording' as value %}{{ value|escapejs }}",
|
||||
playingNow: "{% trans 'Playing now' as value %}{{ value|escapejs }}",
|
||||
resumeRecording: "{% trans 'Resume recording' as value %}{{ value|escapejs }}",
|
||||
paused: "{% trans 'Paused' as value %}{{ value|escapejs }}",
|
||||
replayRecording: "{% trans 'Replay recording' as value %}{{ value|escapejs }}",
|
||||
finished: "{% trans 'Finished' as value %}{{ value|escapejs }}",
|
||||
buffering: "{% trans 'Buffering…' as value %}{{ value|escapejs }}",
|
||||
couldNotLoad: "{% trans 'Could not load this recording.' as value %}{{ value|escapejs }}",
|
||||
manualReport: "{% trans 'Manual report' as value %}{{ value|escapejs }}"
|
||||
};
|
||||
</script>
|
||||
Reference in New Issue
Block a user