Untitled

 avatar
unknown
plain_text
a month ago
2.2 kB
4
Indexable

from rest_framework import serializers
from .models import Drug

class DrugSerializer(serializers.ModelSerializer):
    class Meta:
        model = Drug
        fields = ['name', 'description', 'image']


/////////////////////////////////////////////
from rest_framework import serializers
from .models import Drug

class DrugSerializer(serializers.ModelSerializer):
    class Meta:
        model = Drug
        fields = ['name', 'description', 'image']



        ///////////////////////////////

# DrugSearchByImageView: Searches for the most similar Drug by comparing image hashes.
class DrugSearchByImageView(APIView):
    def post(self, request, *args, **kwargs):
        # Check if the image is provided
        if 'image' not in request.FILES:
            return Response({'error': 'No image provided'}, status=status.HTTP_400_BAD_REQUEST)

        uploaded_image = request.FILES['image']

        # Convert uploaded image to hash
        try:
            uploaded_image_pil = Image.open(uploaded_image)
            uploaded_image_hash = imagehash.phash(uploaded_image_pil)
        except Exception as e:
            return Response({'error': f'Error processing uploaded image: {str(e)}'},
                            status=status.HTTP_400_BAD_REQUEST)

        # Find the drug with the most similar image
        closest_match = None
        min_diff = float('inf')
        drugs = Drug.objects.all()
        for drug in drugs:
            try:
                drug_image = Image.open(drug.image.path)
                drug_image_hash = imagehash.phash(drug_image)
            except Exception as e:
                # Skip this drug if there's an issue with its image.
                continue
            diff = uploaded_image_hash - drug_image_hash
            if diff < min_diff:
                min_diff = diff
                closest_match = drug

        # Return the closest match as JSON response
        if closest_match:
            drug_data = DrugSerializer(closest_match)
            return Response(drug_data.data, status=status.HTTP_200_OK)
        else:
            return Response({'error': 'No matching drug found'}, status=status.HTTP_404_NOT_FOUND)
Editor is loading...
Leave a Comment