File size: 4,311 Bytes
dbd4237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Download the full set of 47 HDRI environment maps used by DeformX renders.

The minimal asset bundle ships only 4 HDRIs to keep the download small. The
DeformX paper randomizes the dome light over all 47 listed here. They are all
CC0 from Poly Haven (https://polyhaven.com), so this script just fetches them
directly rather than re-hosting them.

Usage:
    python scripts/fetch_full_backgrounds.py                  # into ../background
    python scripts/fetch_full_backgrounds.py --out /some/dir
    python scripts/fetch_full_backgrounds.py --resolution 2k  # smaller download
"""

from __future__ import annotations

import argparse
import sys
import urllib.error
import urllib.request
from pathlib import Path

# The 47 Poly Haven HDRIs used for background randomization.
HDRI_SLUGS = [
    "abandoned_factory_canteen_02",
    "abandoned_tiled_room",
    "bambanani_sunset",
    "bell_tower",
    "boiler_room",
    "burnt_warehouse",
    "cedar_bridge_2",
    "christmas_photo_studio_04",
    "church_stairway",
    "cobblestone_street_night",
    "creepy_bathroom",
    "decor_shop",
    "drachenfels_cellar",
    "empty_workshop",
    "ferndale_studio_01",
    "glasshouse_interior",
    "golden_bay",
    "hangar_interior",
    "industrial_pipe_and_valve_01",
    "industrial_wooden_attic",
    "industrial_workshop_foundry",
    "little_paris_eiffel_tower",
    "machine_shop_01",
    "machine_shop_02",
    "machine_shop_03",
    "metro_noord",
    "moon_lab",
    "newman_cafeteria",
    "outdoor_chapel",
    "palermo_sidewalk",
    "peppermint_powerplant",
    "rogland_clear_night",
    "shanghai_bund",
    "small_workshop",
    "street_lamp",
    "studio_small_09",
    "sundowner_deck",
    "sunflowers_puresky",
    "the_sky_is_on_fire",
    "university_workshop",
    "vintage_measuring_lab",
    "warm_bar",
    "warm_restaurant_night",
    "workshop",
    "wrestling_gym",
    "yaris_interior_garage",
    "zwartkops_start_morning",
]

URL_TEMPLATE = "https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/{res}/{slug}_{res}.hdr"


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument(
        "--out",
        type=Path,
        default=Path(__file__).resolve().parents[1] / "background",
        help="Destination directory (default: <bundle>/background).",
    )
    p.add_argument(
        "--resolution",
        default="4k",
        choices=["1k", "2k", "4k", "8k"],
        help="HDRI resolution to fetch (default: 4k, matching the paper).",
    )
    p.add_argument("--force", action="store_true", help="Re-download files that already exist.")
    return p.parse_args()


def download(url: str, dest: Path) -> None:
    """Download to a temp file, then move into place, so interrupts don't leave partials."""
    tmp = dest.with_suffix(dest.suffix + ".part")
    with urllib.request.urlopen(url, timeout=120) as resp, tmp.open("wb") as fh:
        while chunk := resp.read(1 << 20):
            fh.write(chunk)
    tmp.replace(dest)


def main() -> int:
    args = parse_args()
    args.out.mkdir(parents=True, exist_ok=True)

    total = len(HDRI_SLUGS)
    fetched = skipped = 0
    failures: list[tuple[str, str]] = []

    for i, slug in enumerate(HDRI_SLUGS, 1):
        name = f"{slug}_{args.resolution}.hdr"
        dest = args.out / name

        if dest.exists() and not args.force:
            print(f"[{i:2d}/{total}] skip (exists)  {name}", flush=True)
            skipped += 1
            continue

        url = URL_TEMPLATE.format(res=args.resolution, slug=slug)
        print(f"[{i:2d}/{total}] downloading    {name}", flush=True)
        try:
            download(url, dest)
            fetched += 1
        except (urllib.error.URLError, OSError) as exc:
            print(f"    FAILED: {exc}", file=sys.stderr, flush=True)
            failures.append((name, str(exc)))

    print(f"\nDone: {fetched} downloaded, {skipped} already present, {len(failures)} failed -> {args.out}")
    if failures:
        print("\nFailed downloads:", file=sys.stderr)
        for name, exc in failures:
            print(f"  {name}: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())