Spaces:
Sleeping
Sleeping
| from rest_framework.views import APIView | |
| from rest_framework.response import Response | |
| from rest_framework import status | |
| from .models import Detection | |
| from .serializers import DetectionSerializer | |
| from django.core.files.base import ContentFile | |
| import cv2 | |
| import numpy as np | |
| from ultralytics import YOLO | |
| import os | |
| from django.conf import settings | |
| from .utils import run_detection | |
| class DetectView(APIView): | |
| def post(self, request): | |
| if 'image' not in request.FILES: | |
| return Response({"error": "No image provided"}, status=status.HTTP_400_BAD_REQUEST) | |
| image_file = request.FILES['image'] | |
| # Save temporarily to run detection or use the file directly | |
| # For simplicity and consistency with the utility, we save the object first with empty results | |
| # then run detection on the saved file path. | |
| detection_obj = Detection.objects.create( | |
| image=image_file, | |
| results=[], | |
| user=request.user if request.user.is_authenticated else None | |
| ) | |
| # Run detection on the saved file | |
| detections = run_detection(detection_obj.image.path) | |
| # Update results | |
| detection_obj.results = detections | |
| detection_obj.save() | |
| return Response(DetectionSerializer(detection_obj).data, status=status.HTTP_201_CREATED) | |
| class DetectionHistoryView(APIView): | |
| def get(self, request): | |
| if request.user.is_authenticated: | |
| detections = Detection.objects.filter(user=request.user).order_by('-created_at') | |
| else: | |
| detections = Detection.objects.all().order_by('-created_at')[:10] # Last 10 for guests | |
| serializer = DetectionSerializer(detections, many=True) | |
| return Response(serializer.data) | |