Datasets:
Download scripts/ingest_scenes.py from fatmur/dynamicworld-300: direct link, hf CLI and curl.
- Browser
- Download file 3.69 kB
-
https://huggingface.co/datasets/fatmur/dynamicworld-300/resolve/main/scripts/ingest_scenes.py
- Command line
-
hf download hf://datasets/fatmur/dynamicworld-300/scripts/ingest_scenes.py
-
curl -L -o ingest_scenes.py https://huggingface.co/datasets/fatmur/dynamicworld-300/resolve/main/scripts/ingest_scenes.py
3.69 kB
| """Fill missing image and SCL files for the labels prepared in eda.ipynb. | |
| python scripts/ingest_scenes.py processed --threads 4 | |
| """ | |
| import re | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from tempfile import TemporaryDirectory | |
| import pandas as pd | |
| import typer | |
| import xarray as xr | |
| from tqdm import tqdm | |
| import geosave as gs | |
| from geosave.geodata import io | |
| from geosave.ml.pipeline.ingestion import Sentinel2L2AIngestor | |
| BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B11", "B12"] | |
| def write_cog(raster: xr.Dataset, path: Path, **options) -> None: | |
| """Expose the final path only after the COG is complete.""" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with TemporaryDirectory(dir=path.parent) as folder: | |
| partial = Path(folder) / path.name | |
| io.write_cog(raster, partial, compress="ZSTD", **options) | |
| partial.replace(path) | |
| def ingest_scene( | |
| reader: Sentinel2L2AIngestor, | |
| label_path: Path, | |
| day: pd.Timestamp, | |
| image_path: Path, | |
| scl_path: Path, | |
| ) -> None: | |
| need_image = not image_path.is_file() | |
| need_scl = not scl_path.is_file() | |
| if not (need_image or need_scl): | |
| return | |
| with gs.open_raster(label_path, chunks=None) as label: | |
| grid = label.gs.geobox | |
| if grid is None: | |
| raise ValueError(f"Label has no raster grid: {label_path}") | |
| region = gs.GeoRegion.from_geometry(grid.extent, timespan=f"{day:%Y-%m-%d}") | |
| scene = reader.load(reader.search(region), grid) | |
| if need_image: | |
| image = scene["s2/image"].gs.to_dataset().load() | |
| if not image.B04.values.any(): | |
| raise ValueError(f"No valid reflectance on {label_path}") | |
| write_cog( | |
| image.gs.write_rgb("B04", "B03", "B02"), | |
| image_path, | |
| predictor=2, | |
| interleave="BAND", | |
| ) | |
| if need_scl: | |
| # Nine stored bits keep uint16 with a compact TIFF color table. | |
| write_cog(scene["s2/scl"].gs.to_dataset(), scl_path, nbits=9) | |
| def main(processed: Path, threads: int = 4) -> None: | |
| labels = pd.read_parquet( | |
| processed / "label.parquet", | |
| columns=["scene_id", "label_path", "split", "date"], | |
| ).dropna(subset=["label_path"]) | |
| labels = labels.loc[labels["split"].isin(["train", "val", "test"])].copy() | |
| filename = labels["scene_id"] + ".tif" | |
| labels["image_path"] = labels["split"] + "/image/" + filename | |
| labels["scl_path"] = labels["split"] + "/scl/" + filename | |
| reader = Sentinel2L2AIngestor("s2", {"image": BANDS, "scl": ["SCL"]}) | |
| def ingest(row) -> str | None: | |
| try: | |
| ingest_scene( | |
| reader, | |
| processed / row.label_path, | |
| row.date, | |
| processed / row.image_path, | |
| processed / row.scl_path, | |
| ) | |
| except Exception as exc: | |
| # Provider errors can include signed asset URLs. | |
| message = re.sub(r"(https?://[^\s?'\"]+)\?[^\s'\"]+", r"\1", str(exc)) | |
| return f"{type(exc).__name__}: {message}" | |
| return None | |
| with ThreadPoolExecutor(threads) as pool: | |
| errors = pool.map(ingest, labels.itertuples(index=False)) | |
| labels["error"] = list(tqdm(errors, total=len(labels))) | |
| log = labels[["scene_id", "label_path", "image_path", "scl_path", "error"]].copy() | |
| log.loc[log["error"].notna(), ["image_path", "scl_path"]] = None | |
| path = processed / "ingest_log.parquet" | |
| partial = path.with_suffix(".tmp") | |
| log.to_parquet(partial, index=False) | |
| partial.replace(path) | |
| print(f"{len(log)} assigned labels, {log['error'].notna().sum()} missing pairs") | |
| if __name__ == "__main__": | |
| typer.run(main) | |