fatmur commited on
Commit
3b6a37a
·
1 Parent(s): 0e11d09
.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # This file is part of the Copernicus Data Space Ecosystem (CDSE).
2
+ GDAL_HTTP_TCP_KEEPALIVE=YES
3
+ AWS_S3_ENDPOINT=eodata.dataspace.copernicus.eu
4
+ AWS_ACCESS_KEY_ID=changethis
5
+ AWS_SECRET_ACCESS_KEY=changethis
6
+ AWS_HTTPS=YES
7
+ AWS_VIRTUAL_HOSTING=FALSE
8
+ GDAL_HTTP_UNSAFESSL=YES
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .env
2
+ data/
3
+ *.ckpt
4
+ __pycache__/
5
+ .ipynb_checkpoints/
main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from geosave.ml.cli import GeosaveCLI
2
+
3
+
4
+ if __name__ == "__main__":
5
+ GeosaveCLI(
6
+ auto_configure_optimizers=False,
7
+ subclass_mode_model=True,
8
+ subclass_mode_data=True,
9
+ )
scripts/download_dynamic_world.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download and unzip every Dynamic World label release.
2
+
3
+ uv run python workspace/scripts/download_dynamic_world.py
4
+
5
+ writes workspace/data/dynamic_world_raw/<subset>/; a subset already unzipped
6
+ is skipped.
7
+ """
8
+
9
+ import urllib.request
10
+ from pathlib import Path
11
+ from zipfile import ZipFile
12
+
13
+ PANGAEA = "https://download.pangaea.de/dataset/933475/files"
14
+ URLS = {
15
+ "experts": f"{PANGAEA}/Experts_tiles.zip",
16
+ "non_expert": f"{PANGAEA}/Non_expert_tiles.zip",
17
+ "validation": f"{PANGAEA}/validation_set_tiles.zip",
18
+ "test": "https://zenodo.org/records/4766508/files/dw_test.zip?download=1",
19
+ }
20
+ RAW = Path(__file__).resolve().parents[1] / "data" / "dynamic_world_raw"
21
+
22
+
23
+ def download(url: str, archive: Path) -> None:
24
+ archive.parent.mkdir(parents=True, exist_ok=True)
25
+ urllib.request.urlretrieve(url, archive)
26
+
27
+
28
+ def unzip(archive: Path, folder: Path) -> None:
29
+ with ZipFile(archive) as files:
30
+ # macOS resource forks mirror every tile as `__MACOSX/.../._<tile>.tif`.
31
+ members = [name for name in files.namelist() if not name.startswith("__MACOSX")]
32
+ files.extractall(folder, members)
33
+
34
+
35
+ if __name__ == "__main__":
36
+ for subset, url in URLS.items():
37
+ folder = RAW / subset
38
+ if folder.exists():
39
+ print(f"already downloaded: {folder}")
40
+ continue
41
+ archive = folder.with_suffix(".zip")
42
+ download(url, archive)
43
+ unzip(archive, folder)
44
+ archive.unlink()
45
+ print(f"downloaded: {folder}")
scripts/ingest_dynamic_world.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pair each downloaded Dynamic World label with its Sentinel-2 scene.
2
+
3
+ Run download_dynamic_world.py first, then
4
+
5
+ uv run python workspace/scripts/ingest_dynamic_world.py
6
+
7
+ writes workspace/data/dynamic_world/<subset>/{images,labels}/<id>.tif,
8
+ classes.yaml, and manifest.json recording each label as "ok" or its error.
9
+ A rerun skips the "ok" labels and retries the rest.
10
+ """
11
+
12
+ import json
13
+ import re
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ import xarray as xr
19
+ import yaml
20
+
21
+ import geosave as gs
22
+ from geosave.geodata.stac import StacClient, StacSource
23
+
24
+ DATA = Path(__file__).resolve().parents[1] / "data"
25
+ RAW = DATA / "dynamic_world_raw"
26
+ OUT = DATA / "dynamic_world"
27
+ MANIFEST = OUT / "manifest.json"
28
+
29
+ # The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).
30
+ BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B11", "B12"]
31
+
32
+ # Release codes, from the label README: 0 No data (left unmarked), 1 Water,
33
+ # 2 Trees, 3 Grass, 4 Flooded Vegetation, 5 Crops, 6 Scrub, 7 Built Area,
34
+ # 8 Bare Ground, 9 Snow/Ice, 10 Cloud. Remapped to start at 0, with no data
35
+ # as the ignore index.
36
+ IGNORE_INDEX = 255
37
+ REMAP = {0: IGNORE_INDEX, 1: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, 10: 9}
38
+ CLASS_MAP = {
39
+ 0: "water",
40
+ 1: "trees",
41
+ 2: "grass",
42
+ 3: "flooded_vegetation",
43
+ 4: "crops",
44
+ 5: "scrub",
45
+ 6: "built_area",
46
+ 7: "bare_ground",
47
+ 8: "snow_ice",
48
+ 9: "cloud",
49
+ }
50
+ COLOR_MAP = {
51
+ 0: "#419bdf",
52
+ 1: "#397d49",
53
+ 2: "#88b053",
54
+ 3: "#7a87c6",
55
+ 4: "#e49635",
56
+ 5: "#dfc35a",
57
+ 6: "#c4281b",
58
+ 7: "#a59b8f",
59
+ 8: "#b39fe1",
60
+ 9: "#d3d3d3",
61
+ }
62
+
63
+
64
+ def read_label(path: Path) -> xr.Dataset:
65
+ label = gs.open_raster(path)
66
+ # Test labels hold the model's prediction in band 1, the human label in band 2.
67
+ band = "band_2" if "band_2" in label else "band_1"
68
+ label = label[[band]].rename({band: "label"}).compute()
69
+
70
+ lookup = np.full(256, IGNORE_INDEX, dtype="uint8")
71
+ for code, index in REMAP.items():
72
+ lookup[code] = index
73
+ label["label"].values = lookup[label["label"].values]
74
+
75
+ # A date label covers its whole day, so the label's anchor searches that day.
76
+ label = label.expand_dims(time=[read_date(path)])
77
+ label = label.gs.write_nodata(IGNORE_INDEX)
78
+ return label.gs.write_legend(CLASS_MAP, COLOR_MAP)
79
+
80
+
81
+ def read_date(path: Path) -> pd.Timestamp:
82
+ """Read the acquisition day each release puts in its file names."""
83
+ match = re.search(r"-(\d{8})", path.stem)
84
+ if match is None:
85
+ raise ValueError(f"no date in {path.name}")
86
+ return pd.Timestamp(match.group(1))
87
+
88
+
89
+ def fetch_image(source: StacSource, label: xr.Dataset) -> xr.Dataset:
90
+ """Load the Sentinel-2 scene of the label's day onto the label's grid."""
91
+ image = source.load(label.gs.anchor)
92
+ return image.gs.write_rgb("B04", "B03", "B02")
93
+
94
+
95
+ def save_tile(folder: Path, name: str, image: xr.Dataset, label: xr.Dataset) -> None:
96
+ image.gs.to_cog(folder / "images" / name, overwrite=True)
97
+ label.gs.to_cog(folder / "labels" / name, overwrite=True)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ source = StacClient.planetary_computer().source("sentinel-2-l2a")
102
+ source = source.set_config(bands=BANDS, chunks=None, dtype="uint16", nodata=0)
103
+
104
+ OUT.mkdir(parents=True, exist_ok=True)
105
+ classes = {
106
+ "ignore_index": IGNORE_INDEX,
107
+ "class_map": CLASS_MAP,
108
+ "color_map": COLOR_MAP,
109
+ }
110
+ (OUT / "classes.yaml").write_text(yaml.safe_dump(classes, sort_keys=False))
111
+ manifest = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
112
+
113
+ # The test release keeps model probabilities, `probs_*`, beside its labels.
114
+ paths = []
115
+ for path in sorted(RAW.rglob("*.tif")):
116
+ if not path.name.startswith("probs_"):
117
+ paths.append(path)
118
+
119
+ for number, path in enumerate(paths, start=1):
120
+ key = path.relative_to(RAW).as_posix()
121
+ if manifest.get(key) == "ok":
122
+ continue
123
+ try:
124
+ label = read_label(path)
125
+ image = fetch_image(source, label)
126
+ save_tile(OUT / path.relative_to(RAW).parts[0], path.name, image, label)
127
+ manifest[key] = "ok"
128
+ except Exception as error: # a scene Planetary Computer cannot serve
129
+ manifest[key] = f"{type(error).__name__}: {error}"
130
+ MANIFEST.write_text(json.dumps(manifest, indent=2))
131
+ print(f"[{number}/{len(paths)}] {key}: {manifest[key]}", flush=True)