Skip to content

dependencies

titiler.core.dependencies

Common dependency.

AssetsExprParams dataclass

Bases: ExpressionParams, AssetsParams

Assets and Expression parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
190
191
192
193
194
195
196
197
198
199
200
@dataclass
class AssetsExprParams(ExpressionParams, AssetsParams):
    """Assets and Expression parameters."""

    asset_as_band: Annotated[
        bool | None,
        Query(
            title="Consider asset as a 1 band dataset",
            description="Asset as Band",
        ),
    ] = None

AssetsParams dataclass

Bases: DefaultDependency

Assets parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class AssetsParams(DefaultDependency):
    """Assets parameters."""

    assets: Annotated[
        list[str],
        AfterValidator(_parse_asset),
        Query(
            title="Asset names",
            description="Asset's names.",
            openapi_examples={
                "user-provided": {"value": None},
                "one-asset": {
                    "description": "Return results for asset `data`.",
                    "value": ["data"],
                },
                "multi-assets": {
                    "description": "Return results for assets `data` and `cog`.",
                    "value": ["data", "cog"],
                },
                "multi-assets-with-options": {
                    "description": "Return results for assets `data` and `cog`.",
                    "value": ["data|bidx=1", "cog|bidx=1,2"],
                },
            },
        ),
    ]

BidxExprParams dataclass

Bases: ExpressionParams, BidxParams

Band Indexes and Expression parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
129
130
131
132
133
@dataclass
class BidxExprParams(ExpressionParams, BidxParams):
    """Band Indexes and Expression parameters."""

    pass

BidxParams dataclass

Bases: DefaultDependency

Band Indexes parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@dataclass
class BidxParams(DefaultDependency):
    """Band Indexes parameters."""

    indexes: Annotated[
        list[int] | None,
        Query(
            title="Band indexes",
            alias="bidx",
            description="Dataset band indexes",
            openapi_examples={
                "user-provided": {"value": None},
                "one-band": {"value": [1]},
                "multi-bands": {"value": [1, 2, 3]},
            },
        ),
    ] = None

DatasetParams dataclass

Bases: DefaultDependency

Low level WarpedVRT Optional parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class DatasetParams(DefaultDependency):
    """Low level WarpedVRT Optional parameters."""

    nodata: Annotated[
        Literal["nan", "inf", "-inf"] | int | float | None,
        Query(
            title="Nodata value",
            description="Overwrite internal Nodata value; nan or valid float values only.",
        ),
    ] = None
    unscale: Annotated[
        bool | None,
        Query(
            title="Apply internal Scale/Offset",
            description="Apply internal Scale/Offset. Defaults to `False`.",
        ),
    ] = None
    resampling_method: Annotated[
        RIOResampling | None,
        Query(
            alias="resampling",
            description="RasterIO resampling algorithm. Defaults to `nearest`.",
        ),
    ] = None
    reproject_method: Annotated[
        WarpResampling | None,
        Query(
            alias="reproject",
            description="WarpKernel resampling algorithm (only used when doing re-projection). Defaults to `nearest`.",
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if self.nodata is not None:
            self.nodata = numpy.nan if self.nodata == "nan" else float(self.nodata)

        if self.unscale is not None:
            self.unscale = bool(self.unscale)

DefaultDependency dataclass

Dataclass with dict unpacking

Source code in src/titiler/core/titiler/core/dependencies.py
76
77
78
79
80
81
82
83
84
85
@dataclass
class DefaultDependency:
    """Dataclass with dict unpacking"""

    def as_dict(self, exclude_none: bool = True) -> dict:
        """Transform dataclass to dict."""
        if exclude_none:
            return {k: v for k, v in self.__dict__.items() if v is not None}

        return dict(self.__dict__.items())

as_dict

as_dict(exclude_none: bool = True) -> dict

Transform dataclass to dict.

Source code in src/titiler/core/titiler/core/dependencies.py
80
81
82
83
84
85
def as_dict(self, exclude_none: bool = True) -> dict:
    """Transform dataclass to dict."""
    if exclude_none:
        return {k: v for k, v in self.__dict__.items() if v is not None}

    return dict(self.__dict__.items())

ExpressionParams dataclass

Bases: DefaultDependency

Expression parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@dataclass
class ExpressionParams(DefaultDependency):
    """Expression parameters."""

    expression: Annotated[
        str | None,
        Query(
            title="Band Math expression",
            description="rio-tiler's band math expression",
            openapi_examples={
                "user-provided": {"value": None},
                "simple": {"description": "Simple band math.", "value": "b1/b2"},
                "multi-bands": {
                    "description": "Semicolon (;) delimited expressions (band1: b1/b2, band2: b2+b3).",
                    "value": "b1/b2;b2+b3",
                },
            },
        ),
    ] = None

HistogramParams dataclass

Bases: DefaultDependency

Numpy Histogram options.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class HistogramParams(DefaultDependency):
    """Numpy Histogram options."""

    bins: Annotated[
        str | None,
        Query(
            alias="histogram_bins",
            title="Histogram bins.",
            description="""
Defines the number of equal-width bins in the given range (10, by default).

If bins is a sequence (comma `,` delimited values), it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths.

link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
            """,
            openapi_examples={
                "user-provided": {"value": None},
                "simple": {
                    "description": "Defines the number of equal-width bins",
                    "value": 8,
                },
                "array": {
                    "description": "Defines custom bin edges (comma `,` delimited values)",
                    "value": "0,100,200,300",
                },
            },
            pattern=r"^\d+(,\d+)*$",
        ),
    ] = None

    range: Annotated[
        str | None,
        Query(
            alias="histogram_range",
            title="Histogram range",
            description="""
Comma `,` delimited range of the bins.

The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()).

Values outside the range are ignored. The first element of the range must be less than or equal to the second.
range affects the automatic bin computation as well.

link: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
            """,
            openapi_examples={
                "user-provided": {"value": None},
                "array": {
                    "description": "Defines custom histogram range (comma `,` delimited values)",
                    "value": "0,1000",
                },
            },
            pattern=separated_parseable_floats_regex(count=2),
        ),
    ] = None

    def __post_init__(self):
        """Post Init."""
        if self.bins:
            bins = self.bins.split(",")
            if len(bins) == 1:
                self.bins = int(bins[0])  # type: ignore
            else:
                self.bins = list(map(float, bins))  # type: ignore
        else:
            self.bins = 10

        if self.range:
            parsed = list(map(float, self.range.split(",")))
            assert (
                len(parsed) == 2
            ), f"Invalid histogram_range values: {self.range}, should be of form 'min,max'"

            self.range = parsed  # type: ignore

ImageRenderingParams dataclass

Bases: RenderingParams

Image Rendering options.

Source code in src/titiler/core/titiler/core/dependencies.py
328
329
330
331
332
333
334
335
336
337
338
@dataclass
class ImageRenderingParams(RenderingParams):
    """Image Rendering options."""

    add_mask: Annotated[
        bool | None,
        Query(
            alias="return_mask",
            description="Add mask to the output data. Defaults to `True`",
        ),
    ] = None

OGCMapsParams dataclass

Bases: DefaultDependency

OGC Maps options.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class OGCMapsParams(DefaultDependency):
    """OGC Maps options."""

    request: Request

    bbox: Annotated[
        str | None,
        BeforeValidator(validate_bbox),
        Query(
            description="Bounding box of the rendered map. The bounding box is provided as four or six coordinates.",
        ),
    ] = None

    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            description="Reproject the output to the given crs.",
        ),
    ] = None

    bbox_crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            description="crs for the specified bbox.",
            alias="bbox-crs",
        ),
    ] = None

    height: Annotated[
        int | None,
        Query(
            description="Height of the map in pixels. If omitted and `width` is specified, defaults to the `height` maintaining a 1:1 aspect ratio. If both `width` and `height` are omitted, the server will select default dimensions.",
            gt=0,
        ),
    ] = None

    width: Annotated[
        int | None,
        Query(
            description="Width of the map in pixels. If omitted and `height` is specified, defaults to the `width` maintaining a 1:1 aspect ratio. If both `width` and `height` are omitted, the server will select default dimensions.",
            gt=0,
        ),
    ] = None

    f: Annotated[
        ImageType | None,
        Query(description="The format of the map response (e.g. png)."),
    ] = None

    max_size: int | None = field(init=False, default=None)

    format: ImageType | None = field(init=False, default=ImageType.png)

    def __post_init__(self):  # noqa: C901
        """Parse and validate."""
        if self.crs:
            self.crs = CRS.from_user_input(self.crs)  # type: ignore

        if self.bbox_crs:
            self.bbox_crs = CRS.from_user_input(self.bbox_crs)  # type: ignore

        if not self.height and not self.width:
            self.max_size = 1024

        if self.bbox:
            bounds = list(map(float, self.bbox.split(",")))
            if len(bounds) == 6:
                bounds = [bounds[0], bounds[1], bounds[3], bounds[4]]

            self.bbox = bounds  # type: ignore

        if self.f:
            self.format = ImageType[self.f]

        else:
            if media := accept_media_type(
                self.request.headers.get("accept", ""),
                [MediaType[e] for e in ImageType],
            ):
                self.format = ImageType[media.name]

PartFeatureParams dataclass

Bases: DefaultDependency

Common parameters for bbox and feature.

Source code in src/titiler/core/titiler/core/dependencies.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
@dataclass
class PartFeatureParams(DefaultDependency):
    """Common parameters for bbox and feature."""

    # NOTE: the part sizes dependency can either be a Query or a Path Parameter
    max_size: Annotated[
        int | None, Field(description="Maximum image size to read onto.")
    ] = None
    height: Annotated[int | None, Field(description="Force output image height.")] = (
        None
    )
    width: Annotated[int | None, Field(description="Force output image width.")] = None

    def __post_init__(self):
        """Post Init."""
        if self.width or self.height:
            self.max_size = None

PreviewParams dataclass

Bases: DefaultDependency

Common Preview parameters.

Source code in src/titiler/core/titiler/core/dependencies.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
@dataclass
class PreviewParams(DefaultDependency):
    """Common Preview parameters."""

    # NOTE: sizes dependency can either be a Query or a Path Parameter
    max_size: Annotated[int, Field(description="Maximum image size to read onto.")] = (
        1024
    )
    height: Annotated[int | None, Field(description="Force output image height.")] = (
        None
    )
    width: Annotated[int | None, Field(description="Force output image width.")] = None

    def __post_init__(self):
        """Post Init."""
        if self.width or self.height:
            self.max_size = None

RenderingParams dataclass

Bases: DefaultDependency

Image Rendering options.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class RenderingParams(DefaultDependency):
    """Image Rendering options."""

    rescale: Annotated[
        list[str] | None,
        BeforeValidator(validate_rescale),
        Query(
            title="Min/Max data Rescaling",
            description="comma (',') delimited Min,Max range. Can set multiple time for multiple bands.",
            examples=["0,2000", "0,1000", "0,10000"],  # band 1  # band 2  # band 3
        ),
    ] = None

    color_formula: Annotated[
        str | None,
        BeforeValidator(validate_color_formula),
        Query(
            title="Color Formula",
            description="rio-color formula (info: https://github.com/mapbox/rio-color)",
        ),
    ] = None

    def __post_init__(self) -> None:
        """Post Init."""
        if self.rescale:
            rescale_array = []
            for r in self.rescale:
                parsed = tuple(
                    map(
                        float,
                        r.split(","),
                    )
                )
                assert (
                    len(parsed) == 2
                ), f"Invalid rescale values: {self.rescale}, should be of form ['min,max', 'min,max'] or [[min,max], [min, max]]"
                rescale_array.append(parsed)

            self.rescale: RescaleType = rescale_array  # type: ignore

StatisticsParams dataclass

Bases: DefaultDependency

Statistics options.

Source code in src/titiler/core/titiler/core/dependencies.py
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
@dataclass
class StatisticsParams(DefaultDependency):
    """Statistics options."""

    categorical: Annotated[
        bool | None,
        Query(
            description="Return statistics for categorical dataset. Defaults to `False`"
        ),
    ] = None
    categories: Annotated[
        list[float | int] | None,
        Query(
            alias="c",
            title="Pixels values for categories.",
            description="List of values for which to report counts.",
            examples=[1, 2, 3],
        ),
    ] = None
    percentiles: Annotated[
        list[int] | None,
        Query(
            alias="p",
            title="Percentile values",
            description="List of percentile values (default to [2, 98]).",
            examples=[2, 5, 95, 98],
        ),
    ] = None

    def __post_init__(self):
        """Set percentiles default."""
        if not self.percentiles:
            self.percentiles = [2, 98]

TileParams dataclass

Bases: DefaultDependency

Tile options.

Source code in src/titiler/core/titiler/core/dependencies.py
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
@dataclass
class TileParams(DefaultDependency):
    """Tile options."""

    buffer: Annotated[
        float | None,
        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

    padding: Annotated[
        int | None,
        Query(
            gt=0,
            title="Tile padding.",
            description="Padding to apply to each tile edge. Helps reduce resampling artefacts along edges. Defaults to `0`.",
        ),
    ] = None

BufferParams

BufferParams(
    buffer: Annotated[
        float | None,
        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,
) -> float | None

Tile buffer Parameter.

Source code in src/titiler/core/titiler/core/dependencies.py
503
504
505
506
507
508
509
510
511
512
513
514
def BufferParams(
    buffer: Annotated[
        float | None,
        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,
) -> float | None:
    """Tile buffer Parameter."""
    return buffer

CRSParams

CRSParams(
    crs: Annotated[
        str | None, BeforeValidator(validate_crs), Query(description="Coordinate Reference System.")
    ] = None,
) -> CRS | None

Coordinate Reference System Coordinates Param.

Source code in src/titiler/core/titiler/core/dependencies.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def CRSParams(
    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            description="Coordinate Reference System.",
        ),
    ] = None,
) -> CRS | None:
    """Coordinate Reference System Coordinates Param."""
    if crs:
        return CRS.from_user_input(crs)

    return None

CoordCRSParams

CoordCRSParams(
    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            alias=coord_crs,
            description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
        ),
    ] = None,
) -> CRS | None

Coordinate Reference System Coordinates Param.

Source code in src/titiler/core/titiler/core/dependencies.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def CoordCRSParams(
    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            alias="coord_crs",
            description="Coordinate Reference System of the input coords. Default to `epsg:4326`.",
        ),
    ] = None,
) -> CRS | None:
    """Coordinate Reference System Coordinates Param."""
    if crs:
        return CRS.from_user_input(crs)

    return None

DatasetPathParams

DatasetPathParams(url: Annotated[str, Query(description='Dataset URL')]) -> str

Create dataset path from args

Source code in src/titiler/core/titiler/core/dependencies.py
71
72
73
def DatasetPathParams(url: Annotated[str, Query(description="Dataset URL")]) -> str:
    """Create dataset path from args"""
    return url

DstCRSParams

DstCRSParams(
    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(alias=dst_crs, description="Output Coordinate Reference System."),
    ] = None,
) -> CRS | None

Coordinate Reference System Coordinates Param.

Source code in src/titiler/core/titiler/core/dependencies.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def DstCRSParams(
    crs: Annotated[
        str | None,
        BeforeValidator(validate_crs),
        Query(
            alias="dst_crs",
            description="Output Coordinate Reference System.",
        ),
    ] = None,
) -> CRS | None:
    """Coordinate Reference System Coordinates Param."""
    if crs:
        return CRS.from_user_input(crs)

    return None

_parse_asset

_parse_asset(values: list[str]) -> list[AssetType]

Parse assets with optional parameter.

Source code in src/titiler/core/titiler/core/dependencies.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def _parse_asset(values: list[str]) -> list[AssetType]:
    """Parse assets with optional parameter."""
    assets: list[AssetType] = []
    for v in values:
        if "|" in v:
            asset_name, params = v.split("|", 1)
            opts: dict[str, Any] = {"name": asset_name}
            for option in params.split("|"):
                key, value = option.split("=", 1)
                if key == "bidx":
                    opts["indexes"] = list(map(int, value.split(",")))
                elif key == "expression":
                    opts["expression"] = value
                elif key == "bands":
                    opts["bands"] = value.split(",")

            asset = cast(AssetWithOptions, opts)
            assets.append(asset)
        else:
            assets.append(v)

    return assets

create_colormap_dependency

create_colormap_dependency(cmap: ColorMaps) -> Callable

Create Colormap Dependency.

Source code in src/titiler/core/titiler/core/dependencies.py
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
def create_colormap_dependency(cmap: ColorMaps) -> Callable:
    """Create Colormap Dependency."""

    def deps(
        colormap_name: Annotated[  # type: ignore
            Literal[tuple(cmap.list())],
            Query(description="Colormap name"),
        ] = None,
        colormap: Annotated[
            str | None, Query(description="JSON encoded custom Colormap")
        ] = None,
    ):
        if colormap_name:
            return cmap.get(colormap_name)

        if colormap:
            try:
                c = json.loads(
                    colormap,
                    object_hook=lambda x: {
                        int(k): parse_color(v) for k, v in x.items()
                    },
                )

                # Make sure to match colormap type
                if isinstance(c, Sequence):
                    c = [(tuple(inter), parse_color(v)) for (inter, v) in c]

                return c
            except json.JSONDecodeError as e:
                raise HTTPException(
                    status_code=400, detail="Could not parse the colormap value."
                ) from e

        return None

    return deps