Skip to content
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

Add stactools.core.create.item #201

Merged
merged 3 commits into from
Sep 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

## Unreleased

### Added

- `stactools.core.create.item` and associated CLI subcommand ([#201](https://github.com/stac-utils/stactools/pull/201))

### Fixed

- Typing for Python 3.7 in `stactools.core.projection` ([#201](https://github.com/stac-utils/stactools/pull/201))

## stactools 0.2.2

### Added
Expand Down
5 changes: 3 additions & 2 deletions src/stactools/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
def register_plugin(registry: 'Registry') -> None:
# Register subcommands

from stactools.cli.commands import (add, copy, info, layout, merge,
migrate, validate, version)
from stactools.cli.commands import (add, copy, info, layout, merge, create,
version, validate)

registry.register_subcommand(copy.create_copy_command)
registry.register_subcommand(create.create_create_item_command)
registry.register_subcommand(copy.create_move_assets_command)
registry.register_subcommand(info.create_info_command)
registry.register_subcommand(info.create_describe_command)
Expand Down
20 changes: 20 additions & 0 deletions src/stactools/cli/commands/create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import click

from stactools.core import create


def create_create_item_command(cli: click.Group) -> click.Command:
@cli.command('create-item', short_help='Creates an item from an asset')
@click.argument('href')
def create_item_command(href: str) -> None:
"""Creates an Item from a href.

The href must be a `rasterio` readable asset. The item's dictionary will
be printed to stdout. This item is intentinonally _extremely_ minimal.
If you need additional capabilities, we recommend using [rio
stac](https://github.com/developmentseed/rio-stac/).
"""
item = create.item(href)
print(item.to_dict())

return create_item_command
62 changes: 62 additions & 0 deletions src/stactools/core/create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import datetime
import os.path

import shapely.geometry
from pystac import Item, Asset
from pystac.extensions.projection import ProjectionExtension
import rasterio

import stactools.core.projection


def item(href: str) -> Item:
"""Creates a STAC Item from the asset at the provided href.

This function is intentionally minimal in its signature and capabilities. If
you need to customize your Item, do so after creation.

This function sets:
- id
- geometry
- bbox
- datetime (to the time of item creation): you'll probably want to change this
- the proj extension
- either the EPSG code or, if not available, the WKT2
- transform
- shape
- a single asset with key 'data'
- asset href
- asset roles to ['data']

In particular, the datetime and asset media type fields most likely need to be updated.
"""
id = os.path.splitext(os.path.basename(href))[0]
with rasterio.open(href) as dataset:
crs = dataset.crs
proj_bbox = dataset.bounds
proj_transform = list(dataset.transform)[0:6]
proj_shape = dataset.shape
proj_geometry = shapely.geometry.mapping(shapely.geometry.box(*proj_bbox))
geometry = stactools.core.projection.reproject_geom(crs,
'EPSG:4326',
proj_geometry,
precision=6)
bbox = list(shapely.geometry.shape(geometry).bounds)
item = Item(id=id,
geometry=geometry,
bbox=bbox,
datetime=datetime.datetime.now(),
properties={})

projection = ProjectionExtension.ext(item, add_if_missing=True)
epsg = crs.to_epsg()
if epsg:
projection.epsg = epsg
else:
projection.wkt2 = crs.to_wkt('WKT2')
projection.transform = proj_transform
projection.shape = proj_shape

item.add_asset('data', Asset(href=href, roles=['data']))

return item
7 changes: 3 additions & 4 deletions src/stactools/core/projection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from collections import abc
from copy import deepcopy
from typing import Any, List, Optional, Union, Dict
from typing import Any, List, Optional, Union, Dict, Sequence

import pyproj
import rasterio.crs
Expand Down Expand Up @@ -49,11 +48,11 @@ def reproject_geom(src_crs: Union[pyproj.CRS, rasterio.crs.CRS, str],
always_xy=True)
result = deepcopy(geom)

def fn(coords: abc.Sequence[Any]) -> abc.Sequence[Any]:
def fn(coords: Sequence[Any]) -> Sequence[Any]:
coords = list(coords)
for i in range(0, len(coords)):
coord = coords[i]
if isinstance(coord[0], abc.Sequence):
if isinstance(coord[0], Sequence):
coords[i] = fn(coord)
else:
x, y = coord
Expand Down
52 changes: 52 additions & 0 deletions tests/core/test_create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import os.path
from unittest import TestCase

from pystac.extensions.projection import ProjectionExtension

from stactools.core import create

from tests import test_data


class CreateItem(TestCase):
def setUp(self) -> None:
self.path = test_data.get_path(
'data-files/planet-disaster/hurricane-harvey/'
'hurricane-harvey-0831/20170831_172754_101c/20170831_172754_101c_3b_Visual.tif'
)

def test_one_datetime(self) -> None:
item = create.item(self.path)
self.assertEqual(item.id,
os.path.splitext(os.path.basename(self.path))[0])
self.assertIsNotNone(item.datetime)
self.assertEqual(
item.geometry, {
'type':
'Polygon',
'coordinates':
[[[-95.780872, 29.517294], [-95.783782, 29.623358],
[-96.041791, 29.617689], [-96.038613, 29.511649],
[-95.780872, 29.517294]]]
})
self.assertEqual(item.bbox,
[-96.041791, 29.511649, -95.780872, 29.623358])
self.assertIsNone(item.common_metadata.start_datetime)
self.assertIsNone(item.common_metadata.end_datetime)

projection = ProjectionExtension.ext(item)
self.assertEqual(projection.epsg, 32615)
self.assertIsNone(projection.wkt2)
self.assertIsNone(projection.projjson)
self.assertEqual(
projection.transform,
[97.69921875, 0.0, 205437.0, 0.0, -45.9609375, 3280290.0])
self.assertEqual(projection.shape, (256, 256))

data = item.assets['data']
self.assertEqual(data.href, self.path)
self.assertIsNone(data.title)
self.assertIsNone(data.description)
self.assertEqual(data.roles, ['data'])
self.assertEqual(data.media_type, None)
item.validate()