taco-eo 0.7.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. taco/__init__.py +45 -0
  2. taco/_graph.py +129 -0
  3. taco/_lib/taco.dll +0 -0
  4. taco/_repr.py +305 -0
  5. taco/container/__init__.py +5 -0
  6. taco/container/cozip.py +9 -0
  7. taco/container/parquet.py +15 -0
  8. taco/container/publish.py +97 -0
  9. taco/container/view.py +148 -0
  10. taco/contract/__init__.py +23 -0
  11. taco/contract/collection.py +410 -0
  12. taco/contract/contract.py +746 -0
  13. taco/contract/naming.py +215 -0
  14. taco/contract/sample.py +151 -0
  15. taco/contract/schema.py +319 -0
  16. taco/contract/structure.py +130 -0
  17. taco/contract/types.py +279 -0
  18. taco/errors.py +37 -0
  19. taco/extensions/__init__.py +7 -0
  20. taco/extensions/rumi.py +143 -0
  21. taco/extensions/spatiotemporal.py +316 -0
  22. taco/metadata/__init__.py +3 -0
  23. taco/metadata/_base.py +117 -0
  24. taco/metadata/asset.py +44 -0
  25. taco/metadata/collection.py +70 -0
  26. taco/metadata/data/admin/admin0.parquet +0 -0
  27. taco/metadata/data/admin/admin1.parquet +0 -0
  28. taco/metadata/data/admin/admin2.parquet +0 -0
  29. taco/metadata/derived.py +354 -0
  30. taco/metadata/folder.py +30 -0
  31. taco/metadata/sample.py +5 -0
  32. taco/metadata/spatiotemporal.py +280 -0
  33. taco/metadata/split.py +12 -0
  34. taco/py.typed +0 -0
  35. taco/reader/__init__.py +10 -0
  36. taco/reader/api.py +49 -0
  37. taco/reader/collection.py +47 -0
  38. taco/reader/dataset.py +40 -0
  39. taco/reader/engine.py +40 -0
  40. taco/reader/inspect.py +77 -0
  41. taco/reader/manifest.py +59 -0
  42. taco/reader/native.py +230 -0
  43. taco/reader/query.py +76 -0
  44. taco/reader/source.py +38 -0
  45. taco/validate.py +520 -0
  46. taco/writer/__init__.py +6 -0
  47. taco/writer/api.py +73 -0
  48. taco/writer/archive.py +199 -0
  49. taco/writer/base.py +189 -0
  50. taco/writer/catalog.py +157 -0
  51. taco/writer/export.py +161 -0
  52. taco/writer/folder.py +211 -0
  53. taco/writer/metadata.py +275 -0
  54. taco/writer/partition.py +178 -0
  55. taco/writer/progress.py +46 -0
  56. taco/writer/staging.py +44 -0
  57. taco_eo-0.7.0.dist-info/METADATA +122 -0
  58. taco_eo-0.7.0.dist-info/RECORD +60 -0
  59. taco_eo-0.7.0.dist-info/WHEEL +4 -0
  60. taco_eo-0.7.0.dist-info/licenses/LICENSE +21 -0
taco/container/view.py ADDED
@@ -0,0 +1,148 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import zipfile
6
+ from collections.abc import Iterator
7
+ from dataclasses import dataclass
8
+ from os import PathLike
9
+ from pathlib import Path
10
+ from typing import Any, Literal
11
+
12
+ import pyarrow as pa
13
+ import pyarrow.parquet as pq
14
+
15
+ from ..contract.collection import Collection
16
+ from ..contract.contract import SAMPLE_LEVEL, Contract
17
+ from ..contract.naming import (
18
+ COLLECTION_FILENAME,
19
+ DATA_DIR,
20
+ METADATA_DIR,
21
+ OFFSET,
22
+ RELATIVE_PATH,
23
+ SIZE,
24
+ SOURCE_FILE,
25
+ level_folder,
26
+ )
27
+ from ..errors import CollectionError, ContainerError, ContractError
28
+
29
+ Container = Literal["zip", "folder", "tacocat"]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class DataRow:
34
+ """One data file as the metadata layer describes it."""
35
+
36
+ level: str
37
+ row: int
38
+ relative_path: str
39
+ offset: int | None
40
+ size: int | None
41
+ source_file: str | None = None
42
+
43
+ @property
44
+ def archive_name(self) -> str:
45
+ return f"{DATA_DIR}/{self.relative_path}"
46
+
47
+
48
+ @dataclass
49
+ class DatasetView:
50
+ path: Path
51
+ container: Container
52
+ collection: Collection
53
+ collection_json: dict[str, Any]
54
+ tables: dict[str, pa.Table]
55
+
56
+ @property
57
+ def contract(self) -> Contract:
58
+ return self.collection.contract
59
+
60
+ @property
61
+ def levels(self) -> tuple[str, ...]:
62
+ return self.contract.levels
63
+
64
+ @property
65
+ def sample_count(self) -> int:
66
+ return int(self.tables[SAMPLE_LEVEL].num_rows)
67
+
68
+ def level(self, name: str) -> pa.Table:
69
+ try:
70
+ return self.tables[name]
71
+ except KeyError as exc:
72
+ raise KeyError(f"level {name!r} is not part of this dataset; levels: {list(self.tables)}") from exc
73
+
74
+ def is_leaf_level_row(self, level: str, relative_path: str) -> bool:
75
+ if self.contract.is_null:
76
+ return level == SAMPLE_LEVEL
77
+ if level == SAMPLE_LEVEL:
78
+ return False
79
+ return not self.contract.is_folder(level_folder(level), relative_path.rsplit("/", 1)[-1])
80
+
81
+ def iter_data_rows(self) -> Iterator[DataRow]:
82
+ for level in self.levels:
83
+ table = self.tables.get(level)
84
+ if table is None or self.contract.is_null != (level == SAMPLE_LEVEL):
85
+ continue
86
+ columns = [RELATIVE_PATH]
87
+ columns += [name for name in (OFFSET, SIZE, SOURCE_FILE) if name in table.column_names]
88
+ start = 0
89
+ for batch in table.select(columns).to_batches():
90
+ for position, record in enumerate(batch.to_pylist()):
91
+ relative_path = record[RELATIVE_PATH]
92
+ if not isinstance(relative_path, str):
93
+ continue
94
+ if self.is_leaf_level_row(level, relative_path):
95
+ yield DataRow(
96
+ level=level,
97
+ row=start + position,
98
+ relative_path=relative_path,
99
+ offset=record.get(OFFSET),
100
+ size=record.get(SIZE),
101
+ source_file=record.get(SOURCE_FILE),
102
+ )
103
+ start += batch.num_rows
104
+
105
+
106
+ def detect_container(path: Path) -> Container:
107
+ if path.is_file():
108
+ return "zip"
109
+ if path.is_dir():
110
+ if not (path / COLLECTION_FILENAME).is_file():
111
+ raise ContainerError(f"{path} has no {COLLECTION_FILENAME}")
112
+ if (path / METADATA_DIR).is_dir():
113
+ return "folder"
114
+ if any(path.glob("*.parquet")):
115
+ return "tacocat"
116
+ raise ContainerError(f"{path} has neither {METADATA_DIR}/ (FOLDER) nor *.parquet (TACOCAT)")
117
+ raise ContainerError(f"dataset not found: {path}")
118
+
119
+
120
+ def open_view(path: str | PathLike[str]) -> DatasetView:
121
+ location = Path(path).expanduser().resolve()
122
+ container = detect_container(location)
123
+ try:
124
+ if container == "zip":
125
+ with zipfile.ZipFile(location) as archive:
126
+ data = json.loads(archive.read(COLLECTION_FILENAME))
127
+ else:
128
+ data = json.loads((location / COLLECTION_FILENAME).read_bytes())
129
+ collection = Collection.from_dict(data)
130
+ except (CollectionError, ContractError) as exc:
131
+ raise ContainerError(f"invalid {COLLECTION_FILENAME} in {location}: {exc}") from exc
132
+ except Exception as exc:
133
+ raise ContainerError(f"could not read {COLLECTION_FILENAME} from {location}: {exc}") from exc
134
+
135
+ tables: dict[str, pa.Table] = {}
136
+ for level in collection.contract.levels:
137
+ try:
138
+ filename = level.replace("/", "__") + ".parquet"
139
+ if container == "zip":
140
+ with zipfile.ZipFile(location) as archive:
141
+ tables[level] = pq.read_table(io.BytesIO(archive.read(f"{METADATA_DIR}/{filename}")))
142
+ elif container == "folder":
143
+ tables[level] = pq.read_table(location / METADATA_DIR / filename)
144
+ else:
145
+ tables[level] = pq.read_table(location / filename)
146
+ except Exception as exc:
147
+ raise ContainerError(f"could not read level {level!r} from {location}: {exc}") from exc
148
+ return DatasetView(location, container, collection, data, tables)
@@ -0,0 +1,23 @@
1
+ from .collection import KNOWN_TASKS, Collection, Curator, Extent, Provider
2
+ from .contract import CHILDREN_LEVEL, SAMPLE_LEVEL, Contract, Leaf, Node
3
+ from .sample import Asset, Folder, Sample
4
+ from .types import coerce_value, parse_type, type_name
5
+
6
+ __all__ = [
7
+ "CHILDREN_LEVEL",
8
+ "KNOWN_TASKS",
9
+ "SAMPLE_LEVEL",
10
+ "Asset",
11
+ "Collection",
12
+ "Contract",
13
+ "Curator",
14
+ "Extent",
15
+ "Folder",
16
+ "Leaf",
17
+ "Node",
18
+ "Provider",
19
+ "Sample",
20
+ "coerce_value",
21
+ "parse_type",
22
+ "type_name",
23
+ ]
@@ -0,0 +1,410 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass, replace
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+
11
+ from ..errors import CollectionError
12
+ from .contract import Contract
13
+ from .schema import CollectionMetadata
14
+
15
+ TACO_VERSION = "3.0.0"
16
+ SEMVER = re.compile(
17
+ r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)"
18
+ r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
19
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
20
+ )
21
+
22
+ KNOWN_TASKS = frozenset(
23
+ {
24
+ "regression",
25
+ "classification",
26
+ "scene-classification",
27
+ "detection",
28
+ "object-detection",
29
+ "segmentation",
30
+ "semantic-segmentation",
31
+ "instance-segmentation",
32
+ "panoptic-segmentation",
33
+ "change-detection",
34
+ "similarity-search",
35
+ "generative",
36
+ "image-captioning",
37
+ "super-resolution",
38
+ "denoising",
39
+ "inpainting",
40
+ "colorization",
41
+ "style-transfer",
42
+ "deblurring",
43
+ "dehazing",
44
+ "foundation-model",
45
+ "other",
46
+ }
47
+ )
48
+
49
+ _CORE_KEYS = frozenset(
50
+ {
51
+ "taco:version",
52
+ "id",
53
+ "dataset_version",
54
+ "description",
55
+ "licenses",
56
+ "providers",
57
+ "tasks",
58
+ "title",
59
+ "curators",
60
+ "keywords",
61
+ "extent",
62
+ "taco:structure",
63
+ "taco:metadata",
64
+ "taco:derived",
65
+ "taco:sources",
66
+ }
67
+ )
68
+
69
+
70
+ def _string_list(values: object, *, name: str, required: bool) -> tuple[str, ...]:
71
+ if values is None:
72
+ if required:
73
+ raise CollectionError(f"{name} is required")
74
+ return ()
75
+ if isinstance(values, str) or not isinstance(values, Sequence):
76
+ raise CollectionError(f"{name} must be a list of strings")
77
+ result = tuple(values)
78
+ if required and not result:
79
+ raise CollectionError(f"{name} must not be empty")
80
+ if not all(isinstance(item, str) and item.strip() for item in result):
81
+ raise CollectionError(f"{name} must contain non-empty strings")
82
+ return result
83
+
84
+
85
+ def _parse_iso(value: object, *, name: str) -> datetime:
86
+ if isinstance(value, datetime):
87
+ parsed = value
88
+ elif isinstance(value, str):
89
+ text = value.strip().removesuffix("Z") + ("+00:00" if value.strip().endswith("Z") else "")
90
+ try:
91
+ parsed = datetime.fromisoformat(text)
92
+ except ValueError as exc:
93
+ raise CollectionError(f"{name} must be an ISO 8601 datetime") from exc
94
+ else:
95
+ raise CollectionError(f"{name} must be an ISO 8601 datetime")
96
+ if parsed.tzinfo is None:
97
+ parsed = parsed.replace(tzinfo=timezone.utc)
98
+ return parsed.astimezone(timezone.utc)
99
+
100
+
101
+ def format_iso(value: datetime) -> str:
102
+ return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Provider:
107
+ name: str
108
+ roles: tuple[str, ...] | None = None
109
+ url: str | None = None
110
+ links: tuple[dict[str, Any], ...] | None = None
111
+
112
+ def __post_init__(self) -> None:
113
+ if not isinstance(self.name, str) or not self.name.strip():
114
+ raise CollectionError("provider name is required")
115
+ if self.roles is not None:
116
+ object.__setattr__(self, "roles", _string_list(self.roles, name="provider roles", required=False))
117
+ if self.url is not None and not self.url.startswith(("http://", "https://")):
118
+ raise CollectionError("provider url must start with http:// or https://")
119
+ if self.links is not None:
120
+ if isinstance(self.links, (str, bytes)) or not isinstance(self.links, Sequence):
121
+ raise CollectionError("provider links must be a list of objects")
122
+ links = tuple(dict(link) for link in self.links if isinstance(link, Mapping))
123
+ if len(links) != len(self.links):
124
+ raise CollectionError("provider links must be a list of objects")
125
+ object.__setattr__(self, "links", links)
126
+
127
+ @classmethod
128
+ def from_any(cls, value: object) -> Provider:
129
+ if isinstance(value, cls):
130
+ return value
131
+ if isinstance(value, str):
132
+ return cls(value)
133
+ if isinstance(value, Mapping):
134
+ fields = {"name", "roles", "url", "links"}
135
+ extra = sorted(set(value) - fields)
136
+ if extra:
137
+ raise CollectionError(f"provider has unknown fields {extra}")
138
+ if "name" not in value:
139
+ raise CollectionError("provider name is required")
140
+ return cls(**{key: value[key] for key in fields if key in value})
141
+ raise CollectionError(f"invalid provider {value!r}")
142
+
143
+ def to_dict(self) -> dict[str, Any]:
144
+ data: dict[str, Any] = {"name": self.name}
145
+ for name in ("roles", "url", "links"):
146
+ value = getattr(self, name)
147
+ if value is not None:
148
+ data[name] = list(value) if isinstance(value, tuple) else value
149
+ return data
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class Curator:
154
+ name: str | None = None
155
+ organization: str | None = None
156
+ email: str | None = None
157
+ role: str | None = None
158
+
159
+ def __post_init__(self) -> None:
160
+ if not self.name and not self.organization:
161
+ raise CollectionError("a curator needs a name or an organization")
162
+ if self.email is not None and "@" not in self.email:
163
+ raise CollectionError("invalid curator email")
164
+
165
+ @classmethod
166
+ def from_any(cls, value: object) -> Curator:
167
+ if isinstance(value, cls):
168
+ return value
169
+ if isinstance(value, str):
170
+ return cls(name=value)
171
+ if isinstance(value, Mapping):
172
+ fields = {"name", "organization", "email", "role"}
173
+ extra = sorted(set(value) - fields)
174
+ if extra:
175
+ raise CollectionError(f"curator has unknown fields {extra}")
176
+ return cls(**{key: value[key] for key in fields if key in value})
177
+ raise CollectionError(f"invalid curator {value!r}")
178
+
179
+ def to_dict(self) -> dict[str, Any]:
180
+ return {name: value for name, value in vars(self).items() if value is not None}
181
+
182
+
183
+ @dataclass(frozen=True)
184
+ class Extent:
185
+ spatial: tuple[float, float, float, float]
186
+ temporal: tuple[str, str] | None = None
187
+
188
+ def __post_init__(self) -> None:
189
+ if isinstance(self.spatial, str) or not isinstance(self.spatial, Sequence) or len(self.spatial) != 4:
190
+ raise CollectionError("extent.spatial must be [west, south, east, north]")
191
+ try:
192
+ west, south, east, north = (float(value) for value in self.spatial)
193
+ except (TypeError, ValueError) as exc:
194
+ raise CollectionError("extent.spatial must contain numbers") from exc
195
+ if not all(math.isfinite(value) for value in (west, south, east, north)):
196
+ raise CollectionError("extent.spatial values must be finite")
197
+ if not (-180 <= west <= 180 and -180 <= east <= 180 and -90 <= south <= north <= 90):
198
+ raise CollectionError("extent.spatial is outside EPSG:4326 bounds")
199
+ object.__setattr__(self, "spatial", (west, south, east, north))
200
+ if self.temporal is not None:
201
+ if isinstance(self.temporal, str) or len(self.temporal) != 2:
202
+ raise CollectionError("extent.temporal must be [start, end]")
203
+ start = _parse_iso(self.temporal[0], name="extent.temporal[0]")
204
+ end = _parse_iso(self.temporal[1], name="extent.temporal[1]")
205
+ if start > end:
206
+ raise CollectionError("extent.temporal start must not exceed end")
207
+ object.__setattr__(self, "temporal", (format_iso(start), format_iso(end)))
208
+
209
+ @classmethod
210
+ def from_any(cls, value: object) -> Extent:
211
+ if isinstance(value, cls):
212
+ return value
213
+ if isinstance(value, Mapping) and "spatial" in value and not set(value) - {"spatial", "temporal"}:
214
+ return cls(value["spatial"], value.get("temporal"))
215
+ raise CollectionError("invalid extent")
216
+
217
+ def to_dict(self) -> dict[str, Any]:
218
+ return {"spatial": list(self.spatial), "temporal": None if self.temporal is None else list(self.temporal)}
219
+
220
+ @property
221
+ def crosses_antimeridian(self) -> bool:
222
+ return self.spatial[0] > self.spatial[2]
223
+
224
+ @staticmethod
225
+ def union(extents: Sequence[Extent]) -> Extent | None:
226
+ if not extents:
227
+ return None
228
+ south = min(item.spatial[1] for item in extents)
229
+ north = max(item.spatial[3] for item in extents)
230
+ intervals: list[tuple[float, float]] = []
231
+ for item in extents:
232
+ west, _, east, _ = item.spatial
233
+ start, end = west + 180, east + 180
234
+ if west <= east:
235
+ intervals.append((start, end))
236
+ else:
237
+ intervals.extend(((0, end), (start, 360)))
238
+ merged: list[list[float]] = []
239
+ for start, end in sorted(intervals):
240
+ if merged and start <= merged[-1][1]:
241
+ merged[-1][1] = max(merged[-1][1], end)
242
+ else:
243
+ merged.append([start, end])
244
+ gaps = [(merged[index][1], merged[index + 1][0]) for index in range(len(merged) - 1)]
245
+ gaps.append((merged[-1][1], merged[0][0] + 360))
246
+ gap_start, gap_end = max(gaps, key=lambda gap: gap[1] - gap[0])
247
+ if gap_start == gap_end:
248
+ west, east = -180.0, 180.0
249
+ else:
250
+ start = gap_end % 360
251
+ end = gap_start % 360
252
+ if math.isclose(start, end, abs_tol=1e-12):
253
+ start = end
254
+ west = start - 180
255
+ east = 180.0 if end == 0 and start > 0 else end - 180
256
+ temporal_values = [item.temporal for item in extents if item.temporal is not None]
257
+ temporal = None
258
+ if temporal_values:
259
+ starts = [_parse_iso(value[0], name="temporal") for value in temporal_values]
260
+ ends = [_parse_iso(value[1], name="temporal") for value in temporal_values]
261
+ temporal = (format_iso(min(starts)), format_iso(max(ends)))
262
+ return Extent((west, south, east, north), temporal)
263
+
264
+
265
+ @dataclass(frozen=True)
266
+ class Collection:
267
+ contract: Contract
268
+ id: str
269
+ dataset_version: str
270
+ description: str
271
+ licenses: tuple[str, ...]
272
+ providers: tuple[Provider, ...]
273
+ tasks: tuple[str, ...]
274
+ metadata: CollectionMetadata | None = None
275
+ title: str | None = None
276
+ curators: tuple[Curator, ...] | None = None
277
+ keywords: tuple[str, ...] | None = None
278
+ extent: Extent | None = None
279
+ sources: dict[str, Any] | None = None
280
+
281
+ def __post_init__(self) -> None:
282
+ if not isinstance(self.contract, Contract):
283
+ raise CollectionError("contract must be a Contract")
284
+ if not isinstance(self.id, str) or not self.id.strip() or any(char in self.id for char in "/\\:\x00"):
285
+ raise CollectionError("collection id is invalid")
286
+ if not isinstance(self.dataset_version, str) or not SEMVER.fullmatch(self.dataset_version):
287
+ raise CollectionError("dataset_version must follow Semantic Versioning")
288
+ if not isinstance(self.description, str) or not self.description.strip():
289
+ raise CollectionError("collection description is required")
290
+ object.__setattr__(self, "licenses", _string_list(self.licenses, name="licenses", required=True))
291
+ object.__setattr__(self, "tasks", _string_list(self.tasks, name="tasks", required=True))
292
+ if isinstance(self.providers, (str, Mapping, Provider)) or not isinstance(self.providers, Sequence):
293
+ raise CollectionError("providers must be a list")
294
+ if not self.providers:
295
+ raise CollectionError("providers must not be empty")
296
+ object.__setattr__(self, "providers", tuple(Provider.from_any(value) for value in self.providers))
297
+ if self.metadata is not None and not isinstance(self.metadata, CollectionMetadata):
298
+ raise CollectionError("metadata must be taco.CollectionMetadata")
299
+ if self.metadata is not None:
300
+ try:
301
+ json.dumps(self.metadata.flatten(), allow_nan=False)
302
+ except (TypeError, ValueError) as exc:
303
+ raise CollectionError("collection metadata must be JSON serializable") from exc
304
+ if self.curators is not None:
305
+ object.__setattr__(self, "curators", tuple(Curator.from_any(value) for value in self.curators))
306
+ if self.keywords is not None:
307
+ object.__setattr__(self, "keywords", _string_list(self.keywords, name="keywords", required=False))
308
+ if self.extent is not None:
309
+ object.__setattr__(self, "extent", Extent.from_any(self.extent))
310
+ if self.sources is not None:
311
+ try:
312
+ json.dumps(self.sources, allow_nan=False)
313
+ except (TypeError, ValueError) as exc:
314
+ raise CollectionError("taco:sources must be JSON serializable") from exc
315
+
316
+ def replace(self, **changes: Any) -> Collection:
317
+ return replace(self, **changes)
318
+
319
+ def to_dict(self) -> dict[str, Any]:
320
+ data: dict[str, Any] = {
321
+ "taco:version": TACO_VERSION,
322
+ "id": self.id,
323
+ "dataset_version": self.dataset_version,
324
+ "description": self.description,
325
+ "licenses": list(self.licenses),
326
+ "providers": [provider.to_dict() for provider in self.providers],
327
+ "tasks": list(self.tasks),
328
+ **self.contract.to_dict(),
329
+ }
330
+ if self.title is not None:
331
+ data["title"] = self.title
332
+ if self.curators is not None:
333
+ data["curators"] = [curator.to_dict() for curator in self.curators]
334
+ if self.keywords is not None:
335
+ data["keywords"] = list(self.keywords)
336
+ if self.extent is not None:
337
+ data["extent"] = self.extent.to_dict()
338
+ if self.sources is not None:
339
+ data["taco:sources"] = self.sources
340
+ if self.metadata is not None:
341
+ data.update(self.metadata.flatten())
342
+ json.dumps(data, allow_nan=False)
343
+ return data
344
+
345
+ def to_json(self) -> str:
346
+ return json.dumps(self.to_dict(), ensure_ascii=False, indent=2, allow_nan=False) + "\n"
347
+
348
+ @classmethod
349
+ def from_dict(cls, data: Mapping[str, Any]) -> Collection:
350
+ if not isinstance(data, Mapping):
351
+ raise CollectionError("COLLECTION.json must be an object")
352
+ required = (
353
+ "taco:version",
354
+ "id",
355
+ "dataset_version",
356
+ "description",
357
+ "licenses",
358
+ "providers",
359
+ "tasks",
360
+ "taco:structure",
361
+ "taco:metadata",
362
+ )
363
+ missing = [key for key in required if key not in data]
364
+ if missing:
365
+ raise CollectionError(f"COLLECTION.json is missing required fields {missing}")
366
+ if data["taco:version"] != TACO_VERSION:
367
+ raise CollectionError(f"taco:version must be {TACO_VERSION}")
368
+ providers = data["providers"]
369
+ if not isinstance(providers, list) or not all(isinstance(value, Mapping) for value in providers):
370
+ raise CollectionError("providers in COLLECTION.json must be a list of objects")
371
+ curators = data.get("curators")
372
+ if curators is not None and (
373
+ not isinstance(curators, list) or not all(isinstance(value, Mapping) for value in curators)
374
+ ):
375
+ raise CollectionError("curators in COLLECTION.json must be a list of objects")
376
+ unknown_reserved = sorted(
377
+ key for key in data if key.startswith(("taco:", "internal:", "cozip:")) and key not in _CORE_KEYS
378
+ )
379
+ if unknown_reserved:
380
+ raise CollectionError(f"COLLECTION.json uses unknown reserved keys {unknown_reserved}")
381
+ extra = {key: value for key, value in data.items() if key not in _CORE_KEYS}
382
+ unqualified = sorted(key for key in extra if ":" not in key)
383
+ if unqualified:
384
+ raise CollectionError(f"COLLECTION.json has unknown unqualified fields {unqualified}")
385
+ return cls(
386
+ contract=Contract.from_dict(data),
387
+ id=data["id"],
388
+ dataset_version=data["dataset_version"],
389
+ description=data["description"],
390
+ licenses=data["licenses"],
391
+ providers=tuple(Provider.from_any(value) for value in providers),
392
+ tasks=data["tasks"],
393
+ metadata=CollectionMetadata.from_flat(extra) if extra else None,
394
+ title=data.get("title"),
395
+ curators=None if curators is None else tuple(Curator.from_any(value) for value in curators),
396
+ keywords=data.get("keywords"),
397
+ extent=data.get("extent"),
398
+ sources=data.get("taco:sources"),
399
+ )
400
+
401
+ @classmethod
402
+ def from_json(cls, text: str | bytes) -> Collection:
403
+ try:
404
+ data = json.loads(text)
405
+ except json.JSONDecodeError as exc:
406
+ raise CollectionError(f"COLLECTION.json is not valid JSON: {exc}") from exc
407
+ return cls.from_dict(data)
408
+
409
+
410
+ __all__ = ["KNOWN_TASKS", "TACO_VERSION", "Collection", "Curator", "Extent", "Provider"]