70 lines
2.6 KiB
Python
70 lines
2.6 KiB
Python
import logging
|
|
from django.views.generic import FormView, DetailView
|
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
|
from django.contrib import messages
|
|
from django.shortcuts import redirect
|
|
|
|
from .models import PotholeDetection
|
|
from .forms import PotholeDetectionForm
|
|
from .detection import run_detection
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class PotholeDetectionView(LoginRequiredMixin, FormView):
|
|
template_name = 'road_detection/detection_form.html'
|
|
form_class = PotholeDetectionForm
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(**kwargs)
|
|
context['recent_detections'] = PotholeDetection.objects.filter(
|
|
created_by=self.request.user
|
|
).order_by('-created_at')[:5]
|
|
return context
|
|
|
|
def form_valid(self, form):
|
|
detection = form.save(commit=False)
|
|
detection.created_by = self.request.user
|
|
detection.save()
|
|
|
|
try:
|
|
result = run_detection(
|
|
image_path=detection.uploaded_image.path,
|
|
confidence_threshold=detection.confidence_threshold,
|
|
)
|
|
detection.result_image = result['result_image_relative']
|
|
detection.detection_count = result['detection_count']
|
|
detection.detections_data = result['detections']
|
|
|
|
image_gps = result.get('image_gps')
|
|
if image_gps:
|
|
detection.image_lat = image_gps.get('lat')
|
|
detection.image_lon = image_gps.get('lon')
|
|
|
|
detection.save()
|
|
|
|
if result['detection_count'] == 0:
|
|
messages.info(self.request, "Analyse terminée : aucun nid de poule détecté sur cette image.")
|
|
else:
|
|
messages.success(
|
|
self.request,
|
|
f"Analyse terminée : {result['detection_count']} nid(s) de poule détecté(s).",
|
|
)
|
|
except Exception as e:
|
|
logger.error("Erreur lors de la détection YOLO: %s", e, exc_info=True)
|
|
messages.error(self.request, f"Erreur lors de l'analyse : {e}")
|
|
|
|
return redirect('road_detection:result', pk=detection.pk)
|
|
|
|
def form_invalid(self, form):
|
|
messages.error(self.request, "Formulaire invalide. Vérifiez les champs.")
|
|
return super().form_invalid(form)
|
|
|
|
|
|
class PotholeDetectionResultView(LoginRequiredMixin, DetailView):
|
|
model = PotholeDetection
|
|
template_name = 'road_detection/detection_result.html'
|
|
context_object_name = 'detection'
|
|
|
|
def get_queryset(self):
|
|
return PotholeDetection.objects.filter(created_by=self.request.user)
|