267 lines
11 KiB
Python
267 lines
11 KiB
Python
import json
|
|
import mimetypes
|
|
import uuid
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
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.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
|
|
|
|
|
|
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
|
|
MAX_AUDIO_SIZE = 25 * 1024 * 1024 # 25 MiB: enough for this demo, and avoids accidental large uploads.
|
|
|
|
FIREWORK_TERMS = (
|
|
"firework", "firecracker", "explosion", "explosive", "bang", "boom",
|
|
"hiss", "crackle", "burst", "gunshot", "artillery", "cannon", "rocket",
|
|
)
|
|
SPEECH_TERMS = (
|
|
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
|
|
"speaking", "speech synthesizer",
|
|
)
|
|
AUDIO_EXTENSIONS = {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".weba"}
|
|
|
|
|
|
@never_cache
|
|
def fireworks_view(request):
|
|
return render(request, "fireworks_detect/home.html")
|
|
|
|
|
|
@never_cache
|
|
def fireworks_map_view(request):
|
|
return render(request, "fireworks_detect/map.html")
|
|
|
|
|
|
@never_cache
|
|
def events_view(request):
|
|
return render(request, "fireworks_detect/events.html")
|
|
|
|
|
|
def _classification_context(payload):
|
|
predictions = _decorate_predictions(payload.get("predictions"))
|
|
peak_predictions = _decorate_predictions(payload.get("peak_predictions"))
|
|
return {
|
|
"result": payload,
|
|
"predictions": predictions,
|
|
"peak_predictions": peak_predictions,
|
|
"firework_count": sum(item["kind"] == "firework" for item in predictions + peak_predictions),
|
|
"speech_count": sum(item["kind"] == "speech" for item in predictions + peak_predictions),
|
|
}
|
|
|
|
|
|
def _label_kind(label):
|
|
lowered = label.lower()
|
|
if any(term in lowered for term in SPEECH_TERMS):
|
|
return "speech"
|
|
if any(term in lowered for term in FIREWORK_TERMS):
|
|
return "firework"
|
|
return "default"
|
|
|
|
|
|
def _score_details(score):
|
|
try:
|
|
percentage = max(0, min(float(score) * 100, 100))
|
|
except (TypeError, ValueError):
|
|
return "—", 0
|
|
return f"{percentage:.1f}%", round(percentage, 1)
|
|
|
|
|
|
def _decorate_predictions(predictions):
|
|
decorated = []
|
|
for prediction in predictions if isinstance(predictions, list) else []:
|
|
if not isinstance(prediction, dict):
|
|
continue
|
|
label = str(prediction.get("class", "Unknown"))
|
|
score, score_width = _score_details(prediction.get("score"))
|
|
decorated.append({
|
|
**prediction,
|
|
"label": label,
|
|
"kind": _label_kind(label),
|
|
"score_display": score,
|
|
"score_width": score_width,
|
|
})
|
|
return decorated
|
|
|
|
|
|
def _encode_audio_multipart(uploaded_file):
|
|
"""Build the multipart request expected by the classifier without a third-party HTTP client."""
|
|
boundary = f"----DjangoAudioUpload{uuid.uuid4().hex}"
|
|
filename = Path(uploaded_file.name).name.replace('"', "")
|
|
content_type = uploaded_file.content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
header = (
|
|
f"--{boundary}\r\n"
|
|
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
|
|
f"Content-Type: {content_type}\r\n\r\n"
|
|
).encode()
|
|
body = header + uploaded_file.read() + f"\r\n--{boundary}--\r\n".encode()
|
|
return body, f"multipart/form-data; boundary={boundary}"
|
|
|
|
|
|
def _render_error(request, message, status=400):
|
|
return render(request, "fireworks_detect/classification_result.html", {"error": message}, status=status)
|
|
|
|
|
|
@require_http_methods(["GET", "POST"])
|
|
@never_cache
|
|
def classify_upload(request):
|
|
# Opening this endpoint in a browser should return the upload screen rather
|
|
# than a 405 page. Only POST requests perform classification.
|
|
if request.method == "GET":
|
|
return redirect("fireworks_detect:fireworks")
|
|
|
|
uploaded_file = request.FILES.get("audio")
|
|
if not uploaded_file:
|
|
return _render_error(request, "Choose an audio file before starting the analysis.")
|
|
|
|
extension = Path(uploaded_file.name).suffix.lower()
|
|
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
|
|
return _render_error(request, "Please upload a supported audio file (such as WAV, MP3, M4A, or OGG).")
|
|
if uploaded_file.size > MAX_AUDIO_SIZE:
|
|
return _render_error(request, "This demo accepts audio files up to 25 MiB.")
|
|
|
|
body, content_type = _encode_audio_multipart(uploaded_file)
|
|
classifier_request = Request(
|
|
CLASSIFIER_URL,
|
|
data=body,
|
|
headers={"Content-Type": content_type, "Accept": "application/json"},
|
|
method="POST",
|
|
)
|
|
|
|
try:
|
|
with urlopen(classifier_request, timeout=60) as response:
|
|
payload = json.loads(response.read().decode("utf-8"))
|
|
except HTTPError as error:
|
|
return _render_error(request, f"The classifier returned an error (HTTP {error.code}).", status=502)
|
|
except (URLError, TimeoutError):
|
|
return _render_error(request, "The classifier could not be reached. Please try again shortly.", status=502)
|
|
except json.JSONDecodeError:
|
|
return _render_error(request, "The classifier returned an unreadable response.", status=502)
|
|
|
|
if not isinstance(payload, dict):
|
|
return _render_error(request, "The classifier returned an unexpected response.", status=502)
|
|
|
|
# Keep the raw payload in this request flow; this is the future hand-off point
|
|
# for saving the upload and its classification to a database or queue.
|
|
context = _classification_context(payload)
|
|
context["submission_token"] = signing.dumps(payload, salt="fireworks_detect.classification")
|
|
return render(request, "fireworks_detect/classification_result.html", context)
|
|
|
|
|
|
@require_http_methods(["POST"])
|
|
@never_cache
|
|
def submit_pending_event(request):
|
|
uploaded_file = request.FILES.get("audio")
|
|
token = request.POST.get("classification_token")
|
|
if not uploaded_file:
|
|
return render(request, "fireworks_detect/pending_submission.html", {"error": "Keep the analysed audio file selected before submitting it for review."}, status=400)
|
|
if not token:
|
|
return render(request, "fireworks_detect/pending_submission.html", {"error": "Analyse the file before submitting it for review."}, status=400)
|
|
|
|
try:
|
|
payload = signing.loads(token, salt="fireworks_detect.classification", max_age=60 * 60)
|
|
except signing.BadSignature:
|
|
return render(request, "fireworks_detect/pending_submission.html", {"error": "This analysis has expired. Please analyse the audio again."}, status=400)
|
|
|
|
if not isinstance(payload, dict):
|
|
return render(request, "fireworks_detect/pending_submission.html", {"error": "The saved analysis is not valid."}, status=400)
|
|
|
|
pending = PendingEvent.objects.create(
|
|
audio_file=uploaded_file,
|
|
original_filename=uploaded_file.name,
|
|
classifier_response=payload,
|
|
)
|
|
return render(request, "fireworks_detect/pending_submission.html", {"pending": pending})
|
|
|
|
|
|
@never_cache
|
|
def events_list(request):
|
|
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
|
|
|
|
|
|
@never_cache
|
|
def event_detail(request, event_id):
|
|
event = get_object_or_404(Event, pk=event_id)
|
|
context = _classification_context(event.classifier_response)
|
|
context["event"] = event
|
|
return render(request, "fireworks_detect/event_detail.html", context)
|
|
|
|
|
|
def _audio_response(record):
|
|
if not record.audio_file:
|
|
raise Http404("No audio is attached to this record.")
|
|
content_type = mimetypes.guess_type(record.audio_file.name)[0] or "application/octet-stream"
|
|
return FileResponse(record.audio_file.open("rb"), content_type=content_type)
|
|
|
|
|
|
@staff_member_required
|
|
def pending_audio(request, event_id):
|
|
return _audio_response(get_object_or_404(PendingEvent, pk=event_id))
|
|
|
|
|
|
@staff_member_required
|
|
def event_audio(request, event_id):
|
|
return _audio_response(get_object_or_404(Event, pk=event_id))
|
|
|
|
|
|
def _sensor_from_request(request):
|
|
authorization = request.headers.get("Authorization", "")
|
|
token = authorization.removeprefix("Bearer ").strip() if authorization.startswith("Bearer ") else request.headers.get("X-Sensor-Token", "").strip()
|
|
if not token:
|
|
return None
|
|
sensor = Sensor.objects.filter(is_active=True, token_prefix=token[:15]).first()
|
|
return sensor if sensor and sensor.token_matches(token) else None
|
|
|
|
|
|
def _sensor_error(message, status=400):
|
|
return JsonResponse({"detail": message}, status=status)
|
|
|
|
|
|
@csrf_exempt
|
|
@require_http_methods(["POST"])
|
|
def classify_audio(request):
|
|
"""Token-authenticated device API. Browser uploads use classify_upload instead."""
|
|
sensor = _sensor_from_request(request)
|
|
if not sensor:
|
|
return _sensor_error("A valid sensor API token is required.", 401)
|
|
uploaded_file = request.FILES.get("file") or request.FILES.get("audio")
|
|
if not uploaded_file:
|
|
return _sensor_error("Attach audio as multipart field 'file'.")
|
|
extension = Path(uploaded_file.name).suffix.lower()
|
|
if not (uploaded_file.content_type or "").startswith("audio/") and extension not in AUDIO_EXTENSIONS:
|
|
return _sensor_error("Unsupported audio file.")
|
|
if uploaded_file.size > MAX_AUDIO_SIZE:
|
|
return _sensor_error("Audio exceeds the 25 MiB limit.")
|
|
body, content_type = _encode_audio_multipart(uploaded_file)
|
|
classifier_request = Request(CLASSIFIER_URL, data=body, headers={"Content-Type": content_type, "Accept": "application/json"}, method="POST")
|
|
try:
|
|
with urlopen(classifier_request, timeout=60) as response:
|
|
payload = json.loads(response.read().decode("utf-8"))
|
|
except HTTPError as error:
|
|
return _sensor_error(f"Classifier returned HTTP {error.code}.", 502)
|
|
except (URLError, TimeoutError, json.JSONDecodeError):
|
|
return _sensor_error("Classifier is unavailable or returned invalid JSON.", 502)
|
|
if not isinstance(payload, dict):
|
|
return _sensor_error("Classifier returned an unexpected response.", 502)
|
|
uploaded_file.seek(0)
|
|
pending = PendingEvent.objects.create(audio_file=uploaded_file, sensor=sensor, original_filename=uploaded_file.name, classifier_response=payload)
|
|
sensor.record_heartbeat(submission=True)
|
|
return JsonResponse({**payload, "pending_event_id": pending.pk, "sensor": sensor.name}, status=201)
|
|
|
|
|
|
@csrf_exempt
|
|
@require_http_methods(["POST"])
|
|
def sensor_heartbeat(request):
|
|
sensor = _sensor_from_request(request)
|
|
if not sensor:
|
|
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()})
|