Files
2026-09-26 20:59:01 +02:00

194 lines
7.5 KiB
Plaintext

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
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.http import require_http_methods
from .models import Event, PendingEvent
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_audio(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)