Onyxl commited on
Commit
7566fa8
·
verified ·
1 Parent(s): d0444da

Add tile uploader script

Browse files
Files changed (1) hide show
  1. scripts/upload_tiles.py +364 -0
scripts/upload_tiles.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ upload_tiles.py — Download JAXA AW3D30 tiles and upload to HuggingFace
3
+ dataset MegaBites-AI/AW3D30-DEM-Tiles chunk by chunk.
4
+
5
+ Usage:
6
+ python upload_tiles.py --region japan --token $HF_TOKEN
7
+ python upload_tiles.py --lat-range 30 45 --lon-range 130 145 --token $HF_TOKEN
8
+ python upload_tiles.py --all --token $HF_TOKEN # WARNING: ~450 GB
9
+
10
+ Tiles are downloaded from the JAXA open-access HTTP mirror, converted to
11
+ compressed .npy arrays, and uploaded in configurable chunk sizes.
12
+ """
13
+
14
+ import argparse
15
+ import io
16
+ import math
17
+ import os
18
+ import struct
19
+ import sys
20
+ import tempfile
21
+ import time
22
+ import zipfile
23
+ from pathlib import Path
24
+ from typing import Generator, List, Tuple
25
+
26
+ import numpy as np
27
+ import requests
28
+ from huggingface_hub import HfApi
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Configuration
32
+ # ---------------------------------------------------------------------------
33
+
34
+ DATASET_REPO = "MegaBites-AI/AW3D30-DEM-Tiles"
35
+ CHUNK_SIZE = 10 # tiles per upload batch
36
+ TILE_ROWS = 3600
37
+ TILE_COLS = 3600
38
+ NODATA_VAL = -9999
39
+
40
+ # JAXA open-access mirror (no login needed for AW3D30 v3.2)
41
+ # Pattern: https://www.eorc.jaxa.jp/ALOS/aw3d30/data/release_v2303/
42
+ # {lat5_dir}/{tile}.zip e.g. N030E135.zip
43
+ JAXA_BASE = (
44
+ "https://www.eorc.jaxa.jp/ALOS/aw3d30/data/release_v2303"
45
+ )
46
+
47
+ # Known regional bounding boxes (lat_min, lat_max, lon_min, lon_max)
48
+ REGIONS = {
49
+ "japan": (24, 46, 122, 154),
50
+ "korea": (33, 39, 124, 130),
51
+ "china": (18, 53, 73, 135),
52
+ "south_asia": ( 8, 37, 60, 97),
53
+ "southeast_asia":(-11, 28, 92, 141),
54
+ "australia": (-44, -9, 112, 154),
55
+ "europe": (35, 72, -25, 45),
56
+ "north_america": (15, 72, -170, -50),
57
+ "south_america": (-56, 13, -82, -34),
58
+ "africa": (-35, 38, -18, 52),
59
+ "global": (-90, 90, -180, 180),
60
+ }
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Tile enumeration
64
+ # ---------------------------------------------------------------------------
65
+
66
+ def tile_name(lat: int, lon: int) -> str:
67
+ lc = "N" if lat >= 0 else "S"
68
+ oc = "E" if lon >= 0 else "W"
69
+ return f"{lc}{abs(lat):03d}{oc}{abs(lon):03d}"
70
+
71
+
72
+ def lat5_dir(lat: int) -> str:
73
+ """JAXA groups tiles in 5° latitude bands."""
74
+ base = (lat // 5) * 5
75
+ lc = "N" if base >= 0 else "S"
76
+ return f"{lc}{abs(base):03d}"
77
+
78
+
79
+ def enumerate_tiles(
80
+ lat_min: int, lat_max: int,
81
+ lon_min: int, lon_max: int,
82
+ ) -> List[Tuple[int, int]]:
83
+ tiles = []
84
+ for lat in range(lat_min, lat_max):
85
+ for lon in range(lon_min, lon_max):
86
+ tiles.append((lat, lon))
87
+ return tiles
88
+
89
+
90
+ def chunked(lst: list, n: int) -> Generator:
91
+ for i in range(0, len(lst), n):
92
+ yield lst[i:i + n]
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Download + decode
97
+ # ---------------------------------------------------------------------------
98
+
99
+ def download_tile(lat: int, lon: int, session: requests.Session) -> np.ndarray | None:
100
+ """
101
+ Download a JAXA AW3D30 tile and return it as a (3600,3600) int16 numpy array.
102
+ Returns None if tile doesn't exist (ocean / no data).
103
+ """
104
+ name = tile_name(lat, lon)
105
+ lat5 = lat5_dir(lat)
106
+ url = f"{JAXA_BASE}/{lat5}/{name}.zip"
107
+
108
+ try:
109
+ r = session.get(url, timeout=60, stream=True)
110
+ if r.status_code == 404:
111
+ return None
112
+ r.raise_for_status()
113
+ except requests.RequestException as e:
114
+ print(f" [WARN] {name}: download failed — {e}")
115
+ return None
116
+
117
+ # The zip contains {name}/{name}_DSM.tif (GeoTIFF)
118
+ # We'll decode the raw TIFF data without GDAL using basic struct parsing
119
+ raw = b"".join(r.iter_content(chunk_size=65536))
120
+ try:
121
+ with zipfile.ZipFile(io.BytesIO(raw)) as zf:
122
+ tif_name = next(
123
+ (n for n in zf.namelist() if n.endswith("_DSM.tif")), None
124
+ )
125
+ if tif_name is None:
126
+ print(f" [WARN] {name}: no DSM.tif in zip")
127
+ return None
128
+ tif_data = zf.read(tif_name)
129
+ except zipfile.BadZipFile:
130
+ print(f" [WARN] {name}: bad zip")
131
+ return None
132
+
133
+ arr = _parse_geotiff(tif_data, name)
134
+ return arr
135
+
136
+
137
+ def _parse_geotiff(data: bytes, name: str) -> np.ndarray | None:
138
+ """
139
+ Minimal GeoTIFF parser that extracts the raw pixel data.
140
+ Works for stripped, uncompressed or LZW-compressed GeoTIFFs.
141
+ Falls back to numpy frombuffer for raw DEM files.
142
+ """
143
+ try:
144
+ # Try tifffile if available (optional dependency)
145
+ import tifffile
146
+ with tifffile.TiffFile(io.BytesIO(data)) as tif:
147
+ arr = tif.asarray()
148
+ if arr.ndim > 2:
149
+ arr = arr[0]
150
+ return arr.astype(np.int16)
151
+ except ImportError:
152
+ pass
153
+ except Exception as e:
154
+ print(f" [WARN] {name}: tifffile parse error — {e}")
155
+
156
+ # Fallback: raw int16 row-major
157
+ expected = TILE_ROWS * TILE_COLS * 2 # int16 = 2 bytes
158
+ # scan for start of pixel data (after TIFF header)
159
+ if len(data) >= expected:
160
+ raw_pixels = data[-expected:]
161
+ arr = np.frombuffer(raw_pixels, dtype=">i2").reshape(TILE_ROWS, TILE_COLS)
162
+ return arr.astype(np.int16)
163
+
164
+ print(f" [WARN] {name}: cannot parse TIFF, size={len(data)}")
165
+ return None
166
+
167
+
168
+ # ---------------------------------------------------------------------------
169
+ # Upload to HuggingFace
170
+ # ---------------------------------------------------------------------------
171
+
172
+ def upload_chunk(
173
+ api: HfApi,
174
+ chunk: List[Tuple[int, int]],
175
+ session: requests.Session,
176
+ chunk_idx: int,
177
+ dry_run: bool = False,
178
+ ) -> Tuple[int, int]:
179
+ """Download and upload a chunk of tiles. Returns (ok, skipped)."""
180
+ ok = skipped = 0
181
+ operations = []
182
+
183
+ for lat, lon in chunk:
184
+ name = tile_name(lat, lon)
185
+ print(f" ↓ Downloading {name} ...", end=" ", flush=True)
186
+ arr = download_tile(lat, lon, session)
187
+ if arr is None:
188
+ print("skip (no data)")
189
+ skipped += 1
190
+ continue
191
+
192
+ # Compress as .npy
193
+ buf = io.BytesIO()
194
+ np.save(buf, arr)
195
+ buf.seek(0)
196
+
197
+ lat_band = lat5_dir(lat)
198
+ hf_path = f"data/{lat_band}/{name}.npy"
199
+
200
+ if dry_run:
201
+ print(f"dry-run → {hf_path} ({arr.nbytes/1024:.0f} KB)")
202
+ ok += 1
203
+ continue
204
+
205
+ operations.append(
206
+ api.upload_file.__func__ if False else {
207
+ "path_or_fileobj": buf,
208
+ "path_in_repo": hf_path,
209
+ }
210
+ )
211
+
212
+ # Upload immediately per tile (streaming)
213
+ try:
214
+ api.upload_file(
215
+ path_or_fileobj=buf,
216
+ path_in_repo=hf_path,
217
+ repo_id=DATASET_REPO,
218
+ repo_type="dataset",
219
+ commit_message=f"Add tile {name}",
220
+ )
221
+ print(f"✓ {hf_path}")
222
+ ok += 1
223
+ except Exception as e:
224
+ print(f"✗ upload failed: {e}")
225
+ skipped += 1
226
+
227
+ time.sleep(0.3) # be polite to HF API
228
+
229
+ return ok, skipped
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Dataset card
234
+ # ---------------------------------------------------------------------------
235
+
236
+ DATASET_CARD = """\
237
+ ---
238
+ license: cc-by-4.0
239
+ task_categories:
240
+ - other
241
+ language:
242
+ - en
243
+ tags:
244
+ - elevation
245
+ - dem
246
+ - terrain
247
+ - jaxa
248
+ - aw3d30
249
+ - geospatial
250
+ - simulation
251
+ - mskit
252
+ pretty_name: JAXA AW3D30 30m DEM Tiles
253
+ size_categories:
254
+ - 10K<n<100K
255
+ ---
256
+
257
+ # JAXA AW3D30 30m Digital Elevation Model — Tile Dataset
258
+
259
+ Produced by **MegaBites AI** for use with **[MSKit](https://pypi.org/project/mskit/)** (Mini Simulation Kit).
260
+
261
+ ## About the data
262
+
263
+ - **Source:** JAXA ALOS World 3D 30m (AW3D30) v3.2
264
+ - **Resolution:** 30 metres/pixel
265
+ - **Coverage:** Global (tiles available where JAXA data exists)
266
+ - **Tile size:** 1°×1° → 3600×3600 pixels
267
+ - **Format:** NumPy `.npy` files (int16, elevation in metres)
268
+ - **NODATA:** -9999
269
+
270
+ ## File structure
271
+
272
+ ```
273
+ data/
274
+ N000/
275
+ N000E000.npy
276
+ N000E001.npy
277
+ ...
278
+ N005/
279
+ ...
280
+ ```
281
+
282
+ ## Usage with MSKit
283
+
284
+ ```python
285
+ from mskit import DEMLoader, RandomWalk
286
+
287
+ loader = DEMLoader() # pulls tiles on demand
288
+ rw = RandomWalk(loader, start_lat=35.6, start_lon=139.7)
289
+ path = rw.run(steps=500)
290
+ print(f"Walked {rw.total_distance_km():.2f} km, gain {rw.elevation_gain_m():.0f} m")
291
+ ```
292
+
293
+ ## License
294
+
295
+ Original JAXA AW3D30 data: © JAXA, distributed under CC-BY-4.0.
296
+ Dataset packaging: MegaBites AI Team.
297
+ """
298
+
299
+
300
+ # ---------------------------------------------------------------------------
301
+ # CLI
302
+ # ---------------------------------------------------------------------------
303
+
304
+ def main():
305
+ parser = argparse.ArgumentParser(description="Upload AW3D30 tiles to HuggingFace")
306
+ parser.add_argument("--token", default=os.environ.get("HF_TOKEN"), help="HF token")
307
+ parser.add_argument("--region", choices=list(REGIONS.keys()), help="Named region")
308
+ parser.add_argument("--lat-range", nargs=2, type=int, metavar=("MIN", "MAX"))
309
+ parser.add_argument("--lon-range", nargs=2, type=int, metavar=("MIN", "MAX"))
310
+ parser.add_argument("--chunk-size", type=int, default=CHUNK_SIZE)
311
+ parser.add_argument("--dry-run", action="store_true")
312
+ parser.add_argument("--skip-card", action="store_true")
313
+ args = parser.parse_args()
314
+
315
+ if not args.token:
316
+ sys.exit("Error: --token or HF_TOKEN env var required")
317
+
318
+ # Determine tile range
319
+ if args.region:
320
+ lat_min, lat_max, lon_min, lon_max = REGIONS[args.region]
321
+ elif args.lat_range and args.lon_range:
322
+ lat_min, lat_max = args.lat_range
323
+ lon_min, lon_max = args.lon_range
324
+ else:
325
+ parser.error("Specify --region or both --lat-range and --lon-range")
326
+
327
+ tiles = enumerate_tiles(lat_min, lat_max, lon_min, lon_max)
328
+ print(f"📦 {len(tiles)} tiles to process ({lat_min}–{lat_max}°N, {lon_min}–{lon_max}°E)")
329
+ print(f"📤 Target: {DATASET_REPO}")
330
+ print(f"🔢 Chunk size: {args.chunk_size}")
331
+ if args.dry_run:
332
+ print("🔍 DRY RUN — no uploads")
333
+
334
+ api = HfApi(token=args.token)
335
+
336
+ # Upload dataset card first
337
+ if not args.skip_card and not args.dry_run:
338
+ print("\n📝 Uploading dataset card...")
339
+ api.upload_file(
340
+ path_or_fileobj=DATASET_CARD.encode(),
341
+ path_in_repo="README.md",
342
+ repo_id=DATASET_REPO,
343
+ repo_type="dataset",
344
+ commit_message="Add dataset card",
345
+ )
346
+
347
+ session = requests.Session()
348
+ session.headers["User-Agent"] = "MSKit-tile-uploader/0.1"
349
+
350
+ total_ok = total_skip = 0
351
+ chunks = list(chunked(tiles, args.chunk_size))
352
+
353
+ for i, chunk in enumerate(chunks):
354
+ print(f"\n[Chunk {i+1}/{len(chunks)}]")
355
+ ok, skip = upload_chunk(api, chunk, session, i, dry_run=args.dry_run)
356
+ total_ok += ok
357
+ total_skip += skip
358
+ print(f" → {ok} uploaded, {skip} skipped")
359
+
360
+ print(f"\n✅ Done! {total_ok} tiles uploaded, {total_skip} skipped.")
361
+
362
+
363
+ if __name__ == "__main__":
364
+ main()