Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import re
- import logging
- from bing_image_downloader import downloader
- # Setup logging
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
- # Base directory to save images
- BASE_SAVE_DIR = "fish_images"
- os.makedirs(BASE_SAVE_DIR, exist_ok=True)
- # List of fish names
- fish_names = ['hamour', 'sherri', 'safi', 'jesh']
- # Common filter for queries
- common_filter = '"fresh fish UAE" -cooked -fillet -plate -dish -recipe'
- # Function to sanitize filenames and directory names by removing invalid characters
- def sanitize_name(name):
- return re.sub(r'[\\/*?:"<>|]', '', name)
- # Function to sanitize the output directory path
- def sanitize_path(path):
- # Remove invalid characters for Windows paths
- return re.sub(r'[\\/*?:"<>|]', '', path)
- # Download images for each fish name
- for fish_name in fish_names:
- # Sanitize fish name for directory
- sanitized_fish_name = sanitize_name(fish_name)
- species_dir = os.path.join(BASE_SAVE_DIR, sanitized_fish_name)
- # Ensure directory exists
- os.makedirs(species_dir, exist_ok=True)
- query_string = f'{sanitized_fish_name} {common_filter}'
- logging.info(f"Starting download for {sanitized_fish_name} with query: {query_string}")
- try:
- # Download images
- result = downloader.download(
- query_string,
- limit=100,
- output_dir=BASE_SAVE_DIR, # Save to base directory
- adult_filter_off=True,
- force_replace=False,
- timeout=60,
- verbose=True
- )
- # Move and rename downloaded images
- if result and 'paths' in result:
- for i, image_path in enumerate(result['paths']):
- # Create a sanitized filename
- sanitized_filename = f"{sanitized_fish_name}-{str(i + 1).zfill(2)}.jpg"
- logging.info(f"Path {sanitized_filename}")
- # Move and rename file to sanitized filename within the specific species directory
- new_image_path = os.path.join(species_dir, sanitized_filename)
- # Use os.rename to move and rename files
- os.rename(image_path, new_image_path)
- logging.info(f"Download complete for {sanitized_fish_name}")
- except Exception as e:
- logging.error(f"Error downloading images for {sanitized_fish_name}: {e}")
- logging.info("Image download process completed.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement