added compass direction finding
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.
@@ -4,17 +4,28 @@ from django.contrib import admin, messages
|
||||
from django.utils import timezone
|
||||
from django.utils.html import format_html
|
||||
|
||||
from .models import Event, PendingEvent, Sensor
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
@admin.register(ClassificationRule)
|
||||
class ClassificationRuleAdmin(admin.ModelAdmin):
|
||||
list_display = ("value", "rule_type", "enabled")
|
||||
list_filter = ("rule_type", "enabled")
|
||||
search_fields = ("value",)
|
||||
|
||||
|
||||
class ClassificationAdmin(admin.ModelAdmin):
|
||||
list_display = ("original_filename", "sensor", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("created_at",)
|
||||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("source_type", "visually_confirmed", "created_at")
|
||||
search_fields = ("original_filename",)
|
||||
readonly_fields = ("audio_file", "sensor", "original_filename", "created_at", "pretty_classifier_response")
|
||||
fields = ("audio_file", "sensor", "original_filename", "created_at")
|
||||
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")
|
||||
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
|
||||
|
||||
@admin.display(description="Direction")
|
||||
def direction_display(self, obj):
|
||||
return obj.direction_display
|
||||
|
||||
@admin.display(description="Classifier response")
|
||||
def pretty_classifier_response(self, obj):
|
||||
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.urls import path
|
||||
|
||||
from .views import classification_blacklist, classification_whitelist
|
||||
|
||||
|
||||
app_name = "classification_rules"
|
||||
|
||||
urlpatterns = [
|
||||
path("whitelist/", classification_whitelist, name="whitelist"),
|
||||
path("blacklist/", classification_blacklist, name="blacklist"),
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
import h3
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
|
||||
|
||||
|
||||
def h3_resolution():
|
||||
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
|
||||
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
|
||||
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
|
||||
return resolution
|
||||
|
||||
|
||||
def cell_from_coordinates(latitude, longitude):
|
||||
if latitude is None or longitude is None:
|
||||
return None
|
||||
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
|
||||
|
||||
|
||||
def cell_boundary(cell):
|
||||
try:
|
||||
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_center(cell):
|
||||
"""Return the centre of an H3 cell without exposing its source coordinate."""
|
||||
try:
|
||||
latitude, longitude = h3.cell_to_latlng(cell)
|
||||
return [latitude, longitude]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_disk(cell, distance=1):
|
||||
try:
|
||||
return sorted(h3.grid_disk(cell, distance))
|
||||
except (ValueError, h3.H3Error):
|
||||
return []
|
||||
@@ -0,0 +1,33 @@
|
||||
import h3
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
|
||||
|
||||
|
||||
def h3_resolution():
|
||||
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
|
||||
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
|
||||
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
|
||||
return resolution
|
||||
|
||||
|
||||
def cell_from_coordinates(latitude, longitude):
|
||||
if latitude is None or longitude is None:
|
||||
return None
|
||||
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
|
||||
|
||||
|
||||
def cell_boundary(cell):
|
||||
try:
|
||||
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_disk(cell, distance=1):
|
||||
try:
|
||||
return sorted(h3.grid_disk(cell, distance))
|
||||
except (ValueError, h3.H3Error):
|
||||
return []
|
||||
@@ -0,0 +1 @@
|
||||
"""Management commands for fireworks detection."""
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
"""Fireworks detection management commands."""
|
||||
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from fireworks_detect.h3_utils import cell_from_coordinates, h3_resolution
|
||||
from fireworks_detect.models import Event, PendingEvent
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Populate H3 cells for coordinate-bearing Pending and approved events."
|
||||
|
||||
def handle(self, *args, **options):
|
||||
updated = 0
|
||||
for model in (PendingEvent, Event):
|
||||
for record in model.objects.exclude(latitude__isnull=True).exclude(longitude__isnull=True):
|
||||
h3_cell = cell_from_coordinates(record.latitude, record.longitude)
|
||||
if record.h3_cell == h3_cell:
|
||||
continue
|
||||
record.h3_cell = h3_cell
|
||||
record.save(update_fields=["h3_cell"])
|
||||
updated += 1
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
f"Updated {updated} record(s) at H3 resolution {h3_resolution()}."
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("fireworks_detect", "0002_sensor_event_sensor_pendingevent_sensor"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="ClassificationRule",
|
||||
fields=[
|
||||
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||
("value", models.CharField(max_length=255)),
|
||||
(
|
||||
"rule_type",
|
||||
models.CharField(
|
||||
choices=[("whitelist", "Whitelist"), ("blacklist", "Blacklist")],
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
("enabled", models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
"ordering": ["value"],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="classificationrule",
|
||||
constraint=models.UniqueConstraint(fields=("value", "rule_type"), name="unique_classification_rule"),
|
||||
),
|
||||
]
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 20:59
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0003_classificationrule'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='location',
|
||||
field=models.CharField(blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='occurrences',
|
||||
field=models.PositiveIntegerField(default=1),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='source_type',
|
||||
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='visually_confirmed',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='location',
|
||||
field=models.CharField(blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='occurrences',
|
||||
field=models.PositiveIntegerField(default=1),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='source_type',
|
||||
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='visually_confirmed',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='event',
|
||||
name='audio_file',
|
||||
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='pendingevent',
|
||||
name='audio_file',
|
||||
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
|
||||
),
|
||||
]
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 21:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0004_event_location_event_occurrences_event_source_type_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 21:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0005_event_latitude_event_longitude_pendingevent_latitude_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='h3_cell',
|
||||
field=models.CharField(blank=True, db_index=True, max_length=20),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='h3_cell',
|
||||
field=models.CharField(blank=True, db_index=True, max_length=20),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,43 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 07:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0006_event_h3_cell_pendingevent_h3_cell'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_accuracy_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_source',
|
||||
field=models.CharField(blank=True, max_length=32),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_accuracy_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_source',
|
||||
field=models.CharField(blank=True, max_length=32),
|
||||
),
|
||||
]
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -1,6 +1,8 @@
|
||||
import math
|
||||
import secrets
|
||||
|
||||
from django.contrib.auth.hashers import check_password, make_password
|
||||
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
|
||||
@@ -44,13 +46,48 @@ class Sensor(models.Model):
|
||||
self.save(update_fields=fields)
|
||||
|
||||
|
||||
class ClassificationRule(models.Model):
|
||||
"""A configurable inclusion or exclusion rule for a classification label."""
|
||||
|
||||
class RuleType(models.TextChoices):
|
||||
WHITELIST = "whitelist", "Whitelist"
|
||||
BLACKLIST = "blacklist", "Blacklist"
|
||||
|
||||
value = models.CharField(max_length=255)
|
||||
rule_type = models.CharField(max_length=10, choices=RuleType.choices)
|
||||
enabled = models.BooleanField(default=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ["value"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["value", "rule_type"], name="unique_classification_rule"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.value} ({self.get_rule_type_display()})"
|
||||
|
||||
|
||||
class ClassifiedAudio(models.Model):
|
||||
"""Shared fields for a classifier response and its original audio upload."""
|
||||
|
||||
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d")
|
||||
class SourceType(models.TextChoices):
|
||||
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")
|
||||
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)
|
||||
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)
|
||||
h3_cell = models.CharField(max_length=20, blank=True, db_index=True)
|
||||
visually_confirmed = models.BooleanField(default=False)
|
||||
direction_degrees = models.FloatField(null=True, blank=True)
|
||||
direction_accuracy_degrees = models.FloatField(null=True, blank=True)
|
||||
direction_source = models.CharField(max_length=32, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
@@ -60,6 +97,36 @@ class ClassifiedAudio(models.Model):
|
||||
def __str__(self):
|
||||
return self.original_filename
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
errors = {}
|
||||
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."
|
||||
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."
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
|
||||
@property
|
||||
def direction_cardinal(self):
|
||||
if self.direction_degrees is None:
|
||||
return None
|
||||
directions = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
|
||||
return directions[int((self.direction_degrees + 22.5) % 360 // 45)]
|
||||
|
||||
|
||||
@property
|
||||
def direction_display(self):
|
||||
if self.direction_degrees is None:
|
||||
return "—"
|
||||
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
|
||||
|
||||
|
||||
@property
|
||||
def predictions(self):
|
||||
predictions = self.classifier_response.get("predictions", [])
|
||||
@@ -120,6 +187,16 @@ class PendingEvent(ClassifiedAudio):
|
||||
sensor=self.sensor,
|
||||
original_filename=self.original_filename,
|
||||
classifier_response=self.classifier_response,
|
||||
source_type=self.source_type,
|
||||
occurrences=self.occurrences,
|
||||
location=self.location,
|
||||
latitude=self.latitude,
|
||||
longitude=self.longitude,
|
||||
h3_cell=self.h3_cell,
|
||||
visually_confirmed=self.visually_confirmed,
|
||||
direction_degrees=self.direction_degrees,
|
||||
direction_accuracy_degrees=self.direction_accuracy_degrees,
|
||||
direction_source=self.direction_source,
|
||||
)
|
||||
self.delete()
|
||||
return event
|
||||
|
||||
@@ -1 +1,27 @@
|
||||
<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>{% 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>{% endfor %}<h3>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>{% endfor %}
|
||||
{% 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>
|
||||
{% 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>
|
||||
{% 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>
|
||||
{% endfor %}
|
||||
<h3>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>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
@@ -1 +1,18 @@
|
||||
{% if events %}{% for event in events %}<button class="event" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML"><span><strong>{{ event.primary_label }}</strong><br><small>{{ event.original_filename }} · {{ event.duration }}s</small></span><span class="badge">{{ event.primary_score }} →</span></button>{% endfor %}{% else %}<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>{% endif %}
|
||||
{% if events %}
|
||||
{% for event in events %}
|
||||
<button class="event{% if event.source_type == 'manual' %} event--manual{% endif %}" {% if event.source_type == 'manual' %}style="border-color:#e2934a;background:linear-gradient(90deg,#70401e,#15223f);"{% endif %} hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
|
||||
<span>
|
||||
{% if event.source_type == "manual" %}
|
||||
<strong>Manual fireworks report</strong><br>
|
||||
<small>{{ event.occurrences }} occurrence{{ event.occurrences|pluralize }}{% if event.location %} · {{ event.location }}{% endif %}</small>
|
||||
{% else %}
|
||||
<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>
|
||||
</button>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<div id="manual-submission" role="status">
|
||||
{% if error %}
|
||||
<strong>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>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -16,10 +16,10 @@
|
||||
}
|
||||
.topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:3.5rem; }.brand { display:flex; align-items:center; gap:.7rem; color:var(--ink); font-size:.9rem; font-weight:800; letter-spacing:.1em; text-decoration:none; text-transform:uppercase; }.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }.nav { display:flex; gap:.35rem; padding:.25rem; border:1px solid var(--line); border-radius:.75rem; background:#111a31a6; }.nav a { padding:.5rem .75rem; border-radius:.5rem; color:var(--muted); font-size:.86rem; font-weight:700; text-decoration:none; }.nav a[aria-current="page"] { color:var(--ink); background:#2a3b67; }
|
||||
.kicker { margin:0 0 .65rem; color:#bfdbfe; font-size:.76rem; font-weight:800; letter-spacing:.14em; text-transform:uppercase; }.headline { display:flex; align-items:end; justify-content:space-between; gap:2rem; margin-bottom:2rem; }.headline h1 { margin:0; font-size:clamp(2.3rem,5vw,4.5rem); line-height:.98; letter-spacing:-.06em; }.headline p { max-width:30rem; margin:0; color:var(--muted); line-height:1.6; }
|
||||
.filters { display:grid; grid-template-columns:1.3fr repeat(3,minmax(8rem,1fr)) auto; gap:.75rem; align-items:end; margin-bottom:1rem; padding:1rem; border:1px solid var(--line); border-radius:1.1rem; background:#121d37d9; box-shadow:0 1rem 3rem #03071466; }.filter { display:grid; gap:.35rem; }.filter label { color:#9fb1d5; font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }.filter select,.filter input { width:100%; min-height:2.65rem; border:1px solid #354a77; border-radius:.65rem; padding:0 .75rem; color:var(--ink); font:inherit; background:#0c1428; }.filter select:focus,.filter input:focus { outline:2px solid #82b5ff; outline-offset:2px; }.mock-tag { align-self:center; padding:.46rem .65rem; border:1px solid #4a5f8e; border-radius:999px; color:#c9d8f6; font-size:.75rem; font-weight:700; white-space:nowrap; background:#1d2b4e; }
|
||||
.map-panel { overflow:hidden; border:1px solid var(--line); border-radius:1.25rem; background:var(--surface); box-shadow:0 1.5rem 4rem #0206168a; }.map-header { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.2rem; border-bottom:1px solid var(--line); }.map-header strong { font-size:.95rem; }.live { display:flex; align-items:center; gap:.45rem; color:#a7f3d0; font-size:.8rem; }.live i { width:.5rem; height:.5rem; border-radius:50%; background:var(--green); box-shadow:0 0 0 .25rem #34d3992e; }.map-wrap { position:relative; }.map { height:clamp(30rem,65vh,45rem); background:#dce4cf; }.legend { position:absolute; z-index:600; right:1rem; bottom:1rem; width:min(15rem,calc(100% - 2rem)); padding:.85rem; border:1px solid #344973; border-radius:.8rem; color:#dce7fe; font-size:.78rem; background:#101a31e8; box-shadow:0 .75rem 2rem #05091480; backdrop-filter:blur(10px); }.legend h2 { margin:0 0 .6rem; font-size:.82rem; }.legend div { display:flex; align-items:center; gap:.5rem; margin-top:.4rem; }.legend-dot { width:.7rem; height:.7rem; border:2px solid #f2c56b; border-radius:50%; background:#ed8e2e88; }.legend-ring { width:.85rem; height:.85rem; border:2px solid #a98af7; border-radius:50%; background:#8b5cf633; }.legend-line { width:1.1rem; border-top:2px dashed #644b9c; }.sensor-icon { display:grid; width:2.1rem; height:2.1rem; place-items:center; border:2px solid #e6edff; border-radius:50%; color:#14203b; font-size:.72rem; font-weight:900; background:linear-gradient(135deg,#a5c8ff,#c4b5fd); box-shadow:0 .2rem .8rem #18275080; }.source-icon { display:grid; width:2.45rem; height:2.45rem; place-items:center; border:2px solid #fff3d5; border-radius:50% 50% 50% 0; color:#452000; font-size:1.15rem; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; transform:rotate(-45deg); }.source-icon span { transform:rotate(45deg); }.direction-arrow { display:block; color:#5c408d; font-size:1.5rem; font-weight:900; line-height:1; text-shadow:0 .1rem .4rem #fff8; }
|
||||
.leaflet-control-zoom a { color:#243456!important; }.leaflet-popup-content-wrapper,.leaflet-popup-tip { color:#e9f1ff; background:#14203a; }.leaflet-popup-content { margin:.75rem .9rem; font-family:inherit; }.popup-title { display:block; margin-bottom:.2rem; font-weight:800; }.popup-meta { color:#a9b9d8; font-size:.78rem; }
|
||||
@media (max-width:52rem) { .shell { width:min(100% - 1.25rem,80rem); }.topbar { margin-bottom:2.5rem; }.headline { align-items:start; flex-direction:column; gap:1rem; }.filters { grid-template-columns:1fr 1fr; }.filters .filter:first-child { grid-column:1/-1; }.mock-tag { justify-self:start; }.map { height:32rem; } }
|
||||
.filters { display:grid; grid-template-columns:repeat(5,minmax(8rem,1fr)) auto auto; gap:.75rem; align-items:end; margin-bottom:1rem; padding:1rem; border:1px solid var(--line); border-radius:1.1rem; background:#121d37d9; box-shadow:0 1rem 3rem #03071466; }.filter { display:grid; gap:.35rem; }.filter label { color:#9fb1d5; font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }.filter select,.filter input { width:100%; min-height:2.65rem; border:1px solid #354a77; border-radius:.65rem; padding:0 .75rem; color:var(--ink); font:inherit; background:#0c1428; }.filter select:focus,.filter input:focus { outline:2px solid #82b5ff; outline-offset:2px; }.filter-submit { min-height:2.65rem; border:1px solid #8ab7ff; border-radius:.65rem; padding:0 1rem; color:#101a31; font:inherit; font-weight:800; background:#b9d6ff; cursor:pointer; }.map-tag { align-self:center; padding:.46rem .65rem; border:1px solid #4a5f8e; border-radius:999px; color:#c9d8f6; font-size:.75rem; font-weight:700; white-space:nowrap; background:#1d2b4e; }
|
||||
.map-panel { overflow:hidden; border:1px solid var(--line); border-radius:1.25rem; background:var(--surface); box-shadow:0 1.5rem 4rem #0206168a; }.map-header { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.2rem; border-bottom:1px solid var(--line); }.map-header strong { font-size:.95rem; }.live { display:flex; align-items:center; gap:.45rem; color:#a7f3d0; font-size:.8rem; }.live i { width:.5rem; height:.5rem; border-radius:50%; background:var(--green); box-shadow:0 0 0 .25rem #34d3992e; }.map-wrap { position:relative; }.map { height:clamp(30rem,65vh,45rem); background:#dce4cf; }.legend { position:absolute; z-index:600; right:1rem; bottom:1rem; width:min(15rem,calc(100% - 2rem)); padding:.85rem; border:1px solid #344973; border-radius:.8rem; color:#dce7fe; font-size:.78rem; background:#101a31e8; box-shadow:0 .75rem 2rem #05091480; backdrop-filter:blur(10px); }.legend h2 { margin:0 0 .6rem; font-size:.82rem; }.legend div { display:flex; align-items:center; gap:.5rem; margin-top:.4rem; }.legend-dot { width:.7rem; height:.7rem; border:2px solid #f2c56b; border-radius:50%; background:#ed8e2e88; }.legend-ring { width:.85rem; height:.85rem; border:2px solid #a98af7; border-radius:50%; background:#8b5cf633; }.legend-line { width:1.1rem; border-top:2px dashed #644b9c; }.report-icon { display:grid; width:2.3rem; height:2.3rem; place-items:center; border:2px solid #fff3d5; border-radius:50%; color:#452000; font-size:1rem; font-weight:900; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; }.source-icon { display:grid; width:2.45rem; height:2.45rem; place-items:center; border:2px solid #fff3d5; border-radius:50% 50% 50% 0; color:#452000; font-size:1.15rem; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; transform:rotate(-45deg); }.source-icon span { transform:rotate(45deg); }.direction-marker { display:grid; width:3.5rem; height:3.5rem; place-items:center; border:3px solid #fff7e6; border-radius:50%; color:#fff; background:#6d45a0; box-shadow:0 .3rem 1rem #281642b3; }.direction-marker span { display:block; font-size:2.45rem; font-weight:950; line-height:1; text-shadow:0 .1rem .25rem #1e1136; transform-origin:center; }
|
||||
.map-compass { position:relative; width:5rem; height:5rem; border:2px solid #eaf1ff; border-radius:50%; color:#f7fbff; font-size:.72rem; font-weight:900; background:#111a31e8; box-shadow:0 .5rem 1.5rem #05091480; backdrop-filter:blur(8px); }.map-compass span { position:absolute; display:grid; place-items:center; }.map-compass .compass-n { top:.35rem; left:50%; transform:translateX(-50%); color:#ffd18c; }.map-compass .compass-e { top:50%; right:.45rem; transform:translateY(-50%); }.map-compass .compass-s { bottom:.35rem; left:50%; transform:translateX(-50%); }.map-compass .compass-w { top:50%; left:.45rem; transform:translateY(-50%); }.map-compass .compass-needle { top:1.3rem; left:50%; color:#ffd18c; font-size:2rem; line-height:1; transform:translateX(-50%); text-shadow:0 .1rem .35rem #3b1b48; }.leaflet-control-zoom a { color:#243456!important; }.leaflet-popup-content-wrapper,.leaflet-popup-tip { color:#e9f1ff; background:#14203a; }.leaflet-popup-content { margin:.75rem .9rem; font-family:inherit; }.popup-title { display:block; margin-bottom:.2rem; font-weight:800; }.popup-meta { color:#a9b9d8; font-size:.78rem; }
|
||||
@media (max-width:52rem) { .shell { width:min(100% - 1.25rem,80rem); }.topbar { margin-bottom:2.5rem; }.headline { align-items:start; flex-direction:column; gap:1rem; }.filters { grid-template-columns:1fr 1fr; }.filters .filter:first-child { grid-column:1/-1; }.map { height:32rem; } }
|
||||
@media (max-width:30rem) { .nav a { padding:.5rem; }.filters { grid-template-columns:1fr; }.filters .filter:first-child { grid-column:auto; } }
|
||||
</style>
|
||||
</head>
|
||||
@@ -34,59 +34,125 @@
|
||||
</header>
|
||||
|
||||
<section class="headline" aria-labelledby="map-title">
|
||||
<div><p class="kicker">Future event intelligence</p><h1 id="map-title">Sound activity map.</h1></div>
|
||||
<p>A concept view of sensors triangulating a likely source. This uses entirely mock data for Heerenveen, ready for future incoming event records.</p>
|
||||
<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>
|
||||
</section>
|
||||
|
||||
<section class="filters" aria-label="Mock event filters">
|
||||
<div class="filter"><label for="event-type">Event type</label><select id="event-type"><option>All sound events</option><option>Possible fireworks</option><option>Privacy-filtered speech</option></select></div>
|
||||
<div class="filter"><label for="from-date">From</label><input id="from-date" type="date" value="2026-09-19"></div>
|
||||
<div class="filter"><label for="range">Range</label><select id="range"><option>This week</option><option>Today</option><option>Last 30 days</option></select></div>
|
||||
<div class="filter"><label for="confidence">Confidence</label><select id="confidence"><option>Any confidence</option><option>High confidence</option><option>Review needed</option></select></div>
|
||||
<span class="mock-tag">Mock data</span>
|
||||
</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>
|
||||
|
||||
<section class="map-panel" aria-label="Mock sound event map of Heerenveen">
|
||||
<div class="map-header"><strong>Heerenveen, Netherlands</strong><span class="live"><i></i> 3 sensors simulated</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" aria-label="Interactive map centered on Heerenveen"></div>
|
||||
<aside class="legend" aria-label="Map legend"><h2>Triangulation estimate</h2><div><span class="legend-dot"></span> Higher-confidence source area</div><div><span class="legend-ring"></span> Broader possible area</div><div><span class="legend-line"></span> Simulated direction of arrival</div></aside>
|
||||
<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" 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>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
{{ h3_cells|json_script:"h3-cells-data" }}
|
||||
{{ map_events|json_script:"map-events-data" }}
|
||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||
<script>
|
||||
const map = L.map('event-map', { zoomControl: false, scrollWheelZoom: false }).setView([52.9512478, 5.943674], 14);
|
||||
L.control.zoom({ position: 'bottomleft' }).addTo(map);
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png', {
|
||||
const map = L.map("event-map", { zoomControl: false, scrollWheelZoom: false }).setView([52.1326, 5.2913], 7);
|
||||
L.control.zoom({ position: "bottomleft" }).addTo(map);
|
||||
const compassControl = L.control({ position: "topright" });
|
||||
compassControl.onAdd = () => {
|
||||
const compass = L.DomUtil.create("div", "map-compass");
|
||||
compass.setAttribute("role", "img");
|
||||
compass.setAttribute("aria-label", "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;
|
||||
};
|
||||
compassControl.addTo(map);
|
||||
L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png", {
|
||||
maxZoom: 18,
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
attribution: "© OpenStreetMap contributors",
|
||||
}).addTo(map);
|
||||
|
||||
const estimatedSource = [52.9501, 5.9466];
|
||||
const sensors = [
|
||||
{ name: 'Sensor 1', position: [52.9570, 5.9335], confidence: '91% direction confidence' },
|
||||
{ name: 'Sensor 2', position: [52.9586, 5.9508], confidence: '86% direction confidence' },
|
||||
{ name: 'Sensor 3', position: [52.9458, 5.9370], confidence: '78% direction confidence' },
|
||||
];
|
||||
const h3Cells = JSON.parse(document.getElementById("h3-cells-data").textContent);
|
||||
const reports = JSON.parse(document.getElementById("map-events-data").textContent);
|
||||
const bounds = L.latLngBounds([]);
|
||||
|
||||
L.circle(estimatedSource, { radius: 1020, color: '#8b5cf6', weight: 1.5, fillColor: '#8b5cf6', fillOpacity: 0.10, dashArray: '5 8' }).addTo(map);
|
||||
L.circle(estimatedSource, { radius: 370, color: '#f59e0b', weight: 2, fillColor: '#f59e0b', fillOpacity: 0.28 }).addTo(map);
|
||||
const sourceIcon = L.divIcon({ className: '', html: '<div class="source-icon"><span>✦</span></div>', iconSize: [39, 39], iconAnchor: [20, 32] });
|
||||
L.marker(estimatedSource, { icon: sourceIcon }).addTo(map).bindPopup('<span class="popup-title">Estimated sound source</span><span class="popup-meta">High-confidence area · mock event</span>');
|
||||
h3Cells.forEach((cell) => {
|
||||
const polygon = L.polygon(cell.boundary, {
|
||||
color: "#f59e0b", weight: 2, fillColor: "#f59e0b", fillOpacity: 0.25,
|
||||
}).addTo(map);
|
||||
polygon.bindPopup(
|
||||
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
|
||||
"<span class=\"popup-meta\">" + cell.reports + " reports · " + cell.occurrences +
|
||||
" occurrences · resolution {{ h3_resolution }}</span>"
|
||||
);
|
||||
bounds.extend(L.latLngBounds(cell.boundary));
|
||||
});
|
||||
|
||||
function bearing(from, to) {
|
||||
const lat = ((from[0] + to[0]) / 2) * Math.PI / 180;
|
||||
return Math.atan2((to[1] - from[1]) * Math.cos(lat), to[0] - from[0]) * 180 / Math.PI;
|
||||
function cardinalDirection(degrees) {
|
||||
const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
return directions[Math.floor(((degrees + 22.5) % 360) / 45)];
|
||||
}
|
||||
sensors.forEach((sensor, index) => {
|
||||
const line = L.polyline([sensor.position, estimatedSource], { color: '#60438f', weight: 2, opacity: 0.85, dashArray: '8 9' }).addTo(map);
|
||||
line.bindTooltip('Direction of arrival', { sticky: true });
|
||||
const arrowPosition = [sensor.position[0] + (estimatedSource[0] - sensor.position[0]) * 0.58, sensor.position[1] + (estimatedSource[1] - sensor.position[1]) * 0.58];
|
||||
const arrowIcon = L.divIcon({ className: '', html: `<span class="direction-arrow" style="transform:rotate(${bearing(sensor.position, estimatedSource)}deg)">↑</span>`, iconSize: [22, 22], iconAnchor: [11, 11] });
|
||||
L.marker(arrowPosition, { icon: arrowIcon, interactive: false }).addTo(map);
|
||||
const sensorIcon = L.divIcon({ className: '', html: `<div class="sensor-icon">${index + 1}</div>`, iconSize: [34, 34], iconAnchor: [17, 17] });
|
||||
L.marker(sensor.position, { icon: sensorIcon }).addTo(map).bindPopup(`<span class="popup-title">${sensor.name}</span><span class="popup-meta">${sensor.confidence}<br>Mock microphone node</span>`);
|
||||
|
||||
function destinationPoint(origin, bearingDegrees, distanceMetres) {
|
||||
const earthRadius = 6378137;
|
||||
const bearing = bearingDegrees * Math.PI / 180;
|
||||
const latitude = origin[0] * Math.PI / 180;
|
||||
const longitude = origin[1] * Math.PI / 180;
|
||||
const angularDistance = distanceMetres / earthRadius;
|
||||
const targetLatitude = Math.asin(
|
||||
Math.sin(latitude) * Math.cos(angularDistance) +
|
||||
Math.cos(latitude) * Math.sin(angularDistance) * Math.cos(bearing)
|
||||
);
|
||||
const targetLongitude = longitude + Math.atan2(
|
||||
Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(latitude),
|
||||
Math.cos(angularDistance) - Math.sin(latitude) * Math.sin(targetLatitude)
|
||||
);
|
||||
return [targetLatitude * 180 / Math.PI, targetLongitude * 180 / Math.PI];
|
||||
}
|
||||
|
||||
const reportIcon = L.divIcon({
|
||||
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;
|
||||
if (report.direction_degrees !== null) {
|
||||
detail += "<br>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-meta\">" + detail + "</span>"
|
||||
);
|
||||
|
||||
if (report.direction_degrees !== null) {
|
||||
const arrowEnd = destinationPoint(report.center, report.direction_degrees, 900);
|
||||
L.polyline([report.center, arrowEnd], { color: "#fff7e6", weight: 9, opacity: 0.8 }).addTo(map);
|
||||
L.polyline([report.center, arrowEnd], { color: "#6d45a0", weight: 5, opacity: 1 }).addTo(map);
|
||||
const arrowIcon = L.divIcon({
|
||||
className: "",
|
||||
html: "<div class=\"direction-marker\"><span style=\"transform:rotate(" + report.direction_degrees + "deg)\">↑</span></div>",
|
||||
iconSize: [56, 56], iconAnchor: [28, 28],
|
||||
});
|
||||
L.marker(arrowEnd, { icon: arrowIcon, interactive: false }).addTo(map);
|
||||
}
|
||||
});
|
||||
|
||||
if (bounds.isValid()) {
|
||||
map.fitBounds(bounds.pad(0.18));
|
||||
}
|
||||
|
||||
const range = document.getElementById("range");
|
||||
document.querySelectorAll("#from-date, #to-date").forEach((input) => {
|
||||
input.addEventListener("change", () => { range.value = "custom"; });
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
+265
-2
@@ -1,3 +1,266 @@
|
||||
from django.test import TestCase
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
# Create your tests here.
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.test import TestCase, override_settings
|
||||
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
|
||||
|
||||
|
||||
class ClassificationRuleApiTests(TestCase):
|
||||
def test_whitelist_returns_only_enabled_whitelist_entries_in_value_order(self):
|
||||
ClassificationRule.objects.create(value="Explosion", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
ClassificationRule.objects.create(value="Disabled firework", rule_type=ClassificationRule.RuleType.WHITELIST, enabled=False)
|
||||
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
|
||||
response = self.client.get(reverse("classification_rules:whitelist"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"classifications": ["Explosion", "Fireworks"]})
|
||||
|
||||
def test_blacklist_returns_only_enabled_blacklist_entries_in_value_order(self):
|
||||
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
ClassificationRule.objects.create(value="Conversation", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
ClassificationRule.objects.create(value="Disabled music", rule_type=ClassificationRule.RuleType.BLACKLIST, enabled=False)
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
response = self.client.get(reverse("classification_rules:blacklist"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"classifications": ["Conversation", "Speech"]})
|
||||
|
||||
def test_classification_rule_is_unique_within_a_rule_type(self):
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
with transaction.atomic():
|
||||
with self.assertRaises(IntegrityError):
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
|
||||
|
||||
class ManualPendingEventTests(TestCase):
|
||||
def test_manual_report_creates_a_timestamped_pending_event(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "4",
|
||||
"latitude": "52.1234567",
|
||||
"longitude": "5.9876543",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Report sent to Pending")
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.original_filename, "Manual fireworks report")
|
||||
self.assertEqual(pending.source_type, PendingEvent.SourceType.MANUAL)
|
||||
self.assertEqual(pending.occurrences, 4)
|
||||
self.assertEqual(pending.latitude, Decimal("52.123457"))
|
||||
self.assertEqual(pending.longitude, Decimal("5.987654"))
|
||||
self.assertEqual(pending.h3_cell, cell_from_coordinates(pending.latitude, pending.longitude))
|
||||
self.assertIsNone(pending.direction_degrees)
|
||||
self.assertIsNone(pending.direction_accuracy_degrees)
|
||||
self.assertEqual(pending.direction_source, "")
|
||||
self.assertFalse(pending.sensor)
|
||||
self.assertFalse(pending.audio_file)
|
||||
self.assertEqual(pending.classifier_response, {})
|
||||
self.assertIsNotNone(pending.created_at)
|
||||
|
||||
def test_manual_report_rejects_an_invalid_occurrence_count(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "0"})
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "Choose between 1 and 1,000 occurrences.", status_code=400)
|
||||
self.assertFalse(PendingEvent.objects.exists())
|
||||
|
||||
def test_event_details_and_source_type_are_kept_when_a_pending_event_is_approved(self):
|
||||
pending = PendingEvent.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=PendingEvent.SourceType.MANUAL,
|
||||
occurrences=3,
|
||||
location="Back garden",
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")),
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
direction_source="device_compass",
|
||||
visually_confirmed=True,
|
||||
)
|
||||
|
||||
event = pending.approve()
|
||||
|
||||
self.assertEqual(event.source_type, PendingEvent.SourceType.MANUAL)
|
||||
self.assertEqual(event.occurrences, 3)
|
||||
self.assertEqual(event.location, "Back garden")
|
||||
self.assertEqual(event.latitude, Decimal("52.123456"))
|
||||
self.assertEqual(event.longitude, Decimal("5.987654"))
|
||||
self.assertEqual(event.h3_cell, pending.h3_cell)
|
||||
self.assertEqual(event.direction_degrees, 237)
|
||||
self.assertEqual(event.direction_accuracy_degrees, 8)
|
||||
self.assertEqual(event.direction_source, "device_compass")
|
||||
self.assertTrue(event.visually_confirmed)
|
||||
|
||||
def test_existing_style_records_default_to_sensor_source_type(self):
|
||||
pending = PendingEvent.objects.create(original_filename="recording.wav", classifier_response={})
|
||||
|
||||
self.assertEqual(pending.source_type, PendingEvent.SourceType.SENSOR)
|
||||
|
||||
def test_home_page_includes_the_manual_report_form(self):
|
||||
response = self.client.get(reverse("hello"))
|
||||
|
||||
self.assertContains(response, "Report fireworks now")
|
||||
self.assertContains(response, "I heard fireworks — send to Pending")
|
||||
self.assertContains(response, "navigator.geolocation")
|
||||
self.assertContains(response, "Capture direction")
|
||||
self.assertContains(response, "DeviceOrientationEvent.requestPermission")
|
||||
self.assertContains(response, 'manual-direction-panel" hidden')
|
||||
self.assertContains(response, "DeviceOrientationEvent.requestPermission(true)")
|
||||
self.assertContains(response, 'webkitCompassHeading" in event')
|
||||
self.assertContains(response, "direction will update live")
|
||||
self.assertContains(response, "Stop direction capture")
|
||||
|
||||
self.assertContains(response, "htmx.ajax")
|
||||
def test_manual_event_appears_in_the_normal_event_list_with_its_details(self):
|
||||
event = Event.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL,
|
||||
occurrences=5,
|
||||
location="Back garden",
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
visually_confirmed=True,
|
||||
)
|
||||
|
||||
list_response = self.client.get(reverse("fireworks_detect:events_list"))
|
||||
self.assertContains(list_response, "Manual fireworks report")
|
||||
self.assertContains(list_response, "5 occurrences")
|
||||
self.assertContains(list_response, "Back garden")
|
||||
|
||||
detail_response = self.client.get(reverse("fireworks_detect:event_detail", args=[event.pk]))
|
||||
self.assertContains(detail_response, "Report details")
|
||||
self.assertContains(detail_response, "Visually confirmed")
|
||||
self.assertContains(detail_response, "Captured location")
|
||||
self.assertContains(detail_response, cell_from_coordinates(event.latitude, event.longitude))
|
||||
self.assertNotContains(detail_response, "52.123456, 5.987654")
|
||||
self.assertContains(detail_response, "237° (SW)")
|
||||
self.assertContains(detail_response, "Compass accuracy")
|
||||
|
||||
@override_settings(FIREWORKS_H3_RESOLUTION=8)
|
||||
def test_h3_resolution_is_configurable(self):
|
||||
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):
|
||||
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(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL,
|
||||
occurrences=4,
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=manual_cell,
|
||||
visually_confirmed=True,
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
)
|
||||
Event.objects.create(
|
||||
original_filename="Sensor recording.wav",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.SENSOR,
|
||||
occurrences=9,
|
||||
latitude=Decimal("53.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=sensor_cell,
|
||||
)
|
||||
|
||||
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all"})
|
||||
|
||||
self.assertContains(response, "H3 resolution 9")
|
||||
self.assertContains(response, "map-events-data")
|
||||
self.assertContains(response, manual_cell)
|
||||
self.assertContains(response, '"direction_degrees": 237.0')
|
||||
self.assertContains(response, "cardinalDirection(report.direction_degrees)")
|
||||
self.assertContains(response, "sensor layer disabled")
|
||||
self.assertContains(response, "Map compass: north is up")
|
||||
self.assertContains(response, "Sensor events — coming soon")
|
||||
self.assertNotContains(response, sensor_cell)
|
||||
self.assertNotContains(response, "52.123456")
|
||||
self.assertNotContains(response, "H3 demo cell")
|
||||
|
||||
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"))
|
||||
Event.objects.create(
|
||||
original_filename="Recent manual report", classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL, latitude=Decimal("52.400000"),
|
||||
longitude=Decimal("5.700000"), h3_cell=recent_cell,
|
||||
)
|
||||
older = Event.objects.create(
|
||||
original_filename="Older manual report", classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL, latitude=Decimal("53.400000"),
|
||||
longitude=Decimal("5.700000"), h3_cell=older_cell,
|
||||
)
|
||||
Event.objects.filter(pk=older.pk).update(created_at=timezone.now() - timedelta(days=8))
|
||||
|
||||
response = self.client.get(reverse("fireworks_detect:map"), {"range": "7"})
|
||||
|
||||
self.assertContains(response, recent_cell)
|
||||
self.assertNotContains(response, older_cell)
|
||||
self.assertContains(response, "Last 7 days")
|
||||
|
||||
|
||||
def test_manual_report_saves_a_valid_compass_direction_and_accuracy(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "2",
|
||||
"direction_degrees": "237",
|
||||
"direction_accuracy_degrees": "8",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.direction_degrees, 237)
|
||||
self.assertEqual(pending.direction_accuracy_degrees, 8)
|
||||
self.assertEqual(pending.direction_source, "device_compass")
|
||||
self.assertEqual(pending.direction_cardinal, "SW")
|
||||
|
||||
def test_zero_degree_direction_is_valid_and_accuracy_may_be_absent(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "1",
|
||||
"direction_degrees": "0",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.direction_degrees, 0)
|
||||
self.assertIsNone(pending.direction_accuracy_degrees)
|
||||
self.assertEqual(pending.direction_cardinal, "N")
|
||||
|
||||
def test_invalid_directions_are_rejected_by_model_validation_and_not_saved_by_manual_submission(self):
|
||||
for invalid_direction in (-1, 360):
|
||||
pending = PendingEvent(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
direction_degrees=invalid_direction,
|
||||
)
|
||||
with self.assertRaises(ValidationError):
|
||||
pending.full_clean()
|
||||
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "1",
|
||||
"direction_degrees": str(invalid_direction),
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
saved = PendingEvent.objects.latest("created_at")
|
||||
self.assertIsNone(saved.direction_degrees)
|
||||
self.assertIsNone(saved.direction_accuracy_degrees)
|
||||
self.assertEqual(saved.direction_source, "")
|
||||
|
||||
@@ -10,6 +10,7 @@ from .views import (
|
||||
fireworks_map_view,
|
||||
fireworks_view,
|
||||
pending_audio,
|
||||
submit_manual_pending_event,
|
||||
submit_pending_event,
|
||||
sensor_heartbeat,
|
||||
)
|
||||
@@ -23,6 +24,7 @@ urlpatterns = [
|
||||
path("classify/upload/", classify_upload, name="classify_upload"),
|
||||
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("events/", events_view, name="events"),
|
||||
path("events/list/", events_list, name="events_list"),
|
||||
path("admin-audio/pending/<int:event_id>/", pending_audio, name="pending_audio"),
|
||||
|
||||
+187
-2
@@ -1,3 +1,6 @@
|
||||
import math
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import mimetypes
|
||||
import uuid
|
||||
@@ -9,11 +12,14 @@ from django.contrib.admin.views.decorators import staff_member_required
|
||||
from django.http import FileResponse, Http404, JsonResponse
|
||||
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.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import Event, PendingEvent, Sensor
|
||||
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
|
||||
@@ -35,9 +41,107 @@ def fireworks_view(request):
|
||||
return render(request, "fireworks_detect/home.html")
|
||||
|
||||
|
||||
MAP_DATE_RANGES = {
|
||||
"7": 7,
|
||||
"14": 14,
|
||||
"30": 30,
|
||||
"all": None,
|
||||
"custom": None,
|
||||
}
|
||||
|
||||
|
||||
def _map_filters(request):
|
||||
"""Return the selected map filters, using an inclusive date range."""
|
||||
selected_range = request.GET.get("range", "14")
|
||||
if selected_range not in MAP_DATE_RANGES:
|
||||
selected_range = "14"
|
||||
|
||||
if selected_range == "custom":
|
||||
date_from = parse_date(request.GET.get("from", ""))
|
||||
date_to = parse_date(request.GET.get("to", ""))
|
||||
elif MAP_DATE_RANGES[selected_range]:
|
||||
date_to = timezone.localdate()
|
||||
date_from = date_to - timedelta(days=MAP_DATE_RANGES[selected_range] - 1)
|
||||
else:
|
||||
date_from = date_to = None
|
||||
|
||||
visual = request.GET.get("visual", "all")
|
||||
if visual not in {"all", "yes", "no"}:
|
||||
visual = "all"
|
||||
return {
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"range": selected_range,
|
||||
"visual": visual,
|
||||
}
|
||||
|
||||
|
||||
def _events_for_map(filters):
|
||||
"""Create privacy-preserving map data for reviewed manual reports only."""
|
||||
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
|
||||
if filters["date_from"]:
|
||||
events = events.filter(created_at__date__gte=filters["date_from"])
|
||||
if filters["date_to"]:
|
||||
events = events.filter(created_at__date__lte=filters["date_to"])
|
||||
if filters["visual"] == "yes":
|
||||
events = events.filter(visually_confirmed=True)
|
||||
elif filters["visual"] == "no":
|
||||
events = events.filter(visually_confirmed=False)
|
||||
|
||||
cells = {}
|
||||
mapped_events = []
|
||||
for event in events.values(
|
||||
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
|
||||
"direction_degrees", "direction_accuracy_degrees", "created_at",
|
||||
):
|
||||
# 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"])
|
||||
center = cell_center(h3_cell) if h3_cell else None
|
||||
boundary = cell_boundary(h3_cell) if h3_cell else None
|
||||
if not center or not boundary:
|
||||
continue
|
||||
|
||||
aggregate = cells.setdefault(h3_cell, {
|
||||
"cell": h3_cell,
|
||||
"boundary": boundary,
|
||||
"center": center,
|
||||
"reports": 0,
|
||||
"occurrences": 0,
|
||||
})
|
||||
aggregate["reports"] += 1
|
||||
aggregate["occurrences"] += event["occurrences"]
|
||||
mapped_events.append({
|
||||
"cell": h3_cell,
|
||||
"center": center,
|
||||
"occurrences": event["occurrences"],
|
||||
"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(),
|
||||
"direction_degrees": float(event["direction_degrees"]) if event["direction_degrees"] is not None else None,
|
||||
"direction_accuracy_degrees": (
|
||||
float(event["direction_accuracy_degrees"])
|
||||
if event["direction_accuracy_degrees"] is not None else None
|
||||
),
|
||||
})
|
||||
|
||||
return mapped_events, list(cells.values())
|
||||
|
||||
@never_cache
|
||||
def fireworks_map_view(request):
|
||||
return render(request, "fireworks_detect/map.html")
|
||||
filters = _map_filters(request)
|
||||
map_events, h3_cells = _events_for_map(filters)
|
||||
return render(request, "fireworks_detect/map.html", {
|
||||
"h3_resolution": h3_resolution(),
|
||||
"h3_cells": h3_cells,
|
||||
"map_events": map_events,
|
||||
"mapped_event_count": len(map_events),
|
||||
"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"],
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@never_cache
|
||||
@@ -181,6 +285,68 @@ def submit_pending_event(request):
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"pending": pending})
|
||||
|
||||
|
||||
def _manual_coordinates(request):
|
||||
try:
|
||||
latitude = Decimal(request.POST.get("latitude", ""))
|
||||
longitude = Decimal(request.POST.get("longitude", ""))
|
||||
if not -90 <= latitude <= 90 or not -180 <= longitude <= 180:
|
||||
return None, None
|
||||
return latitude.quantize(Decimal("0.000001")), longitude.quantize(Decimal("0.000001"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
return None, None
|
||||
|
||||
|
||||
def _manual_direction(request):
|
||||
try:
|
||||
heading = float(request.POST.get("direction_degrees", ""))
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
|
||||
if not math.isfinite(heading) or not 0 <= heading < 360:
|
||||
return None, None
|
||||
|
||||
try:
|
||||
accuracy = float(request.POST.get("direction_accuracy_degrees", ""))
|
||||
except (TypeError, ValueError):
|
||||
accuracy = None
|
||||
if accuracy is not None and (not math.isfinite(accuracy) or accuracy < 0):
|
||||
accuracy = None
|
||||
return heading, accuracy
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@never_cache
|
||||
def submit_manual_pending_event(request):
|
||||
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,
|
||||
)
|
||||
|
||||
latitude, longitude = _manual_coordinates(request)
|
||||
h3_cell = cell_from_coordinates(latitude, longitude)
|
||||
direction_degrees, direction_accuracy_degrees = _manual_direction(request)
|
||||
|
||||
pending = PendingEvent.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=PendingEvent.SourceType.MANUAL,
|
||||
occurrences=occurrences,
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
h3_cell=h3_cell or "",
|
||||
direction_degrees=direction_degrees,
|
||||
direction_accuracy_degrees=direction_accuracy_degrees,
|
||||
direction_source="device_compass" if direction_degrees is not None else "",
|
||||
)
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending})
|
||||
|
||||
@never_cache
|
||||
def events_list(request):
|
||||
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
|
||||
@@ -191,6 +357,7 @@ def event_detail(request, event_id):
|
||||
event = get_object_or_404(Event, pk=event_id)
|
||||
context = _classification_context(event.classifier_response)
|
||||
context["event"] = event
|
||||
context["event_h3_cell"] = event.h3_cell or cell_from_coordinates(event.latitude, event.longitude)
|
||||
return render(request, "fireworks_detect/event_detail.html", context)
|
||||
|
||||
|
||||
@@ -264,3 +431,21 @@ def sensor_heartbeat(request):
|
||||
return _sensor_error("A valid sensor API token is required.", 401)
|
||||
sensor.record_heartbeat()
|
||||
return JsonResponse({"ok": True, "sensor": sensor.name, "heartbeat_at": sensor.last_heartbeat.isoformat()})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def classification_whitelist(request):
|
||||
classifications = ClassificationRule.objects.filter(
|
||||
rule_type=ClassificationRule.RuleType.WHITELIST,
|
||||
enabled=True,
|
||||
).order_by("value").values_list("value", flat=True)
|
||||
return JsonResponse({"classifications": list(classifications)})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def classification_blacklist(request):
|
||||
classifications = ClassificationRule.objects.filter(
|
||||
rule_type=ClassificationRule.RuleType.BLACKLIST,
|
||||
enabled=True,
|
||||
).order_by("value").values_list("value", flat=True)
|
||||
return JsonResponse({"classifications": list(classifications)})
|
||||
|
||||
Reference in New Issue
Block a user