naveenyuvabe commited on
Commit
deadea6
·
1 Parent(s): d0ae1be

86cx4cwda - [image_embedding_service] FIX: Exception handling

Browse files
exceptions/ImageEmbedExceptions.py CHANGED
@@ -6,3 +6,18 @@ class urlNotFoundException(HTTPException):
6
  super().__init__(
7
  status_code=200, detail="Image file is required for the search."
8
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  super().__init__(
7
  status_code=200, detail="Image file is required for the search."
8
  )
9
+
10
+
11
+ class InvalidUrlException(HTTPException):
12
+ def __init__(self, detail="The provided URL is invalid."):
13
+ super().__init__(status_code=200, detail=detail)
14
+
15
+
16
+ class UnauthorizedUrlException(HTTPException):
17
+ def __init__(self, detail="The provided URL is not authenticated or inaccessible."):
18
+ super().__init__(status_code=200, detail=detail)
19
+
20
+
21
+ class ImageProcessingException(HTTPException):
22
+ def __init__(self, detail: str = "Failed to process image from URL."):
23
+ super().__init__(status_code=200, detail=detail)
requirements.txt CHANGED
@@ -6,3 +6,4 @@ regex
6
  ftfy
7
  opencv-python-headless
8
  requests
 
 
6
  ftfy
7
  opencv-python-headless
8
  requests
9
+ aiohttp
routes/imageEmbeded.py CHANGED
@@ -5,12 +5,23 @@ import numpy as np
5
  from PIL import Image
6
  import base64
7
  import io
8
- from pydantic import BaseModel
9
  from models.models import UrlRequest, ImageEmbedResponse
10
  from services.image_search_utils import handle_image_embeddeding
11
  from services.image_process_utils import process_image_from_url
12
  from services.embed_utils import send_img_to_embed
13
- from exceptions.ImageEmbedExceptions import urlNotFoundException
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  router = APIRouter()
16
 
@@ -27,9 +38,38 @@ async def embed_images(request: UrlRequest):
27
  """The search-by-image endpoint allows users to search for similar images by uploading an image file. It accepts an image file, the number of top similar items to return (top_k), and a list of namespaces to search within. The image is processed to extract its embedding, and then the system retrieves similar images by comparing the embedding across the provided namespaces."""
28
 
29
  url = request.url
 
30
  if not url:
31
- logger.warning("Url not Provided.")
32
- raise urlNotFoundException()
33
- # Handle image search
34
- embedding = await process_image_from_url(url)
35
- return {"ImageEmbeddings": embedding}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  from PIL import Image
6
  import base64
7
  import io
8
+ from pydantic import BaseModel, HttpUrl, ValidationError
9
  from models.models import UrlRequest, ImageEmbedResponse
10
  from services.image_search_utils import handle_image_embeddeding
11
  from services.image_process_utils import process_image_from_url
12
  from services.embed_utils import send_img_to_embed
13
+ from exceptions.ImageEmbedExceptions import (
14
+ urlNotFoundException,
15
+ InvalidUrlException,
16
+ UnauthorizedUrlException,
17
+ ImageProcessingException,
18
+ )
19
+ import aiohttp
20
+
21
+
22
+ class UrlValidator(BaseModel):
23
+ url: HttpUrl
24
+
25
 
26
  router = APIRouter()
27
 
 
38
  """The search-by-image endpoint allows users to search for similar images by uploading an image file. It accepts an image file, the number of top similar items to return (top_k), and a list of namespaces to search within. The image is processed to extract its embedding, and then the system retrieves similar images by comparing the embedding across the provided namespaces."""
39
 
40
  url = request.url
41
+
42
  if not url:
43
+ logger.warning("URL not provided.")
44
+ raise InvalidUrlException("URL is required but not provided.")
45
+ # Validate URL format
46
+ try:
47
+ UrlValidator(url=url)
48
+ except ValidationError:
49
+ logger.warning("Invalid URL format provided.")
50
+ raise InvalidUrlException("Invalid URL format provided.")
51
+
52
+ # Check URL accessibility
53
+ async with aiohttp.ClientSession() as session:
54
+ try:
55
+ async with session.get(url) as response:
56
+ if response.status == 401: # Unauthorized
57
+ logger.warning("URL requires authentication.")
58
+ raise UnauthorizedUrlException()
59
+ elif response.status != 200: # Other HTTP errors
60
+ logger.warning(f"URL returned status code {response.status}.")
61
+ raise HTTPException(
62
+ status_code=response.status,
63
+ detail=f"URL returned status code {response.status}.",
64
+ )
65
+ except aiohttp.ClientError as e:
66
+ logger.warning(f"Error accessing the URL: {e}")
67
+ raise InvalidUrlException("Could not access the provided URL.")
68
+
69
+ # Process image from URL
70
+ try:
71
+ embedding = await process_image_from_url(url)
72
+ return {"ImageEmbeddings": embedding}
73
+ except Exception as e:
74
+ logger.error(f"Failed to process image from URL: {e}")
75
+ raise ImageProcessingException("Failed to process image from URL.")