Skip to content

Commit

Permalink
update to latest titiler
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Jul 27, 2023
1 parent e9ca713 commit 2620b6d
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 118 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ repos:
args: ["--fix"]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
rev: v1.3.0
hooks:
- id: mypy
language_version: python
Expand Down
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@

# 0.11.0 (2023-07-27)

* update titiler requirement to `>=0.13,<0.14`

# 0.10.3 (2023-03-22)

* switch `/map` viewer to maplibre
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ $ pip install -e .["test,dev"]
You can then run the tests with the following command:

```sh
python -m pytest --cov rio-viz --cov-report term-missing
python -m pytest --cov rio_viz --cov-report term-missing
```

**pre-commit**
Expand Down
7 changes: 3 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ classifiers = [
dynamic = ["version"]
dependencies = [
"braceexpand",
"rio-cogeo>=3.1",
"rio-tiler>=4.1.6,<5.0",
"titiler.core>=0.10.1,<0.12",
"rio-cogeo>=5.0",
"rio-tiler>=6.0,<7.0",
"titiler.core>=0.13.0,<0.14",
"starlette-cramjam>=0.3,<0.4",
"uvicorn",
"server-thread>=0.2.0",
"fastapi<0.95",
]

[project.optional-dependencies]
Expand Down
208 changes: 104 additions & 104 deletions rio_viz/app.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
"""rio_viz app."""

import pathlib
import sys
import urllib.parse
from typing import Any, Dict, List, Optional, Tuple, Type, Union
from typing import Any, Dict, List, Literal, Optional, Tuple, Type, Union

import attr
import rasterio
import uvicorn
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Path, Query
from geojson_pydantic.features import Feature
from rio_tiler.io import BaseReader, COGReader, MultiBandReader, MultiBaseReader
from rio_tiler.io import BaseReader, MultiBandReader, MultiBaseReader, Reader
from rio_tiler.models import BandStatistics, Info
from server_thread import ServerManager, ServerThread
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse, Response
from starlette.templating import Jinja2Templates
from starlette.types import ASGIApp
from starlette_cramjam.middleware import CompressionMiddleware
from typing_extensions import Annotated

from rio_viz.resources.enums import RasterFormat, VectorTileFormat, VectorTileType
from rio_viz.resources.enums import RasterFormat, VectorTileFormat

from titiler.core.dependencies import (
AssetsBidxExprParamsOptional,
Expand All @@ -39,6 +40,7 @@
StatisticsParams,
)
from titiler.core.errors import DEFAULT_STATUS_CODES, add_exception_handlers
from titiler.core.middleware import CacheControlMiddleware
from titiler.core.models.mapbox import TileJSON
from titiler.core.resources.responses import JSONResponse, XMLResponse

Expand All @@ -56,35 +58,14 @@
TileFormat = Union[RasterFormat, VectorTileFormat]


class CacheControlMiddleware(BaseHTTPMiddleware):
"""MiddleWare to add CacheControl in response headers."""

def __init__(self, app: ASGIApp, cachecontrol: str = "no-cache") -> None:
"""Init Middleware."""
super().__init__(app)
self.cachecontrol = cachecontrol

async def dispatch(self, request: Request, call_next):
"""Add cache-control."""
response = await call_next(request)
if (
not response.headers.get("Cache-Control")
and self.cachecontrol
and request.method in ["HEAD", "GET"]
and response.status_code < 500
):
response.headers["Cache-Control"] = self.cachecontrol
return response


@attr.s
class viz:
"""Creates a very minimal slippy map tile server using fastAPI + Uvicorn."""

src_path: str = attr.ib()
reader: Union[
Type[BaseReader], Type[MultiBandReader], Type[MultiBaseReader]
] = attr.ib(default=COGReader)
] = attr.ib(default=Reader)

app: FastAPI = attr.ib(default=attr.Factory(FastAPI))

Expand Down Expand Up @@ -119,7 +100,7 @@ def __attrs_post_init__(self):
self.reader_type = "cog"

if self.reader_type == "cog":
# For simple BaseReader (e.g COGReader) we don't add more dependencies.
# For simple BaseReader (e.g Reader) we don't add more dependencies.
self.info_dependency = DefaultDependency
self.statistics_dependency = BidxExprParams
self.layer_dependency = BidxExprParams
Expand Down Expand Up @@ -159,7 +140,7 @@ def register_middleware(self):
allow_methods=["GET"],
allow_headers=["*"],
)
self.app.add_middleware(CacheControlMiddleware)
self.app.add_middleware(CacheControlMiddleware, cachecontrol="no-cache")

def _update_params(self, src_dst, options: Type[DefaultDependency]):
"""Create Reader options."""
Expand Down Expand Up @@ -251,9 +232,10 @@ def statistics(
tags=["API"],
)
def point(
coordinates: str = Query(
..., description="Coma (',') delimited lon,lat coordinates"
),
coordinates: Annotated[
str,
Query(description="Coma (',') delimited lon,lat coordinates"),
],
layer_params=Depends(self.layer_dependency),
dataset_params: DatasetParams = Depends(),
):
Expand Down Expand Up @@ -364,9 +346,10 @@ def part(
miny: float = Path(..., description="Bounding box min Y"),
maxx: float = Path(..., description="Bounding box max X"),
maxy: float = Path(..., description="Bounding box max Y"),
format: RasterFormat = Query(
RasterFormat.png, description="Output image type."
),
format: Annotated[
RasterFormat,
"Output image type.",
] = RasterFormat.png,
layer_params=Depends(self.layer_dependency),
img_params: ImageParams = Depends(),
dataset_params: DatasetParams = Depends(),
Expand Down Expand Up @@ -430,9 +413,7 @@ def part(
)
def geojson_part(
geom: Feature,
format: Optional[RasterFormat] = Query(
None, description="Output image type."
),
format: Annotated[Optional[RasterFormat], "Output image type."] = None,
layer_params=Depends(self.layer_dependency),
img_params: ImageParams = Depends(),
dataset_params: DatasetParams = Depends(),
Expand All @@ -454,7 +435,7 @@ def geojson_part(
self._update_params(src_dst, layer_params)

image = src_dst.feature(
geom.dict(exclude_none=True), **layer_params, **dataset_params
geom.model_dump(exclude_none=True), **layer_params, **dataset_params
)
dst_colormap = getattr(src_dst, "colormap", None)

Expand Down Expand Up @@ -495,21 +476,23 @@ def tile(
z: int,
x: int,
y: int,
format: Optional[TileFormat] = None,
format: Annotated[TileFormat, "Output tile type."] = None,
layer_params=Depends(self.layer_dependency),
dataset_params: DatasetParams = Depends(),
render_params: ImageRenderingParams = Depends(),
rescale: Optional[List[Tuple[float, ...]]] = Depends(RescalingParams),
color_formula: Optional[str] = Query(
None,
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
rescale: RescalingParams = Depends(),
color_formula: Annotated[
Optional[str],
Query(
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
] = None,
colormap: ColorMapParams = Depends(),
feature_type: Optional[VectorTileType] = Query(
None,
title="Feature type (Only for MVT)",
),
feature_type: Annotated[
Optional[Literal["point", "polygon"]],
Query(title="Feature type (Only for MVT)"),
] = None,
tilesize: Optional[int] = Query(None, description="Tile Size."),
):
"""Handle /tiles requests."""
Expand Down Expand Up @@ -556,7 +539,7 @@ def tile(
image.data,
image.mask,
image.band_names,
feature_type=feature_type.value,
feature_type=feature_type,
)

# Raster Tile
Expand Down Expand Up @@ -590,23 +573,30 @@ def tile(
)
def tilejson(
request: Request,
tile_format: Optional[TileFormat] = None,
layer_params=Depends(self.layer_dependency), # noqa
dataset_params: DatasetParams = Depends(), # noqa
render_params: ImageRenderingParams = Depends(), # noqa
rescale: Optional[List[Tuple[float, ...]]] = Depends(
RescalingParams
), # noqa
color_formula: Optional[str] = Query( # noqa
None,
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
tile_format: Annotated[
Optional[TileFormat],
"Output tile type.",
] = None,
layer_params=Depends(self.layer_dependency),
dataset_params: DatasetParams = Depends(),
render_params: ImageRenderingParams = Depends(),
rescale: RescalingParams = Depends(),
color_formula: Annotated[
Optional[str],
Query(
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
] = None,
colormap: ColorMapParams = Depends(), # noqa
feature_type: str = Query( # noqa
None, title="Feature type", regex="^(point)|(polygon)$"
),
tilesize: Optional[int] = Query(None, description="Tile Size."),
feature_type: Annotated[
Optional[Literal["point", "polygon"]],
Query(title="Feature type (Only for MVT)"),
] = None,
tilesize: Annotated[
Optional[int],
Query(description="Tile Size."),
] = None,
):
"""Handle /tilejson.json requests."""
kwargs: Dict[str, Any] = {"z": "{z}", "x": "{x}", "y": "{y}"}
Expand Down Expand Up @@ -646,30 +636,34 @@ def tilejson(
)
def wmts(
request: Request,
tile_format: RasterFormat = Query(
RasterFormat.png, description="Output image type. Default is png."
),
layer_params=Depends(self.layer_dependency), # noqa
dataset_params: DatasetParams = Depends(), # noqa
buffer: Optional[float] = Query( # noqa
None,
gt=0,
title="Tile buffer.",
description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * tile_buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
),
render_params: ImageRenderingParams = Depends(), # noqa
rescale: Optional[List[Tuple[float, ...]]] = Depends(
RescalingParams
), # noqa
color_formula: Optional[str] = Query( # noqa
None,
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
colormap: ColorMapParams = Depends(), # noqa
feature_type: str = Query( # noqa
None, title="Feature type", regex="^(point)|(polygon)$"
),
tile_format: Annotated[
TileFormat,
Query(description="Output image type. Default is png."),
] = RasterFormat.png,
layer_params=Depends(self.layer_dependency),
dataset_params: DatasetParams = Depends(),
buffer: Annotated[
Optional[float],
Query(
gt=0,
title="Tile buffer.",
description="Buffer on each side of the given tile. It must be a multiple of `0.5`. Output **tilesize** will be expanded to `tilesize + 2 * buffer` (e.g 0.5 = 257x257, 1.0 = 258x258).",
),
] = None,
render_params: ImageRenderingParams = Depends(),
rescale: RescalingParams = Depends(),
color_formula: Annotated[
Optional[str],
Query(
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
] = None,
colormap: ColorMapParams = Depends(),
feature_type: Annotated[
Optional[Literal["point", "polygon"]],
Query(title="Feature type (Only for MVT)"),
] = None,
):
"""
This is a hidden gem.
Expand Down Expand Up @@ -733,20 +727,26 @@ def wmts(
@self.router.get("/map", response_class=HTMLResponse)
def map_viewer(
request: Request,
tile_format: Optional[TileFormat] = None, # noqa
layer_params=Depends(self.layer_dependency), # noqa
dataset_params: DatasetParams = Depends(), # noqa
render_params: ImageRenderingParams = Depends(), # noqa
rescale: Optional[List[Tuple[float, ...]]] = Depends(
RescalingParams
), # noqa
color_formula: Optional[str] = Query( # noqa
None,
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
colormap: ColorMapParams = Depends(), # noqa
tilesize: Optional[int] = Query(None, description="Tile Size."), # noqa
tile_format: Annotated[
Optional[RasterFormat],
Query(description="Output raster tile type."),
] = None,
layer_params=Depends(self.layer_dependency),
dataset_params: DatasetParams = Depends(),
render_params: ImageRenderingParams = Depends(),
rescale: RescalingParams = Depends(),
color_formula: Annotated[
Optional[str],
Query(
title="Color Formula",
description="rio-color formula (info: https://github.com/mapbox/rio-color)",
),
] = None,
colormap: ColorMapParams = Depends(),
tilesize: Annotated[
Optional[int],
Query(description="Tile Size."),
] = None,
):
"""Return a simple map viewer."""
tilejson_url = str(request.url_for("tilejson"))
Expand Down
2 changes: 1 addition & 1 deletion rio_viz/io/mosaic.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def info(self) -> Info:
info_metadata = (
self.datasets[item]
.info()
.dict(
.model_dump(
exclude={
"bounds",
"minzoom",
Expand Down
7 changes: 0 additions & 7 deletions rio_viz/resources/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,3 @@ class VectorTileFormat(DataFormat):

pbf = "pbf"
mvt = "mvt"


class VectorTileType(str, Enum):
"""Available Output Vector Tile type."""

point = "point"
polygon = "polygon"

0 comments on commit 2620b6d

Please sign in to comment.