File size: 9,379 Bytes
841deaa
 
 
 
 
 
 
 
8684074
 
841deaa
8684074
 
841deaa
 
8684074
 
 
841deaa
 
 
 
 
 
8684074
 
841deaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8684074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841deaa
 
 
8684074
 
841deaa
 
 
 
 
8684074
841deaa
 
 
 
 
 
8684074
 
 
841deaa
 
8684074
 
841deaa
 
 
 
 
 
 
 
 
8684074
 
841deaa
8684074
841deaa
8684074
841deaa
 
 
 
 
 
 
 
 
 
 
8684074
841deaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8684074
 
 
 
 
 
 
 
 
 
 
 
 
841deaa
 
 
 
 
 
 
 
8684074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841deaa
8684074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
841deaa
 
8684074
 
 
 
 
841deaa
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import re
import shutil
import sys
import tarfile
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from huggingface_hub import hf_hub_download
from huggingface_hub.utils import disable_progress_bars
from tqdm import tqdm

REPO = "links-ads/geoid-flood"
TREES = ("geoid-flood", "geoid-flood-heldout")
LAYERS = ("s1grd", "s1rtc", "s2l2a", "dem", "label", "cloudmask", "floodmask", "permwater", "validity")
SPLITS = ("train", "val", "test")
METADATA = ("data_tiles_s256_st128.csv", "tile_catalog.parquet")
STAGING = ".geoid_flood_staging"
STATE = ".geoid_flood_done"

SHARD_RE = re.compile(r"^(?P<tree>[^/]+)/shards/(?P<split>[^/]+)/(?P<layer>[^/]+)/[^/]+\.tar$")


def _safe_members(tar, root: Path):
    root = root.resolve()
    for info in tar:
        if not info.isreg():
            raise ValueError(f"unexpected member type in shard: {info.name}")
        dest = (root / info.name).resolve()
        if not str(dest).startswith(str(root) + "/"):
            raise ValueError(f"member escapes destination: {info.name}")
        yield info, dest


def select_shards(index: dict, trees, splits, layers) -> list[dict]:
    out = []
    for shard in index["shards"]:
        m = SHARD_RE.match(shard["path"])
        if m and m["tree"] in trees and m["split"] in splits and m["layer"] in layers:
            out.append(shard)
    return out


def fetch_shard(repo: str, path: str, staging: Path, token: str | None) -> Path:
    """Pull one shard to staging over the Xet chunk protocol."""
    return Path(hf_hub_download(repo_id=repo, filename=path, repo_type="dataset",
                                local_dir=str(staging), token=token))


def verify_shard(tar_path: Path, expect_sha: str | None) -> None:
    if not expect_sha:
        return
    h = hashlib.sha256()
    with open(tar_path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    if h.hexdigest() != expect_sha:
        raise ValueError(f"sha256 mismatch for {tar_path.name}")


def unpack_shard(tar_path: Path, out_root: Path) -> None:
    """Extract a staged shard into out_root. Writes via .part so a kill leaves no half files."""
    with tarfile.open(tar_path, mode="r") as tar:
        for info, dest in _safe_members(tar, out_root):
            dest.parent.mkdir(parents=True, exist_ok=True)
            tmp = dest.with_suffix(dest.suffix + ".part")
            with tar.extractfile(info) as src, open(tmp, "wb") as fh:
                shutil.copyfileobj(src, fh, 1 << 20)
            tmp.replace(dest)


def main() -> None:
    ap = argparse.ArgumentParser(
        description="Download GEOID-Flood from the Hugging Face Hub and unpack it to the expected layout"
    )
    ap.add_argument("--repo", default=REPO)
    ap.add_argument("--dest", default="data", type=Path, help="parent dir; trees are created under it")
    ap.add_argument("--tree", nargs="+", choices=TREES, default=list(TREES))
    ap.add_argument("--split", nargs="+", choices=SPLITS, default=list(SPLITS))
    ap.add_argument("--layer", nargs="+", choices=LAYERS, default=list(LAYERS))
    ap.add_argument("--workers", type=int, default=4,
                    help="shards fetched and unpacked concurrently (default 4); raises peak disk")
    ap.add_argument("--force", action="store_true", help="skip the free-space preflight check")
    ap.add_argument("--list", action="store_true", help="print the selection and exit")
    ap.add_argument("--sample", action="store_true",
                    help="fetch only the two-AoI EMSR712 sample: 47 tiles, all nine layers, "
                         "~2.9 GB, and exit")
    ap.add_argument("--token", default=None)
    args = ap.parse_args()

    if args.sample:
        from huggingface_hub import snapshot_download

        tmp = snapshot_download(
            repo_id=args.repo, repo_type="dataset", allow_patterns=["sample/*"], token=args.token
        )
        root = Path(tmp) / "sample"
        for src in root.rglob("*"):
            if src.is_file():
                dst = args.dest / src.relative_to(root)
                dst.parent.mkdir(parents=True, exist_ok=True)
                shutil.move(str(src), dst)
        print(f"sample -> {args.dest}/geoid-flood/")
        print("run a config against it with:")
        print("  --data.init_args.metadata_filename data_tiles_s256_st128_sample.csv")
        return

    index_path = hf_hub_download(
        repo_id=args.repo, filename="shard_index.json.gz", repo_type="dataset", token=args.token
    )
    with gzip.open(index_path, "rt") as fh:
        index = json.load(fh)

    selected = select_shards(index, args.tree, args.split, args.layer)
    total = sum(s["size"] for s in selected)
    print(f"{len(selected)} shards, {total/1e9:.1f} GB")
    if args.list:
        by = {}
        for s in selected:
            m = SHARD_RE.match(s["path"])
            k = (m["tree"], m["split"], m["layer"])
            a, b = by.get(k, (0, 0))
            by[k] = (a + 1, b + s["size"])
        for k in sorted(by):
            n, b = by[k]
            print(f"  {'/'.join(k):45} {n:4d} shards  {b/1e9:8.2f} GB")
        return

    args.dest.mkdir(parents=True, exist_ok=True)
    state = args.dest / STATE
    done = set(state.read_text().split()) if state.exists() else set()
    todo = [s for s in selected if s["path"] not in done]
    remaining = sum(s["size"] for s in todo)

    if todo:
        need = remaining + args.workers * max(s["size"] for s in todo)
        free = shutil.disk_usage(args.dest).free
        if free < need and not args.force:
            sys.exit(f"not enough space at {args.dest}: {free/1e9:.1f} GB free, "
                     f"need ~{need/1e9:.1f} GB ({remaining/1e9:.1f} GB of data plus staging). "
                     f"Narrow the selection with --layer/--split/--tree, or pass --force.")

    for tree in args.tree:
        for name in METADATA:
            p = hf_hub_download(
                repo_id=args.repo, filename=f"{tree}/{name}", repo_type="dataset",
                local_dir=args.dest, token=args.token,
            )
            print(f"metadata {p}")

    staging = args.dest / STAGING
    shutil.rmtree(staging, ignore_errors=True)  # a killed run leaves tars behind
    staging.mkdir(parents=True)


    disable_progress_bars()
    lock = threading.Lock()
    failures: list[tuple[str, str]] = []
    n_done = len(selected) - len(todo)
    done_bytes = 0
    stop = threading.Event()

    def staged_bytes() -> int:
        n = 0
        for p in staging.rglob("*"):  # the in-flight tars plus the .incomplete parts under them
            if p.is_file() and p.suffix != ".metadata":
                try:
                    n += p.stat().st_size
                except OSError:  # unlinked between walk and stat
                    pass
        return n

    def monitor() -> None:
        reported = 0
        while not stop.is_set():
            with lock:
                target = min(done_bytes + staged_bytes(), remaining)
                if target > reported:
                    bar.update(target - reported)
                    reported = target
            stop.wait(0.5)

    def run(shard: dict) -> None:
        nonlocal n_done, done_bytes
        tar = fetch_shard(args.repo, shard["path"], staging, args.token)
        try:
            verify_shard(tar, shard.get("sha256"))
            unpack_shard(tar, args.dest / shard["path"].split("/", 1)[0])
        except BaseException:
            tar.unlink(missing_ok=True)
            raise
        with lock:
            done_bytes += shard["size"]
            tar.unlink(missing_ok=True)
            fh.write(shard["path"] + "\n")
            fh.flush()
            n_done += 1
            bar.set_description_str(f"{n_done}/{len(selected)} shards", refresh=False)

    def guarded(shard: dict) -> None:
        for attempt in (1, 2):
            try:
                run(shard)
                return
            except Exception as exc:
                if attempt == 2:
                    with lock:
                        failures.append((shard["path"], f"{type(exc).__name__}: {exc}"))

    with state.open("a") as fh, \
            tqdm(total=total, initial=total - remaining, unit="B", unit_scale=True,
                 unit_divisor=1000, smoothing=0.05,
                 desc=f"{n_done}/{len(selected)} shards") as bar, \
            ThreadPoolExecutor(max_workers=args.workers) as pool:
        watcher = threading.Thread(target=monitor, daemon=True)
        watcher.start()
        try:
            list(pool.map(guarded, todo))
        finally:
            stop.set()
            watcher.join()

    shutil.rmtree(staging, ignore_errors=True)

    if failures:
        print(f"\n{len(failures)} shard(s) failed; re-run to retry them:", file=sys.stderr)
        for path, err in failures:
            print(f"  {path}: {err}", file=sys.stderr)
        sys.exit(1)

    print(f"\ndone -> {args.dest}/")
    expected = Path("data").resolve()
    if args.dest.resolve() != expected:
        print("configs read data/geoid-flood; link the trees with:")
        for tree in args.tree:
            print(f"  ln -s {args.dest.resolve()}/{tree} data/{tree}")


if __name__ == "__main__":
    main()