|
| 1 | +"""TiTiler.xarray factory.""" |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Dict, List, Literal, Optional, Tuple, Type |
| 5 | +from urllib.parse import urlencode |
| 6 | + |
| 7 | +import xarray |
| 8 | +from fastapi import Depends, Path, Query |
| 9 | +from rio_tiler.io import BaseReader, XarrayReader |
| 10 | +from rio_tiler.models import Info |
| 11 | +from starlette.requests import Request |
| 12 | +from starlette.responses import HTMLResponse, Response |
| 13 | + |
| 14 | +from titiler.core.dependencies import RescalingParams |
| 15 | +from titiler.core.factory import BaseTilerFactory, img_endpoint_params, templates |
| 16 | +from titiler.core.models.mapbox import TileJSON |
| 17 | +from titiler.core.resources.enums import ImageType |
| 18 | +from titiler.core.resources.responses import JSONResponse |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class XarrayTilerFactory(BaseTilerFactory): |
| 23 | + """Xarray Tiler Factory.""" |
| 24 | + |
| 25 | + # Default reader is set to rio_tiler.io.Reader |
| 26 | + reader: Type[BaseReader] = XarrayReader |
| 27 | + |
| 28 | + def register_routes(self) -> None: # noqa: C901 |
| 29 | + """Register Info / Tiles / TileJSON endoints.""" |
| 30 | + |
| 31 | + @self.router.get( |
| 32 | + "/variables", |
| 33 | + response_class=JSONResponse, |
| 34 | + responses={200: {"description": "Return dataset's Variables."}}, |
| 35 | + ) |
| 36 | + def variable_endpoint( |
| 37 | + src_path: str = Depends(self.path_dependency), |
| 38 | + ) -> List[str]: |
| 39 | + """return available variables.""" |
| 40 | + with xarray.open_dataset( |
| 41 | + src_path, engine="zarr", decode_coords="all" |
| 42 | + ) as src: |
| 43 | + return list(src.data_vars) # type: ignore |
| 44 | + |
| 45 | + @self.router.get( |
| 46 | + "/info", |
| 47 | + response_model=Info, |
| 48 | + response_model_exclude_none=True, |
| 49 | + response_class=JSONResponse, |
| 50 | + responses={200: {"description": "Return dataset's basic info."}}, |
| 51 | + ) |
| 52 | + def info_endpoint( |
| 53 | + src_path: str = Depends(self.path_dependency), |
| 54 | + variable: str = Query(..., description="Xarray Variable"), |
| 55 | + show_times: bool = Query( |
| 56 | + None, description="Show info about the time dimension" |
| 57 | + ), |
| 58 | + ) -> Info: |
| 59 | + """Return dataset's basic info.""" |
| 60 | + show_times = show_times or False |
| 61 | + |
| 62 | + with xarray.open_dataset( |
| 63 | + src_path, engine="zarr", decode_coords="all" |
| 64 | + ) as src: |
| 65 | + ds = src[variable] |
| 66 | + times = [] |
| 67 | + if "time" in ds.dims: |
| 68 | + times = [str(x.data) for x in ds.time] |
| 69 | + # To avoid returning huge a `band_metadata` and `band_descriptions` |
| 70 | + # we only return info of the first time slice |
| 71 | + ds = src[variable][0] |
| 72 | + |
| 73 | + # Make sure we are a CRS |
| 74 | + crs = ds.rio.crs or "epsg:4326" |
| 75 | + ds.rio.write_crs(crs, inplace=True) |
| 76 | + |
| 77 | + with self.reader(ds) as dst: |
| 78 | + info = dst.info().dict() |
| 79 | + |
| 80 | + if times and show_times: |
| 81 | + info["count"] = len(times) |
| 82 | + info["times"] = times |
| 83 | + |
| 84 | + return info |
| 85 | + |
| 86 | + @self.router.get(r"/tiles/{z}/{x}/{y}", **img_endpoint_params) |
| 87 | + @self.router.get(r"/tiles/{z}/{x}/{y}.{format}", **img_endpoint_params) |
| 88 | + @self.router.get(r"/tiles/{z}/{x}/{y}@{scale}x", **img_endpoint_params) |
| 89 | + @self.router.get(r"/tiles/{z}/{x}/{y}@{scale}x.{format}", **img_endpoint_params) |
| 90 | + @self.router.get(r"/tiles/{TileMatrixSetId}/{z}/{x}/{y}", **img_endpoint_params) |
| 91 | + @self.router.get( |
| 92 | + r"/tiles/{TileMatrixSetId}/{z}/{x}/{y}.{format}", **img_endpoint_params |
| 93 | + ) |
| 94 | + @self.router.get( |
| 95 | + r"/tiles/{TileMatrixSetId}/{z}/{x}/{y}@{scale}x", **img_endpoint_params |
| 96 | + ) |
| 97 | + @self.router.get( |
| 98 | + r"/tiles/{TileMatrixSetId}/{z}/{x}/{y}@{scale}x.{format}", |
| 99 | + **img_endpoint_params, |
| 100 | + ) |
| 101 | + def tiles_endpoint( # type: ignore |
| 102 | + z: int = Path(..., ge=0, le=30, description="TileMatrixSet zoom level"), |
| 103 | + x: int = Path(..., description="TileMatrixSet column"), |
| 104 | + y: int = Path(..., description="TileMatrixSet row"), |
| 105 | + TileMatrixSetId: Literal[ # type: ignore |
| 106 | + tuple(self.supported_tms.list()) |
| 107 | + ] = Query( |
| 108 | + self.default_tms, |
| 109 | + description=f"TileMatrixSet Name (default: '{self.default_tms}')", |
| 110 | + ), |
| 111 | + scale: int = Query( |
| 112 | + 1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." |
| 113 | + ), |
| 114 | + format: ImageType = Query( |
| 115 | + None, description="Output image type. Default is auto." |
| 116 | + ), |
| 117 | + src_path: str = Depends(self.path_dependency), |
| 118 | + variable: str = Query(..., description="Xarray Variable"), |
| 119 | + time_slice: int = Query( |
| 120 | + None, description="Slice of time to read (if available)" |
| 121 | + ), |
| 122 | + post_process=Depends(self.process_dependency), |
| 123 | + rescale: Optional[List[Tuple[float, ...]]] = Depends(RescalingParams), |
| 124 | + color_formula: Optional[str] = Query( |
| 125 | + None, |
| 126 | + title="Color Formula", |
| 127 | + description=( |
| 128 | + "rio-color formula (info: https://github.com/mapbox/rio-color)" |
| 129 | + ), |
| 130 | + ), |
| 131 | + colormap=Depends(self.colormap_dependency), |
| 132 | + render_params=Depends(self.render_dependency), |
| 133 | + ) -> Response: |
| 134 | + """Create map tile from a dataset.""" |
| 135 | + tms = self.supported_tms.get(TileMatrixSetId) |
| 136 | + |
| 137 | + with xarray.open_dataset( |
| 138 | + src_path, engine="zarr", decode_coords="all" |
| 139 | + ) as src: |
| 140 | + ds = src[variable] |
| 141 | + if "time" in ds.dims: |
| 142 | + time_slice = time_slice or 0 |
| 143 | + ds = ds[time_slice : time_slice + 1] |
| 144 | + |
| 145 | + # Make sure we are a CRS |
| 146 | + crs = ds.rio.crs or "epsg:4326" |
| 147 | + ds.rio.write_crs(crs, inplace=True) |
| 148 | + |
| 149 | + with self.reader(ds, tms=tms) as dst: |
| 150 | + image = dst.tile( |
| 151 | + x, |
| 152 | + y, |
| 153 | + z, |
| 154 | + tilesize=scale * 256, |
| 155 | + ) |
| 156 | + |
| 157 | + if post_process: |
| 158 | + image = post_process(image) |
| 159 | + |
| 160 | + if rescale: |
| 161 | + image.rescale(rescale) |
| 162 | + |
| 163 | + if color_formula: |
| 164 | + image.apply_color_formula(color_formula) |
| 165 | + |
| 166 | + if colormap: |
| 167 | + image = image.apply_colormap(colormap) |
| 168 | + |
| 169 | + if not format: |
| 170 | + format = ImageType.jpeg if image.mask.all() else ImageType.png |
| 171 | + |
| 172 | + content = image.render( |
| 173 | + img_format=format.driver, |
| 174 | + **format.profile, |
| 175 | + **render_params, |
| 176 | + ) |
| 177 | + |
| 178 | + return Response(content, media_type=format.mediatype) |
| 179 | + |
| 180 | + @self.router.get( |
| 181 | + "/tilejson.json", |
| 182 | + response_model=TileJSON, |
| 183 | + responses={200: {"description": "Return a tilejson"}}, |
| 184 | + response_model_exclude_none=True, |
| 185 | + ) |
| 186 | + @self.router.get( |
| 187 | + "/{TileMatrixSetId}/tilejson.json", |
| 188 | + response_model=TileJSON, |
| 189 | + responses={200: {"description": "Return a tilejson"}}, |
| 190 | + response_model_exclude_none=True, |
| 191 | + ) |
| 192 | + def tilejson_endpoint( # type: ignore |
| 193 | + request: Request, |
| 194 | + TileMatrixSetId: Literal[ # type: ignore |
| 195 | + tuple(self.supported_tms.list()) |
| 196 | + ] = Query( |
| 197 | + self.default_tms, |
| 198 | + description=f"TileMatrixSet Name (default: '{self.default_tms}')", |
| 199 | + ), |
| 200 | + src_path: str = Depends(self.path_dependency), |
| 201 | + variable: str = Query(..., description="Xarray Variable"), |
| 202 | + time_slice: int = Query( |
| 203 | + None, description="Slice of time to read (if available)" |
| 204 | + ), # noqa |
| 205 | + tile_format: Optional[ImageType] = Query( |
| 206 | + None, description="Output image type. Default is auto." |
| 207 | + ), |
| 208 | + tile_scale: int = Query( |
| 209 | + 1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." |
| 210 | + ), |
| 211 | + minzoom: Optional[int] = Query( |
| 212 | + None, description="Overwrite default minzoom." |
| 213 | + ), |
| 214 | + maxzoom: Optional[int] = Query( |
| 215 | + None, description="Overwrite default maxzoom." |
| 216 | + ), |
| 217 | + post_process=Depends(self.process_dependency), # noqa |
| 218 | + rescale: Optional[List[Tuple[float, ...]]] = Depends( |
| 219 | + RescalingParams |
| 220 | + ), # noqa |
| 221 | + color_formula: Optional[str] = Query( # noqa |
| 222 | + None, |
| 223 | + title="Color Formula", |
| 224 | + description=( |
| 225 | + "rio-color formula (info: https://github.com/mapbox/rio-color)" |
| 226 | + ), |
| 227 | + ), |
| 228 | + colormap=Depends(self.colormap_dependency), # noqa |
| 229 | + render_params=Depends(self.render_dependency), # noqa |
| 230 | + ) -> Dict: |
| 231 | + """Return TileJSON document for a dataset.""" |
| 232 | + route_params = { |
| 233 | + "z": "{z}", |
| 234 | + "x": "{x}", |
| 235 | + "y": "{y}", |
| 236 | + "scale": tile_scale, |
| 237 | + "TileMatrixSetId": TileMatrixSetId, |
| 238 | + } |
| 239 | + if tile_format: |
| 240 | + route_params["format"] = tile_format.value |
| 241 | + tiles_url = self.url_for(request, "tiles_endpoint", **route_params) |
| 242 | + |
| 243 | + qs_key_to_remove = [ |
| 244 | + "tilematrixsetid", |
| 245 | + "tile_format", |
| 246 | + "tile_scale", |
| 247 | + "minzoom", |
| 248 | + "maxzoom", |
| 249 | + ] |
| 250 | + qs = [ |
| 251 | + (key, value) |
| 252 | + for (key, value) in request.query_params._list |
| 253 | + if key.lower() not in qs_key_to_remove |
| 254 | + ] |
| 255 | + if qs: |
| 256 | + tiles_url += f"?{urlencode(qs)}" |
| 257 | + |
| 258 | + tms = self.supported_tms.get(TileMatrixSetId) |
| 259 | + |
| 260 | + with xarray.open_dataset( |
| 261 | + src_path, engine="zarr", decode_coords="all" |
| 262 | + ) as src: |
| 263 | + ds = src[variable] |
| 264 | + |
| 265 | + # Make sure we are a CRS |
| 266 | + crs = ds.rio.crs or "epsg:4326" |
| 267 | + ds.rio.write_crs(crs, inplace=True) |
| 268 | + |
| 269 | + with self.reader(ds, tms=tms) as src_dst: |
| 270 | + return { |
| 271 | + "bounds": src_dst.geographic_bounds, |
| 272 | + "minzoom": minzoom if minzoom is not None else src_dst.minzoom, |
| 273 | + "maxzoom": maxzoom if maxzoom is not None else src_dst.maxzoom, |
| 274 | + "tiles": [tiles_url], |
| 275 | + } |
| 276 | + |
| 277 | + @self.router.get("/map", response_class=HTMLResponse) |
| 278 | + @self.router.get("/{TileMatrixSetId}/map", response_class=HTMLResponse) |
| 279 | + def map_viewer( |
| 280 | + request: Request, |
| 281 | + TileMatrixSetId: Literal[tuple(self.supported_tms.list())] = Query( # type: ignore |
| 282 | + self.default_tms, |
| 283 | + description=f"TileMatrixSet Name (default: '{self.default_tms}')", |
| 284 | + ), # noqa |
| 285 | + src_path=Depends(self.path_dependency), # noqa |
| 286 | + variable: str = Query(..., description="Xarray Variable"), # noqa |
| 287 | + time_slice: int = Query( |
| 288 | + None, description="Slice of time to read (if available)" |
| 289 | + ), # noqa |
| 290 | + tile_format: Optional[ImageType] = Query( |
| 291 | + None, description="Output image type. Default is auto." |
| 292 | + ), # noqa |
| 293 | + tile_scale: int = Query( |
| 294 | + 1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." |
| 295 | + ), # noqa |
| 296 | + minzoom: Optional[int] = Query( |
| 297 | + None, description="Overwrite default minzoom." |
| 298 | + ), # noqa |
| 299 | + maxzoom: Optional[int] = Query( |
| 300 | + None, description="Overwrite default maxzoom." |
| 301 | + ), # noqa |
| 302 | + layer_params=Depends(self.layer_dependency), # noqa |
| 303 | + dataset_params=Depends(self.dataset_dependency), # noqa |
| 304 | + post_process=Depends(self.process_dependency), # noqa |
| 305 | + rescale: Optional[List[Tuple[float, ...]]] = Depends( |
| 306 | + RescalingParams |
| 307 | + ), # noqa |
| 308 | + color_formula: Optional[str] = Query( # noqa |
| 309 | + None, |
| 310 | + title="Color Formula", |
| 311 | + description="rio-color formula (info: https://github.com/mapbox/rio-color)", |
| 312 | + ), |
| 313 | + colormap=Depends(self.colormap_dependency), # noqa |
| 314 | + render_params=Depends(self.render_dependency), # noqa |
| 315 | + reader_params=Depends(self.reader_dependency), # noqa |
| 316 | + env=Depends(self.environment_dependency), # noqa |
| 317 | + ): |
| 318 | + """Return map Viewer.""" |
| 319 | + tilejson_url = self.url_for( |
| 320 | + request, "tilejson_endpoint", TileMatrixSetId=TileMatrixSetId |
| 321 | + ) |
| 322 | + if request.query_params._list: |
| 323 | + tilejson_url += f"?{urlencode(request.query_params._list)}" |
| 324 | + |
| 325 | + tms = self.supported_tms.get(TileMatrixSetId) |
| 326 | + return templates.TemplateResponse( |
| 327 | + name="index.html", |
| 328 | + context={ |
| 329 | + "request": request, |
| 330 | + "tilejson_endpoint": tilejson_url, |
| 331 | + "tms": tms, |
| 332 | + "resolutions": [tms._resolution(matrix) for matrix in tms], |
| 333 | + }, |
| 334 | + media_type="text/html", |
| 335 | + ) |
0 commit comments