-
Notifications
You must be signed in to change notification settings - Fork 27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
sketch for raw raster support in pcfuncs #150
Draft
vincentsarago
wants to merge
14
commits into
microsoft:main
Choose a base branch
from
developmentseed:PcFuncsGDALRaster
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 4 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
a53c882
sketch for raw raster support in pcfuncs
vincentsarago db20729
remove missing attributes
vincentsarago e2d4976
Merge branch 'main' of https://github.com/microsoft/planetary-compute…
vincentsarago bac4f16
update from main and add more tests
vincentsarago 2b81a69
add requirement.dev for pcfuncs
vincentsarago 355704e
sketch
vincentsarago 76584a2
Merge branch 'main' of https://github.com/developmentseed/planetary-c…
vincentsarago 291b0ee
use only ImageData
vincentsarago 89a79a3
update statistics function
vincentsarago f7dad4b
fix tests
vincentsarago b775c15
fix lint
vincentsarago 17d0b8b
:facepalm:
vincentsarago 39d0391
remove useless
vincentsarago fab0264
add dev container
vincentsarago File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,8 @@ | |
|
||
import aiohttp | ||
import mercantile | ||
from funclib.models import RenderOptions | ||
import numpy | ||
from funclib.models import RenderOptions, RIOImage | ||
from funclib.raster import ( | ||
Bbox, | ||
ExportFormats, | ||
|
@@ -152,8 +153,83 @@ async def create( | |
|
||
|
||
class GDALTileSet(TileSet[GDALRaster]): | ||
async def _get_tile(self, url: str) -> Union[RIOImage, None]: | ||
async def _f() -> RIOImage: | ||
async with aiohttp.ClientSession() as session: | ||
async with self._async_limit: | ||
# We set Accept-Encoding to make sure the response is compressed | ||
async with session.get( | ||
url, headers={"Accept-Encoding": "gzip"} | ||
) as resp: | ||
if resp.status == 200: | ||
return RIOImage.from_bytes(await resp.read()) # type: ignore | ||
|
||
else: | ||
raise TilerError( | ||
f"Error downloading tile: {url}", resp=resp | ||
) | ||
|
||
try: | ||
return await with_backoff_async( | ||
_f, | ||
is_throttle=lambda e: isinstance(e, TilerError), | ||
strategy=BackoffStrategy(waits=[0.2, 0.5, 0.75, 1, 2]), | ||
) | ||
except Exception: | ||
logger.warning(f"Tile request failed with backoff: {url}") | ||
return None | ||
|
||
async def get_mosaic(self, tiles: List[Tile]) -> GDALRaster: | ||
raise NotImplementedError() | ||
tasks: List[asyncio.Future[Union[RIOImage, None]]] = [] | ||
for tile in tiles: | ||
url = self.get_tile_url(tile.z, tile.x, tile.y) | ||
print(f"Downloading {url}") | ||
tasks.append(asyncio.ensure_future(self._get_tile(url))) | ||
|
||
tile_images: List[Union[RIOImage, None]] = list(await asyncio.gather(*tasks)) | ||
|
||
tileset_dimensions = get_tileset_dimensions(tiles, self.tile_size) | ||
|
||
# By default if no tiles where return we create an | ||
# empty mosaic with 3 bands and uint8 | ||
count: int = 3 | ||
dtype: str = "uint8" | ||
for im in tile_images: | ||
if im: | ||
|
||
count = im.count | ||
dtype = im.data.dtype | ||
break # Get Count / datatype from the first valid tile_images | ||
|
||
mosaic = RIOImage( # type: ignore | ||
numpy.zeros( | ||
(count, tileset_dimensions.total_rows, tileset_dimensions.total_cols), | ||
dtype=dtype, | ||
) | ||
) | ||
|
||
x = 0 | ||
y = 0 | ||
for i, img in enumerate(tile_images): | ||
if not img: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if there was an exception in |
||
continue | ||
|
||
mosaic.paste(img, (x * self.tile_size, y * self.tile_size)) | ||
|
||
# Increment the row/col position for subsequent tiles | ||
if (i + 1) % tileset_dimensions.tile_rows == 0: | ||
y = 0 | ||
x += 1 | ||
else: | ||
y += 1 | ||
|
||
raster_extent = RasterExtent( | ||
bbox=Bbox.from_tiles(tiles), | ||
cols=tileset_dimensions.total_cols, | ||
rows=tileset_dimensions.total_rows, | ||
) | ||
|
||
return GDALRaster(raster_extent, mosaic) | ||
|
||
|
||
class PILTileSet(TileSet[PILRaster]): | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import contextlib | ||
import pathlib | ||
import threading | ||
import time | ||
from enum import Enum | ||
from types import DynamicClassAttribute | ||
|
||
import pytest | ||
import uvicorn | ||
from fastapi import FastAPI, Path, Query | ||
from funclib.models import RenderOptions | ||
from funclib.tiles import GDALTileSet | ||
from mercantile import Tile | ||
from rio_tiler.io import Reader | ||
from rio_tiler.profiles import img_profiles | ||
from starlette.responses import Response | ||
|
||
HERE = pathlib.Path(__file__).parent | ||
DATA_FILES = HERE / ".." / "data-files" | ||
|
||
cog_file = HERE / ".." / "data-files" / "cog.tif" | ||
|
||
|
||
class ImageDriver(str, Enum): | ||
"""Supported output GDAL drivers.""" | ||
|
||
jpg = "JPEG" | ||
png = "PNG" | ||
tif = "GTiff" | ||
|
||
|
||
class MediaType(str, Enum): | ||
"""Responses Media types formerly known as MIME types.""" | ||
|
||
tif = "image/tiff; application=geotiff" | ||
png = "image/png" | ||
jpeg = "image/jpeg" | ||
|
||
|
||
class ImageType(str, Enum): | ||
"""Available Output image type.""" | ||
|
||
png = "png" | ||
tif = "tif" | ||
jpg = "jpg" | ||
|
||
@DynamicClassAttribute | ||
def profile(self): | ||
"""Return rio-tiler image default profile.""" | ||
return img_profiles.get(self._name_, {}) | ||
|
||
@DynamicClassAttribute | ||
def driver(self): | ||
"""Return rio-tiler image default profile.""" | ||
return ImageDriver[self._name_].value | ||
|
||
@DynamicClassAttribute | ||
def mediatype(self): | ||
"""Return image media type.""" | ||
return MediaType[self._name_].value | ||
|
||
|
||
class Server(uvicorn.Server): | ||
"""Uvicorn Server.""" | ||
|
||
def install_signal_handlers(self): | ||
"""install handlers.""" | ||
pass | ||
|
||
@contextlib.contextmanager | ||
def run_in_thread(self): | ||
"""run in thread.""" | ||
thread = threading.Thread(target=self.run) | ||
thread.start() | ||
try: | ||
while not self.started: | ||
time.sleep(1e-3) | ||
yield | ||
finally: | ||
self.should_exit = True | ||
thread.join() | ||
|
||
|
||
@pytest.fixture(scope="session") | ||
def application(): | ||
"""Run app in Thread.""" | ||
app = FastAPI() | ||
|
||
@app.get("/{z}/{x}/{y}.{format}", response_class=Response) | ||
def tiler( | ||
z: int = Path(...), | ||
x: int = Path(...), | ||
y: int = Path(...), | ||
format: ImageType = Path(...), | ||
collection: str = Query(...), | ||
tile_scale: int = Query( | ||
1, gt=0, lt=4, description="Tile size scale. 1=256x256, 2=512x512..." | ||
), | ||
): | ||
with Reader(collection) as src: | ||
image = src.tile(x, y, z, tilesize=tile_scale * 256) | ||
|
||
content = image.render( | ||
img_format=format.driver, | ||
**format.profile, | ||
) | ||
return Response(content, media_type=format.mediatype) | ||
|
||
config = uvicorn.Config( | ||
app, host="127.0.0.1", port=5000, log_level="info", loop="asyncio" | ||
) | ||
server = Server(config=config) | ||
with server.run_in_thread(): | ||
yield "http://127.0.0.1:5000" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we create a small tiler which will run in thread |
||
|
||
|
||
async def test_app(application): | ||
"""Test GDAL Tileset application.""" | ||
tileset = GDALTileSet( | ||
f"{application}/{{z}}/{{x}}/{{y}}.tif", | ||
RenderOptions( | ||
collection=str(cog_file), | ||
), | ||
) | ||
expect = f"http://127.0.0.1:5000/0/1/2.tif?collection={cog_file}&tile_scale=2" | ||
assert tileset.get_tile_url(0, 1, 2) == expect | ||
|
||
# Test one Tile | ||
url = tileset.get_tile_url(7, 44, 25) | ||
im = await tileset._get_tile(url) | ||
assert im.size == (512, 512) | ||
|
||
# Test Mosaic | ||
mosaic = await tileset.get_mosaic([Tile(44, 25, 7), Tile(45, 25, 7)]) | ||
assert mosaic.image.size == (1024, 512) # width, height | ||
assert mosaic.image.count == 1 # same as cog_file | ||
assert mosaic.image.data.dtype == "uint16" # same as cog_file |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If there is an exception we return None, it will then be handled later