Skip to content

replace shapely with geojson-pydantic  #227

@vincentsarago

Description

@vincentsarago

def bounds(
self, projection: str = "EPSG:4326", return_polygon: bool = False, return_wkt: bool = False
):
bounds = get_source_bounds(self.reader, projection=projection)
extent = (bounds["bottom"], bounds["top"], bounds["left"], bounds["right"])
if not return_polygon and not return_wkt:
return extent
# Safely import shapely
try:
from shapely.geometry import Polygon
except ImportError as e: # pragma: no cover
raise ImportError(f"Please install `shapely`: {e}")
coords = (
(bounds["left"], bounds["top"]),
(bounds["left"], bounds["top"]),
(bounds["right"], bounds["top"]),
(bounds["right"], bounds["bottom"]),
(bounds["left"], bounds["bottom"]),
(bounds["left"], bounds["top"]), # Close the loop
)
poly = Polygon(coords)
if return_wkt:
return poly.wkt
return poly

with geojson-pydantic (which only depends on pydantic, which you already depends on with rio-tiler) you could do

from geojson_pydantic import Polygon

def bounds(
    self, projection: str = "EPSG:4326", return_polygon: bool = False, return_wkt: bool = False
):
    bounds = get_source_bounds(self.reader, projection=projection)
    extent = (bounds["bottom"], bounds["top"], bounds["left"], bounds["right"])
    if not return_polygon and not return_wkt:
        return extent
    
    poly = Polygon.from_bounds(*extent)
    if return_wkt:
        return poly.wkt
    
    return poly

the only thing geojson-pydantic won't cover is the from_wkt in

def parse_shapely(context):
"""Convert GeoJSON-like or WKT to shapely object.
Parameters
----------
context : str, dict
a GeoJSON-like dict, which provides a "type" member describing the type
of the geometry and "coordinates" member providing a list of coordinates,
or an object which implements __geo_interface__.
If a string, falls back to inferring as Well Known Text (WKT).
"""
try:
from shapely.geometry import shape
import shapely.wkb
import shapely.wkt
except ImportError as e: # pragma: no cover
raise ImportError(f"Please install `shapely`: {e}")
if isinstance(context, str):
# Infer as WKT
return shapely.wkt.loads(context)
elif isinstance(context, bytes):
# Infer as WKB
return shapely.wkb.loads(context)
return shape(context)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions