File size: 4,146 Bytes
60a39ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ad93d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60a39ef
 
 
 
 
 
 
 
0ad93d5
60a39ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ad93d5
60a39ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""Download every Dynamic World label release into raw/.

    python scripts/download_labels.py
    python scripts/download_labels.py --subset experts

Run from the data repo's root. A subset already downloaded is skipped. Each
label is extracted straight from the remote archive, so the test release's
model probabilities, 3.9 of its 3.9 GB, are never fetched.
"""

import time
from tempfile import TemporaryDirectory

import requests
from pathlib import Path
from zipfile import ZipFile, ZipInfo

import fsspec
import typer
from aiohttp import ClientResponseError
from tqdm import tqdm

PANGAEA = "https://download.pangaea.de/dataset/933475/files"
URLS = {
    "experts": f"{PANGAEA}/Experts_tiles.zip",
    "non_expert": f"{PANGAEA}/Non_expert_tiles.zip",
    "validation": f"{PANGAEA}/validation_set_tiles.zip",
    "test": "https://zenodo.org/records/4766508/files/dw_test.zip?download=1",
}
RAW = Path(__file__).resolve().parents[1] / "raw"


def extract(files: ZipFile, member: ZipInfo, folder: Path) -> None:
    """Extract one member, waiting out the server's rate limit as it asks."""
    while True:
        try:
            files.extract(member, folder)
            return
        except ClientResponseError as error:
            # Zenodo allows 133 requests a minute and names the wait itself.
            if error.status != 429 or error.headers is None:
                raise
            time.sleep(int(error.headers.get("Retry-After", 60)))


def fetch(url: str, path: Path, attempts: int = 5) -> None:
    """Stream a URL to a file, retrying server errors with a growing wait."""
    for attempt in range(attempts):
        try:
            with requests.get(url, stream=True, timeout=120) as response:
                response.raise_for_status()
                with path.open("wb") as output:
                    for chunk in response.iter_content(2**20):
                        output.write(chunk)
            return
        except requests.HTTPError as error:
            if error.response.status_code < 500 or attempt == attempts - 1:
                raise
            time.sleep(2**attempt * 5)


def download(url: str, folder: Path) -> None:
    """Download annotation archives; range-read only the probability-heavy test ZIP."""
    partial = folder.with_suffix(".partial")
    with TemporaryDirectory(dir=folder.parent) as temporary:
        if "dw_test.zip" in url:
            remote = fsspec.filesystem("https").open(url, block_size=2**16)
        else:
            archive = Path(temporary) / "labels.zip"
            fetch(url, archive)
            remote = archive.open("rb")
        with remote, ZipFile(remote) as files:
            members = []
            for member in files.infolist():
                if member.is_dir() or member.filename.startswith("__MACOSX"):
                    continue
                if Path(member.filename).name.startswith("probs_"):
                    continue
                members.append(member)
            for member in tqdm(members, desc=folder.name, unit="file"):
                extract(files, member, partial)
    partial.rename(folder)


def download_metadata(raw: Path) -> None:
    """Fetch the separately published training workbook and source README."""
    for name in ("v1_dw_tile_metadata_for_public_release.xlsx", "README.txt"):
        path = raw / name
        if path.exists():
            continue

        partial = path.with_suffix(path.suffix + ".partial")
        fetch(f"{PANGAEA}/{name}", partial)
        partial.replace(path)


def main(raw: Path = RAW, subset: str | None = None) -> None:
    """Download all releases, or one named subset, into RAW."""
    if subset is not None and subset not in URLS:
        raise typer.BadParameter(f"choose one of {', '.join(URLS)}")
    raw.mkdir(parents=True, exist_ok=True)
    download_metadata(raw)

    urls = URLS if subset is None else {subset: URLS[subset]}
    for name, url in urls.items():
        folder = raw / name
        if folder.exists():
            print(f"already downloaded: {folder}")
            continue
        download(url, folder)


if __name__ == "__main__":
    typer.run(main)