Datasets:

Modalities:
Geospatial
Languages:
English
DOI:
Libraries:
License:
cmalbrec commited on
Commit
7dcdc23
·
verified ·
1 Parent(s): 51ace40

updated and improved version of the dataset loader

Browse files
Files changed (1) hide show
  1. dataset.py +139 -79
dataset.py CHANGED
@@ -1,25 +1,47 @@
1
 
2
  import os
 
3
  import datasets
4
  import rasterio
5
- import tqdm
6
- import datetime
7
 
8
  class SSL4EOEUForest(datasets.GeneratorBasedBuilder):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  def _info(self):
10
  return datasets.DatasetInfo(
11
- description="SSL4EO-EU Forest dataset with four-season Sentinel-2 timestamps and bounding box metadata extracted from image folders.",
12
  features=datasets.Features({
13
  "image_paths": datasets.Sequence(datasets.Value("string")),
14
  "mask_path": datasets.Value("string"),
15
  "start_timestamps": datasets.Sequence(datasets.Value("timestamp[ms]")),
16
  "end_timestamps": datasets.Sequence(datasets.Value("timestamp[ms]")),
17
  "sentinel_tile_ids": datasets.Sequence(datasets.Value("string")),
18
- "bboxes": datasets.Sequence({
19
- "minx": datasets.Value("float32"),
20
- "maxx": datasets.Value("float32"),
21
- "miny": datasets.Value("float32"),
22
- "maxy": datasets.Value("float32"),
23
  })
24
  }),
25
  citation="""@misc{ssl4eo_eu_forest,
@@ -27,90 +49,128 @@ class SSL4EOEUForest(datasets.GeneratorBasedBuilder):
27
  title = {SSL4EO-EU Forest Dataset},
28
  year = {2025},
29
  howpublished = {https://huggingface.co/datasets/dm4eo/ssl4eo-eu-forest},
30
- note = {This work was carried under the EvoLand project, cf. https://www.evo-land.eu . This project has received funding from the European Union's Horizon Europe research and innovation programme under grant agreement No. 101082130.}
31
  }""",
32
  homepage="https://www.evo-land.eu",
33
  license="CC-BY-4.0",
34
  )
35
 
36
  def _split_generators(self, dl_manager):
 
37
  use_local = os.environ.get("HF_DATASET_LOCAL", "false").lower() == "true"
 
38
 
39
- if use_local:
40
- root = os.path.abspath(".")
 
41
  else:
42
- root = dl_manager.download_and_extract(".")
43
-
44
- images_dir = os.path.join(root, "images")
45
- masks_dir = os.path.join(root, "masks")
46
-
47
- return [
48
- datasets.SplitGenerator(name=datasets.Split("all"), gen_kwargs={
49
  "images_dir": images_dir,
50
  "masks_dir": masks_dir
51
- })
52
- ]
53
-
54
- def _generate_examples(self, images_dir, masks_dir):
55
- sample_id_list = sorted(os.listdir(images_dir))
56
- key = 0
57
-
58
- for sample_id in sample_id_list:
59
- sample_path = os.path.join(images_dir, sample_id)
60
- if not os.path.isdir(sample_path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  continue
62
 
63
- timestamp_dirs = sorted(os.listdir(sample_path))
64
- mask_path = os.path.join(masks_dir, sample_id, "mask.tif")
65
- if not os.path.exists(mask_path):
66
  continue
67
 
68
- image_paths = []
69
- start_timestamps = []
70
- end_timestamps = []
71
- tile_ids = []
72
- bboxes = []
73
-
74
- for ts in timestamp_dirs:
75
- parts = ts.split("_")
76
- if len(parts) != 3:
77
- continue
78
-
79
- try:
80
- start_ts = datetime.datetime.strptime(parts[0], "%Y%m%dT%H%M%S")
81
- end_ts = datetime.datetime.strptime(parts[1], "%Y%m%dT%H%M%S")
82
- except ValueError:
83
- continue
84
-
85
- tile_id = parts[2]
86
- image_path = os.path.join(sample_path, ts, "all_bands.tif")
87
- if not os.path.exists(image_path):
88
- continue
89
-
90
- try:
91
- with rasterio.open(image_path) as src:
92
- bounds = src.bounds
93
- except Exception:
94
- continue
95
-
96
- image_paths.append(image_path)
97
- start_timestamps.append(start_ts)
98
- end_timestamps.append(end_ts)
99
- tile_ids.append(tile_id)
100
- bboxes.append({
101
- "minx": bounds.left,
102
- "maxx": bounds.right,
103
- "miny": bounds.bottom,
104
- "maxy": bounds.top
105
- })
106
 
107
- if image_paths:
108
- yield key, {
109
- "image_paths": image_paths,
110
- "mask_path": mask_path,
111
- "start_timestamps": start_timestamps,
112
- "end_timestamps": end_timestamps,
113
- "sentinel_tile_ids": tile_ids,
114
- "bboxes": bboxes
115
- }
116
- key += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
  import os
3
+ import json
4
  import datasets
5
  import rasterio
6
+ from datetime import datetime
7
+ from tqdm import tqdm
8
 
9
  class SSL4EOEUForest(datasets.GeneratorBasedBuilder):
10
+ """
11
+ SSL4EO-EU Forest Dataset Loader
12
+
13
+ This loader supports both directory-based scanning and prebuilt index streaming via JSONL.
14
+ It yields one sample at a time, making it compatible with Hugging Face's streaming mode.
15
+
16
+ Each sample includes:
17
+ - A list of image paths (one per timestamp)
18
+ - A single mask path
19
+ - Start and end timestamps for each image
20
+ - Sentinel tile IDs
21
+ - Bounding box metadata
22
+
23
+ Bounding boxes are stored as a dictionary of arrays:
24
+ {
25
+ "minx": [...], "maxx": [...], "miny": [...], "maxy": [...]
26
+ }
27
+
28
+ This avoids redundancy and simplifies downstream parsing.
29
+ """
30
+
31
  def _info(self):
32
  return datasets.DatasetInfo(
33
+ description="SSL4EO-EU Forest dataset with grouped timestamps and bounding box metadata.",
34
  features=datasets.Features({
35
  "image_paths": datasets.Sequence(datasets.Value("string")),
36
  "mask_path": datasets.Value("string"),
37
  "start_timestamps": datasets.Sequence(datasets.Value("timestamp[ms]")),
38
  "end_timestamps": datasets.Sequence(datasets.Value("timestamp[ms]")),
39
  "sentinel_tile_ids": datasets.Sequence(datasets.Value("string")),
40
+ "bboxes": datasets.Features({
41
+ "minx": datasets.Sequence(datasets.Value("float32")),
42
+ "maxx": datasets.Sequence(datasets.Value("float32")),
43
+ "miny": datasets.Sequence(datasets.Value("float32")),
44
+ "maxy": datasets.Sequence(datasets.Value("float32")),
45
  })
46
  }),
47
  citation="""@misc{ssl4eo_eu_forest,
 
49
  title = {SSL4EO-EU Forest Dataset},
50
  year = {2025},
51
  howpublished = {https://huggingface.co/datasets/dm4eo/ssl4eo-eu-forest},
52
+ note = {Funded by the EvoLand project under EU Horizon Europe grant No. 101082130.}
53
  }""",
54
  homepage="https://www.evo-land.eu",
55
  license="CC-BY-4.0",
56
  )
57
 
58
  def _split_generators(self, dl_manager):
59
+ use_index = os.environ.get("HF_DATASET_USE_INDEX", "false").lower() == "true"
60
  use_local = os.environ.get("HF_DATASET_LOCAL", "false").lower() == "true"
61
+ root = os.path.abspath(".") if use_local else dl_manager.download_and_extract(".")
62
 
63
+ if use_index:
64
+ index_path = os.path.join(root, "index.jsonl")
65
+ return [datasets.SplitGenerator(name="all", gen_kwargs={"index_path": index_path})]
66
  else:
67
+ images_dir = os.path.join(root, "images")
68
+ masks_dir = os.path.join(root, "masks")
69
+ return [datasets.SplitGenerator(name="all", gen_kwargs={
 
 
 
 
70
  "images_dir": images_dir,
71
  "masks_dir": masks_dir
72
+ })]
73
+
74
+ def _generate_examples(self, index_path=None, images_dir=None, masks_dir=None):
75
+ if index_path:
76
+ with open(index_path, "r") as f:
77
+ for key, line in enumerate(f):
78
+ entry = json.loads(line)
79
+ entry["start_timestamps"] = [datetime.fromisoformat(ts) for ts in entry["start_timestamps"]]
80
+ entry["end_timestamps"] = [datetime.fromisoformat(ts) for ts in entry["end_timestamps"]]
81
+ yield key, entry
82
+ else:
83
+ sample_ids = sorted(os.listdir(images_dir))
84
+ key = 0
85
+ for sample_id in sample_ids:
86
+ sample = self._parse_sample(sample_id, images_dir, masks_dir)
87
+ if sample:
88
+ yield key, sample
89
+ key += 1
90
+
91
+ @staticmethod
92
+ def _parse_sample(sample_id, images_dir, masks_dir):
93
+ """
94
+ Parses a single sample directory and returns a dictionary with all metadata.
95
+
96
+ Returns None if the sample is incomplete or malformed.
97
+ """
98
+ sample_path = os.path.join(images_dir, sample_id)
99
+ if not os.path.isdir(sample_path):
100
+ return None
101
+
102
+ mask_path = os.path.join(masks_dir, sample_id, "mask.tif")
103
+ if not os.path.exists(mask_path):
104
+ return None
105
+
106
+ image_paths, start_ts, end_ts, tile_ids = [], [], [], []
107
+ minx_list, maxx_list, miny_list, maxy_list = [], [], [], []
108
+
109
+ for ts in sorted(os.listdir(sample_path)):
110
+ parts = ts.split("_")
111
+ if len(parts) != 3:
112
+ continue
113
+ try:
114
+ start = datetime.strptime(parts[0], "%Y%m%dT%H%M%S")
115
+ end = datetime.strptime(parts[1], "%Y%m%dT%H%M%S")
116
+ except ValueError:
117
  continue
118
 
119
+ tile_id = parts[2]
120
+ image_path = os.path.join(sample_path, ts, "all_bands.tif")
121
+ if not os.path.exists(image_path):
122
  continue
123
 
124
+ try:
125
+ with rasterio.open(image_path) as src:
126
+ bounds = src.bounds
127
+ except Exception:
128
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
+ image_paths.append(image_path)
131
+ start_ts.append(start)
132
+ end_ts.append(end)
133
+ tile_ids.append(tile_id)
134
+ minx_list.append(bounds.left)
135
+ maxx_list.append(bounds.right)
136
+ miny_list.append(bounds.bottom)
137
+ maxy_list.append(bounds.top)
138
+
139
+ if not image_paths:
140
+ return None
141
+
142
+ return {
143
+ "image_paths": image_paths,
144
+ "mask_path": mask_path,
145
+ "start_timestamps": start_ts,
146
+ "end_timestamps": end_ts,
147
+ "sentinel_tile_ids": tile_ids,
148
+ "bboxes": {
149
+ "minx": minx_list,
150
+ "maxx": maxx_list,
151
+ "miny": miny_list,
152
+ "maxy": maxy_list
153
+ }
154
+ }
155
+
156
+ @classmethod
157
+ def generate_index(cls, dataset_dir, output_path="index.jsonl"):
158
+ """
159
+ Scans the dataset directory and writes a streaming-friendly index.jsonl file.
160
+
161
+ Each line is a complete sample in JSON format.
162
+ """
163
+ images_dir = os.path.join(dataset_dir, "images")
164
+ masks_dir = os.path.join(dataset_dir, "masks")
165
+ sample_ids = sorted(os.listdir(images_dir))
166
+
167
+ with open(output_path, "w") as f:
168
+ for sample_id in tqdm(sample_ids, desc="Generating index", unit="sample"):
169
+ sample = cls._parse_sample(sample_id, images_dir, masks_dir)
170
+ if sample:
171
+ sample["start_timestamps"] = [ts.isoformat() for ts in sample["start_timestamps"]]
172
+ sample["end_timestamps"] = [ts.isoformat() for ts in sample["end_timestamps"]]
173
+ sample["sample_id"] = sample_id
174
+ f.write(json.dumps(sample) + "\n")
175
+
176
+ print(f"✅ Index written to {output_path}")