diff --git a/MisplaceAI/process_misplaced_manager/urls.py b/MisplaceAI/process_misplaced_manager/urls.py index e5fbda822f847faae7b1f5162b49f6c16cac6619..04a85b3e9c53c86641500e5d1c1d275b20122d3f 100644 --- a/MisplaceAI/process_misplaced_manager/urls.py +++ b/MisplaceAI/process_misplaced_manager/urls.py @@ -4,7 +4,7 @@ from rest_framework.routers import DefaultRouter from .views import ( UploadedImageViewSet, UploadedVideoViewSet, normal_detection, - display_results, display_video_results,upload_video, download_image + display_results, display_video_results,upload_video, download_image, delete_image ) router = DefaultRouter() @@ -21,6 +21,10 @@ urlpatterns = [ path('video-results/<int:video_id>/', display_video_results, name='display_video_results'), path('display-results/<int:image_id>/', display_results, name='display_results'), path('download/<path:file_path>/', download_image, name='download_image'), + path('delete-image/<str:image_name>/', delete_image, name='delete_image_by_name'), + + + ] diff --git a/MisplaceAI/process_misplaced_manager/views.py b/MisplaceAI/process_misplaced_manager/views.py index 6ed5b0b866c3892171be57b7a6f7536cf02bf97b..11d3ac0633a17fae256710d4231297a696e83b4d 100644 --- a/MisplaceAI/process_misplaced_manager/views.py +++ b/MisplaceAI/process_misplaced_manager/views.py @@ -39,33 +39,43 @@ class UploadedImageViewSet(viewsets.ModelViewSet): @api_view(['POST']) @permission_classes([IsAuthenticated]) def normal_detection(request): - if 'capturedImageData' in request.data: - captured_image_data = request.data['capturedImageData'] - format, imgstr = captured_image_data.split(';base64,') - ext = format.split('/')[-1] - image_data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) + try: + if 'capturedImageData' in request.data: + captured_image_data = request.data['capturedImageData'] + format, imgstr = captured_image_data.split(';base64,') + ext = format.split('/')[-1] + image_data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) - new_image = UploadedImage.objects.create(image=image_data) - else: - serializer = UploadedImageSerializer(data=request.data) - if serializer.is_valid(): - new_image = serializer.save() + new_image = UploadedImage.objects.create(image=image_data) else: - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) - - image_path = new_image.image.path - correct_image_orientation(image_path) - detected_objects = run_inference(detection_model, category_index, image_path) - placement_rules = PlacementRules() - misplaced_objects = placement_rules.check_placement(detected_objects) - output_image_path = visualize_misplaced_objects(image_path, detected_objects, misplaced_objects) + serializer = UploadedImageSerializer(data=request.data) + if serializer.is_valid(): + new_image = serializer.save() + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + image_path = new_image.image.path + correct_image_orientation(image_path) + detected_objects = run_inference(detection_model, category_index, image_path) + placement_rules = PlacementRules() + misplaced_objects = placement_rules.check_placement(detected_objects) + output_image_path = visualize_misplaced_objects(image_path, detected_objects, misplaced_objects) + + # Delete the original uploaded image + if os.path.exists(image_path): + os.remove(image_path) - response_data = { - 'image_url': new_image.image.url, - 'output_image_url': request.build_absolute_uri("/media/" + os.path.basename(output_image_path)), - 'misplaced_objects': misplaced_objects - } - return Response(response_data, status=status.HTTP_200_OK) + response_data = { + 'image_id': new_image.id, + 'image_url': new_image.image.url, + 'output_image_url': request.build_absolute_uri("/media/" + os.path.basename(output_image_path)), + 'misplaced_objects': misplaced_objects + } + return Response(response_data, status=status.HTTP_200_OK) + + except Exception as e: + print(f"Error processing image: {str(e)}") + return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def correct_image_orientation(image_path): try: @@ -257,4 +267,27 @@ def download_image(request, file_path): response['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' return response else: - raise Http404 \ No newline at end of file + raise Http404 + + + +@api_view(['DELETE']) +@permission_classes([IsAuthenticated]) +def delete_image(request, image_name): + try: + print(f"Attempting to delete image: {image_name}") + # Construct the file path + file_path = os.path.join(settings.MEDIA_ROOT, image_name) + + # Check if the file exists + if os.path.exists(file_path): + # Delete the file + os.remove(file_path) + print(f"Image {image_name} deleted successfully.") + return Response(status=status.HTTP_204_NO_CONTENT) + else: + print(f"Image {image_name} not found.") + return Response({'error': 'Image not found'}, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + print(f"Error deleting image {image_name}: {str(e)}") + return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) \ No newline at end of file diff --git a/frontend/src/pages/NormalDetection/NormalDetectionPage.js b/frontend/src/pages/NormalDetection/NormalDetectionPage.js index d4e0b0d66c10d9ad97ad09e97ebc05553f138d2e..d86c331a11a4fff70ff54bab14291770f997d0bc 100644 --- a/frontend/src/pages/NormalDetection/NormalDetectionPage.js +++ b/frontend/src/pages/NormalDetection/NormalDetectionPage.js @@ -1,7 +1,8 @@ // src/pages/NormalDetection/NormalDetectionPage.js -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; +import { useNavigate, useLocation } from 'react-router-dom'; import { Modal, Button } from 'react-bootstrap'; -import { normalDetection, downloadImage } from '../../services/processMisplacedManagerApi'; +import { normalDetection, downloadImage, deleteImageByName } from '../../services/processMisplacedManagerApi'; import '../../styles/main.css'; import LoadingIndicator from '../../components/detection/LoadingIndicator'; import DetectionResults from '../../components/detection/DetectionResults'; @@ -15,6 +16,49 @@ const NormalDetectionPage = () => { const [isLoading, setIsLoading] = useState(false); const [showModal, setShowModal] = useState(false); const [detectionComplete, setDetectionComplete] = useState(false); + const [imageName, setImageName] = useState(null); + const navigate = useNavigate(); + const location = useLocation(); + + useEffect(() => { + const handleBeforeUnload = async () => { + console.log('Navigation event detected:'); + if (imageName) { + console.log('Image name detected:', imageName); + try { + const response = await deleteImageByName(imageName); + console.log('Delete image response:', response); + } catch (error) { + console.error('Error deleting image:', error); + } + } + }; + + window.addEventListener('beforeunload', handleBeforeUnload); + + return () => { + window.removeEventListener('beforeunload', handleBeforeUnload); + handleBeforeUnload(); // Trigger the cleanup function manually + }; + }, [imageName]); + + useEffect(() => { + const handleRouteChange = async () => { + console.log('Route change detected:'); + if (imageName) { + try { + const response = await deleteImageByName(imageName); + console.log('Delete image response:', response); + } catch (error) { + console.error('Error deleting image:', error); + } + } + }; + + return () => { + handleRouteChange(); + }; + }, [imageName, location]); const handleCameraClick = () => { document.getElementById('cameraInput').click(); @@ -37,9 +81,11 @@ const NormalDetectionPage = () => { try { const response = await normalDetection(formData); + console.log('Normal detection response:', response); setResultImageUrl(response.output_image_url); setMisplacedObjects(response.misplaced_objects); - setDetectionComplete(true); // Set detection as complete + setDetectionComplete(true); + setImageName(response.output_image_url.split('/').pop()); // Set the image name } catch (error) { console.error('Upload failed', error); } finally { @@ -63,11 +109,12 @@ const NormalDetectionPage = () => { setResultImageUrl(null); setMisplacedObjects([]); setDetectionComplete(false); + setImageName(null); }; const handleDownload = async () => { try { - const filePath = resultImageUrl.split('/').pop(); // Get the file name only + const filePath = resultImageUrl.split('/').pop(); const response = await downloadImage(filePath); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); diff --git a/frontend/src/services/processMisplacedManagerApi.js b/frontend/src/services/processMisplacedManagerApi.js index 0cc683efa49ff7d51cd239a7742f27830ed05421..ed241314d4828e954594bd92469b1e68df1ac708 100644 --- a/frontend/src/services/processMisplacedManagerApi.js +++ b/frontend/src/services/processMisplacedManagerApi.js @@ -133,4 +133,14 @@ export const downloadImage = async (filePath) => { console.error('Error downloading image:', error); throw error; } +}; + +export const deleteImageByName = async (imageName) => { + try { + const response = await api.delete(`/api/process_misplaced_manager/delete-image/${imageName}/`); + return response.data; + } catch (error) { + console.error(`Error deleting image with name ${imageName}:`, error); + throw error; + } }; \ No newline at end of file