-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_stac.py
More file actions
240 lines (213 loc) · 8.23 KB
/
create_stac.py
File metadata and controls
240 lines (213 loc) · 8.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
from datetime import datetime
from pathlib import Path
from typing import Optional, Union
import click
import pandas as pd
from geopandas import GeoDataFrame, GeoSeries
from shapely.geometry import box
from yarl import URL
from .basecommand import BaseCommand, runnable
from .cli.options import JSON_INDENT, VECOREL_FILE_ARG, VECOREL_TARGET_CONSOLE
from .encoding.auto import create_encoding
from .registry import Registry
from .vecorel.collection import Collection
from .vecorel.util import parse_link_str, to_iso8601
class CreateStacCollection(BaseCommand):
cmd_name = "create-stac-collection"
cmd_title = "Create STAC Collection"
cmd_help = f"Creates a STAC Collection for {Registry.project} files."
cmd_final_report = True
processing_extension = "https://stac-extensions.github.io/processing/v1.2.0/schema.json"
table_extension = "https://stac-extensions.github.io/table/v1.2.0/schema.json"
temporal_property = "datetime"
@staticmethod
def get_cli_args():
return {
"source": VECOREL_FILE_ARG,
"target": VECOREL_TARGET_CONSOLE,
"indent": JSON_INDENT,
"temporal": click.option(
"temporal_property",
"--temporal",
"-t",
type=click.STRING,
help="The temporal property to use for the temporal extent.",
show_default=True,
default=CreateStacCollection.temporal_property,
),
# todo: allow additional parameters for missing data in the collection?
# https://stackoverflow.com/questions/36513706/python-click-pass-unspecified-number-of-kwargs
}
@runnable
def create_cli(
self,
source: Union[Path, URL, str],
target: Optional[Union[str, Path]] = None,
temporal_property: Optional[str] = None,
indent: Optional[int] = None,
) -> Union[Path, str, bool]:
stac = self.create_from_file(
source, data_url=str(source), temporal_property=temporal_property
)
if stac:
return self._json_dump_cli(stac, target, indent)
else:
return False
def create_from_file(
self,
source: Union[Path, URL, str],
data_url: str,
temporal_property: Optional[str] = None,
) -> dict:
if isinstance(source, str):
source = Path(source)
if temporal_property is None:
temporal_property = self.temporal_property
# Read source data
source_encoding = create_encoding(source)
properties = source_encoding.get_properties()
if properties is None:
data = source_encoding.read()
else:
property_names = properties.keys()
required_properties = property_names & {"geometry", temporal_property}
data = source_encoding.read(properties=list(required_properties))
collection = source_encoding.get_collection()
# Create STAC collection
stac = self.create(
collection,
data,
data_url,
media_type=source_encoding.media_type,
temporal_property=temporal_property,
)
# Add more asset details
if properties is not None:
table_columns = []
for column, types in properties.items():
if "null" in types:
types.remove("null")
table_columns.append({"name": column, "type": types[0]})
stac["stac_extensions"].append(self.table_extension)
asset = stac["assets"]["data"]
asset["table:columns"] = table_columns
asset["table:primary_geometry"] = "geometry"
asset["table:row_count"] = len(data)
return stac
def create(
self,
collection: Collection,
gdf: GeoDataFrame,
data_url: Union[Path, URL, str],
media_type: Optional[str] = None,
temporal_property: Optional[str] = None,
) -> dict:
"""
Creates a collection for the datasets.
"""
if len(gdf) == 0:
raise Exception("No data available.")
schemas = collection.get_schemas()
if len(schemas) > 1:
raise Exception(
"Multiple collections found. Can only create STAC for files containing a single collection."
)
cid = collection.get("collection", next(iter(schemas.keys())))
if not cid or len(cid) == 0:
raise Exception("Collection ID not found in collection.")
title = collection.get("title", cid)
if title is None:
self.warning("Title is not found in collection, using ID as title.")
description = collection.get("description", "").strip()
if len(description) == 0:
raise Exception("Description is not found in collection.")
bbox = list(GeoSeries([box(*gdf.total_bounds)], crs=gdf.crs).to_crs(epsg=4326).total_bounds)
if isinstance(data_url, Path):
href = "file://" + str(data_url.resolve()).replace("\\", "/")
else:
href = str(data_url)
stac = {
"stac_version": "1.1.0",
"stac_extensions": [
self.processing_extension,
],
"type": "Collection",
"id": cid,
"title": title,
"description": description,
"license": "other",
"extent": {
"spatial": {"bbox": [bbox]},
"temporal": {"interval": [[None, None]]},
},
"assets": {
"data": {
"roles": ["data"],
"href": href,
"processing:software": {
Registry.name: Registry.get_version(),
},
}
},
"links": [],
}
# Add data media type
if media_type:
stac["assets"]["data"]["type"] = media_type
# Add license handling
license = (collection.get("license") or "").strip()
if license.lower() == "dl-de/by-2-0":
stac["links"].append(
{
"href": "https://www.govdata.de/dl-de/by-2-0",
"title": "Data licence Germany - attribution - Version 2.0",
"type": "text/html",
"rel": "license",
}
)
elif license.lower() == "dl-de/zero-2-0":
stac["links"].append(
{
"href": "https://www.govdata.de/dl-de/zero-2-0",
"title": "Data licence Germany - Zero - Version 2.0",
"type": "text/html",
"rel": "license",
}
)
else:
license_name, license_url = parse_link_str(license)
if license_url is None and len(license_name) > 0:
stac["license"] = license_name
elif license_url is not None:
stac["links"].append(
{
"href": license_url,
"title": license_name,
"rel": "license",
}
)
# Add provider information
provider = collection.get("provider", "").strip()
if len(provider) > 0:
provider_name, provider_url = parse_link_str(provider)
stac["providers"] = [
{
"name": provider_name,
"roles": ["producer", "licensor"],
}
]
if provider_url:
stac["providers"][0]["url"] = provider_url
# Add temporal extent
temporal_extent = None
if temporal_property in gdf.columns:
dates = pd.to_datetime(gdf[temporal_property])
min_time = to_iso8601(dates.min())
max_time = to_iso8601(dates.max())
temporal_extent = [min_time, max_time]
elif temporal_property in collection:
time = to_iso8601(datetime.fromisoformat(collection[temporal_property]))
temporal_extent = [time, time]
if temporal_extent is not None:
stac["extent"]["temporal"]["interval"][0] = temporal_extent
return stac