Certainly! To efficiently and reliably download all images from your specified storage, we'll create a Python script leveraging asynchronous programming with asyncio and aiohttp. This approach allows multiple downloads to occur concurrently, significantly speeding up the process compared to a synchronous approach.
Overview
Dependencies: We'll use aiohttp for asynchronous HTTP requests and aiofiles for asynchronous file operations. For progress tracking, tqdm will provide a progress bar.
Handling Multiple Extensions: For each image number, the script will attempt to download the image using a list of possible extensions. It will try each extension in order until a successful download occurs.
Concurrency Control: To prevent overwhelming the server or your local resources, we'll use a semaphore to limit the number of concurrent download tasks.
Retries: Each download attempt will be retried a specified number of times in case of transient failures.
Step-by-Step Implementation
1. Install Required Packages
First, ensure you have the necessary packages installed. You can install them using pip:
bash
pip install aiohttp aiofiles tqdm
2. Python Script
Here's the complete Python script tailored to your requirements:
python
import asyncio
import aiohttp
import aiofiles
import os
from aiohttp import ClientSession
from tqdm.asyncio import tqdm_asyncio
# Configuration
BASE_URL = "https://storage.naayiq.com/resources/{}.{}"
IMAGE_NUM_START = 1000
IMAGE_NUM_END = 5517
EXTENSIONS = ["jpg", "jpeg", "png", "gif", "webp", "bmp", "tiff"] # Add more if needed
OUTPUT_DIR = "downloaded_images"
CONCURRENT_DOWNLOADS = 20 # Adjust based on your internet speed and server capacity
RETRIES = 3 # Number of retries for failed downloads
# Ensure output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
async def fetch_image(session: ClientSession, url: str, filepath: str, retry: int = RETRIES):
"""
Fetches an image from the given URL and saves it to the specified filepath.
Retries the download up to `retry` times in case of failures.
Returns True if download is successful, else False.
"""
for attempt in range(1, retry + 1):
try:
async with session.get(url) as response:
if response.status == 200:
f = await aiofiles.open(filepath, mode='wb')
await f.write(await response.read())
await f.close()
return True
elif response.status == 404:
# Image does not exist with this extension
return False
else:
print(f"Unexpected status {response.status} for URL: {url}")
except Exception as e:
print(f"Error fetching {url} on attempt {attempt}: {e}")
await asyncio.sleep(1) # Wait before retrying
return False
async def download_image(session: ClientSession, semaphore: asyncio.Semaphore, image_num: int):
"""
Attempts to download an image with the given image_num by trying all possible extensions.
Saves the image if download is successful.
"""
async with semaphore:
for ext in EXTENSIONS:
url = BASE_URL.format(image_num, ext)
filename = f"{image_num}.{ext}"
filepath = os.path.join(OUTPUT_DIR, filename)
success = await fetch_image(session, url, filepath)
if success:
return # Image downloaded successfully, proceed to next image_num
# If none of the extensions worked, you can log it or pass
# For example:
# print(f"No image found for number {image_num} with extensions {EXTENSIONS}")
pass
async def main():
semaphore = asyncio.Semaphore(CONCURRENT_DOWNLOADS)
connector = aiohttp.TCPConnector(limit=CONCURRENT_DOWNLOADS)
timeout = aiohttp.ClientTimeout(total=60) # Adjust timeout as needed
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
tasks = [
download_image(session, semaphore, image_num)
for image_num in range(IMAGE_NUM_START, IMAGE_NUM_END + 1)
]
# Use tqdm for progress bar
for f in tqdm_asyncio.as_completed(tasks, total=len(tasks), desc="Downloading images"):
await f
if __name__ == "__main__":
asyncio.run(main())
3. Explanation of the Script
Configuration Section:
BASE_URL: The template URL where {} placeholders are for image number and extension.
IMAGE_NUM_START and IMAGE_NUM_END: Define the range of image numbers to download.
EXTENSIONS: List of possible image file extensions.
OUTPUT_DIR: Directory where downloaded images will be saved.
CONCURRENT_DOWNLOADS: Limits the number of simultaneous downloads to manage resources.
RETRIES: Number of retry attempts for failed downloads.
fetch_image Function:
Attempts to download an image from a specific URL.
Retries the download up to RETRIES times in case of exceptions or non-200 HTTP status codes.
Writes the image to the specified filepath asynchronously.
download_image Function:
For a given image number, it iterates through all possible extensions.
Attempts to download the image with each extension until successful.
If an image is successfully downloaded with a particular extension, it stops trying other extensions for that image number.
main Function:
Sets up an asynchronous semaphore to control concurrency.
Creates an aiohttp session with specified connector and timeout settings.
Creates a list of tasks for all image numbers.
Uses tqdm to display a progress bar as images are downloaded.
Running the Script:
The script starts executing from the main function using asyncio.run.
4. Running the Script
Save the Script: Save the above script to a file, for example, download_images.py.
Execute the Script:
bash
python download_images.py
You'll see a progress bar indicating the download progress. Downloaded images will be saved in the downloaded_images directory.
5. Additional Considerations
Adjusting Concurrency: If you encounter issues with too many concurrent connections (e.g., server rate limiting), consider reducing the CONCURRENT_DOWNLOADS value.
Handling Missing Images: By default, the script silently skips image numbers for which no valid image is found across all extensions. You can modify the download_image function to log these cases if needed.
Extending Extensions: Add or remove file extensions in the EXTENSIONS list based on the actual formats used in your storage.
Resume Capability: For very large ranges or in case of interruptions, consider implementing resume functionality by checking existing files before downloading.
Error Logging: For better diagnostics, integrate a logging framework like Python’s built-in logging module instead of using print statements.
Conclusion
This script provides a fast and reliable way to download a large range of images with multiple possible extensions. By leveraging asynchronous programming, it efficiently handles multiple downloads concurrently while managing resources effectively. Adjust the configuration parameters as needed to optimize performance based on your specific environment and requirements.