Beispiel #1
0
def get_datasets(
        request: Request,
        response: Response,
        cache_client: CacheLayer = Depends(utils.get_cache),
):
    """Return a list of datasets."""
    dataset_hash = utils.get_hash(spotlight_id="all")
    content = None

    if cache_client:
        content = cache_client.get_dataset_from_cache(dataset_hash)
        if content:
            content = Datasets.parse_raw(content)
            response.headers["X-Cache"] = "HIT"
    if not content:
        scheme = request.url.scheme
        host = request.headers["host"]
        if config.API_VERSION_STR:
            host += config.API_VERSION_STR

        content = datasets.get_all(api_url=f"{scheme}://{host}")

        if cache_client and content:
            cache_client.set_dataset_cache(dataset_hash, content)

    return content
Beispiel #2
0
def get_dataset(
        request: Request,
        spotlight_id: str,
        response: Response,
        cache_client: CacheLayer = Depends(utils.get_cache),
):
    """Return dataset info for all datasets available for a given spotlight"""
    try:
        dataset_hash = utils.get_hash(spotlight_id=spotlight_id)
        content = None

        if cache_client:
            content = cache_client.get_dataset_from_cache(dataset_hash)
            if content:
                content = Datasets.parse_raw(content)
                response.headers["X-Cache"] = "HIT"
        if not content:
            scheme = request.url.scheme
            host = request.headers["host"]
            if config.API_VERSION_STR:
                host += config.API_VERSION_STR

            content = datasets.get(spotlight_id, api_url=f"{scheme}://{host}")

            if cache_client and content:
                cache_client.set_dataset_cache(dataset_hash, content)

        return content
    except InvalidIdentifier:
        raise HTTPException(
            status_code=404,
            detail=f"Invalid spotlight identifier: {spotlight_id}")
Beispiel #3
0
async def tile(
        z: int = Path(...,
                      ge=0,
                      le=30,
                      description="Mercator tiles's zoom level"),
        x: int = Path(..., description="Mercator tiles's column"),
        y: int = Path(..., description="Mercator tiles's row"),
        date: str = Query(..., description="date of site for detections"),
        site: str = Query(..., description="id of site for detections"),
        cache_client: CacheLayer = Depends(utils.get_cache),
) -> TileResponse:
    """Handle /planet requests."""
    timings = []
    headers: Dict[str, str] = {}

    scenes = utils.site_date_to_scenes(site, date)

    tile_hash = utils.get_hash(
        **dict(z=z, x=x, y=y, scenes=scenes, planet=True))

    content = None
    if cache_client:
        try:
            content, ext = cache_client.get_image_from_cache(tile_hash)
            headers["X-Cache"] = "HIT"
        except Exception:
            content = None

    if not content:
        with utils.Timer() as t:
            tile, mask = await _tile(scenes, x, y, z)
        timings.append(("Read", t.elapsed))

        content = await _render(tile, mask)

        timings.append(("Format", t.elapsed))

        if cache_client and content:
            cache_client.set_image_cache(tile_hash, (content, ImageType.png))

    if timings:
        headers["X-Server-Timings"] = "; ".join([
            "{} - {:0.2f}".format(name, time * 1000)
            for (name, time) in timings
        ])

    return TileResponse(content,
                        media_type=mimetype[ImageType.png.value],
                        headers=headers)
Beispiel #4
0
async def tile(
        z: int = Path(...,
                      ge=0,
                      le=30,
                      description="Mercator tiles's zoom level"),
        x: int = Path(..., description="Mercator tiles's column"),
        y: int = Path(..., description="Mercator tiles's row"),
        scale: int = Query(
            1,
            gt=0,
            lt=4,
            description="Tile size scale. 1=256x256, 2=512x512..."),
        ext: ImageType = Query(
            None, description="Output image type. Default is auto."),
        url: str = Query(..., description="Cloud Optimized GeoTIFF URL."),
        bidx: Optional[str] = Query(
            None, description="Coma (',') delimited band indexes"),
        nodata: Optional[Union[str, int, float]] = Query(
            None, description="Overwrite internal Nodata value."),
        rescale: Optional[str] = Query(
            None, description="Coma (',') delimited Min,Max bounds"),
        color_formula: Optional[str] = Query(None, title="rio-color formula"),
        color_map: Optional[utils.ColorMapName] = Query(
            None, title="rio-tiler color map name"),
        cache_client: CacheLayer = Depends(utils.get_cache),
) -> TileResponse:
    """Handle /tiles requests."""
    timings = []
    headers: Dict[str, str] = {}

    tile_hash = utils.get_hash(**dict(
        z=z,
        x=x,
        y=y,
        ext=ext,
        scale=scale,
        url=url,
        bidx=bidx,
        nodata=nodata,
        rescale=rescale,
        color_formula=color_formula,
        color_map=color_map.value if color_map else "",
    ))
    tilesize = scale * 256

    content = None
    if cache_client:
        try:
            content, ext = cache_client.get_image_from_cache(tile_hash)
            headers["X-Cache"] = "HIT"
        except Exception:
            content = None

    if not content:
        indexes = tuple(int(s)
                        for s in re.findall(r"\d+", bidx)) if bidx else None

        if nodata is not None:
            nodata = numpy.nan if nodata == "nan" else float(nodata)

        with utils.Timer() as t:
            tile, mask = await _tile(url,
                                     x,
                                     y,
                                     z,
                                     indexes=indexes,
                                     tilesize=tilesize,
                                     nodata=nodata)
        timings.append(("Read", t.elapsed))

        if not ext:
            ext = ImageType.jpg if mask.all() else ImageType.png

        with utils.Timer() as t:
            tile = await _postprocess(tile,
                                      mask,
                                      rescale=rescale,
                                      color_formula=color_formula)
        timings.append(("Post-process", t.elapsed))

        if color_map:
            if color_map.value.startswith("custom_"):
                color_map = utils.get_custom_cmap(
                    color_map.value)  # type: ignore
            else:
                color_map = get_colormap(color_map.value)  # type: ignore

        with utils.Timer() as t:
            if ext == ImageType.npy:
                sio = BytesIO()
                numpy.save(sio, (tile, mask))
                sio.seek(0)
                content = sio.getvalue()
            else:
                driver = drivers[ext.value]
                options = img_profiles.get(driver.lower(), {})
                if ext == ImageType.tif:
                    options = geotiff_options(x, y, z, tilesize=tilesize)

                content = await _render(tile,
                                        mask,
                                        img_format=driver,
                                        colormap=color_map,
                                        **options)

        timings.append(("Format", t.elapsed))

        if cache_client and content:
            cache_client.set_image_cache(tile_hash, (content, ext))

    if timings:
        headers["X-Server-Timings"] = "; ".join([
            "{} - {:0.2f}".format(name, time * 1000)
            for (name, time) in timings
        ])

    return TileResponse(content,
                        media_type=mimetype[ext.value],
                        headers=headers)