File size: 1,756 Bytes
1f748f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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}"))