def label_collection_add_items(
    collection,
    root_catalog,
    uri_list,
    links_func,
    label_description,
    label_type,
    label_classes=None,
    label_tasks=None,
    debug=False,
):
    """ Add uri_list tif uris to collection as LabelItems

    root_catalog is the top level node in the STAC Catalog where the chips labeled by these tifs
    can be found. Required to correctly setup Links to the source chips.

    links_func is a method with the following signature:
        def links_func(root_catalog: Catalog,
                       label_item: LabelItem,
                       country: str,
                       event_id: int): [Link]
    This method should construct a list of links that map the label_item to the STAC objects in
    the root_catalog that label_item is derived from. Assumes for now that the asset referenced
    uses the key "labels"

    The label_ arguments will be passed down to each LabelItem in the collection

    """
    if debug:
        uri_list = list(uri_list)[:10]
    for uri in uri_list:
        if not uri.endswith(".tif"):
            continue

        item_id = os.path.basename(uri).split(".")[0]
        country, event_id, *_ = item_id.split("_")

        params = {}
        params["id"] = item_id
        params["collection"] = collection
        params["datetime"] = image_date_for_country("s1", country)
        params["stac_extensions"] = [Extensions.LABEL]
        params["properties"] = {
            "country": country,
            "event_id": event_id,
        }
        params["bbox"] = get_chip_bbox(uri, country, event_id)
        params["geometry"] = box(*params["bbox"]).__geo_interface__

        label_ext_params = {}
        if isinstance(label_classes, list):
            label_ext_params["label_classes"] = label_classes
        else:
            label_ext_params["label_classes"] = []
        label_ext_params["label_description"] = label_description
        if label_tasks is not None:
            label_ext_params["label_tasks"] = label_tasks
        label_ext_params["label_type"] = label_type

        item = Item(**params)
        item.ext.label.apply(**label_ext_params)
        # Add Asset
        asset = Asset(href=uri,
                      title="GeoTiff",
                      media_type="image/tiff; application=geotiff")
        item.add_asset(key="labels", asset=asset)

        item.links = links_func(root_catalog, item, country, event_id)

        collection.add_item(item)
        print("Collection {}: Added STAC Item {}".format(
            collection.id, item.id))
Пример #2
0
def transform_stac_to_stac(item: Item,
                           enable_proj: bool = True,
                           self_link: str = None,
                           source_link: str = None) -> Item:
    """
    Handle a 0.7.0 item and convert it to a 1.0.0.beta2 item.
    """
    # Remove USGS extension and add back eo
    item.ext.enable("eo")

    # Add and update links
    item.links = []
    if self_link:
        item.links.append(Link(rel="self", target=self_link))
    if source_link:
        item.links.append(
            Link(rel="derived_from",
                 target=source_link,
                 media_type="application/json"))

    # Add some common fields
    item.common_metadata.constellation = "Landsat"
    item.common_metadata.instruments = [
        i.lower() for i in item.properties["eo:instrument"].split("_")
    ]
    del item.properties["eo:instrument"]

    # Handle view extension
    item.ext.enable("view")
    item.ext.view.off_nadir = item.properties["eo:off_nadir"]
    del item.properties["eo:off_nadir"]

    if enable_proj:
        try:
            # If we can load the blue band, use it to add proj information
            blue_asset = item.assets["SR_B2.TIF"]
            blue = rasterio.open(blue_asset.href)
            shape = [blue.height, blue.width]
            transform = blue.transform
            crs = blue.crs.to_epsg()

            # Now we have the info, we can make the fields
            item.ext.enable("projection")
            item.ext.projection.epsg = crs

            new_assets = {}

            for name, asset in item.assets.items():
                if asset.media_type == "image/vnd.stac.geotiff; cloud-optimized=true":
                    item.ext.projection.set_transform(transform, asset=asset)
                    item.ext.projection.set_shape(shape, asset=asset)
                    asset.media_type = MediaType.COG

        except RasterioIOError:
            print("Failed to load blue band, so not handling proj fields")

    # Remove .TIF from asset names
    new_assets = {}

    for name, asset in item.assets.items():
        new_name = name.replace(".TIF", "")
        new_assets[new_name] = asset
    item.assets = new_assets

    return item