""" upload_tiles.py — Download JAXA AW3D30 tiles and upload to HuggingFace dataset MegaBites-AI/AW3D30-DEM-Tiles chunk by chunk. Usage: python upload_tiles.py --region japan --token $HF_TOKEN python upload_tiles.py --lat-range 30 45 --lon-range 130 145 --token $HF_TOKEN python upload_tiles.py --all --token $HF_TOKEN # WARNING: ~450 GB Tiles are downloaded from the JAXA open-access HTTP mirror, converted to compressed .npy arrays, and uploaded in configurable chunk sizes. """ import argparse import io import math import os import struct import sys import tempfile import time import zipfile from pathlib import Path from typing import Generator, List, Tuple import numpy as np import requests from huggingface_hub import HfApi # --------------------------------------------------------------------------- # Configuration # --------------------------------------------------------------------------- DATASET_REPO = "MegaBites-AI/AW3D30-DEM-Tiles" CHUNK_SIZE = 10 # tiles per upload batch TILE_ROWS = 3600 TILE_COLS = 3600 NODATA_VAL = -9999 # JAXA open-access mirror (no login needed for AW3D30 v3.2) # Pattern: https://www.eorc.jaxa.jp/ALOS/aw3d30/data/release_v2303/ # {lat5_dir}/{tile}.zip e.g. N030E135.zip JAXA_BASE = ( "https://www.eorc.jaxa.jp/ALOS/aw3d30/data/release_v2303" ) # Known regional bounding boxes (lat_min, lat_max, lon_min, lon_max) REGIONS = { "japan": (24, 46, 122, 154), "korea": (33, 39, 124, 130), "china": (18, 53, 73, 135), "south_asia": ( 8, 37, 60, 97), "southeast_asia":(-11, 28, 92, 141), "australia": (-44, -9, 112, 154), "europe": (35, 72, -25, 45), "north_america": (15, 72, -170, -50), "south_america": (-56, 13, -82, -34), "africa": (-35, 38, -18, 52), "global": (-90, 90, -180, 180), } # --------------------------------------------------------------------------- # Tile enumeration # --------------------------------------------------------------------------- def tile_name(lat: int, lon: int) -> str: lc = "N" if lat >= 0 else "S" oc = "E" if lon >= 0 else "W" return f"{lc}{abs(lat):03d}{oc}{abs(lon):03d}" def lat5_dir(lat: int) -> str: """JAXA groups tiles in 5° latitude bands.""" base = (lat // 5) * 5 lc = "N" if base >= 0 else "S" return f"{lc}{abs(base):03d}" def enumerate_tiles( lat_min: int, lat_max: int, lon_min: int, lon_max: int, ) -> List[Tuple[int, int]]: tiles = [] for lat in range(lat_min, lat_max): for lon in range(lon_min, lon_max): tiles.append((lat, lon)) return tiles def chunked(lst: list, n: int) -> Generator: for i in range(0, len(lst), n): yield lst[i:i + n] # --------------------------------------------------------------------------- # Download + decode # --------------------------------------------------------------------------- def download_tile(lat: int, lon: int, session: requests.Session) -> np.ndarray | None: """ Download a JAXA AW3D30 tile and return it as a (3600,3600) int16 numpy array. Returns None if tile doesn't exist (ocean / no data). """ name = tile_name(lat, lon) lat5 = lat5_dir(lat) url = f"{JAXA_BASE}/{lat5}/{name}.zip" try: r = session.get(url, timeout=60, stream=True) if r.status_code == 404: return None r.raise_for_status() except requests.RequestException as e: print(f" [WARN] {name}: download failed — {e}") return None # The zip contains {name}/{name}_DSM.tif (GeoTIFF) # We'll decode the raw TIFF data without GDAL using basic struct parsing raw = b"".join(r.iter_content(chunk_size=65536)) try: with zipfile.ZipFile(io.BytesIO(raw)) as zf: tif_name = next( (n for n in zf.namelist() if n.endswith("_DSM.tif")), None ) if tif_name is None: print(f" [WARN] {name}: no DSM.tif in zip") return None tif_data = zf.read(tif_name) except zipfile.BadZipFile: print(f" [WARN] {name}: bad zip") return None arr = _parse_geotiff(tif_data, name) return arr def _parse_geotiff(data: bytes, name: str) -> np.ndarray | None: """ Minimal GeoTIFF parser that extracts the raw pixel data. Works for stripped, uncompressed or LZW-compressed GeoTIFFs. Falls back to numpy frombuffer for raw DEM files. """ try: # Try tifffile if available (optional dependency) import tifffile with tifffile.TiffFile(io.BytesIO(data)) as tif: arr = tif.asarray() if arr.ndim > 2: arr = arr[0] return arr.astype(np.int16) except ImportError: pass except Exception as e: print(f" [WARN] {name}: tifffile parse error — {e}") # Fallback: raw int16 row-major expected = TILE_ROWS * TILE_COLS * 2 # int16 = 2 bytes # scan for start of pixel data (after TIFF header) if len(data) >= expected: raw_pixels = data[-expected:] arr = np.frombuffer(raw_pixels, dtype=">i2").reshape(TILE_ROWS, TILE_COLS) return arr.astype(np.int16) print(f" [WARN] {name}: cannot parse TIFF, size={len(data)}") return None # --------------------------------------------------------------------------- # Upload to HuggingFace # --------------------------------------------------------------------------- def upload_chunk( api: HfApi, chunk: List[Tuple[int, int]], session: requests.Session, chunk_idx: int, dry_run: bool = False, ) -> Tuple[int, int]: """Download and upload a chunk of tiles. Returns (ok, skipped).""" ok = skipped = 0 operations = [] for lat, lon in chunk: name = tile_name(lat, lon) print(f" ↓ Downloading {name} ...", end=" ", flush=True) arr = download_tile(lat, lon, session) if arr is None: print("skip (no data)") skipped += 1 continue # Compress as .npy buf = io.BytesIO() np.save(buf, arr) buf.seek(0) lat_band = lat5_dir(lat) hf_path = f"data/{lat_band}/{name}.npy" if dry_run: print(f"dry-run → {hf_path} ({arr.nbytes/1024:.0f} KB)") ok += 1 continue operations.append( api.upload_file.__func__ if False else { "path_or_fileobj": buf, "path_in_repo": hf_path, } ) # Upload immediately per tile (streaming) try: api.upload_file( path_or_fileobj=buf, path_in_repo=hf_path, repo_id=DATASET_REPO, repo_type="dataset", commit_message=f"Add tile {name}", ) print(f"✓ {hf_path}") ok += 1 except Exception as e: print(f"✗ upload failed: {e}") skipped += 1 time.sleep(0.3) # be polite to HF API return ok, skipped # --------------------------------------------------------------------------- # Dataset card # --------------------------------------------------------------------------- DATASET_CARD = """\ --- license: cc-by-4.0 task_categories: - other language: - en tags: - elevation - dem - terrain - jaxa - aw3d30 - geospatial - simulation - mskit pretty_name: JAXA AW3D30 30m DEM Tiles size_categories: - 10K