super slow and keep reaching full pool: import os import requests from bs4 import…
- User
super slow and keep reaching full pool:
import os import requests from bs4 import BeautifulSoup, SoupStrainer from concurrent.futures import ThreadPoolExecutor from urllib.parse import urljoin, urlparse
ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "bmp", "tiff"}
def has_allowed_extension(image_url): return any(image_url.lower().endswith("." + ext) for ext in ALLOWED_EXTENSIONS)
def is_likely_ad_or_icon(image_url, image_headers, minimum_size_kb=10): common_ad_indicators = ["ad", "banner", "sponsor"] common_icon_indicators = ["favicon", "logo", "icon"]
code# Check if image URL contains ad or icon indicators if any( indicator in image_url.lower() for indicator in common_ad_indicators + common_icon_indicators ): return True # Fetch image content size from the headers and check if it is smaller than the minimum size content_length = image_headers.get("content-length", None) if content_length and int(content_length) < minimum_size_kb * 1024: return True return Falsedef download_image(image_url, destination_folder, session): try: image_ext = os.path.splitext(urlparse(image_url).path)[1][1:].strip().lower() if image_ext not in ALLOWED_EXTENSIONS: print(f"Skipping {image_url}: Unsupported extension {image_ext}") return response = session.head(image_url, timeout=5) if not is_likely_ad_or_icon( image_url, response.headers ) and has_allowed_extension(image_url): with session.get(image_url, stream=True) as r: r.raise_for_status() img_name = os.path.basename(urlparse(image_url).path) img_path = os.path.join(destination_folder, img_name) with open(img_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded {img_name} to {destination_folder}") except Exception as e: print(f"Could not download {image_url}: {e}")
def download_images(url, destination_folder, session): if not os.path.isdir(destination_folder): os.makedirs(destination_folder)
coderesponse = session.get(url) soup = BeautifulSoup(response.text, "html.parser", parse_only=SoupStrainer("img")) images = [ urljoin(url, img.get("src") or img.get("data-src")) for img in soup if img.get("src") or img.get("data-src") ] with ThreadPoolExecutor(max_workers=15) as executor: for image_url in images: executor.submit(download_image, image_url, destination_folder, session) - Assistant
- User
- Assistant
- User
only turn DOWNLOADING to false after it's done with the loop:
async def get_images(urls, destination_dir): global DOWNLOADING loop = asyncio.get_running_loop() await loop.run_in_executor(None, get_pictures.get_images, urls, destination_dir) DOWNLOADING = False
def remove_files(directory): for file_name in os.listdir(directory): file_path = os.path.join(directory, file_name) if os.path.isfile(file_path): os.remove(file_path)
@app.post("/perpareItem") async def perpare_item_endpoint(request: Request, background_tasks: BackgroundTasks): global DOWNLOADING DOWNLOADING = True destination_dir = "downloaded_images" remove_files(destination_dir)
coderequest_data = await request.json() message = request_data.get("message") print(message) urls = request_data.get("urls") print(urls) result = await llm_bot.lookup_ai(message) print(result) avg_price = stats.adding_item(result) result["avg_price"] = avg_price background_tasks.add_task(get_images, urls, destination_dir) return result - Assistant
- User
hey
- Assistant
Hello! How can I assist you today? If you have any questions or need support with something, feel free to ask.