-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmodel.py
240 lines (180 loc) · 6.1 KB
/
model.py
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
"""
Titiler.pgstac models.
Note: This is mostly a copy of https://github.com/stac-utils/stac-fastapi/blob/master/stac_fastapi/pgstac/stac_fastapi/pgstac/types/search.py
"""
import operator
from datetime import datetime
from enum import Enum, auto
from types import DynamicClassAttribute
from typing import Any, Callable, Dict, List, Optional, Union
from geojson_pydantic.geometries import (
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
)
from pydantic import BaseModel, Field, root_validator, validator
from stac_pydantic.shared import BBox
from stac_pydantic.utils import AutoValueEnum
from titiler.core.resources.enums import MediaType
class FilterLang(str, Enum):
"""filter language.
ref: https://github.com/radiantearth/stac-api-spec/tree/master/fragments/filter#get-query-parameters-and-post-json-fields
"""
cql_json = "cql-json"
cql_text = "cql-text"
cql2_json = "cql2-json"
class Operator(str, AutoValueEnum):
"""Defines the set of operators supported by the API."""
eq = auto()
ne = auto()
lt = auto()
lte = auto()
gt = auto()
gte = auto()
# TODO: These are defined in the spec but aren't currently implemented by the api
# startsWith = auto()
# endsWith = auto()
# contains = auto()
# in = auto()
@DynamicClassAttribute
def operator(self) -> Callable[[Any, Any], bool]:
"""Return python operator."""
return getattr(operator, self._value_)
class SearchType(str, Enum):
"""Search type."""
mosaic = "mosaic"
search = "search"
class Metadata(BaseModel):
"""Metadata Model."""
type: SearchType = SearchType.mosaic
# WGS84 bounds
bounds: Optional[BBox]
# Min/Max zoom for WebMercatorQuad TMS
minzoom: Optional[int]
maxzoom: Optional[int]
# Name
name: Optional[str]
# List of available assets
assets: Optional[List[str]]
# Set of default configuration
# e.g
# {
# "true_color": {
# "assets": ["B4", "B3", "B2"],
# "color_formula": "Gamma RGB 3.5 Saturation 1.7 Sigmoidal RGB 15 0.35",
# },
# "ndvi": {
# "expression": "(B4-B3)/(B4+B3)",
# "rescale": "-1,1",
# "colormap_name": "viridis"
# }
# }
defaults: Optional[Dict[str, Any]]
class Config:
"""Config for model."""
use_enum_values = True
extra = "allow"
class PgSTACSearch(BaseModel):
"""Search Query model.
Notes/Diff with standard model:
- 'fields' is not in the Model because it's defined at the tiler level
- we don't set limit
"""
collections: Optional[List[str]] = None
ids: Optional[List[str]] = None
bbox: Optional[BBox]
intersects: Optional[
Union[Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon]
]
query: Optional[Dict[str, Dict[Operator, Any]]]
filter: Optional[Dict]
datetime: Optional[str] = None
sortby: Any
filter_lang: Optional[FilterLang] = Field(None, alias="filter-lang")
class Config:
"""Config for model."""
use_enum_values = True
extra = "allow"
@root_validator(pre=True)
def validate_query_fields(cls, values: Dict) -> Dict:
"""Pgstac does not require the base validator for query fields."""
return values
@validator("datetime")
def validate_datetime(cls, v):
"""Pgstac does not require the base validator for datetime."""
return v
@validator("intersects")
def validate_spatial(cls, v, values):
"""Make sure bbox is not used with Intersects."""
if v and values["bbox"]:
raise ValueError("intersects and bbox parameters are mutually exclusive")
return v
@validator("bbox")
def validate_bbox(cls, v: BBox):
"""Validate BBOX."""
if v:
# Validate order
if len(v) == 4:
xmin, ymin, xmax, ymax = v
else:
xmin, ymin, min_elev, xmax, ymax, max_elev = v
if max_elev < min_elev:
raise ValueError(
"Maximum elevation must greater than minimum elevation"
)
if xmax < xmin:
raise ValueError(
"Maximum longitude must be greater than minimum longitude"
)
if ymax < ymin:
raise ValueError(
"Maximum longitude must be greater than minimum longitude"
)
# Validate against WGS84
if xmin < -180 or ymin < -90 or xmax > 180 or ymax > 90:
raise ValueError("Bounding box must be within (-180, -90, 180, 90)")
return v
class RegisterMosaic(PgSTACSearch):
"""Model of /register endpoint input."""
metadata: Metadata = Field(default_factory=Metadata)
class Search(BaseModel):
"""PgSTAC Search entry.
ref: https://github.com/stac-utils/pgstac/blob/3499daa2bfa700ae7bb07503795c169bf2ebafc7/sql/004_search.sql#L907-L915
"""
id: str = Field(alias="hash")
input_search: Dict[str, Any] = Field(alias="search")
sql_where: str = Field(alias="_where")
orderby: str
lastused: datetime
usecount: int
metadata: Metadata
@validator("metadata", pre=True)
def validate_metadata(cls, v):
"""Set SearchType.search when not present in metadata."""
if "type" not in v:
v["type"] = SearchType.search.name
return v
class Link(BaseModel):
"""Link model.
Ref: http://schemas.opengis.net/ogcapi/features/part1/1.0/openapi/schemas/link.yaml
"""
rel: Optional[str]
title: Optional[str]
type: Optional[MediaType] = MediaType.json
href: str
hreflang: Optional[str]
length: Optional[int]
class Config:
"""Link model configuration."""
use_enum_values = True
class RegisterResponse(BaseModel):
"""Response model for /register endpoint."""
searchid: str
links: Optional[List[Link]]
class Info(BaseModel):
"""Response model for /info endpoint."""
search: Search
links: Optional[List[Link]]