Advertisement
Guest User

Untitled

a guest
Oct 15th, 2024
22
0
5 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. from my_package.web.request import UnifiedRequestHandler
  2. from PIL import Image
  3. from io import BytesIO
  4. import os
  5.  
  6. def process_image(image_bytes, save_path, format=None):
  7.     try:
  8.         image = Image.open(BytesIO(image_bytes))
  9.         os.makedirs(os.path.dirname(save_path), exists_ok=True)
  10.         image.save(save_path, format=format or image.format)
  11.         print(f"Image saved to {save_path}")
  12.     except Exception as e:
  13.         print(f"Error processing image: {e}")
  14.  
  15. def handle_image(image_bytes, idx):
  16.     save_path = f"./images/image_{idx}.jpg"
  17.     process_image(image_bytes, save_path)
  18.  
  19. # Initialize the UnifiedRequestHandler with concurrency settings
  20. handler = UnifiedRequestHandler(range(5, 100, 10), 2.0)
  21. # range(min_workers, max_workers, max_joined_workers_per_interval), interval_in_seconds
  22.  
  23. # List of URLs to download
  24. urls = ["https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"] * 1000
  25.  
  26. # Create a processor for each image
  27. processors = [lambda image_bytes, idx=i: handle_image(image_bytes, idx) for i in range(len(urls))]
  28.  
  29. # Fetch and process the imags using the list of processors
  30. handler.request_many(urls, async_mode=True).into(processors).await_()
  31.  
  32. print(f"{handler.pool._min_workers}/{handler.current_size}/{handler.pool._max_workers}")
  33. print(f"(SEM?{handler.pool._idle_semaphore._value})")
  34. handler.shutdown()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement