Download modules/supervised/datasets.py from fatmur/dynamicworld: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/fatmur/dynamicworld/resolve/main/modules/supervised/datasets.py
- Command line
-
hf download hf://fatmur/dynamicworld/modules/supervised/datasets.py
-
curl -L -o datasets.py https://huggingface.co/fatmur/dynamicworld/resolve/main/modules/supervised/datasets.py
5.21 kB
| """Read Dynamic World scenes: one image GeoTIFF and its label GeoTIFF per sample.""" | |
| from pathlib import Path | |
| from typing import Any | |
| import geopandas as gpd | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| import xarray as xr | |
| from torch.utils.data import Dataset | |
| import geosave as gs | |
| from geosave.geodata.features import scl_valid_mask | |
| from geosave.ml.factory import BuildSpec | |
| from geosave.ml.processing.raster.preprocessing.base import PREPROCESSORS | |
| from .data import Sample | |
| class SceneDataset(Dataset[Sample]): | |
| """Read one whole scene and its class labels per index. | |
| Selection is explicit in the annotation catalogue. Multiple annotations may | |
| share one image; each returned sample uses its own original label file. | |
| Args: | |
| labels: Label GeoParquet from EDA; paths resolve relative to this file. | |
| ingest_log: Ingest log Parquet, with each label's image and SCL. | |
| split: train, val or test. | |
| source_groups: Annotation sources to include, e.g. experts and non_expert. | |
| preprocessor: Native preprocessing component specification. | |
| ignore_index: In-memory ignored target value. | |
| label_scheme: Original-code remapping and class metadata. | |
| voting_rule: Composite to select; None selects individual annotations. | |
| """ | |
| def __init__( | |
| self, | |
| labels: str, | |
| ingest_log: str, | |
| split: str, | |
| source_groups: list[str], | |
| preprocessor: BuildSpec, | |
| ignore_index: int, | |
| label_scheme: dict[str, Any], | |
| voting_rule: str | None = None, | |
| ) -> None: | |
| root = Path(labels).parent | |
| labels_df = gpd.read_parquet(labels).merge( | |
| pd.read_parquet(ingest_log), on="label_path", validate="one_to_one" | |
| ) | |
| selected_df = labels_df.loc[ | |
| (labels_df["split"] == split) | |
| & labels_df["source_group"].isin(source_groups) | |
| & labels_df["image_path"].notna() | |
| ] | |
| if voting_rule is None: | |
| selected_df = selected_df.loc[selected_df["voting_rule"].isna()] | |
| else: | |
| selected_df = selected_df.loc[selected_df["voting_rule"] == voting_rule] | |
| if selected_df.empty: | |
| raise ValueError( | |
| f"no completed annotations for {split}/{source_groups}/{voting_rule}" | |
| ) | |
| duplicate_columns = ( | |
| ["scene_id", "source_group"] if split == "train" else ["scene_id"] | |
| ) | |
| if selected_df.duplicated(duplicate_columns).any(): | |
| raise ValueError("select one annotation per scene and training source") | |
| self.images = [root / path for path in selected_df.image_path] | |
| self.scls = [root / path for path in selected_df.scl_path] | |
| self.labels = [root / path for path in selected_df.label_path] | |
| self.preprocessor = PREPROCESSORS.build(preprocessor) | |
| self.ignore_index = ignore_index | |
| self.label_scheme = label_scheme | |
| if label_scheme["ignore_index"] != ignore_index: | |
| raise ValueError("label scheme and loss must use the same ignore_index") | |
| self.class_of_code = np.full(256, ignore_index, dtype="int64") | |
| for code, class_id in label_scheme["remap"].items(): | |
| self.class_of_code[int(code)] = class_id | |
| def __len__(self) -> int: | |
| """Return the number of scenes.""" | |
| return len(self.images) | |
| def __getitem__(self, index: int) -> Sample: | |
| """Read one scene as tensors. | |
| Raises: | |
| ValueError: The label is not one band on the image grid, or has | |
| values outside the original annotation codes 0–10. | |
| """ | |
| with ( | |
| gs.open_raster(self.images[index]) as image, | |
| gs.open_raster(self.scls[index]) as scl, | |
| gs.open_raster(self.labels[index]) as label, | |
| ): | |
| rasters = xr.DataTree.from_dict({"image": image}) | |
| prepared = self.preprocessor(rasters)["image"].to_dataset() | |
| if len(label.data_vars) != 1: | |
| raise ValueError("expected one original annotation band") | |
| codes = next(iter(label.data_vars.values())).values | |
| if label.gs.geobox != prepared.gs.geobox: | |
| raise ValueError(f"{self.labels[index]} is not on its image's grid") | |
| if not np.isin(codes, np.arange(11)).all(): | |
| raise ValueError( | |
| f"{self.labels[index]} is not original annotation codes 0–10" | |
| ) | |
| sample = prepared.gs.to_tensor( | |
| "image", | |
| dtype="float32", | |
| grid=True, | |
| context=["centroid", "year", "day_of_year"], | |
| ) | |
| target = torch.from_numpy(self.class_of_code[codes.astype("uint8")]) | |
| valid = torch.from_numpy(scl_valid_mask(scl, scl="SCL").values) | |
| target = target.masked_fill(~valid, self.ignore_index) | |
| return { | |
| "image": sample["image"], | |
| "target": target, | |
| "transform": sample["transform"], | |
| "crs": sample["crs"], | |
| "centroid": sample["centroid"], | |
| "year": sample["year"], | |
| "day_of_year": sample["day_of_year"], | |
| } | |