fatmur Claude Opus 5.5 commited on
Commit
ccf1487
·
1 Parent(s): ec89b51

ingest: one L2A image per scene on its label grid, paired by scene key

Browse files
README.md CHANGED
@@ -9,20 +9,20 @@ Training runs through GeoSave's LightningCLI (`main.py`).
9
  | Part | State |
10
  | --- | --- |
11
  | `scripts/download_dynamic_world.py` | works: annotation archives and metadata into `data/raw/` |
12
- | `scripts/ingest_dynamic_world.py` | being rewritten: label grid → matching imagery → catalog |
13
  | `data/labels.yaml` | training targets; source codes live in each label COG's legend |
14
- | `modules/.../datasets.py` | stub, waits on the new catalog and Sample design |
15
  | `modules/.../data.py`, `module.py` | DataModule and LightningModule; import and construct |
16
  | configs, EDA notebook | not yet written |
17
 
18
- No prepared catalog exists; `data/processed/` is produced by the new ingest.
19
 
20
  ## Commands
21
 
22
  ```bash
23
  python scripts/download_dynamic_world.py --subset experts
24
  python scripts/download_dynamic_world.py --subset validation
25
- python scripts/download_dynamic_world.py --subset test
26
  ```
27
 
28
  ## Sources
 
9
  | Part | State |
10
  | --- | --- |
11
  | `scripts/download_dynamic_world.py` | works: annotation archives and metadata into `data/raw/` |
12
+ | `scripts/ingest_dynamic_world.py` | works: one L2A image per scene on its label grid → `data/processed/images/` |
13
  | `data/labels.yaml` | training targets; source codes live in each label COG's legend |
14
+ | `modules/.../datasets.py` | `find_labels` lists every label file by scene; `DynamicWorld` is a stub |
15
  | `modules/.../data.py`, `module.py` | DataModule and LightningModule; import and construct |
16
  | configs, EDA notebook | not yet written |
17
 
18
+ Labels and images pair by scene key; see `data/README.md` for the structure and splits.
19
 
20
  ## Commands
21
 
22
  ```bash
23
  python scripts/download_dynamic_world.py --subset experts
24
  python scripts/download_dynamic_world.py --subset validation
25
+ python -m scripts.ingest_dynamic_world --source experts --source expert_composites
26
  ```
27
 
28
  ## Sources
modules/segmentation/supervised/datasets.py CHANGED
@@ -1,19 +1,62 @@
1
  """Dynamic World scenes as segmentation samples; stubbed until the Sample design settles."""
2
 
 
3
  from pathlib import Path
4
  from typing import Literal
5
 
 
6
  import yaml
7
  from torch.utils.data import Dataset
8
 
9
  DATA = Path(__file__).resolve().parents[3] / "data"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  def read_target(name: str) -> dict:
13
  """Read one training target (remap, classes, colors) from data/labels.yaml."""
14
  return yaml.safe_load((DATA / "labels.yaml").read_text())[name]
15
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  class DynamicWorld(Dataset):
18
  """Paired image/label scenes from the prepared catalog.
19
 
 
1
  """Dynamic World scenes as segmentation samples; stubbed until the Sample design settles."""
2
 
3
+ import re
4
  from pathlib import Path
5
  from typing import Literal
6
 
7
+ import pandas as pd
8
  import yaml
9
  from torch.utils.data import Dataset
10
 
11
  DATA = Path(__file__).resolve().parents[3] / "data"
12
 
13
+ # Where each label source sits under data/raw. The Zenodo test files repeat the
14
+ # consensus composite and are not a source.
15
+ SOURCES = {
16
+ "experts": "experts",
17
+ "non_expert": "non_expert",
18
+ "individual_experts": "validation/validation_set/individual_experts",
19
+ "expert_composites": "validation/validation_set/expert_composites",
20
+ }
21
+
22
+ # dw_{lon}_{lat}-{yyyymmdd}[_{variant}].tif; variant is a composite rule or expert id.
23
+ LABEL_NAME = re.compile(r"^dw_(-?\d+\.\d+)_(-?\d+\.\d+)-(\d{8})_?(.*)$")
24
+
25
 
26
  def read_target(name: str) -> dict:
27
  """Read one training target (remap, classes, colors) from data/labels.yaml."""
28
  return yaml.safe_load((DATA / "labels.yaml").read_text())[name]
29
 
30
 
31
+ def find_labels(raw: Path = DATA / "raw") -> pd.DataFrame:
32
+ """List every label file with the scene it annotates.
33
+
34
+ Every label of one scene shares that scene's grid, so the scene key pairs
35
+ a label with its image, `processed/images/{scene}.tif`.
36
+
37
+ Returns:
38
+ One row per file: `scene` (`{lon}_{lat}-{yyyymmdd}`), `date`, `source`,
39
+ `variant` (composite rule or expert id, empty otherwise) and `path`.
40
+ """
41
+ rows = []
42
+ for source, folder in SOURCES.items():
43
+ for path in sorted((raw / folder).rglob("*.tif")):
44
+ match = LABEL_NAME.match(path.stem)
45
+ if match is None:
46
+ raise ValueError(f"unexpected label name: {path}")
47
+ lon, lat, day, variant = match.groups()
48
+ rows.append(
49
+ {
50
+ "scene": f"{lon}_{lat}-{day}",
51
+ "date": pd.Timestamp(day),
52
+ "source": source,
53
+ "variant": variant,
54
+ "path": path,
55
+ }
56
+ )
57
+ return pd.DataFrame(rows)
58
+
59
+
60
  class DynamicWorld(Dataset):
61
  """Paired image/label scenes from the prepared catalog.
62
 
scripts/ingest_dynamic_world.py CHANGED
@@ -1,411 +1,142 @@
1
- """Download matching Sentinel-2 pixels for the local Dynamic World labels.
2
 
3
- uv run python workspace/dynamicworld/scripts/ingest_dynamic_world.py --threads 8
4
 
5
- Search each label's footprint and acquisition day, mosaic that day's matches
6
- on its exact grid, and save matching TIFFs in train, val and test folders.
7
- Published digital numbers and band metadata are retained; training decodes scale and offset.
8
- The catalog records complete pairs; failures.csv records unsuccessful source matches.
9
  """
10
 
11
- import re
12
- import random
13
- from xml.etree import ElementTree
14
-
15
- import requests
16
- import rasterio
17
- from rasterio.shutil import copy as copy_raster
18
-
19
- import pystac
20
- from upath import UPath
21
  from concurrent.futures import ThreadPoolExecutor, as_completed
22
  from pathlib import Path
23
- from tempfile import TemporaryDirectory
24
 
25
- import numpy as np
26
  import pandas as pd
27
- import geopandas as gpd
28
  import typer
29
  import xarray as xr
30
- import yaml
31
  from tqdm import tqdm
32
 
33
  import geosave as gs
34
- from geosave.geodata.io import load_dataset
35
- from geosave.geodata.stac import StacClient, StacQuery, from_items
36
- from geosave.geodata.stac.asset import build_asset
 
 
37
 
38
- WORKSPACE = Path(__file__).resolve().parents[1]
39
- SPLITS = {
40
- "experts": "train",
41
- "non_expert": "train",
42
- "validation": "val",
43
- "test": "test",
44
- }
45
 
46
  # The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).
47
  BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"]
48
 
49
- ORIGINAL = yaml.safe_load((WORKSPACE / "data" / "labels.yaml").read_text())["original"]
50
- CLASS_MAP = ORIGINAL["class_map"]
51
- COLOR_MAP = ORIGINAL["color_map"]
52
-
53
-
54
- def read_label(path: Path) -> xr.Dataset:
55
- """Read the human annotation band without changing its class codes."""
56
- with gs.open_raster(path) as raster:
57
- # Test files put predictions first and human labels second.
58
- names = list(raster.data_vars)
59
- band = names[1] if len(names) == 2 else names[0]
60
- if len(names) not in (1, 2):
61
- raise ValueError(f"expected one or two label bands in {path}")
62
- label = raster[[band]].rename({band: "label"}).compute()
63
-
64
- if not np.isin(label["label"].values, list(CLASS_MAP)).all():
65
- raise ValueError(f"unknown label codes in {path}")
66
- label = label.expand_dims(time=[read_date(path)])
67
- label = label.gs.write_nodata(0)
68
-
69
- return label.gs.write_legend(CLASS_MAP, COLOR_MAP)
70
-
71
-
72
- def read_date(path: Path) -> pd.Timestamp:
73
- """Read the acquisition day each release puts in its file names."""
74
- match = re.search(r"-(\d{8})", path.stem)
75
- if match is None:
76
- raise ValueError(f"no date in {path.name}")
77
 
78
- return pd.Timestamp(match.group(1))
 
 
 
79
 
80
 
81
- def read_metadata(raw: Path) -> dict[tuple[str, str], dict]:
82
- """Preserve release fields, keyed by source and annotation identifier.
83
 
84
- Source WKT is stored as source_geometry because GeoParquet geometry is the
85
- geographic footprint. Source crs remains alongside the original WKT.
86
  """
87
- metadata = {}
88
- paths = sorted(raw.rglob("*.xlsx")) + sorted(raw.rglob("meta.csv"))
89
- for path in paths:
90
- if path.suffix == ".xlsx":
91
- table = pd.read_excel(path)
92
- else:
93
- table = pd.read_csv(path)
94
-
95
- table = table.rename(columns={"geometry": "source_geometry"})
96
- table = table.astype(object).where(table.notna(), None)
97
- for record in table.to_dict(orient="records"):
98
- for name, value in record.items():
99
- if isinstance(value, pd.Timestamp):
100
- record[name] = value.isoformat()
101
-
102
- if "labeler" in record:
103
- source = {"Experts": "experts", "Non-expert": "non_expert"}[
104
- record["labeler"]
105
- ]
106
- label_id = record["dw_id"]
107
- elif "filename" in record:
108
- source = "test"
109
- label_id = record["filename"]
110
- else:
111
- source = "validation"
112
- label_id = record["dw_id"]
113
-
114
- key = (source, label_id)
115
- if key in metadata:
116
- raise ValueError(f"Duplicate annotation metadata: {key}")
117
- metadata[key] = record
118
-
119
- return metadata
120
-
121
-
122
- def read_calibration(
123
- client: StacClient, item: pystac.Item
124
- ) -> dict[str, tuple[float, float]]:
125
- """Read reflectance calibration from Sentinel product XML, absent in PC STAC."""
126
- href = item.assets["product-metadata"].href
127
- response = requests.get(client.patch_url(href), timeout=60)
128
- response.raise_for_status()
129
- root = ElementTree.fromstring(response.content)
130
- quantification = None
131
- offsets = {}
132
- for element in root.iter():
133
- name = element.tag.split("}")[-1]
134
- if name == "BOA_QUANTIFICATION_VALUE":
135
- quantification = float(element.text)
136
- elif name == "BOA_ADD_OFFSET":
137
- offsets[int(element.attrib["band_id"])] = float(element.text)
138
- if quantification is None or quantification <= 0:
139
- raise ValueError(f"missing BOA quantification: {item.id}")
140
- if float(item.properties["s2:processing_baseline"]) >= 4 and not offsets:
141
- raise ValueError(f"missing BOA offsets for baseline >= 4: {item.id}")
142
- ids = {
143
- "B02": 1,
144
- "B03": 2,
145
- "B04": 3,
146
- "B05": 4,
147
- "B06": 5,
148
- "B07": 6,
149
- "B08": 7,
150
- "B8A": 8,
151
- "B11": 11,
152
- "B12": 12,
153
- }
154
- calibration = {}
155
- if (
156
- float(item.properties["s2:processing_baseline"]) >= 4
157
- and not set(ids.values()) <= offsets.keys()
158
- ):
159
- raise ValueError(f"incomplete BOA offsets for requested bands: {item.id}")
160
- for band in BANDS:
161
- calibration[band] = (
162
- 1 / quantification,
163
- offsets.get(ids[band], 0) / quantification,
164
- )
165
- return calibration
166
-
167
-
168
- def ingest_label(
169
- client: StacClient, path: Path, folder: Path, item_id: str, properties: dict
170
- ) -> pystac.Item:
171
- """Load the label's day and grid, then write a pair of equally named TIFFs."""
172
- label = read_label(path)
173
- region = label.gs.region.replace(timespan=read_date(path).strftime("%Y-%m-%d"))
174
- query = StacQuery(collections=["sentinel-2-l2a"]).set_region(region)
175
  items = client.search_items(query)
176
  if not items:
177
- raise ValueError(f"no Sentinel-2 imagery for {path.name}")
178
- # Stable overlap precedence when neighbouring tiles cover the label.
179
- items.sort(key=lambda item: item.id)
180
- calibration = read_calibration(client, items[0])
181
- for item in items[1:]:
182
- if read_calibration(client, item) != calibration:
183
- raise ValueError(
184
- "cannot mosaic source digital numbers with different calibration"
185
- )
186
- image = load_dataset(
187
  items,
188
- collection=client.collection("sentinel-2-l2a"),
189
- geobox=label.gs.geobox,
190
  bands=BANDS,
191
- groupby=lambda item, parsed, index: 0,
192
- preserve_original_order=True,
193
  resampling="bilinear",
194
  dtype="uint16",
195
  nodata=0,
196
  chunks=None,
197
- pool=2,
198
  patch_url=client.patch_url,
199
  )
200
- for band, (scale, offset) in calibration.items():
201
- image[band].attrs.update(
202
- scale_factor=scale, add_offset=offset, long_name=band, units="1"
203
- )
204
- if not image.to_array().any().item():
205
- raise ValueError(f"imagery contains only nodata for {path.name}")
206
- properties = {
207
- **properties,
208
- "source_ids": [item.id for item in items],
209
- "datetime": read_date(path).tz_localize("UTC").isoformat(),
210
- "source_datetimes": [item.datetime.isoformat() for item in items],
211
- "processing_level": "L2A",
212
- "resampling": "bilinear",
213
- "matching": "same-day mosaic; not exact original product recovery",
214
- "bands": BANDS,
215
- "label_codes": "original-0-10",
216
- "calibration": calibration,
217
- }
218
- dates = sorted(set(properties["source_datetimes"]))
219
- if len(dates) != 1:
220
- raise ValueError("model context requires one acquisition time per mosaic")
221
- image.attrs["acquisition_time"] = dates[0]
222
- folder.mkdir(parents=True, exist_ok=True)
223
- with TemporaryDirectory(dir=folder) as temporary:
224
- stage = Path(temporary)
225
- image.gs.to_cog(stage, path_format="image.tif")
226
- label.gs.to_cog(stage, path_format="label.tif", overview_resampling="NEAREST")
227
- write_time(stage / "image.tif", dates[0])
228
- # Publish the image last: the loader's glob must only discover complete pairs.
229
- for source, destination in [
230
- ("label.tif", folder / "labels" / f"{item_id}.tif"),
231
- ("image.tif", folder / "images" / f"{item_id}.tif"),
232
- ]:
233
- destination.parent.mkdir(parents=True, exist_ok=True)
234
- (stage / source).replace(destination)
235
- return make_item(
236
- folder / "images" / f"{item_id}.tif",
237
- folder / "labels" / f"{item_id}.tif",
238
- properties,
239
- )
240
 
241
 
242
- def write_time(path: Path, date: str) -> None:
243
- """Add actual acquisition time while retaining Cloud Optimized TIFF layout."""
244
- with rasterio.open(path) as source:
245
- if source.tags().get("acquisition_time") == date:
246
- return
247
- with TemporaryDirectory(dir=path.parent) as temporary:
248
- editable = Path(temporary) / "image.tif"
249
- cog = Path(temporary) / "image-cog.tif"
250
- copy_raster(path, editable, driver="GTiff")
251
- with rasterio.open(editable, "r+") as image:
252
- image.update_tags(acquisition_time=date)
253
- copy_raster(editable, cog, driver="COG", compress="DEFLATE")
254
- cog.replace(path)
255
 
256
 
257
  def main(
258
- raw: Path = WORKSPACE / "data" / "raw",
259
- out: Path = WORKSPACE / "data" / "processed",
260
- threads: int = 2,
261
- subset: str | None = None,
262
  limit: int | None = None,
263
- seed: int = 0,
264
  ) -> None:
265
- """Ingest every label under RAW into OUT, THREADS labels at a time."""
266
- raw, out = raw.resolve(), out.resolve()
267
- if subset is not None and subset not in SPLITS:
268
- raise ValueError(f"unknown subset: {subset}")
269
- if limit is not None and limit < 1:
270
- raise ValueError("limit must be positive")
271
- if not raw.is_dir():
272
- raise ValueError(f"label folder does not exist: {raw}")
273
- if threads < 1:
274
- raise ValueError("threads must be positive")
275
- catalog_path = out / "catalog.parquet"
276
- items = {}
277
- if catalog_path.exists():
278
- table = gpd.read_parquet(catalog_path)
279
- if "dw:split" in table:
280
- raise ValueError(
281
- "Refusing to modify the legacy catalog or its files. "
282
- "Use a fresh --out directory to prepare source metadata."
283
- )
284
- for item in table.gs.to_items():
285
- items[item.id] = item
286
-
287
- metadata = read_metadata(raw)
288
- client = StacClient.planetary_computer()
289
- client.collection("sentinel-2-l2a")
290
- out.mkdir(parents=True, exist_ok=True)
291
 
292
  failures_path = out / "failures.csv"
293
  failures = {}
294
  if failures_path.exists():
295
- failures = pd.read_csv(failures_path).set_index("source")["error"].to_dict()
296
-
297
- # The test release keeps model probabilities, `probs_*`, beside its labels.
298
- pending = {}
299
- paths = []
300
- for path in sorted(raw.rglob("*.tif")):
301
- source = path.relative_to(raw).parts[0]
302
- if source not in SPLITS or (subset is not None and source != subset):
303
- continue
304
- if path.name.startswith("probs_"):
305
- continue
306
- if source == "validation" and "expert_composites" not in path.parts:
307
- continue
308
- paths.append(path)
309
- random.Random(seed).shuffle(paths)
310
- if limit is not None:
311
- paths = paths[:limit]
312
- for path in paths:
313
- key = path.relative_to(raw).as_posix()
314
- if path.name.startswith("probs_"):
315
- continue
316
- folder = out / SPLITS[path.relative_to(raw).parts[0]]
317
- item_id = "_".join(Path(key).with_suffix("").parts)
318
- image = folder / "images" / f"{item_id}.tif"
319
- label = folder / "labels" / f"{item_id}.tif"
320
- if item_id not in items or not image.exists() or not label.exists():
321
- pending[key] = path
322
 
 
323
  with ThreadPoolExecutor(threads) as pool:
324
  futures = {}
325
- for key, path in pending.items():
326
- folder = out / SPLITS[path.relative_to(raw).parts[0]]
327
- # Experts and non-experts labelled some of the same tiles, under
328
- # the same file name, so the subset keeps their Items apart.
329
- item_id = "_".join(Path(key).with_suffix("").parts)
330
- # Test labels are named `label_<id>`; their metadata names `<id>`.
331
- source = path.relative_to(raw).parts[0]
332
- label_id = path.stem.removeprefix("label_")
333
- properties = dict(metadata[source, label_id])
334
- properties["annotation_source"] = source
335
- properties["split"] = SPLITS[source]
336
- properties["raw_label"] = key
337
- if source == "validation":
338
- for composite in ("simple_majority", "strict", "majority", "consensus"):
339
- if label_id.endswith("_" + composite):
340
- properties["validation_composite"] = composite
341
- break
342
 
343
- future = pool.submit(
344
- ingest_label, client, path, folder, item_id, properties
345
- )
346
- futures[future] = key
347
-
348
- for future in tqdm(as_completed(futures), total=len(futures), unit="label"):
349
- key = futures[future]
350
  try:
351
- item = future.result()
352
- items[item.id] = item
353
- write_catalog(out, list(items.values()))
354
- failures.pop(key, None)
355
  except Exception as error:
356
- failures[key] = f"{type(error).__name__}: {error}"
357
- tqdm.write(f"{key}: {failures[key]}")
358
- pd.DataFrame(list(failures.items()), columns=["source", "error"]).to_csv(
359
- failures_path, index=False
360
- )
361
-
362
- failed = sum(path.relative_to(raw).as_posix() in failures for path in paths)
363
- print(
364
- f"Selected {len(paths)} samples; {len(paths) - failed} complete; {failed} failed"
365
- )
366
- if failed:
367
- raise typer.Exit(code=1)
368
-
369
-
370
- def make_item(image_path: Path, label_path: Path, properties: dict) -> pystac.Item:
371
- """Describe a completed pair using source provenance and raster headers."""
372
- properties = dict(properties)
373
- date = pd.Timestamp(properties.pop("datetime")).to_pydatetime()
374
- with gs.open_raster(image_path) as image, gs.open_raster(label_path) as label:
375
- geometry = label.gs.geobox.geographic_extent
376
- item = pystac.Item(
377
- image_path.stem, geometry.json, list(geometry.boundingbox), date, properties
378
- )
379
- item.collection_id = "dynamic-world-l2a"
380
- item.add_asset("image", build_asset(UPath(image_path), image, owner=item))
381
- item.add_asset("label", build_asset(UPath(label_path), label, owner=item))
382
- item.assets["label"].roles = ["labels"]
383
- return item
384
-
385
-
386
- def write_catalog(out: Path, items: list[pystac.Item]) -> None:
387
- """Persist complete pairs and their provenance in one STAC GeoParquet table."""
388
- if not items:
389
- return
390
- collection = pystac.Collection(
391
- "dynamic-world-l2a",
392
- "L2A images paired with original Dynamic World human annotations",
393
- pystac.Extent.from_items(items),
394
- license="CC-BY-4.0",
395
- )
396
- table = from_items(items, collections=[collection])
397
- # Hrefs are relative to catalog.parquet so the dataset can move between machines.
398
- for assets in table["assets"]:
399
- for asset in assets.values():
400
- href = Path(asset["href"])
401
- asset["href"] = (
402
- href.relative_to(out).as_posix()
403
- if href.is_absolute()
404
- else href.as_posix()
405
- )
406
- partial = out / "catalog.partial.parquet"
407
- table.gs.to_geoparquet(partial)
408
- partial.replace(out / "catalog.parquet")
409
 
410
 
411
  if __name__ == "__main__":
 
1
+ """Download the Sentinel-2 L2A image of every labelled Dynamic World scene.
2
 
3
+ uv run python -m scripts.ingest_dynamic_world --source experts --source expert_composites
4
 
5
+ Run from the workspace root. Each scene's labels share one grid; its image is
6
+ the same-day L2A acquisition loaded onto that grid, ten bands in one COG at
7
+ data/processed/images/{scene}.tif. Existing images are skipped, so a rerun
8
+ resumes; failures.csv records scenes without usable imagery.
9
  """
10
 
 
 
 
 
 
 
 
 
 
 
11
  from concurrent.futures import ThreadPoolExecutor, as_completed
12
  from pathlib import Path
 
13
 
 
14
  import pandas as pd
 
15
  import typer
16
  import xarray as xr
 
17
  from tqdm import tqdm
18
 
19
  import geosave as gs
20
+ import geosave.geodata.attrs as attrs
21
+ from geosave.geodata import io, stac
22
+ from geosave.geodata.stac import StacClient, StacQuery
23
+
24
+ from modules.segmentation.supervised.datasets import DATA, SOURCES, find_labels
25
 
26
+ COLLECTION = "sentinel-2-l2a"
 
 
 
 
 
 
27
 
28
  # The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).
29
  BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"]
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ def read_packing(baseline: str) -> attrs.CFPacking:
33
+ """Decode L2A digital numbers to reflectance; baseline 04.00 added a -1000 DN offset."""
34
+ offset = -0.1 if float(baseline) >= 4 else 0.0
35
+ return attrs.CFPacking(scale_factor=1e-4, add_offset=offset, fill_value=0)
36
 
37
 
38
+ def load_image(client: StacClient, label: xr.Dataset, date: pd.Timestamp) -> xr.Dataset:
39
+ """Load the label day's L2A acquisition onto the label's grid.
40
 
41
+ Neighbouring tiles of one pass mosaic into one image; tiles processed
42
+ with different baselines decode differently and are refused.
43
  """
44
+ region = label.gs.region.replace(timespan=date.strftime("%Y-%m-%d"))
45
+ query = StacQuery(collections=[COLLECTION]).set_region(region)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  items = client.search_items(query)
47
  if not items:
48
+ raise LookupError("no L2A acquisition on the label day")
49
+
50
+ baselines = set()
51
+ for item in items:
52
+ baselines.add(item.properties["s2:processing_baseline"])
53
+ if len(baselines) != 1:
54
+ raise ValueError(f"tiles mix processing baselines {sorted(baselines)}")
55
+
56
+ image = stac.load_dataset(
 
57
  items,
58
+ label.gs.geobox,
59
+ collection=client.collection(COLLECTION),
60
  bands=BANDS,
 
 
61
  resampling="bilinear",
62
  dtype="uint16",
63
  nodata=0,
64
  chunks=None,
 
65
  patch_url=client.patch_url,
66
  )
67
+ if image.sizes["time"] != 1:
68
+ raise ValueError(f"expected one acquisition, found {image.sizes['time']}")
69
+ image = image.isel(time=0)
70
+ if not image.to_array().any():
71
+ raise ValueError("imagery holds only nodata")
72
+
73
+ return image.gs.write_packing(read_packing(baselines.pop()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
 
76
+ def ingest_scene(client: StacClient, label_path: Path, date: pd.Timestamp, path: Path) -> None:
77
+ """Write one scene's image, publishing the file only once it is complete."""
78
+ with gs.open_raster(label_path, chunks=None) as label:
79
+ image = load_image(client, label, date)
80
+ partial = path.with_suffix(".partial.tif")
81
+ io.write_cog(image, partial, overwrite=True)
82
+ partial.replace(path)
 
 
 
 
 
 
83
 
84
 
85
  def main(
86
+ source: list[str] = list(SOURCES),
87
+ out: Path = DATA / "processed",
88
+ threads: int = 4,
 
89
  limit: int | None = None,
 
90
  ) -> None:
91
+ """Download images for the scenes the chosen label sources annotate."""
92
+ unknown = set(source) - set(SOURCES)
93
+ if unknown:
94
+ raise typer.BadParameter(f"unknown sources {sorted(unknown)}; choose from {list(SOURCES)}")
95
+
96
+ labels = find_labels()
97
+ labels = labels[labels["source"].isin(source)]
98
+ # Every label of a scene shares its grid, so any one of them places the image.
99
+ scenes = labels.groupby("scene").first()
100
+ images = out / "images"
101
+ images.mkdir(parents=True, exist_ok=True)
102
+
103
+ pending = []
104
+ for scene in scenes.index:
105
+ if not (images / f"{scene}.tif").exists():
106
+ pending.append(scene)
107
+ print(f"{len(scenes)} scenes; {len(scenes) - len(pending)} done; {len(pending)} to load")
108
+ if limit is not None:
109
+ pending = pending[:limit]
 
 
 
 
 
 
 
110
 
111
  failures_path = out / "failures.csv"
112
  failures = {}
113
  if failures_path.exists():
114
+ failures = pd.read_csv(failures_path).set_index("scene")["error"].to_dict()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ client = StacClient.planetary_computer()
117
  with ThreadPoolExecutor(threads) as pool:
118
  futures = {}
119
+ for scene in pending:
120
+ row = scenes.loc[scene]
121
+ future = pool.submit(ingest_scene, client, row["path"], row["date"], images / f"{scene}.tif")
122
+ futures[future] = scene
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
+ for future in tqdm(as_completed(futures), total=len(futures), unit="scene"):
125
+ scene = futures[future]
 
 
 
 
 
126
  try:
127
+ future.result()
128
+ failures.pop(scene, None)
 
 
129
  except Exception as error:
130
+ failures[scene] = f"{type(error).__name__}: {error}"
131
+ tqdm.write(f"{scene}: {failures[scene]}")
132
+
133
+ failed = 0
134
+ for scene in futures.values():
135
+ if scene in failures:
136
+ failed += 1
137
+ table = pd.DataFrame(list(failures.items()), columns=["scene", "error"])
138
+ table.to_csv(failures_path, index=False)
139
+ print(f"{len(futures) - failed} loaded; {failed} failed (failures.csv)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
 
142
  if __name__ == "__main__":