"""Download one Sentinel-2 L2A image per prepared label, on the label's grid. python scripts/ingest_scenes.py processed --threads 8 Reads processed/label.parquet. Image and SCL mirror each label's path: processed/label/train/expert/x.tif prepared label processed/image/train/expert/x.tif reflectance digital numbers processed/scl/train/expert/x.tif scene classification processed/ingest_log.parquet label_path, image_path, scl_path, error A rerun skips labels whose image and SCL already exist. """ from concurrent.futures import ThreadPoolExecutor from pathlib import Path import pandas as pd import typer import xarray as xr from tqdm import tqdm import geosave as gs from geosave.geodata import io, stac from geosave.geodata.attrs import CFPacking BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"] def mirror_path(label_path: str, folder: str) -> str: """Move a label's path under another folder: label/a/x.tif -> image/a/x.tif.""" return Path(folder, *Path(label_path).parts[1:]).as_posix() def write_cog(raster: xr.Dataset, path: Path) -> None: """Write through a partial file, so an existing file is always complete.""" path.parent.mkdir(parents=True, exist_ok=True) partial = path.with_suffix(".partial.tif") io.write_cog(raster, partial, overwrite=True) partial.replace(path) def ingest_scene( client: stac.StacClient, label_path: Path, day: pd.Timestamp, image_path: Path, scl_path: Path, ) -> None: """Write the image and SCL of the label's acquisition day on the label's grid.""" with gs.open_raster(label_path) as label: geobox = label.gs.geobox if geobox is None: raise ValueError(f"label has no raster grid: {label_path}") query = stac.StacQuery( collections=["sentinel-2-l2a"], intersects=geobox.extent.to_crs("EPSG:4326").json, datetime=f"{day:%Y-%m-%d}", ) items = client.search_items(query) if not items: raise ValueError(f"no Sentinel-2 scene on {day:%Y-%m-%d}") # Processing baseline 04.00 shifted digital numbers by +1000. offsets = set() for item in items: baseline = float(item.properties["s2:processing_baseline"]) offsets.add(-0.1 if baseline >= 4 else 0.0) if len(offsets) != 1: raise ValueError( f"Sentinel-2 scenes on {day:%Y-%m-%d} mix processing baselines" ) offset = offsets.pop() packing = CFPacking(scale_factor=1e-4, add_offset=offset, fill_value=0) scene = stac.load_dataset( items, bands=[*BANDS, "SCL"], geobox=geobox, groupby="solar_day", resampling={"*": "bilinear", "SCL": "nearest"}, dtype="uint16", nodata=0, patch_url=client.patch_url, ) scene = scene.isel(time=0) write_cog(scene[BANDS].gs.write_packing(packing), image_path) write_cog(scene[["SCL"]], scl_path) def main(processed: Path, threads: int = 4) -> None: """Ingest every prepared label whose image is not yet written.""" labels_df = pd.read_parquet( processed / "label.parquet", columns=["label_path", "date"] ) labels_df = labels_df.loc[labels_df.label_path.notna()] labels_df["image_path"] = labels_df.label_path.map( lambda path: mirror_path(path, "image") ) labels_df["scl_path"] = labels_df.label_path.map( lambda path: mirror_path(path, "scl") ) client = stac.StacClient.planetary_computer() def ingest(label) -> str | None: image_path = processed / label.image_path scl_path = processed / label.scl_path if image_path.exists() and scl_path.exists(): return None try: ingest_scene( client, processed / label.label_path, label.date, image_path, scl_path ) except Exception as error: return f"{type(error).__name__}: {error}" return None with ThreadPoolExecutor(threads) as pool: labels = list(labels_df.itertuples()) errors = list(tqdm(pool.map(ingest, labels), total=len(labels))) log_df = labels_df[["label_path", "image_path", "scl_path"]].copy() log_df["error"] = errors log_df.loc[log_df.error.notna(), ["image_path", "scl_path"]] = None log_df.to_parquet(processed / "ingest_log.parquet", index=False) print(f"{log_df.error.isna().sum()} written, {log_df.error.notna().sum()} failed") if __name__ == "__main__": typer.run(main)