|
import argparse |
|
from concurrent.futures import ThreadPoolExecutor |
|
import os |
|
import requests |
|
import shutil |
|
from tqdm import tqdm |
|
|
|
|
|
def get_image_ids(batch_id: str) -> list[str]: |
|
"""A list of image IDs in the given batch""" |
|
response = requests.get(f"https://iiifintern.ra.se/arkis!{batch_id}/manifest") |
|
response.raise_for_status() |
|
response = response.json() |
|
return [item["id"].split("!")[1][:14] for item in response["items"]] |
|
|
|
|
|
def download_image(url: str, dest: str) -> None: |
|
""" |
|
Download an image |
|
|
|
Arguments: |
|
url: Image url |
|
dest: Destination file name |
|
""" |
|
response = requests.get(url, stream=True) |
|
with open(dest, "wb") as out_file: |
|
shutil.copyfileobj(response.raw, out_file) |
|
del response |
|
|
|
|
|
def download_image_by_image_id(image_id: str): |
|
""" |
|
Download the image with the given image ID |
|
|
|
Creates a directory named after the batch ID and saves the image in |
|
that directory. |
|
""" |
|
batch_id = image_id[:8] |
|
os.makedirs(batch_id, exist_ok=True) |
|
url = f"https://iiifintern.ra.se/arkis!{image_id}/full/max/0/default.jpg" |
|
dest = os.path.join(batch_id, image_id + ".jpg") |
|
download_image(url, dest) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
parser = argparse.ArgumentParser(description="Download a batch of images by its batch ID") |
|
parser.add_argument("batch_id", help="batch ID of batch to download") |
|
parser.add_argument("--workers", default=5, help="number of concurrent workers") |
|
args = parser.parse_args() |
|
|
|
image_ids = get_image_ids(args.batch_id) |
|
|
|
with ThreadPoolExecutor(max_workers=args.workers) as executor: |
|
list(tqdm(executor.map(download_image_by_image_id, image_ids), total=len(image_ids), desc=f"Downloading {args.batch_id}")) |