Datasets:
Update terramesh.py
Browse files- terramesh.py +61 -31
terramesh.py
CHANGED
|
@@ -19,11 +19,8 @@
|
|
| 19 |
import os
|
| 20 |
import io
|
| 21 |
import re
|
| 22 |
-
|
| 23 |
-
import numpy
|
| 24 |
import zarr
|
| 25 |
import fsspec
|
| 26 |
-
import itertools
|
| 27 |
import braceexpand
|
| 28 |
import numpy as np
|
| 29 |
import albumentations
|
|
@@ -52,10 +49,11 @@ split_files = {
|
|
| 52 |
|
| 53 |
def build_terramesh_dataset(
|
| 54 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 55 |
-
modalities=None,
|
| 56 |
split: str = "val",
|
| 57 |
urls: str | None = None,
|
| 58 |
batch_size: int = 8,
|
|
|
|
| 59 |
*args, **kwargs,
|
| 60 |
):
|
| 61 |
if len(modalities) == 1:
|
|
@@ -66,6 +64,7 @@ def build_terramesh_dataset(
|
|
| 66 |
split=split,
|
| 67 |
urls=urls,
|
| 68 |
batch_size=batch_size,
|
|
|
|
| 69 |
*args, **kwargs
|
| 70 |
)
|
| 71 |
return dataset
|
|
@@ -78,6 +77,7 @@ def build_terramesh_dataset(
|
|
| 78 |
split=split,
|
| 79 |
urls=urls,
|
| 80 |
batch_size=batch_size,
|
|
|
|
| 81 |
*args, **kwargs,
|
| 82 |
)
|
| 83 |
return dataset
|
|
@@ -86,7 +86,28 @@ def build_terramesh_dataset(
|
|
| 86 |
def zarr_decoder(key, value):
|
| 87 |
if key == "zarr.zip" or key.endswith(".zarr.zip"):
|
| 88 |
mapper = fsspec.filesystem("zip", fo=io.BytesIO(value), block_size=None).get_mapper("")
|
| 89 |
-
return zarr.open_consolidated(mapper, mode="r")[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
def identity(sample):
|
|
@@ -115,6 +136,7 @@ def build_wds_dataset(
|
|
| 115 |
urls: str | None = None,
|
| 116 |
batch_size: int = 8,
|
| 117 |
transform: Callable = None,
|
|
|
|
| 118 |
*args, **kwargs
|
| 119 |
):
|
| 120 |
if urls is None:
|
|
@@ -134,12 +156,16 @@ def build_wds_dataset(
|
|
| 134 |
kwargs["shardshuffle"] = kwargs.get("shardshuffle", 100) # Shuffle shard by default
|
| 135 |
|
| 136 |
# Build dataset
|
| 137 |
-
dataset = (
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
if transform is not None:
|
| 145 |
dataset = dataset.map(transform)
|
|
@@ -151,19 +177,18 @@ def build_wds_dataset(
|
|
| 151 |
return dataset
|
| 152 |
|
| 153 |
|
| 154 |
-
def combine_datasets(*args):
|
| 155 |
-
return itertools.chain(*args)
|
| 156 |
-
|
| 157 |
-
|
| 158 |
def build_multimodal_dataset(
|
| 159 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 160 |
-
modalities:
|
| 161 |
split: str = "val",
|
| 162 |
urls: str | None = None,
|
| 163 |
batch_size: int = 8,
|
| 164 |
transform: Callable = None,
|
|
|
|
| 165 |
*args, **kwargs
|
| 166 |
):
|
|
|
|
|
|
|
| 167 |
if urls is None:
|
| 168 |
# Filter modalities based availability (S1GRD and S1RTC not present in all subsets)
|
| 169 |
def filter_list(lst, value):
|
|
@@ -180,17 +205,21 @@ def build_multimodal_dataset(
|
|
| 180 |
urls = (os.path.join(path, split, majortom_mod, split_files["majortom"][split][0])
|
| 181 |
+ "::" + os.path.join(path, split, ssl4eos12_mod, split_files["ssl4eos12"][split][0]))
|
| 182 |
|
| 183 |
-
dataset = build_datapipeline(urls, transform, batch_size, *args, **kwargs)
|
| 184 |
return dataset
|
| 185 |
|
| 186 |
|
| 187 |
-
def build_datapipeline(urls, transform, batch_size, *args, **kwargs):
|
| 188 |
datapipeline = wds.DataPipeline(
|
| 189 |
# Infinitely sample shards from the shard list with replacement. Each worker is seeded independently.
|
| 190 |
wds.ResampledShards(urls),
|
| 191 |
multi_tarfile_samples, # Extract individual samples from multi-modal tar files
|
| 192 |
wds.shuffle(100), # Shuffle with a buffer of given size
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
wds.map(drop_time_dim), # Remove time dimension from tensors
|
| 195 |
wds.map(remove_extensions), # Remove "file extensions" from dictionary keys
|
| 196 |
( # Apply transformation
|
|
@@ -211,7 +240,7 @@ def extract_modality_names(s):
|
|
| 211 |
"""
|
| 212 |
Function from https://github.com/apple/ml-4m/blob/main/fourm/data/unified_datasets.py.
|
| 213 |
"""
|
| 214 |
-
# Regular expression pattern to match anything enclosed in
|
| 215 |
pattern = r"\{([^}]*)\}"
|
| 216 |
match = re.search(pattern, s)
|
| 217 |
return match.group(1).split(",") if match else []
|
|
@@ -259,8 +288,8 @@ def multi_tarfile_samples(
|
|
| 259 |
|
| 260 |
Args:
|
| 261 |
src_iter: Iterator over shards that *already brace expanded the shard numbers*,
|
| 262 |
-
e.g. {
|
| 263 |
-
This function will also work when no square braces for multiple modalities are used, e.g. {
|
| 264 |
It can be a drop-in replacement for wds.tarfile_samples.
|
| 265 |
handler: Function that handles exceptions. If it returns True, the shard is skipped. If it returns False, the function exits.
|
| 266 |
|
|
@@ -335,14 +364,14 @@ class Transpose(albumentations.ImageOnlyTransform):
|
|
| 335 |
self.axis = axis
|
| 336 |
|
| 337 |
def apply(self, img, **params):
|
| 338 |
-
return
|
| 339 |
|
| 340 |
def get_transform_init_args_names(self):
|
| 341 |
return "transpose"
|
| 342 |
|
| 343 |
|
| 344 |
def default_non_image_transform(array):
|
| 345 |
-
if hasattr(array,
|
| 346 |
return torch.from_numpy(array)
|
| 347 |
else:
|
| 348 |
return array
|
|
@@ -361,7 +390,6 @@ class MultimodalTransforms:
|
|
| 361 |
def __init__(
|
| 362 |
self,
|
| 363 |
transforms: dict | albumentations.Compose,
|
| 364 |
-
shared: bool = True,
|
| 365 |
non_image_modalities: list[str] | None = None,
|
| 366 |
non_image_transforms: object | None = None,
|
| 367 |
):
|
|
@@ -379,14 +407,16 @@ class MultimodalTransforms:
|
|
| 379 |
self.non_image_transforms = non_image_transforms or default_non_image_transform
|
| 380 |
|
| 381 |
def __call__(self, data: dict):
|
| 382 |
-
# albumentations requires a key
|
| 383 |
-
image_modality =
|
| 384 |
-
|
|
|
|
| 385 |
data = self.transforms(**data)
|
| 386 |
-
data[image_modality] = data.pop(
|
| 387 |
|
| 388 |
-
# Process sequence data which is ignored by albumentations as
|
| 389 |
for modality in self.non_image_modalities:
|
| 390 |
-
|
|
|
|
| 391 |
|
| 392 |
return data
|
|
|
|
| 19 |
import os
|
| 20 |
import io
|
| 21 |
import re
|
|
|
|
|
|
|
| 22 |
import zarr
|
| 23 |
import fsspec
|
|
|
|
| 24 |
import braceexpand
|
| 25 |
import numpy as np
|
| 26 |
import albumentations
|
|
|
|
| 49 |
|
| 50 |
def build_terramesh_dataset(
|
| 51 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 52 |
+
modalities: list | str = None,
|
| 53 |
split: str = "val",
|
| 54 |
urls: str | None = None,
|
| 55 |
batch_size: int = 8,
|
| 56 |
+
return_metadata: bool = False,
|
| 57 |
*args, **kwargs,
|
| 58 |
):
|
| 59 |
if len(modalities) == 1:
|
|
|
|
| 64 |
split=split,
|
| 65 |
urls=urls,
|
| 66 |
batch_size=batch_size,
|
| 67 |
+
return_metadata=return_metadata,
|
| 68 |
*args, **kwargs
|
| 69 |
)
|
| 70 |
return dataset
|
|
|
|
| 77 |
split=split,
|
| 78 |
urls=urls,
|
| 79 |
batch_size=batch_size,
|
| 80 |
+
return_metadata=return_metadata,
|
| 81 |
*args, **kwargs,
|
| 82 |
)
|
| 83 |
return dataset
|
|
|
|
| 86 |
def zarr_decoder(key, value):
|
| 87 |
if key == "zarr.zip" or key.endswith(".zarr.zip"):
|
| 88 |
mapper = fsspec.filesystem("zip", fo=io.BytesIO(value), block_size=None).get_mapper("")
|
| 89 |
+
return zarr.open_consolidated(mapper, mode="r")["bands"][...]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def zarr_metadata_decoder(sample):
|
| 93 |
+
for key, value in list(sample.items()):
|
| 94 |
+
if key == "zarr.zip" or key.endswith(".zarr.zip"):
|
| 95 |
+
mapper = fsspec.filesystem("zip", fo=io.BytesIO(value), block_size=None).get_mapper("")
|
| 96 |
+
data = zarr.open_consolidated(mapper, mode="r")
|
| 97 |
+
sample[key] = data["bands"][...]
|
| 98 |
+
|
| 99 |
+
# Add metadata
|
| 100 |
+
if "center_lon" not in sample.keys(): # Same center point for all modalities
|
| 101 |
+
sample["center_lon"] = data["center_lon"][...]
|
| 102 |
+
sample["center_lat"] = data["center_lat"][...]
|
| 103 |
+
if "cloud_mask" in data and "cloud_mask" not in sample.keys(): # Same S2 mask in all optical modalities
|
| 104 |
+
sample["cloud_mask"] = data["cloud_mask"][...][np.newaxis, ...] # Add channel dim to mask
|
| 105 |
+
if data["time"][...] > 1e6: # DEM has no valid timestamp (value = 0)
|
| 106 |
+
time_key = "time" if key == "zarr.zip" else "time_" + key
|
| 107 |
+
sample[time_key] = data["time"][...] # Integer values of type "datetime64[ns]"
|
| 108 |
+
# TODO Other types are currently not decoded, fall back to autodecode
|
| 109 |
+
|
| 110 |
+
return sample
|
| 111 |
|
| 112 |
|
| 113 |
def identity(sample):
|
|
|
|
| 136 |
urls: str | None = None,
|
| 137 |
batch_size: int = 8,
|
| 138 |
transform: Callable = None,
|
| 139 |
+
return_metadata: bool = False,
|
| 140 |
*args, **kwargs
|
| 141 |
):
|
| 142 |
if urls is None:
|
|
|
|
| 156 |
kwargs["shardshuffle"] = kwargs.get("shardshuffle", 100) # Shuffle shard by default
|
| 157 |
|
| 158 |
# Build dataset
|
| 159 |
+
dataset = wds.WebDataset(urls, *args, **kwargs)
|
| 160 |
+
|
| 161 |
+
# Decode from bytes to numpy arrays, etc.
|
| 162 |
+
dataset = dataset.map(zarr_metadata_decoder) if return_metadata else dataset.decode(zarr_decoder)
|
| 163 |
+
|
| 164 |
+
# Rename modality to "image" and remove temporal dimension
|
| 165 |
+
dataset = (dataset
|
| 166 |
+
.rename(image="zarr.zip")
|
| 167 |
+
.map(drop_time_dim)
|
| 168 |
+
)
|
| 169 |
|
| 170 |
if transform is not None:
|
| 171 |
dataset = dataset.map(transform)
|
|
|
|
| 177 |
return dataset
|
| 178 |
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
def build_multimodal_dataset(
|
| 181 |
path: str = "https://huggingface.co/datasets/ibm-esa-geospatial/TerraMesh/resolve/main/",
|
| 182 |
+
modalities: list = None,
|
| 183 |
split: str = "val",
|
| 184 |
urls: str | None = None,
|
| 185 |
batch_size: int = 8,
|
| 186 |
transform: Callable = None,
|
| 187 |
+
return_metadata: bool = False,
|
| 188 |
*args, **kwargs
|
| 189 |
):
|
| 190 |
+
if modalities is None:
|
| 191 |
+
modalities = ["S2L2A", "S2L1C", "S2RGB", "S1GRD", "S1RTC", "DEM", "NDVI", "LULC"] # Default
|
| 192 |
if urls is None:
|
| 193 |
# Filter modalities based availability (S1GRD and S1RTC not present in all subsets)
|
| 194 |
def filter_list(lst, value):
|
|
|
|
| 205 |
urls = (os.path.join(path, split, majortom_mod, split_files["majortom"][split][0])
|
| 206 |
+ "::" + os.path.join(path, split, ssl4eos12_mod, split_files["ssl4eos12"][split][0]))
|
| 207 |
|
| 208 |
+
dataset = build_datapipeline(urls, transform, batch_size, return_metadata, *args, **kwargs)
|
| 209 |
return dataset
|
| 210 |
|
| 211 |
|
| 212 |
+
def build_datapipeline(urls, transform, batch_size, return_metadata, *args, **kwargs):
|
| 213 |
datapipeline = wds.DataPipeline(
|
| 214 |
# Infinitely sample shards from the shard list with replacement. Each worker is seeded independently.
|
| 215 |
wds.ResampledShards(urls),
|
| 216 |
multi_tarfile_samples, # Extract individual samples from multi-modal tar files
|
| 217 |
wds.shuffle(100), # Shuffle with a buffer of given size
|
| 218 |
+
(
|
| 219 |
+
wds.map(zarr_metadata_decoder)
|
| 220 |
+
if return_metadata
|
| 221 |
+
else wds.decode(zarr_decoder) # Decode from bytes to numpy arrays, etc.
|
| 222 |
+
),
|
| 223 |
wds.map(drop_time_dim), # Remove time dimension from tensors
|
| 224 |
wds.map(remove_extensions), # Remove "file extensions" from dictionary keys
|
| 225 |
( # Apply transformation
|
|
|
|
| 240 |
"""
|
| 241 |
Function from https://github.com/apple/ml-4m/blob/main/fourm/data/unified_datasets.py.
|
| 242 |
"""
|
| 243 |
+
# Regular expression pattern to match anything enclosed in "{" and "}", and comma separated
|
| 244 |
pattern = r"\{([^}]*)\}"
|
| 245 |
match = re.search(pattern, s)
|
| 246 |
return match.group(1).split(",") if match else []
|
|
|
|
| 288 |
|
| 289 |
Args:
|
| 290 |
src_iter: Iterator over shards that *already brace expanded the shard numbers*,
|
| 291 |
+
e.g. {"url": "shard_root_train_[rgb,caption]/00000.tar"}, {"url": "shard_root_train_[rgb,caption]/00001.tar"}, ...
|
| 292 |
+
This function will also work when no square braces for multiple modalities are used, e.g. {"url": "shard_root_train/00000.tar"}, ...
|
| 293 |
It can be a drop-in replacement for wds.tarfile_samples.
|
| 294 |
handler: Function that handles exceptions. If it returns True, the shard is skipped. If it returns False, the function exits.
|
| 295 |
|
|
|
|
| 364 |
self.axis = axis
|
| 365 |
|
| 366 |
def apply(self, img, **params):
|
| 367 |
+
return np.transpose(img, self.axis)
|
| 368 |
|
| 369 |
def get_transform_init_args_names(self):
|
| 370 |
return "transpose"
|
| 371 |
|
| 372 |
|
| 373 |
def default_non_image_transform(array):
|
| 374 |
+
if hasattr(array, "dtype") and (array.dtype == float or array.dtype == int):
|
| 375 |
return torch.from_numpy(array)
|
| 376 |
else:
|
| 377 |
return array
|
|
|
|
| 390 |
def __init__(
|
| 391 |
self,
|
| 392 |
transforms: dict | albumentations.Compose,
|
|
|
|
| 393 |
non_image_modalities: list[str] | None = None,
|
| 394 |
non_image_transforms: object | None = None,
|
| 395 |
):
|
|
|
|
| 407 |
self.non_image_transforms = non_image_transforms or default_non_image_transform
|
| 408 |
|
| 409 |
def __call__(self, data: dict):
|
| 410 |
+
# albumentations requires a key "image" and treats all other keys as additional targets
|
| 411 |
+
image_modality = "image" if "image" in data else \
|
| 412 |
+
[k for k in data.keys() if k not in self.non_image_modalities][0] # Find an image modality name
|
| 413 |
+
data["image"] = data.pop(image_modality) # albumentations expects an input called "image"
|
| 414 |
data = self.transforms(**data)
|
| 415 |
+
data[image_modality] = data.pop("image")
|
| 416 |
|
| 417 |
+
# Process sequence data which is ignored by albumentations as "global_label"
|
| 418 |
for modality in self.non_image_modalities:
|
| 419 |
+
if modality in data:
|
| 420 |
+
data[modality] = self.non_image_transforms(data[modality])
|
| 421 |
|
| 422 |
return data
|