ibombonato commited on
Commit
e752a05
·
verified ·
1 Parent(s): 033e2b2

fix: handle 404 images

Browse files
Files changed (1) hide show
  1. utils_tools.py +26 -0
utils_tools.py CHANGED
@@ -4,6 +4,30 @@ import re
4
  from typing import Any
5
  from merchs.merch import Merchant, NaturaMerchant, MercadoLivreMerchant
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  class CalculateDiscountedPriceTool(BaseTool):
8
  """
9
  A tool to calculate the final price of an item after a discount is applied.
@@ -113,6 +137,8 @@ class GetImageUrlTool(BaseTool):
113
  else:
114
  raise ValueError(f"Unsupported product type: {product_type}")
115
 
 
 
116
  return image_url
117
 
118
  class MerchantSelectorTool(BaseTool):
 
4
  from typing import Any
5
  from merchs.merch import Merchant, NaturaMerchant, MercadoLivreMerchant
6
 
7
+ def get_valid_image_url(url):
8
+ """
9
+ Checks if an image URL is accessible.
10
+ Returns the URL if it's valid, otherwise returns None.
11
+ """
12
+ if not url:
13
+ return None
14
+ try:
15
+ # Use a HEAD request to check headers without downloading the full image
16
+ # A timeout is added as a good practice
17
+ response = requests.head(url, allow_redirects=True, timeout=5)
18
+
19
+ # Check if the status code is 200 (OK)
20
+ if response.status_code == 200:
21
+ print(f"URL is valid: {url}")
22
+ return url
23
+ else:
24
+ print(f"URL is invalid, status code: {response.status_code}")
25
+ return None
26
+ except requests.RequestException as e:
27
+ # Handle connection errors, timeouts, etc.
28
+ print(f"An error occurred while checking the URL: {e}")
29
+ return None
30
+
31
  class CalculateDiscountedPriceTool(BaseTool):
32
  """
33
  A tool to calculate the final price of an item after a discount is applied.
 
137
  else:
138
  raise ValueError(f"Unsupported product type: {product_type}")
139
 
140
+ image_url = get_valid_image_url(image_url)
141
+
142
  return image_url
143
 
144
  class MerchantSelectorTool(BaseTool):