added scheduling
This commit is contained in:
+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