Spaces:
Build error
Build error
File size: 1,744 Bytes
9ff48a8 32d844a 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 9ff48a8 1471914 29a91ee 1471914 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import requests
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
import json
import os
from langchain.tools import tool
# Ensure that this tool returns the correct type (e.g., a string path or a list of strings)
@tool
def image_search_tool(query: str, num_images: int = 5) -> list:
"""
A tool to search for images based on the given query and download them.
Parameters:
- query (str): The search query for finding images.
- num_images (int): The number of images to retrieve (default is 5).
Returns:
- list: The paths where the downloaded images are saved.
"""
url = 'https://www.bing.com/images/search'
headers = {
'User-Agent': 'Mozilla/5.0'
}
params = {'q': query, 'count': num_images}
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
return [f"Failed to retrieve results: {response.status_code}"]
soup = BeautifulSoup(response.text, 'html.parser')
results = []
for img_tag in soup.find_all('a', class_='iusc')[:num_images]:
m = img_tag.get('m')
m_json = json.loads(m)
img_url = m_json.get('murl')
results.append(img_url)
image_paths = []
folder = 'images'
if not os.path.exists(folder):
os.makedirs(folder)
for i, img_url in enumerate(results, 1):
try:
img_response = requests.get(img_url)
img = Image.open(BytesIO(img_response.content))
img_path = os.path.join(folder, f"image_{i}.jpg")
img.save(img_path)
image_paths.append(img_path)
except Exception as e:
return [f"Failed to download {img_url}: {e}"]
return image_paths
|