SPB Git

Repository Public

fetch_textures.py 12.9 KB 296 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Cosmos10# File             : DataPipeline/textures/fetch_textures.py11# Description      : Downloads every raw source listed in sources.json into the12#                    git-ignored cache DataPipeline/raw/textures (resumable13#                    curl for files, WMTS tiles for NASA Trek layers), saves14#                    the licence pages, and records sizes and SHA-256 in15#                    RAW_INDEX.json. Standard library + curl only.16# Module           : DataPipeline17# Repository       : https://git.spboucher.ai/orix-cosmos18# Project Website  : https://www.orixlab.dev19# Created          : 2026-11-2420# Last Modified    : 2026-11-2421#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author           : Simon-Pierre Boucher27# Position         : Professor of Finance28# Institution      : Université du Québec en Outaouais (UQO)29# Department       : Département des sciences administratives30# Organization     : SP Boucher31#32# Website          : https://spboucher.ai33# Git              : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General          : info@spboucher.ai40# Professional     : contact@spboucher.ai41# Direct           : simon@spboucher.ai42# Research         : research@spboucher.ai43# Development      : dev@spboucher.ai44# Support          : support@spboucher.ai45# Security/Admin   : admin@spboucher.ai46# Notifications    : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification   : Public73# Distribution     : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License          : None specified (no license file in this repository)87# Maintainer       : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394"""Usage: fetch_textures.py <repository root> [--only <source id>[,<id>...]] [--max-total-gb 3.2]9596Network: official public archives only (science.nasa.gov assets, svs.gsfc.nasa.gov, trek.nasa.gov, planetarymaps.usgs.gov,97pds-geosciences.wustl.edu, archive.stsci.edu). No personal data is sent; the User-Agent is generic.98Re-running is cheap: complete files and tiles are skipped, partial files are resumed (curl -C -)."""99import concurrent.futures100import datetime101import hashlib102import json103import os104import re105import subprocess106import sys107import urllib.request108109UA = "orix-cosmos-pipeline/1.0"110111112def sha256(path):113    h = hashlib.sha256()114    with open(path, "rb") as f:115        for block in iter(lambda: f.read(1 << 20), b""):116            h.update(block)117    return h.hexdigest()118119120def remote_size(url):121    out = subprocess.run(["curl", "-sSIL", "-m", "60", "-A", UA, url], capture_output=True, text=True).stdout122    size = None123    for line in out.splitlines():124        if line.lower().startswith("content-length:"):125            size = int(line.split(":", 1)[1].strip())126    return size127128129def fetch_file(url, dest):130    """Resumable download. Returns True when the local file is complete."""131    os.makedirs(os.path.dirname(dest), exist_ok=True)132    want = remote_size(url)133    have = os.path.getsize(dest) if os.path.exists(dest) else 0134    if want is not None and have == want:135        print(f"ok       {os.path.basename(dest)} ({have} bytes, already complete)")136        return True137    if want is not None and have > want:138        os.remove(dest)139    print(f"download {os.path.basename(dest)} ({want} bytes expected, {have} present)", flush=True)140    for _ in range(5):141        r = subprocess.run(["curl", "-sSL", "--fail", "-C", "-", "--retry", "3", "--retry-delay", "5", "-A", UA, "-o", dest, url])142        have = os.path.getsize(dest) if os.path.exists(dest) else 0143        if r.returncode == 0 and (want is None or have == want):144            return True145    print(f"FAILED   {url}", file=sys.stderr)146    return False147148149def http_get(url, timeout=60):150    req = urllib.request.Request(url, headers={"User-Agent": UA})151    with urllib.request.urlopen(req, timeout=timeout) as r:152        return r.read()153154155def fetch_trek(src, raw):156    """Downloads one zoom level of a Trek WMTS layer (plate carree, top-left -180/+90, 2:1 tile matrix)."""157    out = os.path.join(raw, src["dir"])158    os.makedirs(out, exist_ok=True)159    cap_path = os.path.join(out, "WMTSCapabilities.xml")160    if not os.path.exists(cap_path):161        with open(cap_path, "wb") as f:162            f.write(http_get(src["endpoint"] + "/1.0.0/WMTSCapabilities.xml"))163    cap = open(cap_path, encoding="utf-8", errors="replace").read()164    template = re.search(r'<ResourceURL[^>]*template="([^"]*)"', cap).group(1)165    ext = template.rsplit(".", 1)[1]166    top_left = re.search(r"<TopLeftCorner>([^<]*)", cap).group(1).split()167    if [float(v) for v in top_left] != [-180.0, 90.0]:168        raise SystemExit(f"{src['id']}: unexpected TopLeftCorner {top_left}; the stitcher assumes -180/+90")169    z = src["zoom"]170    matrices = re.findall(r"<TileMatrix>\s*<ows:Identifier>(\d+)</ows:Identifier>.*?<TileWidth>(\d+)</TileWidth>.*?"171                          r"<MatrixWidth>([\d.]+)</MatrixWidth>\s*<MatrixHeight>([\d.]+)</MatrixHeight>", cap, flags=re.S)172    dims = {int(m[0]): (int(m[1]), int(float(m[2])), int(float(m[3]))) for m in matrices}173    if z not in dims:174        raise SystemExit(f"{src['id']}: zoom {z} not offered (levels {sorted(dims)})")175    tile, cols, rows = dims[z]176    set_name = re.search(r"<TileMatrixSet>([^<]*)</TileMatrixSet>", cap).group(1)177    jobs = []178    for row in range(rows):179        for col in range(cols):180            url = (template.replace("{Style}", "default").replace("{TileMatrixSet}", set_name)181                   .replace("{TileMatrix}", str(z)).replace("{TileRow}", str(row)).replace("{TileCol}", str(col)))182            jobs.append((url, os.path.join(out, f"{row}_{col}.{ext}")))183184    def one(job):185        url, dest = job186        if os.path.exists(dest) and os.path.getsize(dest) > 0:187            return True188        for _ in range(4):189            try:190                data = http_get(url)191                if len(data) > 0:192                    with open(dest + ".part", "wb") as f:193                        f.write(data)194                    os.replace(dest + ".part", dest)195                    return True196            except Exception:  # retried below; the final failure is reported197                continue198        return False199200    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:201        results = list(pool.map(one, jobs))202    missing = results.count(False)203    with open(os.path.join(out, "tiles.json"), "w") as f:204        json.dump({"zoom": z, "tile": tile, "cols": cols, "rows": rows, "ext": ext, "template": template,205                   "tileMatrixSet": set_name, "missing": missing}, f, indent=1)206    print(f"{'ok      ' if missing == 0 else 'PARTIAL '} {src['id']}: {len(jobs) - missing}/{len(jobs)} tiles, {cols * tile} x {rows * tile}")207    return missing == 0208209210def dir_stats(path):211    total, h = 0, hashlib.sha256()212    for name in sorted(os.listdir(path)):213        p = os.path.join(path, name)214        if os.path.isfile(p) and not name.endswith(".part"):215            total += os.path.getsize(p)216            h.update(name.encode())217            h.update(sha256(p).encode())218    return total, h.hexdigest()219220221def main():222    if len(sys.argv) < 2:223        raise SystemExit(__doc__)224    root = os.path.abspath(sys.argv[1])225    only = None226    limit_gb = 3.2227    args = sys.argv[2:]228    while args:229        a = args.pop(0)230        if a == "--only":231            only = set(args.pop(0).split(","))232        elif a == "--max-total-gb":233            limit_gb = float(args.pop(0))234    here = os.path.join(root, "DataPipeline", "textures")235    raw = os.path.join(root, "DataPipeline", "raw", "textures")236    os.makedirs(raw, exist_ok=True)237    table = json.load(open(os.path.join(here, "sources.json"), encoding="utf-8"))238    index_path = os.path.join(raw, "RAW_INDEX.json")239    index = json.load(open(index_path)) if os.path.exists(index_path) else {"sources": {}, "licencePages": {}}240    today = datetime.date.today().isoformat()241    failed = []242    for src in table["sources"]:243        if only and src["id"] not in only:244            continue245        try:246            if src["kind"] == "file":247                dest = os.path.join(raw, src["file"])248                ok = fetch_file(src["url"], dest)249                for extra in src.get("extra", []):250                    ok = fetch_file(extra, os.path.join(os.path.dirname(dest), os.path.basename(extra))) and ok251                if ok:252                    prev = index["sources"].get(src["id"], {})253                    size = os.path.getsize(dest)254                    digest = prev.get("sha256") if prev.get("bytes") == size else sha256(dest)255                    index["sources"][src["id"]] = {"bytes": size, "sha256": digest, "url": src["url"],256                                                   "retrieved": prev.get("retrieved", today) if prev.get("bytes") == size else today}257            else:258                ok = fetch_trek(src, raw)259                if ok:260                    size, digest = dir_stats(os.path.join(raw, src["dir"]))261                    prev = index["sources"].get(src["id"], {})262                    index["sources"][src["id"]] = {"bytes": size, "sha256": digest, "url": src["endpoint"],263                                                   "retrieved": prev.get("retrieved", today) if prev.get("sha256") == digest else today}264        except Exception as exc:  # recorded and reported; other sources continue265            print(f"ERROR    {src['id']}: {exc}", file=sys.stderr)266            ok = False267        if not ok:268            failed.append(src["id"])269        with open(index_path, "w") as f:270            json.dump(index, f, indent=1, sort_keys=True)271    if not only:272        for page in table.get("licencePages", []):273            dest = os.path.join(raw, page["file"])274            os.makedirs(os.path.dirname(dest), exist_ok=True)275            if not os.path.exists(dest):276                r = subprocess.run(["curl", "-sSL", "--fail", "-m", "90", "-A", UA, "-o", dest, page["url"]])277                if r.returncode != 0:278                    print(f"FAILED   licence page {page['url']}", file=sys.stderr)279                    continue280            index["licencePages"][page["file"]] = {"url": page["url"], "bytes": os.path.getsize(dest), "sha256": sha256(dest),281                                                   "retrieved": index["licencePages"].get(page["file"], {}).get("retrieved", today)}282    total = sum(v["bytes"] for v in index["sources"].values())283    index["totalBytes"] = total284    with open(index_path, "w") as f:285        json.dump(index, f, indent=1, sort_keys=True)286    print(f"raw cache: {total / 1e9:.2f} GB in {len(index['sources'])} sources")287    if total > limit_gb * 1e9:288        print(f"WARNING: raw cache exceeds the {limit_gb} GB budget", file=sys.stderr)289    if failed:290        print("could not be obtained: " + ", ".join(failed), file=sys.stderr)291        sys.exit(2)292293294if __name__ == "__main__":295    main()296
Files main
Menu

Theme