-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfactory.py
1363 lines (1215 loc) · 51.2 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 TiTiler-STACAPI Mosaic Backend."""
import datetime as python_datetime
import json
import os
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List, Literal, Optional, Type
from urllib.parse import urlencode
import jinja2
import rasterio
from cachetools import TTLCache, cached
from cachetools.keys import hashkey
from cogeo_mosaic.backends import BaseBackend
from fastapi import Depends, HTTPException, Path, Query
from fastapi.dependencies.utils import get_dependant, request_params_to_args
from morecantile import tms as morecantile_tms
from morecantile.defaults import TileMatrixSets
from pydantic import conint
from pystac_client import Client
from pystac_client.stac_api_io import StacApiIO
from rasterio.transform import xy as rowcol_to_coords
from rasterio.warp import transform as transform_points
from rio_tiler.constants import MAX_THREADS
from rio_tiler.models import ImageData
from rio_tiler.mosaic.methods.base import MosaicMethodBase
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response
from starlette.routing import compile_path, replace_params
from starlette.templating import Jinja2Templates
from typing_extensions import Annotated
from urllib3 import Retry
from titiler.core.dependencies import (
AssetsBidxExprParams,
ColorFormulaParams,
DefaultDependency,
TileParams,
)
from titiler.core.factory import BaseTilerFactory, img_endpoint_params
from titiler.core.models.mapbox import TileJSON
from titiler.core.resources.enums import ImageType, MediaType, OptionalHeader
from titiler.core.resources.responses import GeoJSONResponse, XMLResponse
from titiler.core.utils import render_image
from titiler.mosaic.factory import PixelSelectionParams
from titiler.stacapi.backend import STACAPIBackend
from titiler.stacapi.dependencies import APIParams, STACApiParams, STACSearchParams
from titiler.stacapi.models import FeatureInfo, LayerDict
from titiler.stacapi.settings import CacheSettings, RetrySettings
from titiler.stacapi.utils import _tms_limits
cache_config = CacheSettings()
retry_config = RetrySettings()
MOSAIC_THREADS = int(os.getenv("MOSAIC_CONCURRENCY", MAX_THREADS))
MOSAIC_STRICT_ZOOM = str(os.getenv("MOSAIC_STRICT_ZOOM", False)).lower() in [
"true",
"yes",
]
jinja2_env = jinja2.Environment(
loader=jinja2.ChoiceLoader(
[
jinja2.PackageLoader(__package__, "templates"),
jinja2.PackageLoader("titiler.core", "templates"),
]
),
)
DEFAULT_TEMPLATES = Jinja2Templates(env=jinja2_env)
def get_dependency_params(*, dependency: Callable, query_params: Dict) -> Any:
"""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
"""
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)
return dependency(**query_values)
return
@dataclass
class MosaicTilerFactory(BaseTilerFactory):
"""Custom MosaicTiler for STACAPI Mosaic Backend."""
path_dependency: Callable[..., APIParams] = STACApiParams
search_dependency: Callable[..., Dict] = STACSearchParams
# In this factory, `reader` should be a Mosaic Backend
# https://developmentseed.org/cogeo-mosaic/advanced/backends/
reader: Type[BaseBackend] = STACAPIBackend
# Because the endpoints should work with STAC Items,
# the `layer_dependency` define which query parameters are mandatory/optional to `display` images
# Defaults to `titiler.core.dependencies.AssetsBidxExprParams`, `assets=` or `expression=` is required
layer_dependency: Type[DefaultDependency] = AssetsBidxExprParams
# The `tile_dependency` define options like `buffer` or `padding`
# used in Tile/Tilejson/WMTS Dependencies
tile_dependency: Type[DefaultDependency] = TileParams
pixel_selection_dependency: Callable[..., MosaicMethodBase] = PixelSelectionParams
backend_dependency: Type[DefaultDependency] = DefaultDependency
add_viewer: bool = False
templates: Jinja2Templates = DEFAULT_TEMPLATES
def get_base_url(self, request: Request) -> str:
"""return endpoints base url."""
base_url = str(request.base_url).rstrip("/")
if self.router_prefix:
prefix = self.router_prefix.lstrip("/")
# If we have prefix with custom path param we check and replace them with
# the path params provided
if "{" in prefix:
_, path_format, param_convertors = compile_path(prefix)
prefix, _ = replace_params(
path_format, param_convertors, request.path_params.copy()
)
base_url += prefix
return base_url
def register_routes(self) -> None:
"""register endpoints."""
self.register_tiles()
self.register_tilejson()
self.register_wmts()
if self.add_viewer:
self.register_map()
def register_tiles(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(
request: Request,
tileMatrixSetId: Annotated[ # type: ignore
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.",
),
],
api_params=Depends(self.path_dependency),
search_query=Depends(self.search_dependency),
scale: Annotated[ # type: ignore
Optional[conint(gt=0, le=4)],
"Tile size scale. 1=256x256, 2=512x512...",
] = None,
format: Annotated[
Optional[ImageType],
"Default will be automatically defined if the output image needs a mask (png) or not (jpeg).",
] = None,
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
rescale=Depends(self.rescale_dependency),
color_formula=Depends(ColorFormulaParams),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_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.reader(
url=api_params["api_url"],
headers=api_params.get("headers", {}),
tms=tms,
reader_options={**reader_params},
**backend_params,
) 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,
search_query=search_query,
tilesize=scale * 256,
pixel_selection=pixel_selection,
threads=MOSAIC_THREADS,
**tile_params,
**layer_params,
**dataset_params,
)
if post_process:
image = post_process(image)
if rescale:
image.rescale(rescale)
if color_formula:
image.apply_color_formula(color_formula)
content, media_type = render_image(
image,
output_format=format,
colormap=colormap,
**render_params,
)
headers: Dict[str, str] = {}
if OptionalHeader.x_assets in self.optional_headers:
ids = [x["id"] for x in assets]
headers["X-Assets"] = ",".join(ids)
if (
OptionalHeader.server_timing in self.optional_headers
and image.metadata.get("timings")
):
headers["Server-Timing"] = ", ".join(
[f"{name};dur={time}" for (name, time) in image.metadata["timings"]]
)
return Response(content, media_type=media_type, headers=headers)
def register_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"
),
],
search_query=Depends(self.search_dependency),
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,
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
rescale=Depends(self.rescale_dependency),
color_formula=Depends(ColorFormulaParams),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
):
"""Return TileJSON document."""
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)}"
tms = self.supported_tms.get(tileMatrixSetId)
minzoom = minzoom if minzoom is not None else tms.minzoom
maxzoom = maxzoom if maxzoom is not None else tms.maxzoom
bounds = search_query.get("bbox") or tms.bbox
return {
"bounds": bounds,
"minzoom": minzoom,
"maxzoom": maxzoom,
"name": "STACAPI",
"tiles": [tiles_url],
}
def register_map(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"
),
],
search_query=Depends(self.search_dependency),
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,
layer_params=Depends(self.layer_dependency),
dataset_params=Depends(self.dataset_dependency),
pixel_selection=Depends(self.pixel_selection_dependency),
tile_params=Depends(self.tile_dependency),
post_process=Depends(self.process_dependency),
rescale=Depends(self.rescale_dependency),
color_formula=Depends(ColorFormulaParams),
colormap=Depends(self.colormap_dependency),
render_params=Depends(self.render_dependency),
backend_params=Depends(self.backend_dependency),
reader_params=Depends(self.reader_dependency),
env=Depends(self.environment_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)}"
tms = self.supported_tms.get(tileMatrixSetId)
return self.templates.TemplateResponse(
name="map.html",
context={
"request": request,
"tilejson_endpoint": tilejson_url,
"tms": tms,
"resolutions": [matrix.cellSize for matrix in tms],
"template": {
"api_root": str(request.base_url).rstrip("/"),
"params": request.query_params,
"title": "Map",
},
},
media_type="text/html",
)
def register_wmts(self): # noqa: C901
"""Add wmts endpoint."""
@self.router.get(
"/{tileMatrixSetId}/WMTSCapabilities.xml",
response_class=XMLResponse,
)
def wmts(
request: Request,
tileMatrixSetId: Annotated[
Literal[tuple(self.supported_tms.list())],
Path(
description="Identifier selecting one of the TileMatrixSetId supported"
),
],
search_query=Depends(self.search_dependency),
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,
):
"""OGC WMTS endpoint."""
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)
qs_key_to_remove = [
"tilematrixsetid",
"tile_format",
"tile_scale",
"minzoom",
"maxzoom",
"service",
"request",
]
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)}"
tms = self.supported_tms.get(tileMatrixSetId)
minzoom = minzoom if minzoom is not None else tms.minzoom
maxzoom = maxzoom if maxzoom is not None else tms.maxzoom
bounds = search_query.get("bbox") or 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)
return self.templates.TemplateResponse(
"wmts.xml",
{
"request": request,
"title": "STAC API",
"bounds": bounds,
"tileMatrix": tileMatrix,
"tms": tms,
"media_type": tile_format.mediatype,
},
media_type="application/xml",
)
class WMTSMediaType(str, Enum):
"""Responses Media types for WMTS"""
tif = "image/tiff; application=geotiff"
jp2 = "image/jp2"
png = "image/png"
jpeg = "image/jpeg"
jpg = "image/jpg"
webp = "image/webp"
@cached( # type: ignore
TTLCache(maxsize=cache_config.maxsize, ttl=cache_config.ttl),
key=lambda url, headers, supported_tms: hashkey(url, json.dumps(headers)),
)
def get_layer_from_collections( # noqa: C901
url: str,
headers: Optional[Dict] = None,
supported_tms: Optional[TileMatrixSets] = None,
) -> Dict[str, LayerDict]:
"""Get Layers from STAC Collections."""
supported_tms = supported_tms or morecantile_tms
stac_api_io = StacApiIO(
max_retries=Retry(
total=retry_config.retry,
backoff_factor=retry_config.retry_factor,
),
headers=headers,
)
catalog = Client.open(url, stac_io=stac_api_io)
layers: Dict[str, LayerDict] = {}
for collection in catalog.get_collections():
spatial_extent = collection.extent.spatial
temporal_extent = collection.extent.temporal
if "renders" in collection.extra_fields:
for name, render in collection.extra_fields["renders"].items():
tilematrixsets = render.pop("tilematrixsets", None)
output_format = render.pop("format", None)
_ = render.pop("minmax_zoom", None) # Not Used
_ = render.pop("title", None) # Not Used
# see https://github.com/developmentseed/eoAPI-vito/issues/9#issuecomment-2034025021
render_title = f"{collection.id}_{name}"
layer = {
"id": render_title,
"collection": collection.id,
"bbox": [-180, -90, 180, 90],
"style": "default",
"render": render,
}
if output_format:
layer["format"] = output_format
if spatial_extent:
layer["bbox"] = spatial_extent.bboxes[0]
# NB. The WMTS spec is contradictory re. the multiplicity
# relationships between Layer and TileMatrixSetLink, and
# TileMatrixSetLink and tileMatrixSet (URI).
# WMTS only support 1 set of limits for a TileMatrixSet
if tilematrixsets:
if len(tilematrixsets) == 1:
layer["tilematrixsets"] = {
tms_id: _tms_limits(
supported_tms.get(tms_id), layer["bbox"], zooms=zooms
)
for tms_id, zooms in tilematrixsets.items()
}
else:
layer["tilematrixsets"] = {
tms_id: None for tms_id, _ in tilematrixsets.items()
}
else:
tilematrixsets = supported_tms.list()
if len(tilematrixsets) == 1:
layer["tilematrixsets"] = {
tms_id: _tms_limits(
supported_tms.get(tms_id), layer["bbox"]
)
for tms_id in tilematrixsets
}
else:
layer["tilematrixsets"] = {
tms_id: None for tms_id in tilematrixsets
}
# TODO: handle multiple intervals
# Check datacube extension
# https://github.com/stac-extensions/datacube?tab=readme-ov-file#temporal-dimension-object
if intervals := temporal_extent.intervals:
start_date = intervals[0][0]
end_date = (
intervals[0][1]
if intervals[0][1]
else python_datetime.datetime.now(python_datetime.timezone.utc)
)
layer["time"] = [
(start_date + python_datetime.timedelta(days=x)).strftime(
"%Y-%m-%d"
)
for x in range(0, (end_date - start_date).days + 1)
]
render = layer["render"] or {}
# special encoding for rescale
# Per Specification, the rescale entry is a 2d array in form of `[[min, max], [min,max]]`
# We need to convert this to `['{min},{max}', '{min},{max}']` for titiler dependency
if rescale := render.pop("rescale", None):
rescales = []
for r in rescale:
if not isinstance(r, str):
rescales.append(",".join(map(str, r)))
else:
rescales.append(r)
render["rescale"] = rescales
# special encoding for ColorMaps
# Per Specification, the colormap is a JSON object. TiTiler dependency expects a string encoded dict
if colormap := render.pop("colormap", None):
if not isinstance(colormap, str):
colormap = json.dumps(colormap)
render["colormap"] = colormap
qs = urlencode(
[(k, v) for k, v in render.items() if v is not None],
doseq=True,
)
layer["query_string"] = str(qs)
layers[render_title] = LayerDict(
id=layer["id"],
collection=layer["collection"],
bbox=layer["bbox"],
format=layer.get("format"),
style=layer["style"],
render=layer.get("render", {}),
tilematrixsets=layer["tilematrixsets"],
time=layer.get("time"),
query_string=layer["query_string"],
)
return layers
@dataclass
class OGCWMTSFactory(BaseTilerFactory):
"""Create /wmts endpoint"""
path_dependency: Callable[..., APIParams] = STACApiParams
# In this factory, `reader` should be a Mosaic Backend
# https://developmentseed.org/cogeo-mosaic/advanced/backends/
reader: Type[BaseBackend] = STACAPIBackend
# Because the endpoints should work with STAC Items,
# the `layer_dependency` define which query parameters are mandatory/optional to `display` images
# Defaults to `titiler.core.dependencies.AssetsBidxExprParams`, `assets=` or `expression=` is required
layer_dependency: Type[DefaultDependency] = AssetsBidxExprParams
# The `tile_dependency` define options like `buffer` or `padding`
# used in Tile/Tilejson/WMTS Dependencies
tile_dependency: Type[DefaultDependency] = TileParams
pixel_selection_dependency: Callable[..., MosaicMethodBase] = PixelSelectionParams
backend_dependency: Type[DefaultDependency] = DefaultDependency
supported_format: List[str] = field(
default_factory=lambda: [
"image/png",
"image/jpeg",
"image/jpg",
"image/webp",
"image/jp2",
"image/tiff; application=geotiff",
]
)
supported_version: List[str] = field(default_factory=lambda: ["1.0.0"])
templates: Jinja2Templates = DEFAULT_TEMPLATES
def get_tile( # noqa: C901
self,
req: Dict,
layer: LayerDict,
stac_url: str,
headers: Optional[Dict] = None,
) -> ImageData:
"""Get Tile Data."""
layer_time = layer.get("time")
req_time = req.get("time")
if layer_time and "time" not in req:
raise HTTPException(
status_code=400,
detail=f"Missing TIME parameters for layer {layer['id']}",
)
if layer_time and req_time not in layer_time:
raise HTTPException(
status_code=400,
detail=f"Invalid 'TIME' parameter: {req_time}. Not available.",
)
tms_id = req["tilematrixset"]
if tms_id not in self.supported_tms.list():
raise HTTPException(
status_code=400,
detail=f"Invalid 'TILEMATRIXSET' parameter: {tms_id}. Should be one of {self.supported_tms.list()}.",
)
z = int(req["tilematrix"])
x = int(req["tilecol"])
y = int(req["tilerow"])
tms = self.supported_tms.get(tms_id)
with self.reader(
url=stac_url,
headers=headers,
tms=tms,
) 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}",
)
###########################################################
# STAC Query parameter provided by the the render extension and QueryParameters
###########################################################
search_query: Dict[str, Any] = {
"collections": [layer["collection"]],
}
if req_time:
start_datetime = python_datetime.datetime.strptime(
req_time,
"%Y-%m-%d",
).replace(tzinfo=python_datetime.timezone.utc)
end_datetime = start_datetime + python_datetime.timedelta(days=1)
search_query[
"datetime"
] = f"{start_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')}/{end_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')}"
query_params = layer.get("render") or {}
layer_params = get_dependency_params(
dependency=self.layer_dependency,
query_params=query_params,
)
tile_params = get_dependency_params(
dependency=self.tile_dependency,
query_params=query_params,
)
dataset_params = get_dependency_params(
dependency=self.dataset_dependency,
query_params=query_params,
)
pixel_selection = get_dependency_params(
dependency=self.pixel_selection_dependency,
query_params=query_params,
)
image, _ = src_dst.tile(
x,
y,
z,
# STAC Query Params
search_query=search_query,
pixel_selection=pixel_selection,
threads=MOSAIC_THREADS,
**tile_params,
**layer_params,
**dataset_params,
)
if post_process := get_dependency_params(
dependency=self.process_dependency,
query_params=query_params,
):
image = post_process(image)
if rescale := get_dependency_params(
dependency=self.rescale_dependency,
query_params=query_params,
):
image.rescale(rescale)
if color_formula := get_dependency_params(
dependency=self.color_formula_dependency,
query_params=query_params,
):
image.apply_color_formula(color_formula)
return image
def register_routes(self): # noqa: C901
"""Register endpoints."""
# WMTS - KPV Implementation
@self.router.get(
"/wmts",
response_class=Response,
responses={
200: {
"description": "Web Map Tile Server responses",
"content": {
"application/xml": {},
"application/geo+json": {"schema": FeatureInfo.schema()},
"image/png": {},
"image/jpeg": {},
"image/jpg": {},
"image/webp": {},
"image/jp2": {},
"image/tiff; application=geotiff": {},
},
},
},
openapi_extra={
"parameters": [
{
"required": True,
"schema": {
"title": "Operation name",
"type": "string",
"enum": ["GetCapabilities", "GetTile", "GetFeatureInfo"],
},
"name": "Request",
"in": "query",
},
{
"required": True,
"schema": {
"title": "Service type identifier",
"type": "string",
"enum": ["wmts"],
},
"name": "Service",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Standard and schema version",
"type": "string",
"enum": self.supported_version,
},
"name": "Version",
"in": "query",
},
{
"required": False,
"schema": {"title": "Layer identifier"},
"name": "Layer",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Output image format",
"type": "string",
"enum": self.supported_format,
},
"name": "Format",
"in": "query",
},
{
"required": False,
"schema": {"title": "Style identifier."},
"name": "Style",
"in": "query",
},
################
# GetTile
{
"required": False,
"schema": {
"title": "TileMatrixSet identifier.",
"type": "str",
"enum": self.supported_tms.list(),
},
"name": "TileMatrixSet",
"in": "query",
},
{
"required": False,
"schema": {
"title": "TileMatrix identifier",
"type": "integer",
},
"name": "TileMatrix",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Row index of tile matrix",
"type": "integer",
},
"name": "TileRow",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Column index of tile matrix",
"type": "integer",
},
"name": "TileCol",
"in": "query",
},
################
# GetFeatureInfo
# InfoFormat
{
"required": False,
"schema": {
"title": "Column index of a pixel in the tile",
"type": "integer",
},
"name": "I",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Row index of a pixel in the tile",
"type": "integer",
},
"name": "J",
"in": "query",
},
{
"required": False,
"schema": {
"title": "Output format of the retrieved information",
"type": "str",
"enum": ["application/geo+json"],
},
"name": "InfoFormat",
"in": "query",
},
# TIME dimension
{
"required": False,
"schema": {
"title": "Time value of layer desired.",
"type": "string",
},
"name": "Time",