Utilities#

Colormap & Palettes#

localtileserver.tiler.palettes.get_palettes()#

Return the available color palettes.

Returns:

Dictionary mapping palette source names to lists of colormap names.

Return type:

dict

localtileserver.tiler.palettes.register_colormap(colormap_data: dict) str#

Register a custom colormap and return its hash key.

Parameters:

colormap_data (dict) – Colormap as {int: (r, g, b, a)} dict.

Returns:

Hash key for the registered colormap (e.g., "custom:abc123def456").

Return type:

str

localtileserver.tiler.palettes.get_registered_colormap(key: str) dict | None#

Look up a registered colormap by its custom:<hash> key.

Parameters:

key (str) – The full custom:<hash> key returned by register_colormap().

Returns:

The colormap dictionary, or None if the key is not in the registry.

Return type:

dict or None

localtileserver.tiler.palettes.palette_valid_or_raise(name: str)#

Validate that a palette name is available, raising on failure.

Parameters:

name (str) – Colormap name to validate. May be a custom:<hash> key or a rio-tiler colormap name.

Raises:

ValueError – If the colormap name is not found in the registry or rio-tiler.

Helpers#

class localtileserver.tiler.utilities.ImageBytes(source: bytes, mimetype: str | None = None)#

Wrapper around bytes for improved image representation in IPython.

Accepts source (raw image bytes) and an optional mimetype (e.g., "image/png") to enable rich display in Jupyter notebooks.

property mimetype#

Return the MIME type of the image.

Returns:

The MIME type string, or None if not set.

Return type:

str or None

localtileserver.helpers.hillshade(arr, azimuth=30, altitude=30)#

Create hillshade from a numpy array containing elevation data.

Originally sourced from earthpy (BSD 3-Clause, Copyright (c) 2018 Earth Lab).

Parameters:
  • arr (numpy.ndarray) – Numpy array of shape (rows, columns) with elevation values to be used to create the hillshade.

  • azimuth (float, optional) – The desired azimuth for the hillshade. Default is 30.

  • altitude (float, optional) – The desired sun angle altitude for the hillshade. Default is 30.

Returns:

A numpy array containing hillshade values.

Return type:

numpy.ndarray

localtileserver.helpers.save_new_raster(src, data, out_path: str | None = None)#

Save new raster from a numpy array using the metadata of another raster.

Parameters:
  • src (str or rasterio.io.DatasetReaderBase or TilerInterface) – The source rasterio data whose spatial reference will be copied.

  • data (numpy.ndarray) – The bands of data to save to the new raster.

  • out_path (str or None, optional) – The path for which to write the new raster. If None, this will use a temporary file.

Returns:

The path to the written raster file.

Return type:

str or pathlib.Path

localtileserver.helpers.parse_shapely(context)#

Convert GeoJSON-like or WKT to shapely object.

Parameters:

context (str or bytes or 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). If bytes, falls back to inferring as Well Known Binary (WKB).

Returns:

The parsed shapely geometry object.

Return type:

shapely.geometry.BaseGeometry

localtileserver.helpers.polygon_to_geojson(polygon) str#

Dump a shapely Polygon to a GeoJSON string.

Parameters:

polygon (shapely.geometry.Polygon) – The shapely polygon to convert.

Returns:

A GeoJSON-formatted string containing the polygon as a Feature.

Return type:

str

localtileserver.helpers.numpy_to_raster(ras_meta, data, out_path: str | None = None)#

Save new raster from a numpy array using the metadata of another raster.

Parameters:
  • ras_meta (dict) – Raster metadata.

  • data (numpy.ndarray) – The bands of data to save to the new raster.

  • out_path (str or None, optional) – The path for which to write the new raster. If None, this will use a temporary file.

Returns:

The path to the written raster file.

Return type:

str or pathlib.Path

localtileserver.validate.validate_cog(path: str | Reader | TilerInterface, strict: bool = True, quiet: bool = False) bool#

Validate whether a raster file is a valid Cloud Optimized GeoTIFF (COG).

Parameters:
  • path (str or Reader or TilerInterface) – The path to the raster file, or an open rio_tiler.io.Reader or TilerInterface instance.

  • strict (bool, optional) – Whether to use strict validation rules. Default is True.

  • quiet (bool, optional) – Whether to suppress validation output. Default is False.

Returns:

True if the file is a valid COG, False otherwise.

Return type:

bool

localtileserver.tiler.utilities.make_vsi(url: str, **options)#

Build a GDAL virtual filesystem (VSI) path from a URL.

S3 URLs are converted to /vsis3/ paths; all other URLs are converted to /vsicurl? paths with sensible defaults.

Parameters:
  • url (str) – The source URL (http://, https://, or s3://).

  • **options (dict) – Additional key-value pairs appended to the /vsicurl query string. Ignored for S3 URLs.

Returns:

A GDAL-compatible VSI path string.

Return type:

str

localtileserver.tiler.utilities.format_to_encoding(fmt: str | None) str#

Validate encoding and return the canonical GDAL format string.

Supported formats: png, jpeg/jpg, webp, tif/tiff/geotiff, npy.

Parameters:

fmt (str or None) – A short format name (case-insensitive). If None or empty, defaults to "png".

Returns:

The canonical GDAL driver name (e.g., "PNG", "JPEG", "GTiff").

Return type:

str

Raises:

ValueError – If fmt is not a recognised format name.

localtileserver.tiler.utilities.get_clean_filename(filename: str)#

Resolve a filename to a local path or GDAL virtual filesystem path.

Built-in example dataset names (e.g., "blue_marble", "bahamas") are expanded to their bundled data paths. Remote URLs are converted to GDAL VSI paths, and local paths are resolved to absolute pathlib.Path objects.

Parameters:

filename (str) – A local file path, a remote URL, a GDAL driver prefix string, or a built-in example dataset name.

Returns:

A GDAL-compatible VSI string for remote sources and GDAL driver prefixes, or an absolute pathlib.Path for local files.

Return type:

str or pathlib.Path

Raises:

OSError – If filename is empty or the resolved local path does not exist.

localtileserver.tiler.utilities.get_cache_dir()#

Return the localtileserver cache directory, creating it if needed.

Returns:

Path to the cache directory under the system temporary directory.

Return type:

pathlib.Path

localtileserver.tiler.utilities.purge_cache()#

Completely purge all files from the file cache.

This should be used with caution, it could delete files that are in use.

Returns:

Path to the newly created, empty cache directory.

Return type:

pathlib.Path

Configuration#

localtileserver.configure.get_default_client_params(host: str | None = None, port: int | None = None, prefix: str | None = None)#

Get default client connection parameters from environment variables.

Each parameter is resolved from the corresponding environment variable (LOCALTILESERVER_CLIENT_HOST, LOCALTILESERVER_CLIENT_PORT, LOCALTILESERVER_CLIENT_PREFIX) when the caller does not provide an explicit value.

Parameters:
  • host (str or None, optional) – The client host. If None, falls back to the LOCALTILESERVER_CLIENT_HOST environment variable.

  • port (int or None, optional) – The client port. If None, falls back to the LOCALTILESERVER_CLIENT_PORT environment variable.

  • prefix (str or None, optional) – The client URL prefix. If None, falls back to the LOCALTILESERVER_CLIENT_PREFIX environment variable.

Returns:

The resolved (host, port, prefix) values.

Return type:

tuple of (str or None, int or None, str or None)

class localtileserver.manager.AppManager#

Singleton manager for the shared FastAPI tile-serving application.

static get_or_create_app(cors_all: bool = False)#

Return the shared FastAPI app, creating it if necessary.

Parameters:

cors_all (bool, optional) – If True, enable permissive CORS headers allowing all origins.

Returns:

The singleton FastAPI application instance.

Return type:

fastapi.FastAPI

static set_rasterio_env(env_dict: dict)#

Forward rasterio/GDAL environment options to the tile server.

Sets each option as a process-level environment variable so that GDAL picks them up from any thread (including the background tile-server thread).

Parameters:

env_dict (dict) – Dictionary of rasterio/GDAL environment options.

Application Factory#

localtileserver.web.fastapi_app.create_app(url_prefix: str = '/', cors_all: bool = False, debug: bool = False, cesium_token: str = '')#

Create and configure the FastAPI application.

Parameters:
  • url_prefix (str, optional) – URL prefix for the application routes. Default is "/".

  • cors_all (bool, optional) – If True, enable permissive CORS headers allowing all origins.

  • debug (bool, optional) – Run the application in debug mode with verbose logging.

  • cesium_token (str, optional) – Cesium Ion access token for the 3-D globe viewer.

Returns:

The configured FastAPI application instance.

Return type:

fastapi.FastAPI

localtileserver.web.fastapi_app.run_app(filename, port: int = 0, debug: bool = False, browser: bool = True, cesium_token: str = '', host: str = '127.0.0.1', cors_all: bool = False, run: bool = True)#

Serve tiles from the raster at filename.

You can also pass the name of one of the example datasets: elevation, blue_marble, virtual_earth, arcgis or bahamas.

Parameters:
  • filename (str or pathlib.Path) – Path to a raster file or the name of a built-in example dataset.

  • port (int, optional) – Port to bind the server to. 0 (default) picks an available port.

  • debug (bool, optional) – Run the server with verbose debug logging.

  • browser (bool, optional) – Open a web browser pointing to the viewer on startup.

  • cesium_token (str, optional) – Cesium Ion access token for the 3-D globe viewer.

  • host (str, optional) – Hostname to bind the server to. Default is "127.0.0.1".

  • cors_all (bool, optional) – If True, enable permissive CORS headers allowing all origins.

  • run (bool, optional) – If True (default), start the uvicorn server. If False, return the app without running it.

Returns:

The configured and (optionally running) FastAPI application.

Return type:

fastapi.FastAPI

Diagnostics#

class localtileserver.Report(additional=None, ncol=3, text_width=80, sort=False)#

Generate a report on the dependencies of localtileserver.