AW3D30-DEM-Tiles / scripts /upload_tiles.py
Onyxl's picture
Add tile uploader script
7566fa8 verified
Raw
History Blame Contribute Delete
11.1 kB
"""
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<n<100K
---
# JAXA AW3D30 30m Digital Elevation Model — Tile Dataset
Produced by **MegaBites AI** for use with **[MSKit](https://pypi.org/project/mskit/)** (Mini Simulation Kit).
## About the data
- **Source:** JAXA ALOS World 3D 30m (AW3D30) v3.2
- **Resolution:** 30 metres/pixel
- **Coverage:** Global (tiles available where JAXA data exists)
- **Tile size:** 1°×1° → 3600×3600 pixels
- **Format:** NumPy `.npy` files (int16, elevation in metres)
- **NODATA:** -9999
## File structure
```
data/
N000/
N000E000.npy
N000E001.npy
...
N005/
...
```
## Usage with MSKit
```python
from mskit import DEMLoader, RandomWalk
loader = DEMLoader() # pulls tiles on demand
rw = RandomWalk(loader, start_lat=35.6, start_lon=139.7)
path = rw.run(steps=500)
print(f"Walked {rw.total_distance_km():.2f} km, gain {rw.elevation_gain_m():.0f} m")
```
## License
Original JAXA AW3D30 data: © JAXA, distributed under CC-BY-4.0.
Dataset packaging: MegaBites AI Team.
"""
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="Upload AW3D30 tiles to HuggingFace")
parser.add_argument("--token", default=os.environ.get("HF_TOKEN"), help="HF token")
parser.add_argument("--region", choices=list(REGIONS.keys()), help="Named region")
parser.add_argument("--lat-range", nargs=2, type=int, metavar=("MIN", "MAX"))
parser.add_argument("--lon-range", nargs=2, type=int, metavar=("MIN", "MAX"))
parser.add_argument("--chunk-size", type=int, default=CHUNK_SIZE)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--skip-card", action="store_true")
args = parser.parse_args()
if not args.token:
sys.exit("Error: --token or HF_TOKEN env var required")
# Determine tile range
if args.region:
lat_min, lat_max, lon_min, lon_max = REGIONS[args.region]
elif args.lat_range and args.lon_range:
lat_min, lat_max = args.lat_range
lon_min, lon_max = args.lon_range
else:
parser.error("Specify --region or both --lat-range and --lon-range")
tiles = enumerate_tiles(lat_min, lat_max, lon_min, lon_max)
print(f"📦 {len(tiles)} tiles to process ({lat_min}{lat_max}°N, {lon_min}{lon_max}°E)")
print(f"📤 Target: {DATASET_REPO}")
print(f"🔢 Chunk size: {args.chunk_size}")
if args.dry_run:
print("🔍 DRY RUN — no uploads")
api = HfApi(token=args.token)
# Upload dataset card first
if not args.skip_card and not args.dry_run:
print("\n📝 Uploading dataset card...")
api.upload_file(
path_or_fileobj=DATASET_CARD.encode(),
path_in_repo="README.md",
repo_id=DATASET_REPO,
repo_type="dataset",
commit_message="Add dataset card",
)
session = requests.Session()
session.headers["User-Agent"] = "MSKit-tile-uploader/0.1"
total_ok = total_skip = 0
chunks = list(chunked(tiles, args.chunk_size))
for i, chunk in enumerate(chunks):
print(f"\n[Chunk {i+1}/{len(chunks)}]")
ok, skip = upload_chunk(api, chunk, session, i, dry_run=args.dry_run)
total_ok += ok
total_skip += skip
print(f" → {ok} uploaded, {skip} skipped")
print(f"\n✅ Done! {total_ok} tiles uploaded, {total_skip} skipped.")
if __name__ == "__main__":
main()