added scheduling
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -10,7 +10,7 @@ from django.urls import path, reverse
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext as _, gettext_lazy, ngettext
|
||||
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, ManualReportRevision, PendingEvent, Sensor
|
||||
from . import views as classifier_views
|
||||
|
||||
|
||||
@@ -49,11 +49,11 @@ class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
|
||||
|
||||
|
||||
class ClassificationAdmin(admin.ModelAdmin):
|
||||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "event_kind", "observation_duration_minutes", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("source_type", "visually_confirmed", "created_at")
|
||||
search_fields = ("original_filename",)
|
||||
readonly_fields = ("audio_file", "sensor", "h3_cell", "direction_display", "direction_accuracy_degrees", "original_filename", "created_at", "pretty_classifier_response")
|
||||
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
|
||||
fields = ("audio_file", "sensor", "source_type", "occurrences", "observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
|
||||
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
|
||||
|
||||
@admin.display(description=gettext_lazy("Direction"))
|
||||
@@ -149,13 +149,28 @@ class PendingEventAdmin(ClassificationAdmin):
|
||||
|
||||
@admin.register(Event)
|
||||
class EventAdmin(ClassificationAdmin):
|
||||
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
|
||||
fields = ClassificationAdmin.fields + ("approved_at",)
|
||||
readonly_fields = ClassificationAdmin.readonly_fields + ("submitted_at", "approved_at")
|
||||
fields = ClassificationAdmin.fields + ("submitted_at", "approved_at")
|
||||
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
|
||||
|
||||
@admin.register(ManualReportRevision)
|
||||
class ManualReportRevisionAdmin(admin.ModelAdmin):
|
||||
list_display = ("original_pending_id", "previous_occurrences", "new_occurrences", "previous_duration_minutes", "new_duration_minutes", "changed_at")
|
||||
readonly_fields = list_display
|
||||
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
|
||||
def has_change_permission(self, request, obj=None):
|
||||
return False
|
||||
|
||||
def has_delete_permission(self, request, obj=None):
|
||||
return False
|
||||
|
||||
|
||||
@admin.register(Sensor)
|
||||
class SensorAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "owner", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix", "archived_at")
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Derived burst presentation rules; rates describe frequency, not loudness."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
BURST_MIN_BANGS = 3
|
||||
DEFAULT_ESTIMATED_DURATION_MINUTES = 15
|
||||
MODERATE_RATE_PER_15_MINUTES = Decimal("5")
|
||||
INTENSE_RATE_PER_15_MINUTES = Decimal("10")
|
||||
|
||||
|
||||
def burst_rate(bang_count, duration_minutes):
|
||||
if bang_count < BURST_MIN_BANGS or not duration_minutes or duration_minutes <= 0:
|
||||
return None
|
||||
return Decimal(bang_count) * 15 / Decimal(duration_minutes)
|
||||
|
||||
|
||||
def burst_intensity(bang_count, duration_minutes):
|
||||
rate = burst_rate(bang_count, duration_minutes)
|
||||
if rate is None:
|
||||
return None
|
||||
if rate >= INTENSE_RATE_PER_15_MINUTES:
|
||||
return "intense"
|
||||
if rate >= MODERATE_RATE_PER_15_MINUTES:
|
||||
return "moderate"
|
||||
return "light"
|
||||
@@ -0,0 +1,57 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-09 23:43
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0011_event_captured_at_event_device_metadata_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='observation_duration_kind',
|
||||
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='observation_duration_minutes',
|
||||
field=models.PositiveSmallIntegerField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='occurrence_time_approximate',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='observation_duration_kind',
|
||||
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='observation_duration_minutes',
|
||||
field=models.PositiveSmallIntegerField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='occurrence_time_approximate',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='ManualReportRevision',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('original_pending_id', models.PositiveBigIntegerField()),
|
||||
('previous_occurrences', models.PositiveIntegerField()),
|
||||
('new_occurrences', models.PositiveIntegerField()),
|
||||
('previous_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
|
||||
('new_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
|
||||
('changed_at', models.DateTimeField(auto_now_add=True)),
|
||||
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-09 23:51
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0012_event_observation_duration_kind_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='submitted_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -117,12 +117,19 @@ class ClassifiedAudio(models.Model):
|
||||
SENSOR = "sensor", _("Sensor")
|
||||
MANUAL = "manual", _("Manual report")
|
||||
|
||||
class DurationKind(models.TextChoices):
|
||||
ESTIMATED = "estimated", _("Estimated")
|
||||
MEASURED = "measured", _("Measured")
|
||||
|
||||
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d", blank=True)
|
||||
sensor = models.ForeignKey(Sensor, null=True, blank=True, on_delete=models.SET_NULL, related_name="%(class)s_records")
|
||||
original_filename = models.CharField(max_length=255)
|
||||
classifier_response = models.JSONField()
|
||||
source_type = models.CharField(max_length=10, choices=SourceType.choices, default=SourceType.SENSOR)
|
||||
occurrences = models.PositiveIntegerField(default=1)
|
||||
observation_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
|
||||
observation_duration_kind = models.CharField(max_length=10, choices=DurationKind.choices, blank=True)
|
||||
occurrence_time_approximate = models.BooleanField(default=False)
|
||||
location = models.CharField(max_length=255, blank=True)
|
||||
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
@@ -154,6 +161,10 @@ class ClassifiedAudio(models.Model):
|
||||
not math.isfinite(self.direction_accuracy_degrees) or self.direction_accuracy_degrees < 0
|
||||
):
|
||||
errors["direction_accuracy_degrees"] = _("Compass accuracy must be a finite, non-negative value.")
|
||||
if self.observation_duration_minutes is not None and not 1 <= self.observation_duration_minutes <= 1440:
|
||||
errors["observation_duration_minutes"] = _("Observation duration must be between 1 and 1,440 minutes.")
|
||||
if bool(self.observation_duration_minutes) != bool(self.observation_duration_kind):
|
||||
errors["observation_duration_kind"] = _("A duration needs an estimated or measured source.")
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
@@ -172,6 +183,33 @@ class ClassifiedAudio(models.Model):
|
||||
return "—"
|
||||
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
|
||||
|
||||
@property
|
||||
def is_burst(self):
|
||||
from .bursts import BURST_MIN_BANGS
|
||||
return self.occurrences >= BURST_MIN_BANGS
|
||||
|
||||
@property
|
||||
def event_kind(self):
|
||||
return "burst" if self.is_burst else "ordinary"
|
||||
|
||||
@property
|
||||
def bangs_per_15_minutes(self):
|
||||
from .bursts import burst_rate
|
||||
if not self.observation_duration_kind:
|
||||
return None
|
||||
return burst_rate(self.occurrences, self.observation_duration_minutes)
|
||||
|
||||
@property
|
||||
def burst_intensity(self):
|
||||
from .bursts import burst_intensity
|
||||
if not self.observation_duration_kind:
|
||||
return None
|
||||
return burst_intensity(self.occurrences, self.observation_duration_minutes)
|
||||
|
||||
@property
|
||||
def burst_intensity_display(self):
|
||||
return {"light": _("Light"), "moderate": _("Moderate"), "intense": _("Intense")}.get(self.burst_intensity)
|
||||
|
||||
|
||||
@property
|
||||
def predictions(self):
|
||||
@@ -229,6 +267,7 @@ class PendingEvent(ClassifiedAudio):
|
||||
@transaction.atomic
|
||||
def approve(self):
|
||||
event = Event.objects.create(
|
||||
submitted_at=self.created_at,
|
||||
audio_file=self.audio_file.name,
|
||||
sensor=self.sensor,
|
||||
captured_at=self.captured_at,
|
||||
@@ -238,6 +277,9 @@ class PendingEvent(ClassifiedAudio):
|
||||
classifier_response=self.classifier_response,
|
||||
source_type=self.source_type,
|
||||
occurrences=self.occurrences,
|
||||
observation_duration_minutes=self.observation_duration_minutes,
|
||||
observation_duration_kind=self.observation_duration_kind,
|
||||
occurrence_time_approximate=self.occurrence_time_approximate,
|
||||
location=self.location,
|
||||
latitude=self.latitude,
|
||||
longitude=self.longitude,
|
||||
@@ -261,12 +303,25 @@ class Event(ClassifiedAudio):
|
||||
"""A reviewed classification that is safe to appear in the event feed."""
|
||||
|
||||
approved_at = models.DateTimeField(auto_now_add=True)
|
||||
submitted_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta(ClassifiedAudio.Meta):
|
||||
verbose_name = _("Event")
|
||||
verbose_name_plural = _("Events")
|
||||
|
||||
|
||||
class ManualReportRevision(models.Model):
|
||||
"""Record edits to a session-owned manual Pending report."""
|
||||
|
||||
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
|
||||
original_pending_id = models.PositiveBigIntegerField()
|
||||
previous_occurrences = models.PositiveIntegerField()
|
||||
new_occurrences = models.PositiveIntegerField()
|
||||
previous_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
|
||||
new_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
|
||||
changed_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
|
||||
class SensorSubmission(models.Model):
|
||||
"""Durable idempotency receipt, retained after moderation."""
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
{% load i18n %}
|
||||
{% if event.source_type == "manual" %}
|
||||
<h2>{% trans "Manual fireworks report" %}</h2>
|
||||
<h2>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</h2>
|
||||
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" %}Approved {{ date }} · Reported manually{% endblocktrans %}</p>
|
||||
<h3>{% trans "Report details" %}</h3>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Occurrences" %}</strong><span>{{ event.occurrences }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Occurred" %}</strong><span>{% if event.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ event.captured_at|date:"j M Y, H:i"|default:"Unknown" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Submitted" %}</strong><span>{% if event.submitted_at %}{{ event.submitted_at|date:"j M Y, H:i" }}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
|
||||
{% if event.is_burst %}<div class="prediction prediction--firework"><strong>{% trans "Duration" %}</strong><span>{% if event.observation_duration_minutes %}{{ event.observation_duration_minutes }} {% if event.observation_duration_kind == "estimated" %}{% trans "minutes (estimated)" %}{% else %}{% trans "minutes (measured)" %}{% endif %}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Intensity" %}</strong><span>{% if event.burst_intensity %}{{ event.burst_intensity_display }} · {{ event.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}{% else %}{% trans "Not rated" %}{% endif %}</span></div>{% endif %}
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Location" %}</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Captured location" %}</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>{% trans "Direction" %}</strong><span>{{ event.direction_display }}</span></div>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<span class="event__content">
|
||||
{% if event.source_type == "manual" %}
|
||||
<span class="event__source">{% trans "Manual report" %}</span>
|
||||
<strong>{% trans "Manual fireworks report" %}</strong><br>
|
||||
<strong>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</strong><br>
|
||||
<small>{% blocktrans count count=event.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}{% if event.location %} · {{ event.location }}{% endif %}</small>
|
||||
{% else %}
|
||||
<span class="event__source">{% trans "Sensor classification" %}</span>
|
||||
|
||||
@@ -20,6 +20,12 @@
|
||||
<input id="manual-longitude" name="longitude" type="hidden">
|
||||
<input id="manual-direction-degrees" name="direction_degrees" type="hidden">
|
||||
<input id="manual-direction-accuracy" name="direction_accuracy_degrees" type="hidden">
|
||||
<div class="manual-report__occurrence">
|
||||
<label class="manual-report__label" for="manual-occurred-at">{% trans "When did it happen?" %}</label>
|
||||
<div class="manual-report__time-row"><input id="manual-occurred-at" name="occurred_at" type="datetime-local" aria-describedby="manual-time-help"><button id="manual-use-now" type="button">{% trans "Use now" %}</button></div>
|
||||
<label class="manual-report__check"><input id="manual-time-approximate" name="time_approximate" type="checkbox"> {% trans "Time is approximate" %}</label>
|
||||
<small id="manual-time-help">{% trans "Leave the time empty to use the submission time." %}</small>
|
||||
</div>
|
||||
<div class="manual-report__primary">
|
||||
<div class="manual-report__quantity">
|
||||
<label class="manual-report__label" for="manual-occurrences">{% trans "How many times did you hear it?" %}</label>
|
||||
@@ -28,6 +34,13 @@
|
||||
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric">
|
||||
<button id="manual-increase" type="button" aria-label="{% trans 'Increase occurrences' %}">+</button>
|
||||
</div>
|
||||
<p id="manual-burst-status" class="manual-report__burst-status" role="status">{% trans "Ordinary report" %}</p>
|
||||
</div>
|
||||
<div id="manual-burst-duration" class="manual-report__duration">
|
||||
<label class="manual-report__label" for="manual-duration-minutes">{% trans "Estimated observation window (minutes, for 3+ bangs)" %}</label>
|
||||
<input id="manual-duration-minutes" name="duration_minutes" type="number" min="1" max="1440" value="15" inputmode="numeric">
|
||||
<label class="manual-report__check"><input id="manual-duration-confirmed" name="duration_confirmed" type="checkbox"> {% trans "Use this estimated window for burst intensity" %}</label>
|
||||
<small>{% trans "Optional. Without an accepted window, BoomCast reports the count without an intensity rating." %}</small>
|
||||
</div>
|
||||
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
|
||||
</div>
|
||||
@@ -55,7 +68,7 @@
|
||||
<p id="burst-error" role="alert" hidden></p>
|
||||
</div>
|
||||
</section>
|
||||
<button id="manual-submit" class="manual-report__submit" type="button"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
|
||||
<button id="manual-submit" class="manual-report__submit" type="submit"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
|
||||
</form>
|
||||
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
|
||||
<div id="manual-compass-home">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{% 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>
|
||||
<section class="map-panel" aria-label="{% trans "Reviewed fireworks report map" %}">
|
||||
<div class="map-header"><strong>{% trans "Reviewed reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }}{% endblocktrans %}</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of reviewed fireworks reports" %}"></div>
|
||||
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Map legend" %}</h2>{% if map_source != "sensor" %}<div><span class="legend-dot"></span> {% trans "Manual report" %}</div>{% endif %}{% if map_source == "sensor" or map_source == "all" %}<div><span class="legend-sensor"></span> {% trans "Sensor event" %}</div>{% endif %}<div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div>{% if map_source != "sensor" %}<div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div>{% endif %}</aside>
|
||||
</div>
|
||||
</section>
|
||||
{{ h3_cells|json_script:"h3-cells-data" }}
|
||||
|
||||
@@ -6,12 +6,24 @@
|
||||
<p>{{ error }}</p>
|
||||
{% else %}
|
||||
<span class="manual-submission__icon" aria-hidden="true">✓</span>
|
||||
<strong>{% trans "Report received!" %}</strong>
|
||||
<strong>{% if updated %}{% trans "Report updated!" %}{% else %}{% trans "Report received!" %}{% endif %}</strong>
|
||||
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
|
||||
<p class="manual-submission__summary">
|
||||
{{ pending.created_at|date:"H:i" }} ·
|
||||
{% if pending.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ pending.captured_at|date:"j M Y, H:i" }} ·
|
||||
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
|
||||
{% if direction_label %} · {{ direction_label }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
|
||||
{% if pending.direction_degrees is not None %} · {{ direction_label|default:pending.direction_cardinal }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
|
||||
</p>
|
||||
<p>{% if pending.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Ordinary report" %}{% endif %} · {% trans "Submitted" %} {{ pending.created_at|date:"j M Y, H:i" }}</p>
|
||||
{% if pending.is_burst %}<p>{% trans "Duration" %}: {% if pending.observation_duration_minutes %}{{ pending.observation_duration_minutes }} {% trans "minutes (estimated)" %}{% else %}{% trans "Unknown" %}{% endif %}</p>
|
||||
<p>{% trans "Intensity" %}: {% if pending.burst_intensity %}{{ pending.burst_intensity_display }} ({{ pending.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}){% else %}{% trans "Not rated" %}{% endif %}</p>{% endif %}
|
||||
{% if editable %}<form class="manual-submission__edit" method="post" action="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-post="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-target="#manual-submission" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<label for="manual-edit-count">{% trans "Correct bang count" %}</label>
|
||||
<input id="manual-edit-count" name="occurrences" type="number" min="1" max="1000" value="{{ pending.occurrences }}" required>
|
||||
<label for="manual-edit-duration">{% trans "Estimated minutes for a burst" %}</label>
|
||||
<input id="manual-edit-duration" name="duration_minutes" type="number" min="1" max="1440" value="{{ pending.observation_duration_minutes|default:15 }}">
|
||||
<label><input name="duration_confirmed" type="checkbox" {% if pending.observation_duration_kind %}checked{% endif %}> {% trans "Use this estimated window" %}</label>
|
||||
<button type="submit">{% trans "Update report" %}</button>
|
||||
</form>{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -14,12 +14,12 @@
|
||||
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
|
||||
|
||||
<section class="headline" aria-labelledby="map-title">
|
||||
<div><p class="kicker">{% trans "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>
|
||||
<div><p class="kicker">{% trans "Reviewed sound reports" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
|
||||
<p>{% trans "Reviewed reports with a stored location appear at their H3 cell centre, not their precise coordinates. Sensor events use only saved event locations; device-reported coordinates are not trusted for this map." %}</p>
|
||||
</section>
|
||||
|
||||
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="{% trans "Map filters" %}">
|
||||
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" disabled><option selected>{% trans "Manual reports" %}</option><option>{% trans "Sensor events — coming soon" %}</option></select></div>
|
||||
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" name="source"><option value="manual" {% if map_filters.source == "manual" %}selected{% endif %}>{% trans "Manual reports" %}</option><option value="sensor" {% if map_filters.source == "sensor" %}selected{% endif %}>{% trans "Sensor events" %}</option><option value="all" {% if map_filters.source == "all" %}selected{% endif %}>{% trans "Both sources" %}</option></select></div>
|
||||
<div class="filter"><label for="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>
|
||||
|
||||
@@ -44,11 +44,18 @@ class SensorSubmissionTests(TestCase):
|
||||
def test_authenticated_upload_is_classified_and_retry_is_idempotent(self):
|
||||
response_body = io.BytesIO(json.dumps({"predictions": [{"class": "Fireworks", "score": 0.8}], "duration_seconds": 1}).encode())
|
||||
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body) as classify:
|
||||
first = self.submit(trigger_type="audio_spike", latitude="52.1")
|
||||
first = self.submit(
|
||||
trigger_type="audio_spike", latitude="52.1",
|
||||
capture_started_at="2026-10-09T10:00:00Z",
|
||||
triggered_at="2026-10-09T10:00:02Z",
|
||||
queued_at="2026-10-09T10:00:05Z",
|
||||
)
|
||||
second = self.submit()
|
||||
self.assertEqual(first.status_code, 201)
|
||||
self.assertEqual(second.status_code, 200)
|
||||
self.assertEqual(first.json()["submission_id"], second.json()["submission_id"])
|
||||
self.assertEqual(first.json()["event_id"], "device-event-1")
|
||||
self.assertEqual(second.json()["event_id"], "device-event-1")
|
||||
self.assertEqual(PendingEvent.objects.count(), 1)
|
||||
self.assertEqual(SensorSubmission.objects.count(), 1)
|
||||
self.assertEqual(classify.call_count, 1)
|
||||
@@ -57,8 +64,17 @@ class SensorSubmissionTests(TestCase):
|
||||
self.assertEqual(pending.source_type, "sensor")
|
||||
self.assertFalse(pending.latitude)
|
||||
self.assertEqual(pending.device_metadata["latitude"], "52.1")
|
||||
self.assertEqual(pending.device_metadata["triggered_at"], "2026-10-09T10:00:02Z")
|
||||
self.assertTrue(pending.audio_file.storage.exists(pending.audio_file.name))
|
||||
|
||||
def test_unknown_capture_time_is_explicit_and_retained(self):
|
||||
response_body = io.BytesIO(json.dumps({"predictions": [], "duration_seconds": 1}).encode())
|
||||
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body):
|
||||
response = self.submit(captured_at="", time_state="unknown")
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertIsNone(PendingEvent.objects.get().captured_at)
|
||||
self.assertEqual(PendingEvent.objects.get().device_metadata["time_state"], "unknown")
|
||||
|
||||
def test_pending_admin_shows_sensor_details(self):
|
||||
staff = get_user_model().objects.create_superuser("reviewer-sensor", password="test")
|
||||
pending = PendingEvent.objects.create(sensor=self.sensor, source_type="sensor", original_filename="event.wav", classifier_response={"predictions": [{"class": "Fireworks", "score": 0.8}]}, firmware_version="0.1.0-concept", device_metadata={"trigger_type": "audio_spike"})
|
||||
|
||||
+143
-5
@@ -14,7 +14,8 @@ from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from .h3_utils import cell_from_coordinates, h3_resolution
|
||||
from .models import ClassificationRule, Event, PendingEvent
|
||||
from .models import ClassificationRule, Event, ManualReportRevision, PendingEvent
|
||||
from .bursts import burst_intensity, burst_rate
|
||||
|
||||
|
||||
class ClassificationRuleApiTests(TestCase):
|
||||
@@ -88,6 +89,114 @@ class ManualPendingEventTests(TestCase):
|
||||
self.assertContains(response, 'data-result="error"', status_code=400)
|
||||
self.assertFalse(PendingEvent.objects.exists())
|
||||
|
||||
def test_burst_boundaries_and_intensity_rates(self):
|
||||
for count, duration, category in ((1, 15, None), (2, 15, None), (3, 15, "light"), (10, 15, "intense"), (10, 30, "moderate"), (10, 60, "light")):
|
||||
with self.subTest(count=count, duration=duration):
|
||||
pending = PendingEvent(occurrences=count, observation_duration_minutes=duration, observation_duration_kind="estimated")
|
||||
self.assertEqual(pending.is_burst, count >= 3)
|
||||
self.assertEqual(pending.burst_intensity, category)
|
||||
self.assertEqual(burst_rate(10, 30), Decimal("5"))
|
||||
self.assertEqual(burst_intensity(10, None), None)
|
||||
|
||||
def test_server_rendered_quick_report_with_estimated_duration_and_approximate_time(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "10", "occurred_at": "2026-10-09T20:30", "time_approximate": "on",
|
||||
"duration_minutes": "30", "duration_confirmed": "on",
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Burst Event")
|
||||
self.assertContains(response, "Moderate")
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.occurrences, 10)
|
||||
self.assertEqual(pending.observation_duration_minutes, 30)
|
||||
self.assertEqual(pending.observation_duration_kind, "estimated")
|
||||
self.assertTrue(pending.occurrence_time_approximate)
|
||||
self.assertNotEqual(pending.captured_at, pending.created_at)
|
||||
self.assertEqual(pending.bangs_per_15_minutes, Decimal("5"))
|
||||
reviewed = pending.approve()
|
||||
self.assertEqual(reviewed.observation_duration_minutes, 30)
|
||||
self.assertEqual(reviewed.captured_at, pending.captured_at)
|
||||
self.assertEqual(reviewed.submitted_at, pending.created_at)
|
||||
|
||||
def test_unaccepted_window_has_no_intensity_and_legacy_burst_stays_compatible(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "3", "duration_minutes": "15"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertTrue(pending.is_burst)
|
||||
self.assertIsNone(pending.observation_duration_minutes)
|
||||
self.assertIsNone(pending.burst_intensity)
|
||||
old = Event.objects.create(occurrences=10, original_filename="old report", classifier_response={}, source_type="manual")
|
||||
self.assertTrue(old.is_burst)
|
||||
self.assertIsNone(old.burst_intensity)
|
||||
|
||||
accepted = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "3", "duration_confirmed": "on",
|
||||
})
|
||||
self.assertEqual(accepted.status_code, 200)
|
||||
self.assertEqual(PendingEvent.objects.latest("pk").observation_duration_minutes, 15)
|
||||
|
||||
measured = Event.objects.create(occurrences=10, original_filename="measured", classifier_response={},
|
||||
observation_duration_minutes=30, observation_duration_kind="measured")
|
||||
self.assertEqual(measured.burst_intensity, "moderate")
|
||||
self.assertEqual(measured.observation_duration_kind, "measured")
|
||||
|
||||
def test_session_scoped_count_edits_recalculate_and_preserve_original_time(self):
|
||||
self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "2", "occurred_at": "2026-10-09T20:30",
|
||||
})
|
||||
pending = PendingEvent.objects.get()
|
||||
occurred_at, submitted_at = pending.captured_at, pending.created_at
|
||||
url = reverse("fireworks_detect:update_manual_pending", args=[pending.pk])
|
||||
response = self.client.post(url, {"occurrences": "3", "duration_minutes": "15", "duration_confirmed": "on"})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending.refresh_from_db()
|
||||
self.assertEqual(pending.burst_intensity, "light")
|
||||
self.client.post(url, {"occurrences": "10", "duration_minutes": "10", "duration_confirmed": "on"})
|
||||
pending.refresh_from_db()
|
||||
self.assertEqual(pending.burst_intensity, "intense")
|
||||
self.client.post(url, {"occurrences": "10", "duration_minutes": "30", "duration_confirmed": "on"})
|
||||
pending.refresh_from_db()
|
||||
self.assertEqual(pending.burst_intensity, "moderate")
|
||||
self.client.post(url, {"occurrences": "2"})
|
||||
pending.refresh_from_db()
|
||||
self.assertFalse(pending.is_burst)
|
||||
self.assertIsNone(pending.burst_intensity)
|
||||
self.assertEqual(pending.captured_at, occurred_at)
|
||||
self.assertEqual(pending.created_at, submitted_at)
|
||||
self.assertEqual(ManualReportRevision.objects.filter(original_pending_id=pending.pk).count(), 4)
|
||||
from django.test import Client
|
||||
self.assertEqual(Client().post(url, {"occurrences": "10"}).status_code, 404)
|
||||
|
||||
def test_invalid_estimated_duration_and_future_occurrence_are_rejected(self):
|
||||
for data in (
|
||||
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "0"},
|
||||
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "1441"},
|
||||
{"occurrences": "10", "occurred_at": (timezone.localtime() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")},
|
||||
):
|
||||
with self.subTest(data=data):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), data)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertFalse(PendingEvent.objects.exists())
|
||||
|
||||
def test_map_data_exposes_derived_burst_fields_without_precise_location(self):
|
||||
event = Event.objects.create(
|
||||
original_filename="manual burst", classifier_response={}, source_type="manual", occurrences=10,
|
||||
latitude=Decimal("52.123456"), longitude=Decimal("5.987654"),
|
||||
observation_duration_minutes=30, observation_duration_kind="estimated",
|
||||
occurrence_time_approximate=True, captured_at=timezone.now() - timedelta(hours=1),
|
||||
)
|
||||
from .views import _events_for_map
|
||||
mapped, _ = _events_for_map({"date_from": None, "date_to": None, "visual": "all", "source": "manual"})
|
||||
item = next(item for item in mapped if item["occurrences"] == 10)
|
||||
self.assertEqual(item["event_kind"], "burst")
|
||||
self.assertEqual(item["observation_duration_kind"], "estimated")
|
||||
self.assertEqual(item["bangs_per_15_minutes"], 5.0)
|
||||
self.assertEqual(item["burst_intensity"], "moderate")
|
||||
self.assertTrue(item["occurrence_time_approximate"])
|
||||
self.assertIsNone(item["submitted_on"])
|
||||
self.assertNotIn("latitude", item)
|
||||
self.assertNotIn("longitude", item)
|
||||
|
||||
def test_manual_report_accepts_optional_wav_on_the_same_pending_event(self):
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
@@ -220,7 +329,7 @@ class ManualPendingEventTests(TestCase):
|
||||
)
|
||||
|
||||
list_response = self.client.get(reverse("fireworks_detect:events_list"))
|
||||
self.assertContains(list_response, "Manual fireworks report")
|
||||
self.assertContains(list_response, "Burst Event")
|
||||
self.assertContains(list_response, "5 occurrences")
|
||||
self.assertContains(list_response, "Back garden")
|
||||
|
||||
@@ -238,7 +347,7 @@ class ManualPendingEventTests(TestCase):
|
||||
self.assertEqual(h3_resolution(), 8)
|
||||
self.assertTrue(cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")))
|
||||
|
||||
def test_map_uses_manual_h3_data_and_excludes_sensor_events(self):
|
||||
def test_map_source_filter_separates_reviewed_sensor_events(self):
|
||||
manual_cell = cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654"))
|
||||
sensor_cell = cell_from_coordinates(Decimal("53.123456"), Decimal("5.987654"))
|
||||
Event.objects.create(
|
||||
@@ -271,12 +380,41 @@ class ManualPendingEventTests(TestCase):
|
||||
self.assertContains(response, '"direction_degrees": 237.0')
|
||||
self.assertContains(response, "data-h3-resolution")
|
||||
self.assertContains(response, 'type="module"')
|
||||
self.assertContains(response, "sensor layer disabled")
|
||||
self.assertContains(response, "Sensor events — coming soon")
|
||||
self.assertContains(response, 'name="source"')
|
||||
self.assertContains(response, "Sensor events")
|
||||
self.assertNotContains(response, sensor_cell)
|
||||
self.assertNotContains(response, "52.123456")
|
||||
self.assertNotContains(response, "H3 demo cell")
|
||||
|
||||
sensor_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
|
||||
self.assertEqual(len(sensor_response.context["map_events"]), 1)
|
||||
self.assertEqual(sensor_response.context["map_events"][0]["source_type"], "sensor")
|
||||
self.assertContains(sensor_response, sensor_cell)
|
||||
self.assertNotContains(sensor_response, manual_cell)
|
||||
self.assertNotContains(sensor_response, "53.123456")
|
||||
|
||||
both_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "all"})
|
||||
self.assertEqual(len(both_response.context["map_events"]), 2)
|
||||
self.assertContains(both_response, manual_cell)
|
||||
self.assertContains(both_response, sensor_cell)
|
||||
|
||||
def test_sensor_map_excludes_pending_and_device_only_locations(self):
|
||||
pending_cell = cell_from_coordinates(Decimal("51.876543"), Decimal("5.123456"))
|
||||
PendingEvent.objects.create(
|
||||
original_filename="pending.wav", classifier_response={},
|
||||
source_type=PendingEvent.SourceType.SENSOR, h3_cell=pending_cell,
|
||||
)
|
||||
Event.objects.create(
|
||||
original_filename="unlocated.wav", classifier_response={},
|
||||
source_type=Event.SourceType.SENSOR,
|
||||
device_metadata={"latitude": "52.654321", "longitude": "5.654321"},
|
||||
)
|
||||
|
||||
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
|
||||
self.assertEqual(response.context["map_events"], [])
|
||||
self.assertNotContains(response, pending_cell)
|
||||
self.assertNotContains(response, "52.654321")
|
||||
|
||||
def test_map_date_range_filters_manual_reports(self):
|
||||
recent_cell = cell_from_coordinates(Decimal("52.400000"), Decimal("5.700000"))
|
||||
older_cell = cell_from_coordinates(Decimal("53.400000"), Decimal("5.700000"))
|
||||
|
||||
@@ -12,6 +12,7 @@ from .views import (
|
||||
pending_audio,
|
||||
manual_direction_panel,
|
||||
submit_manual_pending_event,
|
||||
update_manual_pending_event,
|
||||
submit_pending_event,
|
||||
sensor_heartbeat,
|
||||
submit_sensor_pending,
|
||||
@@ -29,6 +30,7 @@ urlpatterns = [
|
||||
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
|
||||
path("submit-pending/", submit_pending_event, name="submit_pending"),
|
||||
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
|
||||
path("submit-manual-pending/<int:event_id>/update/", update_manual_pending_event, name="update_manual_pending"),
|
||||
path("manual-direction/", manual_direction_panel, name="manual_direction_panel"),
|
||||
path("events/", events_view, name="events"),
|
||||
path("events/list/", events_list, name="events_list"),
|
||||
|
||||
+128
-18
@@ -29,7 +29,8 @@ from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
|
||||
from .browser_policy import advisory_browser_metadata, browser_config, browser_policy
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor, SensorSubmission
|
||||
from .models import BrowserProcessingSettings, ClassificationRule, Event, ManualReportRevision, PendingEvent, Sensor, SensorSubmission
|
||||
from .bursts import BURST_MIN_BANGS, DEFAULT_ESTIMATED_DURATION_MINUTES, burst_intensity, burst_rate
|
||||
|
||||
|
||||
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
|
||||
@@ -85,17 +86,24 @@ def _map_filters(request):
|
||||
visual = request.GET.get("visual", "all")
|
||||
if visual not in {"all", "yes", "no"}:
|
||||
visual = "all"
|
||||
source = request.GET.get("source", "manual")
|
||||
if source not in {"manual", "sensor", "all"}:
|
||||
source = "manual"
|
||||
return {
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"range": selected_range,
|
||||
"visual": visual,
|
||||
"source": source,
|
||||
}
|
||||
|
||||
|
||||
def _events_for_map(filters):
|
||||
"""Create privacy-preserving map data for reviewed manual reports only."""
|
||||
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
|
||||
"""Create H3 map data for reviewed events with a stored, trusted location."""
|
||||
source = filters.get("source", "manual")
|
||||
events = Event.objects.all()
|
||||
if source != "all":
|
||||
events = events.filter(source_type=source)
|
||||
if filters["date_from"]:
|
||||
events = events.filter(created_at__date__gte=filters["date_from"])
|
||||
if filters["date_to"]:
|
||||
@@ -109,7 +117,8 @@ def _events_for_map(filters):
|
||||
mapped_events = []
|
||||
for event in events.values(
|
||||
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
|
||||
"direction_degrees", "direction_accuracy_degrees", "created_at",
|
||||
"direction_degrees", "direction_accuracy_degrees", "created_at", "captured_at", "submitted_at", "source_type",
|
||||
"observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate",
|
||||
):
|
||||
# Coordinates are used only here to derive an H3 cell; they never leave the server.
|
||||
h3_cell = event["h3_cell"] or cell_from_coordinates(event["latitude"], event["longitude"])
|
||||
@@ -124,13 +133,26 @@ def _events_for_map(filters):
|
||||
"center": center,
|
||||
"reports": 0,
|
||||
"occurrences": 0,
|
||||
"manual_reports": 0,
|
||||
"sensor_reports": 0,
|
||||
})
|
||||
aggregate["reports"] += 1
|
||||
aggregate["occurrences"] += event["occurrences"]
|
||||
aggregate[f'{event["source_type"]}_reports'] += 1
|
||||
rate = burst_rate(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None
|
||||
mapped_events.append({
|
||||
"cell": h3_cell,
|
||||
"center": center,
|
||||
"source_type": event["source_type"],
|
||||
"occurrences": event["occurrences"],
|
||||
"event_kind": "burst" if event["occurrences"] >= BURST_MIN_BANGS else "ordinary",
|
||||
"observation_duration_minutes": event["observation_duration_minutes"],
|
||||
"observation_duration_kind": event["observation_duration_kind"],
|
||||
"bangs_per_15_minutes": float(rate) if rate is not None else None,
|
||||
"burst_intensity": burst_intensity(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None,
|
||||
"occurrence_time_approximate": event["occurrence_time_approximate"],
|
||||
"occurred_on": (event["captured_at"] or event["created_at"]).date().isoformat(),
|
||||
"submitted_on": event["submitted_at"].date().isoformat() if event["submitted_at"] else None,
|
||||
"visually_confirmed": event["visually_confirmed"],
|
||||
# A day is sufficient for this map and avoids sharing a precise report time.
|
||||
"reported_on": event["created_at"].date().isoformat(),
|
||||
@@ -152,11 +174,13 @@ def fireworks_map_view(request):
|
||||
"h3_cells": h3_cells,
|
||||
"map_events": map_events,
|
||||
"mapped_event_count": len(map_events),
|
||||
"map_source": filters["source"],
|
||||
"map_filters": {
|
||||
"date_from": filters["date_from"].isoformat() if filters["date_from"] else "",
|
||||
"date_to": filters["date_to"].isoformat() if filters["date_to"] else "",
|
||||
"range": filters["range"],
|
||||
"visual": filters["visual"],
|
||||
"source": filters["source"],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -395,6 +419,10 @@ def submit_manual_pending_event(request):
|
||||
status=400,
|
||||
)
|
||||
|
||||
details, error = _manual_observation_details(request, occurrences)
|
||||
if error:
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
|
||||
|
||||
uploaded_file = request.FILES.get("audio")
|
||||
if uploaded_file:
|
||||
if uploaded_file.size > MAX_AUDIO_SIZE or uploaded_file.content_type not in ("audio/wav", "audio/wave", "audio/x-wav"):
|
||||
@@ -415,6 +443,7 @@ def submit_manual_pending_event(request):
|
||||
classifier_response={},
|
||||
source_type=PendingEvent.SourceType.MANUAL,
|
||||
occurrences=occurrences,
|
||||
**details,
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
h3_cell=h3_cell or "",
|
||||
@@ -422,15 +451,86 @@ def submit_manual_pending_event(request):
|
||||
direction_accuracy_degrees=direction_accuracy_degrees,
|
||||
direction_source="device_compass" if direction_degrees is not None else "",
|
||||
)
|
||||
owned = request.session.get("manual_pending_ids", [])
|
||||
request.session["manual_pending_ids"] = (owned + [pending.pk])[-20:]
|
||||
direction_names = {
|
||||
"N": _("North"), "NE": _("Northeast"), "E": _("East"), "SE": _("Southeast"),
|
||||
"S": _("South"), "SW": _("Southwest"), "W": _("West"), "NW": _("Northwest"),
|
||||
}
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {
|
||||
"pending": pending,
|
||||
"editable": True,
|
||||
"direction_label": direction_names.get(pending.direction_cardinal) if direction_degrees is not None else "",
|
||||
})
|
||||
|
||||
|
||||
def _manual_observation_details(request, occurrences):
|
||||
raw_time = request.POST.get("occurred_at", "").strip()
|
||||
if raw_time:
|
||||
occurred_at = parse_datetime(raw_time)
|
||||
if occurred_at is None:
|
||||
return None, _("Enter a valid occurrence date and time.")
|
||||
if timezone.is_naive(occurred_at):
|
||||
occurred_at = timezone.make_aware(occurred_at, timezone.get_current_timezone())
|
||||
if occurred_at > timezone.now() + timedelta(minutes=5):
|
||||
return None, _("Occurrence time cannot be in the future.")
|
||||
else:
|
||||
occurred_at = timezone.now()
|
||||
|
||||
details = {
|
||||
"captured_at": occurred_at,
|
||||
"occurrence_time_approximate": request.POST.get("time_approximate") == "on",
|
||||
"observation_duration_minutes": None,
|
||||
"observation_duration_kind": "",
|
||||
}
|
||||
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
|
||||
raw_duration = request.POST.get("duration_minutes", "").strip()
|
||||
try:
|
||||
duration = int(raw_duration) if raw_duration else DEFAULT_ESTIMATED_DURATION_MINUTES
|
||||
except ValueError:
|
||||
return None, _("Enter a duration between 1 and 1,440 minutes.")
|
||||
if not 1 <= duration <= 1440:
|
||||
return None, _("Enter a duration between 1 and 1,440 minutes.")
|
||||
details["observation_duration_minutes"] = duration
|
||||
details["observation_duration_kind"] = PendingEvent.DurationKind.ESTIMATED
|
||||
return details, None
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@never_cache
|
||||
def update_manual_pending_event(request, event_id):
|
||||
if event_id not in request.session.get("manual_pending_ids", []):
|
||||
raise Http404
|
||||
try:
|
||||
occurrences = int(request.POST.get("occurrences", ""))
|
||||
except (TypeError, ValueError):
|
||||
occurrences = 0
|
||||
if not 1 <= occurrences <= 1000:
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Choose between 1 and 1,000 occurrences.")}, status=400)
|
||||
_, error = _manual_observation_details(request, occurrences)
|
||||
if error:
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
|
||||
# The occurrence time and location belong to the original observation.
|
||||
duration = None
|
||||
kind = ""
|
||||
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
|
||||
raw = request.POST.get("duration_minutes", "").strip()
|
||||
duration = int(raw) if raw else DEFAULT_ESTIMATED_DURATION_MINUTES
|
||||
kind = PendingEvent.DurationKind.ESTIMATED
|
||||
with transaction.atomic():
|
||||
pending = get_object_or_404(PendingEvent.objects.select_for_update(), pk=event_id, source_type=PendingEvent.SourceType.MANUAL)
|
||||
ManualReportRevision.objects.create(
|
||||
pending_event=pending, original_pending_id=pending.pk,
|
||||
previous_occurrences=pending.occurrences, new_occurrences=occurrences,
|
||||
previous_duration_minutes=pending.observation_duration_minutes,
|
||||
new_duration_minutes=duration,
|
||||
)
|
||||
pending.occurrences = occurrences
|
||||
pending.observation_duration_minutes = duration
|
||||
pending.observation_duration_kind = kind
|
||||
pending.save(update_fields=["occurrences", "observation_duration_minutes", "observation_duration_kind"])
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending, "editable": True, "updated": True})
|
||||
|
||||
@never_cache
|
||||
def events_list(request):
|
||||
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
|
||||
@@ -549,23 +649,30 @@ def submit_sensor_pending(request):
|
||||
finally:
|
||||
uploaded.seek(0)
|
||||
raw_time = request.POST.get("captured_at", "")
|
||||
try:
|
||||
captured_at = datetime.fromtimestamp(float(raw_time), datetime_timezone.utc) if re.fullmatch(r"[0-9]{10}(?:\.[0-9]+)?", raw_time) else parse_datetime(raw_time)
|
||||
if captured_at is None or timezone.is_naive(captured_at):
|
||||
raise ValueError()
|
||||
if captured_at > timezone.now() + timedelta(minutes=5):
|
||||
raise ValueError()
|
||||
except (ValueError, OverflowError, OSError):
|
||||
return _submission_error("invalid_capture_time", "captured_at must be a valid past UTC time.")
|
||||
if not raw_time and request.POST.get("time_state") == "unknown":
|
||||
captured_at = None
|
||||
else:
|
||||
try:
|
||||
captured_at = datetime.fromtimestamp(float(raw_time), datetime_timezone.utc) if re.fullmatch(r"[0-9]{10}(?:\.[0-9]+)?", raw_time) else parse_datetime(raw_time)
|
||||
if captured_at is None or timezone.is_naive(captured_at):
|
||||
raise ValueError()
|
||||
if captured_at > timezone.now() + timedelta(minutes=5):
|
||||
raise ValueError()
|
||||
except (ValueError, OverflowError, OSError):
|
||||
return _submission_error("invalid_capture_time", "Provide a valid UTC captured_at or time_state=unknown.")
|
||||
firmware = request.POST.get("firmware_version", "")
|
||||
if not 1 <= len(firmware) <= 64 or not firmware.isprintable():
|
||||
return _submission_error("invalid_firmware_version", "Provide a printable firmware_version of at most 64 characters.")
|
||||
metadata = {}
|
||||
for key in ("trigger_type", "signal_rms", "signal_peak", "latitude", "longitude"):
|
||||
metadata = {"time_state": "unknown"} if captured_at is None else {}
|
||||
for key in ("trigger_type", "signal_rms", "signal_peak", "latitude", "longitude", "capture_started_at", "triggered_at", "queued_at"):
|
||||
value = request.POST.get(key)
|
||||
if value is None or value == "":
|
||||
continue
|
||||
if key == "trigger_type":
|
||||
if key.endswith("_at"):
|
||||
parsed = parse_datetime(value)
|
||||
if parsed is None or timezone.is_naive(parsed):
|
||||
return _submission_error("invalid_metadata", f"Invalid {key}.")
|
||||
elif key == "trigger_type":
|
||||
if len(value) > 64 or not value.isprintable():
|
||||
return _submission_error("invalid_metadata", "Invalid trigger_type.")
|
||||
else:
|
||||
@@ -585,7 +692,7 @@ def submit_sensor_pending(request):
|
||||
if existing:
|
||||
if existing.audio_sha256 != audio_hash:
|
||||
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
|
||||
return JsonResponse({"submission_id": str(existing.submission_id), "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True}, status=200)
|
||||
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True}, status=200)
|
||||
rate_key = f"sensor-submissions:{sensor.pk}"
|
||||
if cache.get(rate_key, 0) >= 30:
|
||||
response = _submission_error("rate_limited", "Sensor submission rate exceeded.", 429)
|
||||
@@ -606,17 +713,20 @@ def submit_sensor_pending(request):
|
||||
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError):
|
||||
return _submission_error("classifier_unavailable", "Classification failed; retain the queued recording.", 502)
|
||||
uploaded.seek(0)
|
||||
pending = None
|
||||
try:
|
||||
with transaction.atomic():
|
||||
pending = PendingEvent.objects.create(audio_file=uploaded, sensor=sensor, source_type=PendingEvent.SourceType.SENSOR, original_filename=Path(uploaded.name).name[:255], classifier_response=payload, captured_at=captured_at, firmware_version=firmware, device_metadata=metadata)
|
||||
receipt = SensorSubmission.objects.create(sensor=sensor, event_id=event_id, audio_sha256=audio_hash, pending_event=pending)
|
||||
except IntegrityError:
|
||||
if pending and pending.audio_file:
|
||||
pending.audio_file.storage.delete(pending.audio_file.name)
|
||||
existing = SensorSubmission.objects.get(sensor=sensor, event_id=event_id)
|
||||
if existing.audio_sha256 != audio_hash:
|
||||
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
|
||||
return JsonResponse({"submission_id": str(existing.submission_id), "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True})
|
||||
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True})
|
||||
sensor.record_heartbeat(submission=True)
|
||||
return JsonResponse({"submission_id": str(receipt.submission_id), "pending_event_id": pending.pk, "status": "pending", "classification": payload}, status=201)
|
||||
return JsonResponse({"submission_id": str(receipt.submission_id), "event_id": event_id, "pending_event_id": pending.pk, "status": "pending", "classification": payload}, status=201)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
|
||||
Reference in New Issue
Block a user