Advertisement
Ananjaser1211

Untitled

Sep 10th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. import os
  2. import re
  3. import logging
  4. from bing_image_downloader import downloader
  5.  
  6. # Setup logging
  7. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  8.  
  9. # Base directory to save images
  10. BASE_SAVE_DIR = "fish_images"
  11. os.makedirs(BASE_SAVE_DIR, exist_ok=True)
  12.  
  13. # List of fish names
  14. fish_names = ['hamour', 'sherri', 'safi', 'jesh']
  15.  
  16. # Common filter for queries
  17. common_filter = '"fresh fish UAE" -cooked -fillet -plate -dish -recipe'
  18.  
  19. # Function to sanitize filenames and directory names by removing invalid characters
  20. def sanitize_name(name):
  21. return re.sub(r'[\\/*?:"<>|]', '', name)
  22.  
  23. # Function to sanitize the output directory path
  24. def sanitize_path(path):
  25. # Remove invalid characters for Windows paths
  26. return re.sub(r'[\\/*?:"<>|]', '', path)
  27.  
  28. # Download images for each fish name
  29. for fish_name in fish_names:
  30. # Sanitize fish name for directory
  31. sanitized_fish_name = sanitize_name(fish_name)
  32. species_dir = os.path.join(BASE_SAVE_DIR, sanitized_fish_name)
  33.  
  34. # Ensure directory exists
  35. os.makedirs(species_dir, exist_ok=True)
  36.  
  37. query_string = f'{sanitized_fish_name} {common_filter}'
  38.  
  39. logging.info(f"Starting download for {sanitized_fish_name} with query: {query_string}")
  40.  
  41. try:
  42. # Download images
  43. result = downloader.download(
  44. query_string,
  45. limit=100,
  46. output_dir=BASE_SAVE_DIR, # Save to base directory
  47. adult_filter_off=True,
  48. force_replace=False,
  49. timeout=60,
  50. verbose=True
  51. )
  52.  
  53. # Move and rename downloaded images
  54. if result and 'paths' in result:
  55. for i, image_path in enumerate(result['paths']):
  56. # Create a sanitized filename
  57. sanitized_filename = f"{sanitized_fish_name}-{str(i + 1).zfill(2)}.jpg"
  58. logging.info(f"Path {sanitized_filename}")
  59. # Move and rename file to sanitized filename within the specific species directory
  60. new_image_path = os.path.join(species_dir, sanitized_filename)
  61. # Use os.rename to move and rename files
  62. os.rename(image_path, new_image_path)
  63.  
  64. logging.info(f"Download complete for {sanitized_fish_name}")
  65. except Exception as e:
  66. logging.error(f"Error downloading images for {sanitized_fish_name}: {e}")
  67.  
  68. logging.info("Image download process completed.")
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement