-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathfactory.py
1618 lines (1467 loc) · 60.9 KB
/
factory.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Custom MosaicTiler Factory for PgSTAC Mosaic Backend."""
import os
import re
import warnings
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Literal,
Optional,
Tuple,
Type,
Union,
)
from urllib.parse import urlencode
import jinja2
import rasterio
from attrs import define, field
from cogeo_mosaic.errors import MosaicNotFoundError
from fastapi import Body, Depends, FastAPI, HTTPException, Path, Query
from fastapi.dependencies.utils import get_dependant, request_params_to_args
from geojson_pydantic import Feature, FeatureCollection
from morecantile import TileMatrixSets
from morecantile import tms as morecantile_tms
from morecantile.models import crs_axis_inverted
from psycopg import errors as pgErrors
from psycopg import sql
from psycopg.rows import class_row, dict_row
from pydantic import Field
from rio_tiler.constants import MAX_THREADS, WGS84_CRS
from rio_tiler.mosaic.methods.base import MosaicMethodBase
from rio_tiler.types import ColorMapType
from rio_tiler.utils import CRS_to_uri
from starlette.datastructures import QueryParams
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response
from starlette.routing import NoMatchFound
from starlette.templating import Jinja2Templates
from typing_extensions import Annotated
from titiler.core.algorithm import BaseAlgorithm
from titiler.core.algorithm import algorithms as available_algorithms
from titiler.core.dependencies import (
AssetsBidxExprParams,
ColorMapParams,
CoordCRSParams,
CRSParams,
DatasetParams,
DefaultDependency,
DstCRSParams,
HistogramParams,
ImageRenderingParams,
PartFeatureParams,
StatisticsParams,
TileParams,
)
from titiler.core.factory import BaseFactory, img_endpoint_params
from titiler.core.models.mapbox import TileJSON
from titiler.core.models.OGC import TileSet, TileSetList
from titiler.core.models.responses import MultiBaseStatisticsGeoJSON
from titiler.core.resources.enums import ImageType, MediaType, OptionalHeader
from titiler.core.resources.responses import GeoJSONResponse, JSONResponse, XMLResponse
from titiler.core.utils import render_image
from titiler.mosaic.factory import PixelSelectionParams
from titiler.mosaic.models.responses import Point
from titiler.pgstac import model
from titiler.pgstac.backend import PGSTACBackend
from titiler.pgstac.dependencies import BackendParams, PgSTACParams, SearchParams
from titiler.pgstac.errors import ReadOnlyPgSTACError
from titiler.pgstac.reader import SimpleSTACReader
MOSAIC_THREADS = int(os.getenv("MOSAIC_CONCURRENCY", MAX_THREADS))
MOSAIC_STRICT_ZOOM = str(os.getenv("MOSAIC_STRICT_ZOOM", False)).lower() in [
"true",
"yes",
]
def _first_value(values: List[Any], default: Any = None):
"""Return the first not None value."""
return next(filter(lambda x: x is not None, values), default)
jinja2_env = jinja2.Environment(
loader=jinja2.ChoiceLoader(
[
jinja2.PackageLoader(__package__, "templates"),
jinja2.PackageLoader("titiler.core", "templates"),
]
),
)
DEFAULT_TEMPLATES = Jinja2Templates(env=jinja2_env)
def check_query_params(
*, dependencies: List[Callable], query_params: Union[QueryParams, Dict]
) -> None:
"""Check QueryParams for Query dependency.
1. `get_dependant` is used to get the query-parameters required by the `callable`
2. we use `request_params_to_args` to construct arguments needed to call the `callable`
3. we call the `callable` and catch any errors
Important: We assume the `callable` in not a co-routine
"""
for dependency in dependencies:
dep = get_dependant(path="", call=dependency)
if dep.query_params:
# call the dependency with the query-parameters values
query_values, _ = request_params_to_args(dep.query_params, query_params)
_ = dependency(**query_values)
return
@define(kw_only=True)
class MosaicTilerFactory(BaseFactory):
"""Custom MosaicTiler for PgSTAC Mosaic Backend."""
path_dependency: Callable[..., str]
backend: Type[PGSTACBackend] = PGSTACBackend
backend_dependency: Type[DefaultDependency] = BackendParams
dataset_reader: Type[SimpleSTACReader] = SimpleSTACReader
reader_dependency: Type[DefaultDependency] = DefaultDependency
# Assets/Indexes/Expression Dependencies
layer_dependency: Type[DefaultDependency] = AssetsBidxExprParams
# Rasterio Dataset Options (nodata, unscale, resampling, reproject)
dataset_dependency: Type[DefaultDependency] = DatasetParams
# Tile/Tilejson/WMTS Dependencies
tile_dependency: Type[DefaultDependency] = TileParams
# Post Processing Dependencies (algorithm)
process_dependency: Callable[..., Optional[BaseAlgorithm]] = (
available_algorithms.dependency
)
# Image rendering Dependencies
colormap_dependency: Callable[..., Optional[ColorMapType]] = ColorMapParams
render_dependency: Type[DefaultDependency] = ImageRenderingParams
# Mosaic Dependency
pixel_selection_dependency: Callable[..., MosaicMethodBase] = PixelSelectionParams
# GDAL ENV dependency
environment_dependency: Callable[..., Dict] = field(default=lambda: {})
# Statistics/Histogram Dependencies
stats_dependency: Type[DefaultDependency] = StatisticsParams
histogram_dependency: Type[DefaultDependency] = HistogramParams
# Crop endpoints Dependencies
# WARNINGS: `/bbox` and `/feature` endpoints should be used carefully because
# each request might need to open/read a lot of files if the user decide to
# submit large bbox/geojson. This will also depends on the STAC Items resolution.
img_part_dependency: Type[DefaultDependency] = PartFeatureParams
pgstac_dependency: Type[DefaultDependency] = PgSTACParams
supported_tms: TileMatrixSets = morecantile_tms
templates: Jinja2Templates = DEFAULT_TEMPLATES
render_func: Callable[..., Tuple[bytes, str]] = render_image
optional_headers: List[OptionalHeader] = field(factory=list)
# Add/Remove some endpoints
add_viewer: bool = False
add_statistics: bool = False
add_part: bool = False
def register_routes(self) -> None:
"""This Method register routes to the router."""
self.tilesets()
self.assets_tile()
self.tile()
if self.add_viewer:
self.map_viewer()
self.tilejson()
self.wmts()
self.point()
self.assets_point()
if self.add_part:
self.part()
if self.add_statistics:
self.statistics()
############################################################################
# /tileset
############################################################################
def tilesets(self):
"""Register OGC tilesets endpoints."""
@self.router.get(
"/tiles",
response_model=TileSetList,
response_class=JSONResponse,
response_model_exclude_none=True,
responses={
200: {
"content": {
"application/json": {},
}
}
},
summary="Retrieve a list of available raster tilesets for the specified dataset.",
)
async def tileset_list(
request: Request,
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
crs=Depends(CRSParams),
env=Depends(self.environment_dependency),
):
"""Retrieve a list of available raster tilesets for the specified dataset."""
with rasterio.Env(**env):
with self.backend(
search_id,
reader=self.dataset_reader,
reader_options=reader_params.as_dict(),
**backend_params.as_dict(),
) as src_dst:
bounds = src_dst.get_geographic_bounds(crs or WGS84_CRS)
collection_bbox = {
"lowerLeft": [bounds[0], bounds[1]],
"upperRight": [bounds[2], bounds[3]],
"crs": CRS_to_uri(crs or WGS84_CRS),
}
qs = [
(key, value)
for (key, value) in request.query_params._list
if key.lower() not in ["crs"]
]
query_string = f"?{urlencode(qs)}" if qs else ""
tilesets = []
for tms in self.supported_tms.list():
tileset = {
"title": f"tileset tiled using {tms} TileMatrixSet",
"dataType": "map",
"crs": self.supported_tms.get(tms).crs,
"boundingBox": collection_bbox,
"links": [
{
"href": self.url_for(
request, "tileset", tileMatrixSetId=tms
)
+ query_string,
"rel": "self",
"type": "application/json",
"title": f"Tileset tiled using {tms} TileMatrixSet",
},
{
"href": self.url_for(
request,
"tile",
tileMatrixSetId=tms,
z="{z}",
x="{x}",
y="{y}",
)
+ query_string,
"rel": "tile",
"title": "Templated link for retrieving Raster tiles",
},
],
}
try:
tileset["links"].append(
{
"href": str(
request.url_for("tilematrixset", tileMatrixSetId=tms)
),
"rel": "http://www.opengis.net/def/rel/ogc/1.0/tiling-schemes",
"type": "application/json",
"title": f"Definition of '{tms}' tileMatrixSet",
}
)
except NoMatchFound:
pass
tilesets.append(tileset)
data = TileSetList.model_validate({"tilesets": tilesets})
return data
@self.router.get(
"/tiles/{tileMatrixSetId}",
response_model=TileSet,
response_class=JSONResponse,
response_model_exclude_none=True,
responses={200: {"content": {"application/json": {}}}},
summary="Retrieve the raster tileset metadata for the specified dataset and tiling scheme (tile matrix set).",
)
async def tileset(
request: Request,
tileMatrixSetId: Annotated[
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
env=Depends(self.environment_dependency),
):
"""Retrieve the raster tileset metadata for the specified dataset and tiling scheme (tile matrix set)."""
tms = self.supported_tms.get(tileMatrixSetId)
with rasterio.Env(**env):
with self.backend(
search_id,
tms=tms,
reader=self.dataset_reader,
reader_options=reader_params.as_dict(),
**backend_params.as_dict(),
) as src_dst:
bounds = src_dst.get_geographic_bounds(tms.rasterio_geographic_crs)
minzoom = src_dst.minzoom
maxzoom = src_dst.maxzoom
collection_bbox = {
"lowerLeft": [bounds[0], bounds[1]],
"upperRight": [bounds[2], bounds[3]],
"crs": CRS_to_uri(tms.rasterio_geographic_crs),
}
tilematrix_limit = []
for zoom in range(minzoom, maxzoom + 1, 1):
matrix = tms.matrix(zoom)
ulTile = tms.tile(bounds[0], bounds[3], int(matrix.id))
lrTile = tms.tile(bounds[2], bounds[1], int(matrix.id))
minx, maxx = (min(ulTile.x, lrTile.x), max(ulTile.x, lrTile.x))
miny, maxy = (min(ulTile.y, lrTile.y), max(ulTile.y, lrTile.y))
tilematrix_limit.append(
{
"tileMatrix": matrix.id,
"minTileRow": max(miny, 0),
"maxTileRow": min(maxy, matrix.matrixHeight),
"minTileCol": max(minx, 0),
"maxTileCol": min(maxx, matrix.matrixWidth),
}
)
qs = list(request.query_params._list)
query_string = f"?{urlencode(qs)}" if qs else ""
links = [
{
"href": self.url_for(
request,
"tileset",
tileMatrixSetId=tileMatrixSetId,
),
"rel": "self",
"type": "application/json",
"title": f"Tileset tiled using {tileMatrixSetId} TileMatrixSet",
},
{
"href": self.url_for(
request,
"tile",
tileMatrixSetId=tileMatrixSetId,
z="{z}",
x="{x}",
y="{y}",
)
+ query_string,
"rel": "tile",
"title": "Templated link for retrieving Raster tiles",
"templated": True,
},
]
try:
links.append(
{
"href": str(
request.url_for(
"tilematrixset", tileMatrixSetId=tileMatrixSetId
)
),
"rel": "http://www.opengis.net/def/rel/ogc/1.0/tiling-schemes",
"type": "application/json",
"title": f"Definition of '{tileMatrixSetId}' tileMatrixSet",
}
)
except NoMatchFound:
pass
if self.add_viewer:
links.append(
{
"href": self.url_for(
request,
"map_viewer",
tileMatrixSetId=tileMatrixSetId,
)
+ query_string,
"type": "text/html",
"rel": "data",
"title": f"Map viewer for '{tileMatrixSetId}' tileMatrixSet",
}
)
# TODO: add render links
data = TileSet.model_validate(
{
"title": f"tileset tiled using {tileMatrixSetId} TileMatrixSet",
"dataType": "map",
"crs": tms.crs,
"boundingBox": collection_bbox,
"links": links,
"tileMatrixSetLimits": tilematrix_limit,
}
)
return data
def tile(self) -> None:
"""register tiles routes."""
@self.router.get("/tiles/{tileMatrixSetId}/{z}/{x}/{y}", **img_endpoint_params)
@self.router.get(
"/tiles/{tileMatrixSetId}/{z}/{x}/{y}.{format}",
**img_endpoint_params,
)
@self.router.get(
"/tiles/{tileMatrixSetId}/{z}/{x}/{y}@{scale}x",
**img_endpoint_params,
)
@self.router.get(
"/tiles/{tileMatrixSetId}/{z}/{x}/{y}@{scale}x.{format}",
**img_endpoint_params,
)
def tile(
z: Annotated[
int,
Path(
description="Identifier (Z) selecting one of the scales defined in the TileMatrixSet and representing the scaleDenominator the tile.",
),
],
x: Annotated[
int,
Path(
description="Column (X) index of the tile on the selected TileMatrix. It cannot exceed the MatrixHeight-1 for the selected TileMatrix.",
),
],
y: Annotated[
int,
Path(
description="Row (Y) index of the tile on the selected TileMatrix. It cannot exceed the MatrixWidth-1 for the selected TileMatrix.",
),
],
tileMatrixSetId: Annotated[ # type: ignore
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
scale: Annotated[
int,
Field(
gt=0, le=4, description="Tile size scale. 1=256x256, 2=512x512..."
),
] = 1,
format: Annotated[
Optional[ImageType],
"Default will be automatically defined if the output image needs a mask (png) or not (jpeg).",
] = None,
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pgstac_params=Depends(self.pgstac_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
env=Depends(self.environment_dependency),
):
"""Create map tile."""
scale = scale or 1
tms = self.supported_tms.get(tileMatrixSetId)
with rasterio.Env(**env):
with self.backend(
search_id,
tms=tms,
reader=self.dataset_reader,
reader_options=reader_params.as_dict(),
**backend_params.as_dict(),
) as src_dst:
if MOSAIC_STRICT_ZOOM and (
z < src_dst.minzoom or z > src_dst.maxzoom
):
raise HTTPException(
400,
f"Invalid ZOOM level {z}. Should be between {src_dst.minzoom} and {src_dst.maxzoom}",
)
image, assets = src_dst.tile(
x,
y,
z,
tilesize=scale * 256,
pixel_selection=pixel_selection,
threads=MOSAIC_THREADS,
**tile_params.as_dict(),
**layer_params.as_dict(),
**dataset_params.as_dict(),
**pgstac_params.as_dict(),
)
if post_process:
image = post_process(image)
content, media_type = self.render_func(
image,
output_format=format,
colormap=colormap,
**render_params.as_dict(),
)
headers: Dict[str, str] = {}
if OptionalHeader.x_assets in self.optional_headers:
ids = [x["id"] for x in assets]
headers["X-Assets"] = ",".join(ids)
return Response(content, media_type=media_type, headers=headers)
def tilejson(self) -> None:
"""register tiles routes."""
@self.router.get(
"/{tileMatrixSetId}/tilejson.json",
response_model=TileJSON,
responses={200: {"description": "Return a tilejson"}},
response_model_exclude_none=True,
)
def tilejson(
request: Request,
tileMatrixSetId: Annotated[ # type: ignore
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
tile_format: Annotated[
Optional[ImageType],
Query(
description="Default will be automatically defined if the output image needs a mask (png) or not (jpeg).",
),
] = None,
tile_scale: Annotated[
Optional[int],
Query(
gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..."
),
] = None,
minzoom: Annotated[
Optional[int],
Query(description="Overwrite default minzoom."),
] = None,
maxzoom: Annotated[
Optional[int],
Query(description="Overwrite default maxzoom."),
] = None,
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pgstac_params=Depends(self.pgstac_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
):
"""Return TileJSON document for a search_id."""
with request.app.state.dbpool.connection() as conn:
with conn.cursor(row_factory=class_row(model.Search)) as cursor:
cursor.execute(
"SELECT * FROM searches WHERE hash=%s;",
(search_id,),
)
search_info = cursor.fetchone()
if not search_info:
raise MosaicNotFoundError(f"SearchId `{search_id}` not found")
route_params = {
"z": "{z}",
"x": "{x}",
"y": "{y}",
"tileMatrixSetId": tileMatrixSetId,
}
if tile_scale:
route_params["scale"] = tile_scale
if tile_format:
route_params["format"] = tile_format.value
tiles_url = self.url_for(request, "tile", **route_params)
qs_key_to_remove = [
"tilematrixsetid",
"tile_format",
"tile_scale",
"minzoom",
"maxzoom",
]
qs = [
(key, value)
for (key, value) in request.query_params._list
if key.lower() not in qs_key_to_remove
]
if qs:
tiles_url += f"?{urlencode(qs, doseq=True)}"
tms = self.supported_tms.get(tileMatrixSetId)
minzoom = _first_value([minzoom, search_info.metadata.minzoom], tms.minzoom)
maxzoom = _first_value([maxzoom, search_info.metadata.maxzoom], tms.maxzoom)
bounds = _first_value(
[search_info.input_search.get("bbox"), search_info.metadata.bounds],
tms.bbox,
)
return {
"bounds": bounds,
"minzoom": minzoom,
"maxzoom": maxzoom,
"name": search_info.metadata.name or search_info.id,
"tiles": [tiles_url],
}
def map_viewer(self): # noqa: C901
"""Register /map endpoint."""
@self.router.get("/{tileMatrixSetId}/map", response_class=HTMLResponse)
def map_viewer(
request: Request,
tileMatrixSetId: Annotated[
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
tile_format: Annotated[
Optional[ImageType],
Query(
description="Default will be automatically defined if the output image needs a mask (png) or not (jpeg).",
),
] = None,
tile_scale: Annotated[
Optional[int],
Query(
gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..."
),
] = None,
minzoom: Annotated[
Optional[int],
Query(description="Overwrite default minzoom."),
] = None,
maxzoom: Annotated[
Optional[int],
Query(description="Overwrite default maxzoom."),
] = None,
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pgstac_params=Depends(self.pgstac_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
):
"""Return a simple map viewer."""
tilejson_url = self.url_for(
request,
"tilejson",
tileMatrixSetId=tileMatrixSetId,
)
if request.query_params._list:
tilejson_url += f"?{urlencode(request.query_params._list, doseq=True)}"
tms = self.supported_tms.get(tileMatrixSetId)
return self.templates.TemplateResponse(
request,
name="map.html",
context={
"tilejson_endpoint": tilejson_url,
"tms": tms,
"resolutions": [matrix.cellSize for matrix in tms],
},
media_type="text/html",
)
def wmts(self): # noqa: C901
"""Add wmts endpoint."""
@self.router.get(
"/{tileMatrixSetId}/WMTSCapabilities.xml",
response_class=XMLResponse,
)
def wmts( # noqa: C901
request: Request,
tileMatrixSetId: Annotated[
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
tile_format: Annotated[
ImageType,
Query(description="Output image type. Default is png."),
] = ImageType.png,
tile_scale: Annotated[
int,
Query(
gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..."
),
] = 1,
minzoom: Annotated[
Optional[int],
Query(description="Overwrite default minzoom."),
] = None,
maxzoom: Annotated[
Optional[int],
Query(description="Overwrite default maxzoom."),
] = None,
use_epsg: Annotated[
bool,
Query(
description="Use EPSG code, not opengis.net, for the ows:SupportedCRS in the TileMatrixSet (set to True to enable ArcMap compatability)"
),
] = False,
search_id=Depends(self.path_dependency),
):
"""OGC WMTS endpoint."""
with request.app.state.dbpool.connection() as conn:
with conn.cursor(row_factory=class_row(model.Search)) as cursor:
cursor.execute(
"SELECT * FROM searches WHERE hash=%s;",
(search_id,),
)
search_info = cursor.fetchone()
if not search_info:
raise MosaicNotFoundError(f"SearchId `{search_id}` not found")
route_params = {
"z": "{TileMatrix}",
"x": "{TileCol}",
"y": "{TileRow}",
"scale": tile_scale,
"format": tile_format.value,
"tileMatrixSetId": tileMatrixSetId,
}
tiles_url = self.url_for(request, "tile", **route_params)
tms = self.supported_tms.get(tileMatrixSetId)
minzoom = _first_value([minzoom, search_info.metadata.minzoom], tms.minzoom)
maxzoom = _first_value([maxzoom, search_info.metadata.maxzoom], tms.maxzoom)
bounds = _first_value(
[search_info.input_search.get("bbox"), search_info.metadata.bounds],
tms.bbox,
)
tileMatrix = []
for zoom in range(minzoom, maxzoom + 1): # type: ignore
matrix = tms.matrix(zoom)
tm = f"""
<TileMatrix>
<ows:Identifier>{matrix.id}</ows:Identifier>
<ScaleDenominator>{matrix.scaleDenominator}</ScaleDenominator>
<TopLeftCorner>{matrix.pointOfOrigin[0]} {matrix.pointOfOrigin[1]}</TopLeftCorner>
<TileWidth>{matrix.tileWidth}</TileWidth>
<TileHeight>{matrix.tileHeight}</TileHeight>
<MatrixWidth>{matrix.matrixWidth}</MatrixWidth>
<MatrixHeight>{matrix.matrixHeight}</MatrixHeight>
</TileMatrix>"""
tileMatrix.append(tm)
if use_epsg:
supported_crs = f"EPSG:{tms.crs.to_epsg()}"
else:
supported_crs = tms.crs.srs
# List of dependencies a `/tile` URL should validate
# Note: Those dependencies should only require Query() inputs
tile_dependencies = [
self.layer_dependency,
self.dataset_dependency,
self.pixel_selection_dependency,
self.tile_dependency,
self.process_dependency,
self.render_dependency,
self.pgstac_dependency,
self.reader_dependency,
self.backend_dependency,
]
layers: List[Dict[str, Any]] = []
# LAYERS from mosaic metadata
if renders := search_info.metadata.defaults_params:
for name, values in renders.items():
try:
check_query_params(
dependencies=tile_dependencies, # type: ignore
query_params=values,
)
except Exception as e:
warnings.warn(
f"Cannot construct URL for layer `{name}`: {repr(e)}",
UserWarning,
stacklevel=2,
)
continue
layers.append(
{
"titler": search_info.metadata.name or search_id,
"name": name,
"tiles_url": tiles_url,
"query_string": urlencode(values, doseq=True)
if values
else None,
"bounds": bounds,
}
)
# LAYER from query-parameters
qs_key_to_remove = [
"tilematrixsetid",
"tile_format",
"tile_scale",
"minzoom",
"maxzoom",
"service",
"use_epsg",
"request",
]
qs = [
(key, value)
for (key, value) in request.query_params._list
if key.lower() not in qs_key_to_remove
]
# Checking if we can construct a valid tile URL
# 1. we use `check_query_params` to validate the query-parameter
# 2. if there is no layers (from mosaic metadata) we raise the caught error
# 3. if there no errors we then add a default `layer` to the layers stack
try:
check_query_params(
dependencies=tile_dependencies, # type: ignore
query_params=QueryParams(qs),
)
except Exception as e:
if not layers:
raise e
else:
layers.append(
{
"titler": search_info.metadata.name or search_id,
"name": "default",
"tiles_url": tiles_url,
"query_string": urlencode(qs, doseq=True) if qs else None,
"bounds": bounds,
}
)
bbox_crs_type = "WGS84BoundingBox"
bbox_crs_uri = "urn:ogc:def:crs:OGC:2:84"
if tms.rasterio_geographic_crs != WGS84_CRS:
bbox_crs_type = "BoundingBox"
bbox_crs_uri = CRS_to_uri(tms.rasterio_geographic_crs)
# WGS88BoundingBox is always xy ordered, but BoundingBox must match the CRS order
if crs_axis_inverted(tms.geographic_crs):
# match the bounding box coordinate order to the CRS
bounds = [bounds[1], bounds[0], bounds[3], bounds[2]]
return self.templates.TemplateResponse(
request,
name="wmts.xml",
context={
"tileMatrixSetId": tms.id,
"tileMatrix": tileMatrix,
"supported_crs": supported_crs,
"bbox_crs_type": bbox_crs_type,
"bbox_crs_uri": bbox_crs_uri,
"layers": layers,
"media_type": tile_format.mediatype,
},
media_type=MediaType.xml.value,
)
def assets_tile(self):
"""Register assets routes."""
@self.router.get(
"/tiles/{tileMatrixSetId}/{z}/{x}/{y}/assets",
responses={200: {"description": "Return list of assets"}},
response_model=List[Dict],
)
def assets_for_tile(
tileMatrixSetId: Annotated[
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported."
),
],
z: Annotated[
int,
Path(
description="Identifier (Z) selecting one of the scales defined in the TileMatrixSet and representing the scaleDenominator the tile.",
),
],
x: Annotated[
int,
Path(
description="Column (X) index of the tile on the selected TileMatrix. It cannot exceed the MatrixHeight-1 for the selected TileMatrix.",
),
],
y: Annotated[
int,
Path(
description="Row (Y) index of the tile on the selected TileMatrix. It cannot exceed the MatrixWidth-1 for the selected TileMatrix.",
),
],
search_id=Depends(self.path_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
pgstac_params=Depends(self.pgstac_dependency),
):
"""Return a list of assets which overlap a given tile"""
tms = self.supported_tms.get(tileMatrixSetId)
with self.backend(
search_id,
tms=tms,
reader=self.dataset_reader,
reader_options=reader_params.as_dict(),
**backend_params.as_dict(),
) as src_dst:
return src_dst.assets_for_tile(
x,
y,
z,
**pgstac_params.as_dict(),
)
def assets_point(self):
"""Register assets routes."""
@self.router.get(
"/point/{lon},{lat}/assets",
responses={200: {"description": "Return list of assets"}},
response_model=List[Dict],
)
def assets_for_point(
lon: Annotated[float, Path(description="Longitude")],
lat: Annotated[float, Path(description="Latitude")],
search_id=Depends(self.path_dependency),
coord_crs=Depends(CoordCRSParams),
pgstac_params=Depends(self.pgstac_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
):
"""Return a list of assets for a given point."""
with self.backend(
search_id,
reader=self.dataset_reader,
reader_options=reader_params.as_dict(),
**backend_params.as_dict(),
) as src_dst:
return src_dst.assets_for_point(
lon,
lat,
coord_crs=coord_crs or WGS84_CRS,
**pgstac_params.as_dict(),