Spaces:
Build error
Build error
Update image_search_tool.py
Browse files- image_search_tool.py +13 -10
image_search_tool.py
CHANGED
|
@@ -5,17 +5,12 @@ from io import BytesIO
|
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
from crewai_tools import tool
|
| 9 |
-
|
| 10 |
-
@tool
|
| 11 |
def image_search_tool(query: str, num_images: int = 5) -> str:
|
| 12 |
"""
|
| 13 |
A tool to search for images based on the given query and download them.
|
| 14 |
-
|
| 15 |
Parameters:
|
| 16 |
- query (str): The search query for finding images.
|
| 17 |
- num_images (int): The number of images to retrieve (default is 5).
|
| 18 |
-
|
| 19 |
Returns:
|
| 20 |
- str: The paths where the downloaded images are saved.
|
| 21 |
"""
|
|
@@ -34,10 +29,15 @@ def image_search_tool(query: str, num_images: int = 5) -> str:
|
|
| 34 |
results = []
|
| 35 |
for img_tag in soup.find_all('a', class_='iusc')[:num_images]:
|
| 36 |
m = img_tag.get('m')
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
image_paths = []
|
| 43 |
folder = 'images'
|
|
@@ -54,4 +54,7 @@ def image_search_tool(query: str, num_images: int = 5) -> str:
|
|
| 54 |
except Exception as e:
|
| 55 |
return f"Failed to download {result['title']}: {e}"
|
| 56 |
|
| 57 |
-
return f"Downloaded images to: {', '.join(image_paths)}"
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
|
|
|
|
|
|
|
|
|
|
| 8 |
def image_search_tool(query: str, num_images: int = 5) -> str:
|
| 9 |
"""
|
| 10 |
A tool to search for images based on the given query and download them.
|
|
|
|
| 11 |
Parameters:
|
| 12 |
- query (str): The search query for finding images.
|
| 13 |
- num_images (int): The number of images to retrieve (default is 5).
|
|
|
|
| 14 |
Returns:
|
| 15 |
- str: The paths where the downloaded images are saved.
|
| 16 |
"""
|
|
|
|
| 29 |
results = []
|
| 30 |
for img_tag in soup.find_all('a', class_='iusc')[:num_images]:
|
| 31 |
m = img_tag.get('m')
|
| 32 |
+
if m:
|
| 33 |
+
try:
|
| 34 |
+
m_json = json.loads(m)
|
| 35 |
+
img_url = m_json.get('murl')
|
| 36 |
+
img_title = m_json.get('turl')
|
| 37 |
+
if img_url:
|
| 38 |
+
results.append({'title': img_title, 'url': img_url})
|
| 39 |
+
except (json.JSONDecodeError, TypeError) as e:
|
| 40 |
+
continue
|
| 41 |
|
| 42 |
image_paths = []
|
| 43 |
folder = 'images'
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
return f"Failed to download {result['title']}: {e}"
|
| 56 |
|
| 57 |
+
return f"Downloaded images to: {', '.join(image_paths)}"
|
| 58 |
+
|
| 59 |
+
# Example usage:
|
| 60 |
+
print(image_search_tool("artificial intelligence", 3))
|