├── .gitignore ├── .md_replace.csv ├── AdvancedExamples.ipynb ├── AdvancedExamples.md ├── Dockerfile ├── Experimental.ipynb ├── Experimental.md ├── LICENSE ├── README.ipynb ├── README.md ├── README_files ├── README_1_1.jpg ├── README_20_0.png ├── README_20_1.png └── README_20_2.png ├── StacItem.ipynb ├── StacItem.md ├── nsl └── stac │ ├── __init__.py │ ├── client.py │ ├── destinations │ ├── __init__.py │ ├── aws.py │ ├── base.py │ ├── gcp.py │ └── memory.py │ ├── enum.py │ ├── experimental.py │ ├── subscription.py │ └── utils.py ├── requirements-demo.txt ├── requirements-test.txt ├── requirements.txt ├── setup.cfg ├── setup.py └── test ├── __init__.py └── test_client.py /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | nsl.stac.egg-info/ 3 | 4 | ipynb2md.py 5 | 6 | build/ 7 | dist/ 8 | tmp/ 9 | venv/ 10 | -------------------------------------------------------------------------------- /.md_replace.csv: -------------------------------------------------------------------------------- 1 | .jpg), .jpeg) -------------------------------------------------------------------------------- /AdvancedExamples.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Complex Queries\n", 8 | "Below are a few complex queries, downloading and filtering of StacItem results. You can also look through the [test directory](./test) for more examples of how to use queries.\n", 9 | "\n", 10 | "- [View Optical](#view)\n", 11 | "- [Limits and Offsets](#limits-and-offsets)\n", 12 | "\n", 13 | "## View\n", 14 | "Proto3, the version of proto definition used for gRPC STAC, creates messages that are similar to structs in C. One of the drawbacks to structs is that for floats, integers, enums and booleans all fields that are not set are initialized to a value of zero. In geospatial sciences, defaulting to zero can cause problems in that an algorithm or user might interpret that as a true value. \n", 15 | "\n", 16 | "To get around this, Google uses wrappers for floats and ints and some of those are used in gRPC STAC. For example, some of the fields like `off_nadir`, `azimuth` and others in the View protobuf message, [View](https://geo-grpc.github.io/api/#epl.protobuf.v1.View), use the `google.protobuf.FloatValue` wrapper. As a consequence, accessing those values requires calling `field_name.value` instead of `field_name` to access the data.\n", 17 | "\n", 18 | "For our ground sampling distance query we're using another query filter; this time it's the [FloatFilter](https://geo-grpc.github.io/api/#epl.protobuf.v1.FloatFilter). It behaves just as the TimestampFilter, but with floats for `value` or for `start` + `end`.\n", 19 | "\n", 20 | "In order to make our off nadir query we need to insert it inside of an [ViewRequest](https://geo-grpc.github.io/api/#epl.protobuf.v1.ViewRequest) container and set that to the `view` field of the `StacRequest`.\n" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 1, 26 | "metadata": {}, 27 | "outputs": [ 28 | { 29 | "name": "stdout", 30 | "output_type": "stream", 31 | "text": [ 32 | "nsl client connecting to stac service at: api.nearspacelabs.net:9090\n", 33 | "\n", 34 | "attempting NSL authentication against https://api.nearspacelabs.net\n", 35 | "fetching new authorization in 60 minutes\n", 36 | "SWIFT STAC item '20200703T174443Z_650_POM1_ST2_P' from 2020-07-03T17:44:43+00:00\n", 37 | "has a off_nadir 1.980, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 38 | "SWIFT STAC item '20200703T174028Z_513_POM1_ST2_P' from 2020-07-03T17:40:28+00:00\n", 39 | "has a off_nadir 9.310, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 40 | "SWIFT STAC item '20200703T174021Z_509_POM1_ST2_P' from 2020-07-03T17:40:21+00:00\n", 41 | "has a off_nadir 8.052, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 42 | "SWIFT STAC item '20190822T183518Z_746_POM1_ST2_P' from 2019-08-22T18:35:18+00:00\n", 43 | "has a off_nadir 9.423, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 44 | "SWIFT STAC item '20190822T183510Z_742_POM1_ST2_P' from 2019-08-22T18:35:10+00:00\n", 45 | "has a off_nadir 9.349, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 46 | "SWIFT STAC item '20190821T180042Z_568_POM1_ST2_P' from 2019-08-21T18:00:42+00:00\n", 47 | "has a off_nadir 9.685, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 48 | "SWIFT STAC item '20190821T180028Z_561_POM1_ST2_P' from 2019-08-21T18:00:28+00:00\n", 49 | "has a off_nadir 8.978, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 50 | "SWIFT STAC item '20190821T180002Z_548_POM1_ST2_P' from 2019-08-21T18:00:02+00:00\n", 51 | "has a off_nadir 9.282, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 52 | "SWIFT STAC item '20190821T175954Z_544_POM1_ST2_P' from 2019-08-21T17:59:54+00:00\n", 53 | "has a off_nadir 8.855, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 54 | "SWIFT STAC item '20190821T175943Z_539_POM1_ST2_P' from 2019-08-21T17:59:43+00:00\n", 55 | "has a off_nadir 8.956, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 56 | "SWIFT STAC item '20190818T174304Z_205_POM1_ST2_P' from 2019-08-18T17:43:04+00:00\n", 57 | "has a off_nadir 7.015, which should be less than or equal to requested off_nadir 10.0: confirmed True\n", 58 | "SWIFT STAC item '20190818T174227Z_181_POM1_ST2_P' from 2019-08-18T17:42:27+00:00\n", 59 | "has a off_nadir 8.237, which should be less than or equal to requested off_nadir 10.0: confirmed True\n" 60 | ] 61 | } 62 | ], 63 | "source": [ 64 | "from datetime import datetime, timezone\n", 65 | "from nsl.stac.client import NSLClient\n", 66 | "from nsl.stac import StacRequest, GeometryData, ProjectionData, ViewRequest, View, FloatFilter\n", 67 | "from nsl.stac.enum import FilterRelationship, Mission\n", 68 | "\n", 69 | "# create our off_nadir query to only return data captured with an angle of less than or \n", 70 | "# equal to 10 degrees\n", 71 | "off_nadir = FloatFilter(value=10.0, rel_type=FilterRelationship.LTE)\n", 72 | "# create an eo_request container\n", 73 | "view_request = ViewRequest(off_nadir=off_nadir)\n", 74 | "# define ourselves a point in Texas\n", 75 | "ut_stadium_wkt = \"POINT(-97.7323317 30.2830764)\"\n", 76 | "geometry_data = GeometryData(wkt=ut_stadium_wkt, proj=ProjectionData(epsg=4326))\n", 77 | "# create a StacRequest with geometry, eo_request and a limit of 20\n", 78 | "stac_request = StacRequest(intersects=geometry_data, view=view_request, limit=20)\n", 79 | "\n", 80 | "# get a client interface to the gRPC channel\n", 81 | "client = NSLClient()\n", 82 | "for stac_item in client.search(stac_request):\n", 83 | " print(\"{0} STAC item '{1}' from {2}\\nhas a off_nadir {3:.3f}, which should be less than or \"\n", 84 | " \"equal to requested off_nadir {4}: confirmed {5}\".format(\n", 85 | " stac_item.mission,\n", 86 | " stac_item.id,\n", 87 | " datetime.fromtimestamp(stac_item.observed.seconds, tz=timezone.utc).isoformat(),\n", 88 | " stac_item.view.off_nadir.value,\n", 89 | " off_nadir.value,\n", 90 | " True))" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "metadata": {}, 96 | "source": [ 97 | "Notice that the off_nadir value is printed with some floating point limiting (`:.3f`). Printing out the full value in python would introduce floating point precicion errors for the item. This is because the FloatValue is a float32, but python want's all number to be as large and precise as possible. This is something to be aware of when using Python in general.\n", 98 | "\n", 99 | "Also, even though we set the `limit` to 20, the print out only returns 2 values. For this location, there were only two scenes that were captured with that off nadir angle.\n", 100 | "\n", 101 | "## Limits and Offsets\n", 102 | "It may be that while using the `client.search` request, you've requested so much data that you overrun the 15 second timeout. If that's the case, then you can search for data using `limit` and `offset`.\n", 103 | "\n", 104 | "For most simple requests, a `limit` and `offset` are not necessary. But if you're going through all the data in the archive or if you've constructed a complex request, it may be necessary." 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 2, 110 | "metadata": {}, 111 | "outputs": [ 112 | { 113 | "name": "stdout", 114 | "output_type": "stream", 115 | "text": [ 116 | "stac item id: 20190829T172909Z_1600_POM1_ST2_P at 200 index in request\n", 117 | "stac item id: 20190829T172054Z_1354_POM1_ST2_P at 400 index in request\n", 118 | "stac item id: 20190829T171353Z_1152_POM1_ST2_P at 600 index in request\n", 119 | "stac item id: 20190829T170044Z_770_POM1_ST2_P at 800 index in request\n", 120 | "stac item id: 20190829T165121Z_495_POM1_ST2_P at 1000 index in request\n" 121 | ] 122 | } 123 | ], 124 | "source": [ 125 | "from datetime import date\n", 126 | "from nsl.stac.client import NSLClient\n", 127 | "from nsl.stac import StacRequest, GeometryData, ProjectionData, enum\n", 128 | "from nsl.stac.utils import pb_timestampfield\n", 129 | "# wkt geometry of Travis County, Texas\n", 130 | "travis_wkt = \"POLYGON((-97.9736 30.6251, -97.9188 30.6032, -97.9243 30.5703, \\\n", 131 | " -97.8695 30.5484, -97.8476 30.4717, -97.7764 30.4279, \\\n", 132 | " -97.5793 30.4991, -97.3711 30.4170, -97.4916 30.2089, \\\n", 133 | " -97.6505 30.0719, -97.6669 30.0665, -97.7107 30.0226, \\\n", 134 | " -98.1708 30.3567, -98.1270 30.4279, -98.0503 30.6251))\" \n", 135 | "\n", 136 | "# Query data from before September 1, 2019\n", 137 | "time_filter = pb_timestampfield(value=date(2019, 9, 1), rel_type=enum.FilterRelationship.LTE)\n", 138 | "\n", 139 | "geometry_data = GeometryData(wkt=travis_wkt, \n", 140 | " proj=ProjectionData(epsg=4326))\n", 141 | "\n", 142 | "# get a client interface to the gRPC channel\n", 143 | "client = NSLClient()\n", 144 | "\n", 145 | "limit = 200\n", 146 | "offset = 0\n", 147 | "total = 0\n", 148 | "while total < 1000:\n", 149 | " # make our request\n", 150 | " stac_request = StacRequest(datetime=time_filter, intersects=geometry_data, limit=limit, offset=offset)\n", 151 | " # prepare request for next \n", 152 | " offset += limit\n", 153 | " for stac_item in client.search(stac_request):\n", 154 | " total += 1\n", 155 | " # do cool things with data here\n", 156 | " if total % limit == 0:\n", 157 | " print(\"stac item id: {0} at {1} index in request\".format(stac_item.id, total))" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": {}, 163 | "source": [ 164 | "As you can see in the above results, the `search` request is made 5 different times in the while loop. Each time the `limit` is 200 and the `offset` is increased by 200. " 165 | ] 166 | } 167 | ], 168 | "metadata": { 169 | "kernelspec": { 170 | "display_name": "Python 3", 171 | "language": "python", 172 | "name": "python3" 173 | }, 174 | "language_info": { 175 | "codemirror_mode": { 176 | "name": "ipython", 177 | "version": 3 178 | }, 179 | "file_extension": ".py", 180 | "mimetype": "text/x-python", 181 | "name": "python", 182 | "nbconvert_exporter": "python", 183 | "pygments_lexer": "ipython3", 184 | "version": "3.9.2" 185 | } 186 | }, 187 | "nbformat": 4, 188 | "nbformat_minor": 2 189 | } 190 | -------------------------------------------------------------------------------- /AdvancedExamples.md: -------------------------------------------------------------------------------- 1 | # Complex Queries 2 | Below are a few complex queries, downloading and filtering of StacItem results. You can also look through the [test directory](./test) for more examples of how to use queries. 3 | 4 | - [View Optical](#view) 5 | - [Limits and Offsets](#limits-and-offsets) 6 | 7 | ## View 8 | Proto3, the version of proto definition used for gRPC STAC, creates messages that are similar to structs in C. One of the drawbacks to structs is that for floats, integers, enums and booleans all fields that are not set are initialized to a value of zero. In geospatial sciences, defaulting to zero can cause problems in that an algorithm or user might interpret that as a true value. 9 | 10 | To get around this, Google uses wrappers for floats and ints and some of those are used in gRPC STAC. For example, some of the fields like `off_nadir`, `azimuth` and others in the View protobuf message, [View](https://geo-grpc.github.io/api/#epl.protobuf.v1.View), use the `google.protobuf.FloatValue` wrapper. As a consequence, accessing those values requires calling `field_name.value` instead of `field_name` to access the data. 11 | 12 | For our ground sampling distance query we're using another query filter; this time it's the [FloatFilter](https://geo-grpc.github.io/api/#epl.protobuf.v1.FloatFilter). It behaves just as the TimestampFilter, but with floats for `value` or for `start` + `end`. 13 | 14 | In order to make our off nadir query we need to insert it inside of an [ViewRequest](https://geo-grpc.github.io/api/#epl.protobuf.v1.ViewRequest) container and set that to the `view` field of the `StacRequest`. 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Expand Python Code Sample 22 | 23 | 24 | ```python 25 | from datetime import datetime, timezone 26 | from nsl.stac.client import NSLClient 27 | from nsl.stac import StacRequest, GeometryData, ProjectionData, ViewRequest, View, FloatFilter 28 | from nsl.stac.enum import FilterRelationship, Mission 29 | 30 | # create our off_nadir query to only return data captured with an angle of less than or 31 | # equal to 10 degrees 32 | off_nadir = FloatFilter(value=10.0, rel_type=FilterRelationship.LTE) 33 | # create an eo_request container 34 | view_request = ViewRequest(off_nadir=off_nadir) 35 | # define ourselves a point in Texas 36 | ut_stadium_wkt = "POINT(-97.7323317 30.2830764)" 37 | geometry_data = GeometryData(wkt=ut_stadium_wkt, proj=ProjectionData(epsg=4326)) 38 | # create a StacRequest with geometry, eo_request and a limit of 20 39 | stac_request = StacRequest(intersects=geometry_data, view=view_request, limit=20) 40 | 41 | # get a client interface to the gRPC channel 42 | client = NSLClient() 43 | for stac_item in client.search(stac_request): 44 | print("{0} STAC item '{1}' from {2}\nhas a off_nadir {3:.3f}, which should be less than or " 45 | "equal to requested off_nadir {4}: confirmed {5}".format( 46 | stac_item.mission, 47 | stac_item.id, 48 | datetime.fromtimestamp(stac_item.observed.seconds, tz=timezone.utc).isoformat(), 49 | stac_item.view.off_nadir.value, 50 | off_nadir.value, 51 | True)) 52 | ``` 53 | 54 | 55 |
56 | 57 | 58 | 59 | 60 |
Expand Python Print-out 61 | 62 | 63 | ```text 64 | found NSL_ID under profile name `default` 65 | nsl client connecting to stac service at: api.nearspacelabs.net:9090 66 | 67 | authorizing NSL_ID: `` 68 | attempting NSL authentication against https://api.nearspacelabs.net/oauth/token... 69 | successfully authenticated with NSL_ID: `` 70 | will attempt re-authorization in 60 minutes 71 | SWIFT STAC item '20200703T174443Z_650_POM1_ST2_P' from 2020-07-03T17:44:43+00:00 72 | has a off_nadir 1.980, which should be less than or equal to requested off_nadir 10.0: confirmed True 73 | SWIFT STAC item '20200703T174028Z_513_POM1_ST2_P' from 2020-07-03T17:40:28+00:00 74 | has a off_nadir 9.310, which should be less than or equal to requested off_nadir 10.0: confirmed True 75 | SWIFT STAC item '20200703T174021Z_509_POM1_ST2_P' from 2020-07-03T17:40:21+00:00 76 | has a off_nadir 8.052, which should be less than or equal to requested off_nadir 10.0: confirmed True 77 | SWIFT STAC item '20190822T183518Z_746_POM1_ST2_P' from 2019-08-22T18:35:18+00:00 78 | has a off_nadir 9.423, which should be less than or equal to requested off_nadir 10.0: confirmed True 79 | SWIFT STAC item '20190822T183510Z_742_POM1_ST2_P' from 2019-08-22T18:35:10+00:00 80 | has a off_nadir 9.349, which should be less than or equal to requested off_nadir 10.0: confirmed True 81 | SWIFT STAC item '20190821T180042Z_568_POM1_ST2_P' from 2019-08-21T18:00:42+00:00 82 | has a off_nadir 9.685, which should be less than or equal to requested off_nadir 10.0: confirmed True 83 | SWIFT STAC item '20190821T180028Z_561_POM1_ST2_P' from 2019-08-21T18:00:28+00:00 84 | has a off_nadir 8.978, which should be less than or equal to requested off_nadir 10.0: confirmed True 85 | SWIFT STAC item '20190821T180002Z_548_POM1_ST2_P' from 2019-08-21T18:00:02+00:00 86 | has a off_nadir 9.282, which should be less than or equal to requested off_nadir 10.0: confirmed True 87 | SWIFT STAC item '20190821T175954Z_544_POM1_ST2_P' from 2019-08-21T17:59:54+00:00 88 | has a off_nadir 8.855, which should be less than or equal to requested off_nadir 10.0: confirmed True 89 | SWIFT STAC item '20190821T175943Z_539_POM1_ST2_P' from 2019-08-21T17:59:43+00:00 90 | has a off_nadir 8.956, which should be less than or equal to requested off_nadir 10.0: confirmed True 91 | SWIFT STAC item '20190818T174304Z_205_POM1_ST2_P' from 2019-08-18T17:43:04+00:00 92 | has a off_nadir 7.015, which should be less than or equal to requested off_nadir 10.0: confirmed True 93 | SWIFT STAC item '20190818T174227Z_181_POM1_ST2_P' from 2019-08-18T17:42:27+00:00 94 | has a off_nadir 8.237, which should be less than or equal to requested off_nadir 10.0: confirmed True 95 | ``` 96 | 97 | 98 |
99 | 100 | 101 | 102 | Notice that the off_nadir value is printed with some floating point limiting (`:.3f`). Printing out the full value in python would introduce floating point precicion errors for the item. This is because the FloatValue is a float32, but python want's all number to be as large and precise as possible. This is something to be aware of when using Python in general. 103 | 104 | Also, even though we set the `limit` to 20, the print out only returns 2 values. For this location, there were only two scenes that were captured with that off nadir angle. 105 | 106 | ## Limits and Offsets 107 | It may be that while using the `client.search` request, you've requested so much data that you overrun the 15 second timeout. If that's the case, then you can search for data using `limit` and `offset`. 108 | 109 | For most simple requests, a `limit` and `offset` are not necessary. But if you're going through all the data in the archive or if you've constructed a complex request, it may be necessary. 110 | 111 | 112 | 113 | 114 | 115 |
Expand Python Code Sample 116 | 117 | 118 | ```python 119 | from datetime import date 120 | from nsl.stac.client import NSLClient 121 | from nsl.stac import StacRequest, GeometryData, ProjectionData, enum 122 | from nsl.stac.utils import pb_timestampfield 123 | # wkt geometry of Travis County, Texas 124 | travis_wkt = "POLYGON((-97.9736 30.6251, -97.9188 30.6032, -97.9243 30.5703, \ 125 | -97.8695 30.5484, -97.8476 30.4717, -97.7764 30.4279, \ 126 | -97.5793 30.4991, -97.3711 30.4170, -97.4916 30.2089, \ 127 | -97.6505 30.0719, -97.6669 30.0665, -97.7107 30.0226, \ 128 | -98.1708 30.3567, -98.1270 30.4279, -98.0503 30.6251))" 129 | 130 | # Query data from before September 1, 2019 131 | time_filter = pb_timestampfield(value=date(2019, 9, 1), rel_type=enum.FilterRelationship.LTE) 132 | 133 | geometry_data = GeometryData(wkt=travis_wkt, 134 | proj=ProjectionData(epsg=4326)) 135 | 136 | # get a client interface to the gRPC channel 137 | client = NSLClient() 138 | 139 | limit = 200 140 | offset = 0 141 | total = 0 142 | while total < 1000: 143 | # make our request 144 | stac_request = StacRequest(datetime=time_filter, intersects=geometry_data, limit=limit, offset=offset) 145 | # prepare request for next 146 | offset += limit 147 | for stac_item in client.search(stac_request): 148 | total += 1 149 | # do cool things with data here 150 | if total % limit == 0: 151 | print("stac item id: {0} at {1} index in request".format(stac_item.id, total)) 152 | ``` 153 | 154 | 155 |
156 | 157 | 158 | 159 | 160 |
Expand Python Print-out 161 | 162 | 163 | ```text 164 | stac item id: 20190829T172909Z_1600_POM1_ST2_P at 200 index in request 165 | stac item id: 20190829T172054Z_1354_POM1_ST2_P at 400 index in request 166 | stac item id: 20190829T171353Z_1152_POM1_ST2_P at 600 index in request 167 | stac item id: 20190829T170044Z_770_POM1_ST2_P at 800 index in request 168 | stac item id: 20190829T165121Z_495_POM1_ST2_P at 1000 index in request 169 | ``` 170 | 171 | 172 |
173 | 174 | 175 | 176 | As you can see in the above results, the `search` request is made 5 different times in the while loop. Each time the `limit` is 200 and the `offset` is increased by 200. 177 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7.7-slim-buster 2 | 3 | RUN DEBIAN_FRONTEND=noninteractive apt-get update 4 | 5 | WORKDIR /opt/src/stac-client-python 6 | COPY ./ /opt/src/stac-client-python 7 | 8 | RUN pip3 install --upgrade pip 9 | RUN pip3 install . 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README_files/README_1_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nearspacelabs/stac-client-python/e3a5695075a2439c63e95f80fb2d01f83fb483ff/README_files/README_1_1.jpg -------------------------------------------------------------------------------- /README_files/README_20_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nearspacelabs/stac-client-python/e3a5695075a2439c63e95f80fb2d01f83fb483ff/README_files/README_20_0.png -------------------------------------------------------------------------------- /README_files/README_20_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nearspacelabs/stac-client-python/e3a5695075a2439c63e95f80fb2d01f83fb483ff/README_files/README_20_1.png -------------------------------------------------------------------------------- /README_files/README_20_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nearspacelabs/stac-client-python/e3a5695075a2439c63e95f80fb2d01f83fb483ff/README_files/README_20_2.png -------------------------------------------------------------------------------- /StacItem.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## STAC Item Properties\n", 8 | "A STAC item is a metadata container for spatially and temporally bounded earth observation data. The data can be aerial imagery, radar data or other types of earth observation data. A STAC item has metadata properties describing the dataset and `Assets` that contain information for downloading the data being described. Almost all properties of a STAC item are aspects you can query by using a `StacRequest` with different types of filters.\n", 9 | "\n", 10 | "Return to [README.md](./README.md)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 1, 16 | "metadata": {}, 17 | "outputs": [ 18 | { 19 | "name": "stdout", 20 | "output_type": "stream", 21 | "text": [ 22 | "nsl client connecting to stac service at: api.nearspacelabs.net:9090\n", 23 | "\n", 24 | "attempting NSL authentication against https://api.nearspacelabs.net\n", 25 | "fetching new authorization in 60 minutes\n" 26 | ] 27 | } 28 | ], 29 | "source": [ 30 | "from nsl.stac.client import NSLClient\n", 31 | "from nsl.stac import StacRequest\n", 32 | "\n", 33 | "stac_request = StacRequest(id='20190822T183518Z_746_POM1_ST2_P')\n", 34 | "\n", 35 | "# get a client interface to the gRPC channel\n", 36 | "client = NSLClient()\n", 37 | "# for this request we might as well use the search one, as STAC ids ought to be unique\n", 38 | "stac_item = client.search_one(stac_request)" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "Here are the sections where we go into more detail about properties and assets.\n", 46 | "\n", 47 | "- [ID, Temporal, and Spatial](#id-temporal-and-spatial)\n", 48 | "- [Assets](#assets)\n", 49 | "- [Electro Optical](#electro-optical)\n", 50 | "\n", 51 | "Printing out all the data demonstrates what is typically in a StacItem:" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": 2, 57 | "metadata": {}, 58 | "outputs": [ 59 | { 60 | "name": "stdout", 61 | "output_type": "stream", 62 | "text": [ 63 | "id: \"20190822T183518Z_746_POM1_ST2_P\"\n", 64 | "collection: \"NSL_SCENE\"\n", 65 | "properties {\n", 66 | " type_url: \"nearspacelabs.com/proto/st.protobuf.v1.NslDatast.protobuf.v1.NslData/st.protobuf.v1.NslData\"\n", 67 | " value: \"\\n\\340\\014\\n\\03620190822T162258Z_TRAVIS_COUNTY\\\"\\003 \\352\\0052\\03520200702T102306Z_746_ST2_POM1:\\03520190822T183518Z_746_POM1_ST2:\\03520200702T101632Z_746_ST2_POM1:\\03520200702T102302Z_746_ST2_POM1:\\03520200702T102306Z_746_ST2_POM1B\\03520190822T183518Z_746_POM1_ST2H\\001R\\374\\n\\n$\\004\\304{?\\216\\371\\350=\\376\\377\\306>\\300\\327\\256\\275\\323rv?2\\026*D3Qy6\\177>\\3675\\000\\000\\200?\\022\\024\\r+}\\303\\302\\025\\033;\\362A\\0353}\\367\\300%g\\232\\250@\\022\\024\\r\\026}\\303\\302\\025\\376?\\362A\\035\\000\\367\\235@%\\232\\t\\331?\\022\\024\\r\\351|\\303\\302\\025\\021A\\362A\\035M\\370\\033\\301%g\\016\\226\\277\\022\\024\\r\\201|\\303\\302\\025\\3709\\362A\\035\\000\\252\\245@%\\315\\3547?\\022\\024\\r\\310|\\303\\302\\025\\245G\\362A\\035\\232\\315l\\301%3\\347\\270\\300\\022\\024\\rq|\\303\\302\\025\\2149\\362A\\035\\000\\376o@%\\000(\\017@\\022\\024\\rD|\\303\\302\\025oD\\362A\\0353\\323\\302\\301%\\315\\306\\230\\300\\022\\024\\r\\031|\\303\\302\\025\\035=\\362A\\035g\\277$A%\\000\\340\\231?\\022\\024\\rE|\\303\\302\\025\\215I\\362A\\0353\\275z\\300%g\\020\\236\\300\\022\\024\\r\\345{\\303\\302\\0258C\\362A\\035\\0008\\242?%\\232\\231\\226\\277\\022\\024\\r\\010|\\303\\302\\025!I\\362A\\0353\\377\\212\\300%\\000V\\241\\300\\022\\024\\r|{\\303\\302\\025\\207F\\362A\\0353\\203Y@%\\315,\\313\\276\\022\\024\\r\\001{\\303\\302\\025FJ\\362A\\035g^\\025@%\\315\\010\\214?\\022\\024\\r\\313z\\303\\302\\025\\353H\\362A\\0353\\3377@%g\\326\\325\\277\\022\\024\\rjz\\303\\302\\025\\260@\\362A\\035\\315F\\006A%g\\246[\\277\\022\\024\\r\\035z\\303\\302\\0254E\\362A\\035\\232\\001|@%\\232!\\265?\\022\\024\\r\\330y\\303\\302\\025\\320@\\362A\\0353Sa\\300%\\000@\\245>\\022\\024\\r\\362y\\303\\302\\025zE\\362A\\035\\232\\221\\020\\300%3U\\206@\\022\\024\\r\\337y\\303\\302\\025\\210F\\362A\\035g\\246l?%gf\\234\\276\\022\\024\\r\\335y\\303\\302\\025aF\\362A\\035\\000\\260\\023@%\\315,#\\277\\022\\024\\r\\321y\\303\\302\\025\\234F\\362A\\035\\000 7@%\\232!\\221?\\022\\024\\r\\307y\\303\\302\\025\\177F\\362A\\035\\232\\371\\371?%\\315\\224\\225?\\022\\024\\r\\213y\\303\\302\\025\\350@\\362A\\0353\\'\\343\\300%3g&\\300\\022\\024\\r\\300y\\303\\302\\025\\tF\\362A\\035\\315h\\312@%g\\266\\013?\\022\\024\\r_y\\303\\302\\025\\236A\\362A\\035\\315\\340\\311@%3\\363j>\\022\\024\\r\\271x\\303\\302\\025G?\\362A\\0353\\334\\272\\301%gb\\201\\300\\022\\024\\r\\307x\\303\\302\\025WG\\362A\\035\\000|6\\301%\\232\\231i>\\022\\024\\r\\200x\\303\\302\\025\\016F\\362A\\035\\315\\007\\244\\301%\\315L\\000>\\022\\024\\rqx\\303\\302\\025jI\\362A\\035\\315\\254\\007\\301%\\232E\\247?\\022\\024\\rjx\\303\\302\\025(I\\362A\\035\\232\\305\\000\\301%\\315L\\'>\\022\\024\\r\\027x\\303\\302\\025\\356A\\362A\\035\\232I\\246?%\\315\\004\\246\\277\\022\\024\\r\\010x\\303\\302\\025AB\\362A\\035\\232y\\305\\300%\\315\\3740?\\022\\024\\r\\032x\\303\\302\\0257D\\362A\\0353\\003\\275\\277%\\232\\311.?\\022\\024\\r\\002x\\303\\302\\025&C\\362A\\035\\315\\014\\301\\277%g*2@\\022\\024\\r\\361w\\303\\302\\025\\330B\\362A\\035\\000T\\347\\300%\\232\\235\\025\\300\\022\\024\\r\\372v\\303\\302\\025\\030<\\362A\\0353\\323\\364?%gNt\\300\\022\\024\\r;w\\303\\302\\025\\273I\\362A\\03533\\335>%\\232\\025\\213?\\022\\024\\r\\324v\\303\\302\\025QC\\362A\\035\\315,\\305\\277%\\232\\375\\035@\\022\\024\\r\\340v\\303\\302\\025@G\\362A\\035\\315@\\234\\300%\\232)\\342?\\022\\024\\r\\312v\\303\\302\\025yC\\362A\\035\\315\\214\\247\\276%g\\246\\375>\\022\\024\\r\\222v\\303\\302\\025\\233A\\362A\\035\\315\\334\\244?%g\\366\\035\\277\\022\\024\\r\\256v\\303\\302\\025\\\\F\\362A\\0353G\\204@%\\232A\\017@\\022\\024\\rov\\303\\302\\025\\215=\\362A\\035\\232\\325\\340@%3\\263\\033\\276\\022\\024\\r\\206v\\303\\302\\025SC\\362A\\0353\\263k?%3\\363\\177\\276\\022\\024\\r\\267v\\303\\302\\025NK\\362A\\035\\315\\0148\\277%3\\323\\000>\\022\\024\\r\\255v\\303\\302\\025kK\\362A\\035gf4\\277%\\000\\312\\201\\277\\022\\024\\r)v\\303\\302\\025\\316=\\362A\\035\\232\\271Z\\277%\\315\\014\\375\\277\\022\\024\\r_v\\303\\302\\025\\356H\\362A\\035\\315\\004n@%3\\243\\240\\276\\022\\024\\r7v\\303\\302\\025\\350H\\362A\\0353#\\212@%g~\\272?\\022\\024\\r\\314u\\303\\302\\025Y;\\362A\\035\\000\\000F=%gF\\253?\\022\\024\\r\\276u\\303\\302\\025q>\\362A\\0353/\\234\\300%g\\246T\\277\\022\\024\\r\\266u\\303\\302\\025\\321>\\362A\\035\\315 \\272\\300%3SW\\300\\022\\024\\r\\307u\\303\\302\\025\\211A\\362A\\035\\000$\\264\\300%3\\243\\r\\277\\022\\024\\r\\360u\\303\\302\\025RK\\362A\\0353\\347\\231@%\\315\\325\\036\\300\\022\\024\\r\\262u\\303\\302\\025\\035F\\362A\\0353\\2633\\276%\\232i3?\\032#m_3009743_sw_14_1_20160928_20161129\\\"Y\\t&\\2068NM\\357\\\"A\\021\\003\\3272rL\\217IA\\031\\267G\\014x\\260\\375\\\"A!\\202I\\225>\\020\\222IA*3\\0221+proj=utm +zone=14 +datum=NAD83 +units=m +no_defs*\\005\\r\\205[\\\"A2\\005\\r\\000\\356\\\\@:\\005\\r\\227\\210\\306AB\\005\\r\\205E\\257@\\022\\315\\001\\n e502fe83507f0d28c826f33619a678e9\\022\\03120200806T033934Z_SWIFTERA\\030\\010 \\377\\377\\377\\377\\377\\377\\377\\377\\377\\001(A0\\0018\\340\\025@\\330\\247\\004H\\270\\275\\004R\\03620190822T162258Z_TRAVIS_COUNTYR\\03120200701T112634Z_SWIFTERAR\\03120200701T112634Z_SWIFTERAR\\03120200701T112634Z_SWIFTERAX\\263\\027\"\n", 68 | "}\n", 69 | "assets {\n", 70 | " key: \"GEOTIFF_RGB\"\n", 71 | " value {\n", 72 | " href: \"https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif\"\n", 73 | " type: \"image/vnd.stac.geotiff\"\n", 74 | " eo_bands: RGB\n", 75 | " asset_type: GEOTIFF\n", 76 | " cloud_platform: GCP\n", 77 | " bucket_manager: \"Near Space Labs\"\n", 78 | " bucket_region: \"us-central1\"\n", 79 | " bucket: \"swiftera-processed-data\"\n", 80 | " object_path: \"20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif\"\n", 81 | " }\n", 82 | "}\n", 83 | "assets {\n", 84 | " key: \"THUMBNAIL_RGB\"\n", 85 | " value {\n", 86 | " href: \"https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png\"\n", 87 | " type: \"image/png\"\n", 88 | " eo_bands: RGB\n", 89 | " asset_type: THUMBNAIL\n", 90 | " cloud_platform: GCP\n", 91 | " bucket_manager: \"Near Space Labs\"\n", 92 | " bucket_region: \"us-central1\"\n", 93 | " bucket: \"swiftera-processed-data\"\n", 94 | " object_path: \"20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png\"\n", 95 | " }\n", 96 | "}\n", 97 | "geometry {\n", 98 | " wkb: \"\\001\\006\\000\\000\\000\\001\\000\\000\\000\\001\\003\\000\\000\\000\\001\\000\\000\\000\\005\\000\\000\\000\\352\\244L\\267\\311oX\\300\\316\\340\\320\\247\\234I>@\\241\\273\\2606\\267oX\\300<\\002\\205\\'EG>@\\031\\003\\203\\307\\266nX\\3001z\\244\\372\\233G>@CCAI\\306nX\\300\\326\\013\\351\\023\\343I>@\\352\\244L\\267\\311oX\\300\\316\\340\\320\\247\\234I>@\"\n", 99 | " proj {\n", 100 | " epsg: 4326\n", 101 | " }\n", 102 | " envelope {\n", 103 | " xmin: -97.7466867683867\n", 104 | " ymin: 30.278398961994966\n", 105 | " xmax: -97.72990596574927\n", 106 | " ymax: 30.288621181865743\n", 107 | " proj {\n", 108 | " epsg: 4326\n", 109 | " }\n", 110 | " }\n", 111 | " simple: STRONG_SIMPLE\n", 112 | "}\n", 113 | "bbox {\n", 114 | " xmin: -97.7466867683867\n", 115 | " ymin: 30.278398961994966\n", 116 | " xmax: -97.72990596574927\n", 117 | " ymax: 30.288621181865743\n", 118 | " proj {\n", 119 | " epsg: 4326\n", 120 | " }\n", 121 | "}\n", 122 | "datetime {\n", 123 | " seconds: 1566498918\n", 124 | " nanos: 505476000\n", 125 | "}\n", 126 | "observed {\n", 127 | " seconds: 1566498918\n", 128 | " nanos: 505476000\n", 129 | "}\n", 130 | "created {\n", 131 | " seconds: 1596743811\n", 132 | " nanos: 247169000\n", 133 | "}\n", 134 | "updated {\n", 135 | " seconds: 1612193286\n", 136 | " nanos: 12850810\n", 137 | "}\n", 138 | "platform_enum: SWIFT_2\n", 139 | "platform: \"SWIFT_2\"\n", 140 | "instrument_enum: POM_1\n", 141 | "instrument: \"POM_1\"\n", 142 | "constellation: \"UNKNOWN_CONSTELLATION\"\n", 143 | "mission_enum: SWIFT\n", 144 | "mission: \"SWIFT\"\n", 145 | "gsd {\n", 146 | " value: 0.20000000298023224\n", 147 | "}\n", 148 | "eo {\n", 149 | "}\n", 150 | "view {\n", 151 | " off_nadir {\n", 152 | " value: 9.42326831817627\n", 153 | " }\n", 154 | " azimuth {\n", 155 | " value: -74.85270690917969\n", 156 | " }\n", 157 | " sun_azimuth {\n", 158 | " value: 181.26959228515625\n", 159 | " }\n", 160 | " sun_elevation {\n", 161 | " value: 71.41288757324219\n", 162 | " }\n", 163 | "}\n", 164 | "\n" 165 | ] 166 | } 167 | ], 168 | "source": [ 169 | "print(stac_item)" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "In addition to spatial and temporal details there are also details about the capturing device. We use both strings (to stay compliant with STAC JSON) and enum fields for these details. The `platform_enum` and `platform` is the model of the vehicle holding the sensor. The `instrument_enum` and `instrument` is the sensor that collected the scenes. In our case we're using `mission_enum` and `mission` to represent a class of flight vehicles that we're flying. In the case of the Landsat satellite program the breakdown would be:\n", 177 | "\n", 178 | " * `platform_enum`: `enum.PLATFORM.LANDSAT_8`\n", 179 | " * `sensor_enum`: `enum.SENSOR.OLI_TIRS`\n", 180 | " * `mission_enum`: `enum.MISSION.LANDSAT`\n", 181 | " * `platform`: \"LANDSAT_8\"\n", 182 | " * `sensor`: \"OLI_TIRS\"\n", 183 | " * `mission`: \"LANDSAT\"\n", 184 | "\n", 185 | "\n", 186 | "### ID Temporal and Spatial\n", 187 | "Every STAC Item has a unique id, a datetime/observation, and a geometry/bbox (bounding-box)." 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 3, 193 | "metadata": {}, 194 | "outputs": [ 195 | { 196 | "name": "stdout", 197 | "output_type": "stream", 198 | "text": [ 199 | "STAC Item id: 20190822T183518Z_746_POM1_ST2_P\n", 200 | "\n", 201 | "STAC Item observed: seconds: 1566498918\n", 202 | "nanos: 505476000\n", 203 | "\n", 204 | "STAC Item datetime: seconds: 1566498918\n", 205 | "nanos: 505476000\n", 206 | "\n", 207 | "STAC Item bbox: xmin: -97.7466867683867\n", 208 | "ymin: 30.278398961994966\n", 209 | "xmax: -97.72990596574927\n", 210 | "ymax: 30.288621181865743\n", 211 | "proj {\n", 212 | " epsg: 4326\n", 213 | "}\n", 214 | "\n", 215 | "STAC Item geometry: wkb: \"\\001\\006\\000\\000\\000\\001\\000\\000\\000\\001\\003\\000\\000\\000\\001\\000\\000\\000\\005\\000\\000\\000\\352\\244L\\267\\311oX\\300\\316\\340\\320\\247\\234I>@\\241\\273\\2606\\267oX\\300<\\002\\205\\'EG>@\\031\\003\\203\\307\\266nX\\3001z\\244\\372\\233G>@CCAI\\306nX\\300\\326\\013\\351\\023\\343I>@\\352\\244L\\267\\311oX\\300\\316\\340\\320\\247\\234I>@\"\n", 216 | "proj {\n", 217 | " epsg: 4326\n", 218 | "}\n", 219 | "envelope {\n", 220 | " xmin: -97.7466867683867\n", 221 | " ymin: 30.278398961994966\n", 222 | " xmax: -97.72990596574927\n", 223 | " ymax: 30.288621181865743\n", 224 | " proj {\n", 225 | " epsg: 4326\n", 226 | " }\n", 227 | "}\n", 228 | "simple: STRONG_SIMPLE\n", 229 | "\n" 230 | ] 231 | } 232 | ], 233 | "source": [ 234 | "print(\"STAC Item id: {}\\n\".format(stac_item.id))\n", 235 | "print(\"STAC Item observed: {}\".format(stac_item.observed))\n", 236 | "print(\"STAC Item datetime: {}\".format(stac_item.datetime))\n", 237 | "print(\"STAC Item bbox: {}\".format(stac_item.bbox))\n", 238 | "print(\"STAC Item geometry: {}\".format(stac_item.geometry))" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "metadata": {}, 244 | "source": [ 245 | "As you can see above, the `id` is a string value. The format of the id is typically not guessable (ours is based of off the time the data was processed, the image index, the platform and the sensor).\n", 246 | "\n", 247 | "The `observed` and `datetime` fields are the same value. STAC specification uses a generic field `datetime` to define the spatial component, the `S`, in STAC. We wanted a more descriptive variable, so we use `observed`, as in, the moment the scene was captured. This is a UTC timestamp in seconds and nano seconds.\n", 248 | "\n", 249 | "The `bbox` field describes the xmin, ymin, xmax, and ymax points that describe the bounding box that contains the scene. The `sr` field has an [epsg](http://www.epsg.org/) `wkid`. In this case the 4326 `wkid` indicates [WGS-84](http://epsg.io/4326)\n", 250 | "\n", 251 | "The `geometry` field has subfields `wkb`, `sr`, and `simple`. The `wkb` is a [well known binary](https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary) geometry format preferred for it's size. `sr` is the same as in the `bbox`. `simple` can be ignored.\n", 252 | "\n", 253 | "Below we demonstrate how you can create python `datetime` objects:" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 4, 259 | "metadata": {}, 260 | "outputs": [ 261 | { 262 | "name": "stdout", 263 | "output_type": "stream", 264 | "text": [ 265 | "UTC Observed Scene: 2019-08-22 18:35:18\n", 266 | "UTC Processed Data: 2020-08-06 19:56:51\n", 267 | "UTC Updated Metadata: 2021-02-01 15:28:06\n" 268 | ] 269 | } 270 | ], 271 | "source": [ 272 | "from datetime import datetime\n", 273 | "print(\"UTC Observed Scene: {}\".format(datetime.utcfromtimestamp(stac_item.observed.seconds)))\n", 274 | "print(\"UTC Processed Data: {}\".format(datetime.utcfromtimestamp(stac_item.created.seconds)))\n", 275 | "print(\"UTC Updated Metadata: {}\".format(datetime.utcfromtimestamp(stac_item.updated.seconds)))" 276 | ] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "metadata": {}, 281 | "source": [ 282 | "Updated is when the metadata was last updated. Typically that will be right after it's `processed` timestamp.\n", 283 | "\n", 284 | "Below is a demo of using shapely to get at the geometry data." 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 5, 290 | "metadata": {}, 291 | "outputs": [ 292 | { 293 | "name": "stdout", 294 | "output_type": "stream", 295 | "text": [ 296 | "wkt printout of polygon:\n", 297 | "MULTIPOLYGON (((-97.7466867683867 30.28754662370266, -97.74555747279238 30.27839896199497, -97.72990596574927 30.27972380176124, -97.73085242627444 30.28862118186574, -97.7466867683867 30.28754662370266)))\n", 298 | "\n", 299 | "centroid of polygon:\n", 300 | "POINT (-97.738289581264 30.28357703330576)\n", 301 | "\n", 302 | "bounds:\n", 303 | "POLYGON ((-97.7466867683867 30.27839896199497, -97.7466867683867 30.28862118186574, -97.72990596574927 30.28862118186574, -97.72990596574927 30.27839896199497, -97.7466867683867 30.27839896199497))\n", 304 | "\n" 305 | ] 306 | } 307 | ], 308 | "source": [ 309 | "from shapely.geometry import Polygon\n", 310 | "from shapely.wkb import loads\n", 311 | "\n", 312 | "print(\"wkt printout of polygon:\\n{}\\n\".format(loads(stac_item.geometry.wkb)))\n", 313 | "print(\"centroid of polygon:\\n{}\\n\".format(loads(stac_item.geometry.wkb).centroid))\n", 314 | "print(\"bounds:\\n{}\\n\".format(Polygon.from_bounds(stac_item.bbox.xmin, \n", 315 | " stac_item.bbox.ymin, \n", 316 | " stac_item.bbox.xmax, \n", 317 | " stac_item.bbox.ymax)))" 318 | ] 319 | }, 320 | { 321 | "cell_type": "markdown", 322 | "metadata": {}, 323 | "source": [ 324 | "### Assets\n", 325 | "Each STAC item should have at least one asset. An asset should be all the information you'll need to download the asset in question. For Near Space Labs customers, you'll be using the href, but you can also see the private bucket details of the asset. In protobuf the asset map has a key for each asset available. There's no part of the STAC specification for defining key names. Near Space Labs typically uses the data type, the optical bands and the cloud storage provider to construct a key name." 326 | ] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "execution_count": 6, 331 | "metadata": {}, 332 | "outputs": [ 333 | { 334 | "name": "stdout", 335 | "output_type": "stream", 336 | "text": [ 337 | "there are 2 assets\n", 338 | "THUMBNAIL\n", 339 | " href: https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png\n", 340 | " type: image/png\n", 341 | " protobuf enum number and name: 9, THUMBNAIL\n", 342 | "\n", 343 | "GEOTIFF\n", 344 | " href: https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif\n", 345 | " type: image/vnd.stac.geotiff\n", 346 | " protobuf enum number and name: 2, GEOTIFF\n", 347 | "\n" 348 | ] 349 | } 350 | ], 351 | "source": [ 352 | "from nsl.stac import Asset, utils\n", 353 | "from nsl.stac.enum import AssetType\n", 354 | "def print_asset(asset: Asset):\n", 355 | " asset_name = AssetType(asset.asset_type).name\n", 356 | " print(\" href: {}\".format(asset.href))\n", 357 | " print(\" type: {}\".format(asset.type))\n", 358 | " print(\" protobuf enum number and name: {0}, {1}\".format(asset.asset_type, asset_name))\n", 359 | " print()\n", 360 | "\n", 361 | "print(\"there are {} assets\".format(len(stac_item.assets)))\n", 362 | "print(AssetType.THUMBNAIL.name)\n", 363 | "print_asset(utils.get_asset(stac_item, asset_type=AssetType.THUMBNAIL))\n", 364 | "\n", 365 | "print(AssetType.GEOTIFF.name)\n", 366 | "print_asset(utils.get_asset(stac_item, asset_type=AssetType.GEOTIFF))" 367 | ] 368 | }, 369 | { 370 | "cell_type": "markdown", 371 | "metadata": {}, 372 | "source": [ 373 | "As you can see above, our data only consists of jpg thumbnails and Geotiffs. But there can be other data stored in Assets in the future.\n", 374 | "\n", 375 | "You can read more details about Assets [here](https://geo-grpc.github.io/api/#epl.protobuf.Asset)\n", 376 | "\n", 377 | "### View\n", 378 | "Some imagery analysis tools require knowing certain types of angular information. Here's a printout of the information we've collected with data. A summary of View values can be found [here](https://geo-grpc.github.io/api/#epl.protobuf.v1.View)." 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": 7, 384 | "metadata": {}, 385 | "outputs": [ 386 | { 387 | "name": "stdout", 388 | "output_type": "stream", 389 | "text": [ 390 | "off_nadir {\n", 391 | " value: 9.42326831817627\n", 392 | "}\n", 393 | "azimuth {\n", 394 | " value: -74.85270690917969\n", 395 | "}\n", 396 | "sun_azimuth {\n", 397 | " value: 181.26959228515625\n", 398 | "}\n", 399 | "sun_elevation {\n", 400 | " value: 71.41288757324219\n", 401 | "}\n", 402 | "\n" 403 | ] 404 | } 405 | ], 406 | "source": [ 407 | "print(stac_item.view)" 408 | ] 409 | }, 410 | { 411 | "cell_type": "markdown", 412 | "metadata": {}, 413 | "source": [ 414 | "These `sun_azimuth`, `sun_elevation`, `off_nadir` and `azimuth` are all boxed in the [google.protobuf.FloatValue type](https://developers.google.com/protocol-buffers/docs/reference/csharp/class/google/protobuf/well-known-types/float-value). To get at the value you must access the `value` field." 415 | ] 416 | }, 417 | { 418 | "cell_type": "code", 419 | "execution_count": 8, 420 | "metadata": {}, 421 | "outputs": [ 422 | { 423 | "name": "stdout", 424 | "output_type": "stream", 425 | "text": [ 426 | "sun_azimuth: 181.26959\n", 427 | "sun_elevation: 71.41289\n", 428 | "off_nadir: 9.42327\n", 429 | "azimuth: -74.85271\n" 430 | ] 431 | } 432 | ], 433 | "source": [ 434 | "print(\"sun_azimuth: {:.5f}\".format(stac_item.view.sun_azimuth.value))\n", 435 | "print(\"sun_elevation: {:.5f}\".format(stac_item.view.sun_elevation.value))\n", 436 | "print(\"off_nadir: {:.5f}\".format(stac_item.view.off_nadir.value))\n", 437 | "print(\"azimuth: {:.5f}\".format(stac_item.view.azimuth.value))" 438 | ] 439 | }, 440 | { 441 | "cell_type": "markdown", 442 | "metadata": {}, 443 | "source": [ 444 | "Notice that we're only printing out 5 decimal places. As these are stored as float values, we can't trust any of the precision that Python provides us beyond what we know the data to possess.\n", 445 | "\n", 446 | "You can read more details about electro-optical data [here](https://geo-grpc.github.io/api/#epl.protobuf.Eo)\n", 447 | "\n", 448 | "Return to [README.md](./README.md)" 449 | ] 450 | } 451 | ], 452 | "metadata": { 453 | "kernelspec": { 454 | "display_name": "Python 3", 455 | "language": "python", 456 | "name": "python3" 457 | }, 458 | "language_info": { 459 | "codemirror_mode": { 460 | "name": "ipython", 461 | "version": 3 462 | }, 463 | "file_extension": ".py", 464 | "mimetype": "text/x-python", 465 | "name": "python", 466 | "nbconvert_exporter": "python", 467 | "pygments_lexer": "ipython3", 468 | "version": "3.9.2" 469 | } 470 | }, 471 | "nbformat": 4, 472 | "nbformat_minor": 2 473 | } 474 | -------------------------------------------------------------------------------- /StacItem.md: -------------------------------------------------------------------------------- 1 | ## STAC Item Properties 2 | A STAC item is a metadata container for spatially and temporally bounded earth observation data. The data can be aerial imagery, radar data or other types of earth observation data. A STAC item has metadata properties describing the dataset and `Assets` that contain information for downloading the data being described. Almost all properties of a STAC item are aspects you can query by using a `StacRequest` with different types of filters. 3 | 4 | Return to [README.md](./README.md) 5 | 6 | 7 | 8 | 9 | 10 |
Expand Python Code Sample 11 | 12 | 13 | ```python 14 | from nsl.stac.client import NSLClient 15 | from nsl.stac import StacRequest 16 | 17 | stac_request = StacRequest(id='20190822T183518Z_746_POM1_ST2_P') 18 | 19 | # get a client interface to the gRPC channel 20 | client = NSLClient() 21 | # for this request we might as well use the search one, as STAC ids ought to be unique 22 | stac_item = client.search_one(stac_request) 23 | ``` 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Expand Python Print-out 32 | 33 | 34 | ```text 35 | found NSL_ID under profile name `default` 36 | nsl client connecting to stac service at: api.nearspacelabs.net:9090 37 | 38 | authorizing NSL_ID: `` 39 | attempting NSL authentication against https://api.nearspacelabs.net/oauth/token... 40 | successfully authenticated with NSL_ID: `` 41 | will attempt re-authorization in 60 minutes 42 | ``` 43 | 44 | 45 |
46 | 47 | 48 | 49 | Here are the sections where we go into more detail about properties and assets. 50 | 51 | - [ID, Temporal, and Spatial](#id-temporal-and-spatial) 52 | - [Assets](#assets) 53 | - [Electro Optical](#electro-optical) 54 | 55 | Printing out all the data demonstrates what is typically in a StacItem: 56 | 57 | 58 | 59 | 60 | 61 |
Expand Python Code Sample 62 | 63 | 64 | ```python 65 | print(stac_item) 66 | ``` 67 | 68 | 69 |
70 | 71 | 72 | 73 | 74 |
Expand Python Print-out 75 | 76 | 77 | ```text 78 | id: "20190822T183518Z_746_POM1_ST2_P" 79 | collection: "NSL_SCENE" 80 | properties { 81 | type_url: "nearspacelabs.com/proto/st.protobuf.v1.NslDatast.protobuf.v1.NslData/st.protobuf.v1.NslData" 82 | value: "\n\340\014\n\03620190822T162258Z_TRAVIS_COUNTY\"\003 \352\0052\03520200702T102306Z_746_ST2_POM1:\03520190822T183518Z_746_POM1_ST2:\03520200702T101632Z_746_ST2_POM1:\03520200702T102302Z_746_ST2_POM1:\03520200702T102306Z_746_ST2_POM1B\03520190822T183518Z_746_POM1_ST2H\001R\374\n\n$\004\304{?\216\371\350=\376\377\306>\300\327\256\275\323rv?2\026*D3Qy6\177>\3675\000\000\200?\022\024\r+}\303\302\025\033;\362A\0353}\367\300%g\232\250@\022\024\r\026}\303\302\025\376?\362A\035\000\367\235@%\232\t\331?\022\024\r\351|\303\302\025\021A\362A\035M\370\033\301%g\016\226\277\022\024\r\201|\303\302\025\3709\362A\035\000\252\245@%\315\3547?\022\024\r\310|\303\302\025\245G\362A\035\232\315l\301%3\347\270\300\022\024\rq|\303\302\025\2149\362A\035\000\376o@%\000(\017@\022\024\rD|\303\302\025oD\362A\0353\323\302\301%\315\306\230\300\022\024\r\031|\303\302\025\035=\362A\035g\277$A%\000\340\231?\022\024\rE|\303\302\025\215I\362A\0353\275z\300%g\020\236\300\022\024\r\345{\303\302\0258C\362A\035\0008\242?%\232\231\226\277\022\024\r\010|\303\302\025!I\362A\0353\377\212\300%\000V\241\300\022\024\r|{\303\302\025\207F\362A\0353\203Y@%\315,\313\276\022\024\r\001{\303\302\025FJ\362A\035g^\025@%\315\010\214?\022\024\r\313z\303\302\025\353H\362A\0353\3377@%g\326\325\277\022\024\rjz\303\302\025\260@\362A\035\315F\006A%g\246[\277\022\024\r\035z\303\302\0254E\362A\035\232\001|@%\232!\265?\022\024\r\330y\303\302\025\320@\362A\0353Sa\300%\000@\245>\022\024\r\362y\303\302\025zE\362A\035\232\221\020\300%3U\206@\022\024\r\337y\303\302\025\210F\362A\035g\246l?%gf\234\276\022\024\r\335y\303\302\025aF\362A\035\000\260\023@%\315,#\277\022\024\r\321y\303\302\025\234F\362A\035\000 7@%\232!\221?\022\024\r\307y\303\302\025\177F\362A\035\232\371\371?%\315\224\225?\022\024\r\213y\303\302\025\350@\362A\0353\'\343\300%3g&\300\022\024\r\300y\303\302\025\tF\362A\035\315h\312@%g\266\013?\022\024\r_y\303\302\025\236A\362A\035\315\340\311@%3\363j>\022\024\r\271x\303\302\025G?\362A\0353\334\272\301%gb\201\300\022\024\r\307x\303\302\025WG\362A\035\000|6\301%\232\231i>\022\024\r\200x\303\302\025\016F\362A\035\315\007\244\301%\315L\000>\022\024\rqx\303\302\025jI\362A\035\315\254\007\301%\232E\247?\022\024\rjx\303\302\025(I\362A\035\232\305\000\301%\315L\'>\022\024\r\027x\303\302\025\356A\362A\035\232I\246?%\315\004\246\277\022\024\r\010x\303\302\025AB\362A\035\232y\305\300%\315\3740?\022\024\r\032x\303\302\0257D\362A\0353\003\275\277%\232\311.?\022\024\r\002x\303\302\025&C\362A\035\315\014\301\277%g*2@\022\024\r\361w\303\302\025\330B\362A\035\000T\347\300%\232\235\025\300\022\024\r\372v\303\302\025\030<\362A\0353\323\364?%gNt\300\022\024\r;w\303\302\025\273I\362A\03533\335>%\232\025\213?\022\024\r\324v\303\302\025QC\362A\035\315,\305\277%\232\375\035@\022\024\r\340v\303\302\025@G\362A\035\315@\234\300%\232)\342?\022\024\r\312v\303\302\025yC\362A\035\315\214\247\276%g\246\375>\022\024\r\222v\303\302\025\233A\362A\035\315\334\244?%g\366\035\277\022\024\r\256v\303\302\025\\F\362A\0353G\204@%\232A\017@\022\024\rov\303\302\025\215=\362A\035\232\325\340@%3\263\033\276\022\024\r\206v\303\302\025SC\362A\0353\263k?%3\363\177\276\022\024\r\267v\303\302\025NK\362A\035\315\0148\277%3\323\000>\022\024\r\255v\303\302\025kK\362A\035gf4\277%\000\312\201\277\022\024\r)v\303\302\025\316=\362A\035\232\271Z\277%\315\014\375\277\022\024\r_v\303\302\025\356H\362A\035\315\004n@%3\243\240\276\022\024\r7v\303\302\025\350H\362A\0353#\212@%g~\272?\022\024\r\314u\303\302\025Y;\362A\035\000\000F=%gF\253?\022\024\r\276u\303\302\025q>\362A\0353/\234\300%g\246T\277\022\024\r\266u\303\302\025\321>\362A\035\315 \272\300%3SW\300\022\024\r\307u\303\302\025\211A\362A\035\000$\264\300%3\243\r\277\022\024\r\360u\303\302\025RK\362A\0353\347\231@%\315\325\036\300\022\024\r\262u\303\302\025\035F\362A\0353\2633\276%\232i3?\032#m_3009743_sw_14_1_20160928_20161129\"Y\t&\2068NM\357\"A\021\003\3272rL\217IA\031\267G\014x\260\375\"A!\202I\225>\020\222IA*3\0221+proj=utm +zone=14 +datum=NAD83 +units=m +no_defs*\005\r\205[\"A2\005\r\000\356\\@:\005\r\227\210\306AB\005\r\205E\257@\022\315\001\n e502fe83507f0d28c826f33619a678e9\022\03120200806T033934Z_SWIFTERA\030\010 \377\377\377\377\377\377\377\377\377\001(A0\0018\340\025@\330\247\004H\270\275\004R\03620190822T162258Z_TRAVIS_COUNTYR\03120200701T112634Z_SWIFTERAR\03120200701T112634Z_SWIFTERAR\03120200701T112634Z_SWIFTERAX\263\027" 83 | } 84 | assets { 85 | key: "GEOTIFF_RGB" 86 | value { 87 | href: "https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif" 88 | type: "image/vnd.stac.geotiff" 89 | eo_bands: RGB 90 | asset_type: GEOTIFF 91 | cloud_platform: GCP 92 | bucket_manager: "Near Space Labs" 93 | bucket_region: "us-central1" 94 | bucket: "swiftera-processed-data" 95 | object_path: "20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif" 96 | } 97 | } 98 | assets { 99 | key: "THUMBNAIL_RGB" 100 | value { 101 | href: "https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png" 102 | type: "image/png" 103 | eo_bands: RGB 104 | asset_type: THUMBNAIL 105 | cloud_platform: GCP 106 | bucket_manager: "Near Space Labs" 107 | bucket_region: "us-central1" 108 | bucket: "swiftera-processed-data" 109 | object_path: "20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png" 110 | } 111 | } 112 | geometry { 113 | wkb: "\001\006\000\000\000\001\000\000\000\001\003\000\000\000\001\000\000\000\005\000\000\000\352\244L\267\311oX\300\316\340\320\247\234I>@\241\273\2606\267oX\300<\002\205\'EG>@\031\003\203\307\266nX\3001z\244\372\233G>@CCAI\306nX\300\326\013\351\023\343I>@\352\244L\267\311oX\300\316\340\320\247\234I>@" 114 | proj { 115 | epsg: 4326 116 | } 117 | envelope { 118 | xmin: -97.7466867683867 119 | ymin: 30.278398961994966 120 | xmax: -97.72990596574927 121 | ymax: 30.288621181865743 122 | proj { 123 | epsg: 4326 124 | } 125 | } 126 | simple: STRONG_SIMPLE 127 | } 128 | bbox { 129 | xmin: -97.7466867683867 130 | ymin: 30.278398961994966 131 | xmax: -97.72990596574927 132 | ymax: 30.288621181865743 133 | proj { 134 | epsg: 4326 135 | } 136 | } 137 | datetime { 138 | seconds: 1566498918 139 | nanos: 505476000 140 | } 141 | observed { 142 | seconds: 1566498918 143 | nanos: 505476000 144 | } 145 | created { 146 | seconds: 1596743811 147 | nanos: 247169000 148 | } 149 | updated { 150 | seconds: 1612193286 151 | nanos: 12850810 152 | } 153 | platform_enum: SWIFT_2 154 | platform: "SWIFT_2" 155 | instrument_enum: POM_1 156 | instrument: "POM_1" 157 | constellation: "UNKNOWN_CONSTELLATION" 158 | mission_enum: SWIFT 159 | mission: "SWIFT" 160 | gsd { 161 | value: 0.20000000298023224 162 | } 163 | eo { 164 | } 165 | view { 166 | off_nadir { 167 | value: 9.42326831817627 168 | } 169 | azimuth { 170 | value: -74.85270690917969 171 | } 172 | sun_azimuth { 173 | value: 181.26959228515625 174 | } 175 | sun_elevation { 176 | value: 71.41288757324219 177 | } 178 | } 179 | 180 | ``` 181 | 182 | 183 |
184 | 185 | 186 | 187 | In addition to spatial and temporal details there are also details about the capturing device. We use both strings (to stay compliant with STAC JSON) and enum fields for these details. The `platform_enum` and `platform` is the model of the vehicle holding the sensor. The `instrument_enum` and `instrument` is the sensor that collected the scenes. In our case we're using `mission_enum` and `mission` to represent a class of flight vehicles that we're flying. In the case of the Landsat satellite program the breakdown would be: 188 | 189 | * `platform_enum`: `enum.PLATFORM.LANDSAT_8` 190 | * `sensor_enum`: `enum.SENSOR.OLI_TIRS` 191 | * `mission_enum`: `enum.MISSION.LANDSAT` 192 | * `platform`: "LANDSAT_8" 193 | * `sensor`: "OLI_TIRS" 194 | * `mission`: "LANDSAT" 195 | 196 | 197 | ### ID Temporal and Spatial 198 | Every STAC Item has a unique id, a datetime/observation, and a geometry/bbox (bounding-box). 199 | 200 | 201 | 202 | 203 | 204 |
Expand Python Code Sample 205 | 206 | 207 | ```python 208 | print("STAC Item id: {}\n".format(stac_item.id)) 209 | print("STAC Item observed: {}".format(stac_item.observed)) 210 | print("STAC Item datetime: {}".format(stac_item.datetime)) 211 | print("STAC Item bbox: {}".format(stac_item.bbox)) 212 | print("STAC Item geometry: {}".format(stac_item.geometry)) 213 | ``` 214 | 215 | 216 |
217 | 218 | 219 | 220 | 221 |
Expand Python Print-out 222 | 223 | 224 | ```text 225 | STAC Item id: 20190822T183518Z_746_POM1_ST2_P 226 | 227 | STAC Item observed: seconds: 1566498918 228 | nanos: 505476000 229 | 230 | STAC Item datetime: seconds: 1566498918 231 | nanos: 505476000 232 | 233 | STAC Item bbox: xmin: -97.7466867683867 234 | ymin: 30.278398961994966 235 | xmax: -97.72990596574927 236 | ymax: 30.288621181865743 237 | proj { 238 | epsg: 4326 239 | } 240 | 241 | STAC Item geometry: wkb: "\001\006\000\000\000\001\000\000\000\001\003\000\000\000\001\000\000\000\005\000\000\000\352\244L\267\311oX\300\316\340\320\247\234I>@\241\273\2606\267oX\300<\002\205\'EG>@\031\003\203\307\266nX\3001z\244\372\233G>@CCAI\306nX\300\326\013\351\023\343I>@\352\244L\267\311oX\300\316\340\320\247\234I>@" 242 | proj { 243 | epsg: 4326 244 | } 245 | envelope { 246 | xmin: -97.7466867683867 247 | ymin: 30.278398961994966 248 | xmax: -97.72990596574927 249 | ymax: 30.288621181865743 250 | proj { 251 | epsg: 4326 252 | } 253 | } 254 | simple: STRONG_SIMPLE 255 | 256 | ``` 257 | 258 | 259 |
260 | 261 | 262 | 263 | As you can see above, the `id` is a string value. The format of the id is typically not guessable (ours is based of off the time the data was processed, the image index, the platform and the sensor). 264 | 265 | The `observed` and `datetime` fields are the same value. STAC specification uses a generic field `datetime` to define the spatial component, the `S`, in STAC. We wanted a more descriptive variable, so we use `observed`, as in, the moment the scene was captured. This is a UTC timestamp in seconds and nano seconds. 266 | 267 | The `bbox` field describes the xmin, ymin, xmax, and ymax points that describe the bounding box that contains the scene. The `sr` field has an [epsg](http://www.epsg.org/) `wkid`. In this case the 4326 `wkid` indicates [WGS-84](http://epsg.io/4326) 268 | 269 | The `geometry` field has subfields `wkb`, `sr`, and `simple`. The `wkb` is a [well known binary](https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary) geometry format preferred for it's size. `sr` is the same as in the `bbox`. `simple` can be ignored. 270 | 271 | Below we demonstrate how you can create python `datetime` objects: 272 | 273 | 274 | 275 | 276 | 277 |
Expand Python Code Sample 278 | 279 | 280 | ```python 281 | from datetime import datetime 282 | print("UTC Observed Scene: {}".format(datetime.utcfromtimestamp(stac_item.observed.seconds))) 283 | print("UTC Processed Data: {}".format(datetime.utcfromtimestamp(stac_item.created.seconds))) 284 | print("UTC Updated Metadata: {}".format(datetime.utcfromtimestamp(stac_item.updated.seconds))) 285 | ``` 286 | 287 | 288 |
289 | 290 | 291 | 292 | 293 |
Expand Python Print-out 294 | 295 | 296 | ```text 297 | UTC Observed Scene: 2019-08-22 18:35:18 298 | UTC Processed Data: 2020-08-06 19:56:51 299 | UTC Updated Metadata: 2021-02-01 15:28:06 300 | ``` 301 | 302 | 303 |
304 | 305 | 306 | 307 | Updated is when the metadata was last updated. Typically that will be right after it's `processed` timestamp. 308 | 309 | Below is a demo of using shapely to get at the geometry data. 310 | 311 | 312 | 313 | 314 | 315 |
Expand Python Code Sample 316 | 317 | 318 | ```python 319 | from shapely.geometry import Polygon 320 | from shapely.wkb import loads 321 | 322 | print("wkt printout of polygon:\n{}\n".format(loads(stac_item.geometry.wkb))) 323 | print("centroid of polygon:\n{}\n".format(loads(stac_item.geometry.wkb).centroid)) 324 | print("bounds:\n{}\n".format(Polygon.from_bounds(stac_item.bbox.xmin, 325 | stac_item.bbox.ymin, 326 | stac_item.bbox.xmax, 327 | stac_item.bbox.ymax))) 328 | ``` 329 | 330 | 331 |
332 | 333 | 334 | 335 | 336 |
Expand Python Print-out 337 | 338 | 339 | ```text 340 | wkt printout of polygon: 341 | MULTIPOLYGON (((-97.7466867683867 30.28754662370266, -97.74555747279238 30.27839896199497, -97.72990596574927 30.27972380176124, -97.73085242627444 30.28862118186574, -97.7466867683867 30.28754662370266))) 342 | 343 | centroid of polygon: 344 | POINT (-97.738289581264 30.28357703330576) 345 | 346 | bounds: 347 | POLYGON ((-97.7466867683867 30.27839896199497, -97.7466867683867 30.28862118186574, -97.72990596574927 30.28862118186574, -97.72990596574927 30.27839896199497, -97.7466867683867 30.27839896199497)) 348 | 349 | ``` 350 | 351 | 352 |
353 | 354 | 355 | 356 | ### Assets 357 | Each STAC item should have at least one asset. An asset should be all the information you'll need to download the asset in question. For Near Space Labs customers, you'll be using the href, but you can also see the private bucket details of the asset. In protobuf the asset map has a key for each asset available. There's no part of the STAC specification for defining key names. Near Space Labs typically uses the data type, the optical bands and the cloud storage provider to construct a key name. 358 | 359 | 360 | 361 | 362 | 363 |
Expand Python Code Sample 364 | 365 | 366 | ```python 367 | from nsl.stac import Asset, utils 368 | from nsl.stac.enum import AssetType 369 | def print_asset(asset: Asset): 370 | asset_name = AssetType(asset.asset_type).name 371 | print(" href: {}".format(asset.href)) 372 | print(" type: {}".format(asset.type)) 373 | print(" protobuf enum number and name: {0}, {1}".format(asset.asset_type, asset_name)) 374 | print() 375 | 376 | print("there are {} assets".format(len(stac_item.assets))) 377 | print(AssetType.THUMBNAIL.name) 378 | print_asset(utils.get_asset(stac_item, asset_type=AssetType.THUMBNAIL)) 379 | 380 | print(AssetType.GEOTIFF.name) 381 | print_asset(utils.get_asset(stac_item, asset_type=AssetType.GEOTIFF)) 382 | ``` 383 | 384 | 385 |
386 | 387 | 388 | 389 | 390 |
Expand Python Print-out 391 | 392 | 393 | ```text 394 | there are 2 assets 395 | THUMBNAIL 396 | href: https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.png 397 | type: image/png 398 | protobuf enum number and name: 9, THUMBNAIL 399 | 400 | GEOTIFF 401 | href: https://api.nearspacelabs.net/download/20190822T162258Z_TRAVIS_COUNTY/Published/REGION_0/20190822T183518Z_746_POM1_ST2_P.tif 402 | type: image/vnd.stac.geotiff 403 | protobuf enum number and name: 2, GEOTIFF 404 | 405 | ``` 406 | 407 | 408 |
409 | 410 | 411 | 412 | As you can see above, our data only consists of jpg thumbnails and Geotiffs. But there can be other data stored in Assets in the future. 413 | 414 | You can read more details about Assets [here](https://geo-grpc.github.io/api/#epl.protobuf.Asset) 415 | 416 | ### View 417 | Some imagery analysis tools require knowing certain types of angular information. Here's a printout of the information we've collected with data. A summary of View values can be found [here](https://geo-grpc.github.io/api/#epl.protobuf.v1.View). 418 | 419 | 420 | 421 | 422 | 423 |
Expand Python Code Sample 424 | 425 | 426 | ```python 427 | print(stac_item.view) 428 | ``` 429 | 430 | 431 |
432 | 433 | 434 | 435 | 436 |
Expand Python Print-out 437 | 438 | 439 | ```text 440 | off_nadir { 441 | value: 9.42326831817627 442 | } 443 | azimuth { 444 | value: -74.85270690917969 445 | } 446 | sun_azimuth { 447 | value: 181.26959228515625 448 | } 449 | sun_elevation { 450 | value: 71.41288757324219 451 | } 452 | 453 | ``` 454 | 455 | 456 |
457 | 458 | 459 | 460 | These `sun_azimuth`, `sun_elevation`, `off_nadir` and `azimuth` are all boxed in the [google.protobuf.FloatValue type](https://developers.google.com/protocol-buffers/docs/reference/csharp/class/google/protobuf/well-known-types/float-value). To get at the value you must access the `value` field. 461 | 462 | 463 | 464 | 465 | 466 |
Expand Python Code Sample 467 | 468 | 469 | ```python 470 | print("sun_azimuth: {:.5f}".format(stac_item.view.sun_azimuth.value)) 471 | print("sun_elevation: {:.5f}".format(stac_item.view.sun_elevation.value)) 472 | print("off_nadir: {:.5f}".format(stac_item.view.off_nadir.value)) 473 | print("azimuth: {:.5f}".format(stac_item.view.azimuth.value)) 474 | ``` 475 | 476 | 477 |
478 | 479 | 480 | 481 | 482 |
Expand Python Print-out 483 | 484 | 485 | ```text 486 | sun_azimuth: 181.26959 487 | sun_elevation: 71.41289 488 | off_nadir: 9.42327 489 | azimuth: -74.85271 490 | ``` 491 | 492 | 493 |
494 | 495 | 496 | 497 | Notice that we're only printing out 5 decimal places. As these are stored as float values, we can't trust any of the precision that Python provides us beyond what we know the data to possess. 498 | 499 | You can read more details about electro-optical data [here](https://geo-grpc.github.io/api/#epl.protobuf.Eo) 500 | 501 | Return to [README.md](./README.md) 502 | -------------------------------------------------------------------------------- /nsl/stac/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | 18 | import abc 19 | import base64 20 | import os 21 | import re 22 | import json 23 | import math 24 | import time 25 | import warnings 26 | import logging 27 | 28 | import grpc 29 | import requests 30 | 31 | from dataclasses import dataclass 32 | from pathlib import Path 33 | from random import randint 34 | from typing import Dict, Optional, Set, Tuple 35 | 36 | from google.auth.exceptions import DefaultCredentialsError 37 | from google.cloud import storage as gcp_storage 38 | from google.oauth2 import service_account 39 | from tenacity import retry, stop_after_delay, wait_fixed 40 | 41 | from epl.protobuf.v1 import stac_service_pb2_grpc 42 | from epl.protobuf.v1.geometry_pb2 import GeometryData, ProjectionData, EnvelopeData 43 | from epl.protobuf.v1.query_pb2 import TimestampFilter, FloatFilter, StringFilter, UInt32Filter 44 | from epl.protobuf.v1.stac_pb2 import StacRequest, StacItem, Asset, Collection, CollectionRequest, Eo, EoRequest, \ 45 | LandsatRequest, Mosaic, MosaicRequest, DatetimeRange, View, ViewRequest, Extent, Interval, Provider 46 | 47 | __all__ = [ 48 | 'bearer_auth', 'gcs_storage_client', 'stac_service', 'url_to_channel', 49 | 'CollectionRequest', 'EoRequest', 'StacRequest', 'LandsatRequest', 'MosaicRequest', 'ViewRequest', 50 | 'Collection', 'Eo', 'StacItem', 'Mosaic', 'View', 'Asset', 51 | 'GeometryData', 'ProjectionData', 'EnvelopeData', 'FloatFilter', 'TimestampFilter', 'StringFilter', 'UInt32Filter', 52 | 'DatetimeRange', 'Extent', 'Interval', 'Provider', 53 | 'AUTH0_TENANT', 'API_AUDIENCE', 'ISSUER', 'STAC_SERVICE', 'AuthInfo', 54 | ] 55 | 56 | CLOUD_PROJECT = os.getenv("CLOUD_PROJECT") 57 | GOOGLE_APPLICATION_CREDENTIALS = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") 58 | SERVICE_ACCOUNT_DETAILS = os.getenv("SERVICE_ACCOUNT_DETAILS") 59 | 60 | NSL_ID = os.getenv("NSL_ID") 61 | NSL_SECRET = os.getenv("NSL_SECRET") 62 | # if an application uses this package, this singleton pattern of using an __init__.py file means that the package 63 | # and all the network calls will be made immediately upon application start. In some cases a virtual machine might 64 | # be able to start an application before it has network access. 65 | NSL_NETWORK_DELAY = int(os.getenv("NSL_NETWORK_DELAY", 0)) 66 | 67 | # URL of the OAuth service 68 | AUTH0_TENANT = os.getenv('AUTH0_TENANT', 'https://api.nearspacelabs.net') 69 | # Name of the API for which we issue tokens 70 | API_AUDIENCE = os.getenv('API_AUDIENCE', 'https://api.nearspacelabs.com') 71 | # Name of the service responsible for issuing NSL tokens 72 | ISSUER = 'https://api.nearspacelabs.net/' 73 | 74 | TOKEN_REFRESH_THRESHOLD = 60 # seconds 75 | 76 | MAX_GRPC_ATTEMPTS = int(os.getenv('MAX_ATTEMPTS', 4)) 77 | INIT_BACKOFF_MS = int(os.getenv('INIT_BACKOFF_MS', 4)) 78 | MAX_BACKOFF_MS = int(os.getenv('MAX_BACKOFF_MS', 4)) 79 | MULTIPLIER = int(os.getenv('MULTIPLIER', 4)) 80 | 81 | STAC_SERVICE_HOST = os.getenv('STAC_SERVICE_HOST', 'api.nearspacelabs.net') 82 | STAC_SERVICE = os.getenv('STAC_SERVICE', f'{STAC_SERVICE_HOST}:9090') 83 | BYTES_IN_MB = 1024 * 1024 84 | # at this point only allowing 10 MB or smaller messages 85 | MESSAGE_SIZE_MB = int(os.getenv('MESSAGE_SIZE_MB', 10)) 86 | GRPC_CHANNEL_OPTIONS = [('grpc.max_message_length', MESSAGE_SIZE_MB * BYTES_IN_MB), 87 | ('grpc.max_receive_message_length', MESSAGE_SIZE_MB * BYTES_IN_MB)] 88 | 89 | # TODO prep for ip v6 90 | IP_REGEX = re.compile(r"[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}") 91 | # DEFAULT Insecure until we have a https service 92 | INSECURE = True 93 | NSL_CREDENTIALS = Path(Path.home(), '.nsl', 'credentials') 94 | 95 | logger = logging.getLogger() 96 | 97 | 98 | class SleepingPolicy(abc.ABC): 99 | @abc.abstractmethod 100 | def sleep(self, try_i: int): 101 | """ 102 | How long to sleep in milliseconds. 103 | :param try_i: the number of retry (starting from zero) 104 | """ 105 | assert try_i >= 0 106 | 107 | 108 | # Retry mechanism 109 | # https://github.com/grpc/grpc/issues/19514#issuecomment-531700657 110 | class ExponentialBackoff(SleepingPolicy): 111 | def __init__(self, *, init_backoff_ms: int, max_backoff_ms: int, multiplier: int): 112 | self.init_backoff = randint(0, init_backoff_ms) 113 | self.max_backoff = max_backoff_ms 114 | self.multiplier = multiplier 115 | 116 | def sleep(self, try_i: int): 117 | sleep_range = min(self.init_backoff * self.multiplier ** try_i, self.max_backoff) 118 | sleep_ms = randint(0, sleep_range) 119 | logger.debug(f"Sleeping for {sleep_ms}") 120 | time.sleep(sleep_ms / 1000) 121 | 122 | 123 | class RetryOnRpcErrorClientInterceptor(grpc.UnaryUnaryClientInterceptor, grpc.StreamUnaryClientInterceptor): 124 | def __init__(self, 125 | *, 126 | max_attempts: int, 127 | sleeping_policy: SleepingPolicy, 128 | status_for_retry: Optional[Tuple[grpc.StatusCode]] = None): 129 | self.max_attempts = max_attempts 130 | self.sleeping_policy = sleeping_policy 131 | self.status_for_retry = status_for_retry 132 | 133 | def _intercept_call(self, continuation, client_call_details, request_or_iterator): 134 | for try_i in range(self.max_attempts): 135 | response = continuation(client_call_details, request_or_iterator) 136 | 137 | if isinstance(response, grpc.RpcError): 138 | 139 | # Return if it was last attempt 140 | if try_i == (self.max_attempts - 1): 141 | return response 142 | 143 | # If status code is not in retryable status codes 144 | if self.status_for_retry and response.code() not in self.status_for_retry: 145 | return response 146 | 147 | self.sleeping_policy.sleep(try_i) 148 | else: 149 | return response 150 | 151 | def intercept_unary_unary(self, continuation, client_call_details, request): 152 | return self._intercept_call(continuation, client_call_details, request) 153 | 154 | def intercept_stream_unary(self, continuation, client_call_details, request_iterator): 155 | return self._intercept_call(continuation, client_call_details, request_iterator) 156 | 157 | 158 | interceptors = ( 159 | RetryOnRpcErrorClientInterceptor( 160 | max_attempts=MAX_GRPC_ATTEMPTS, 161 | sleeping_policy=ExponentialBackoff(init_backoff_ms=INIT_BACKOFF_MS, 162 | max_backoff_ms=MAX_BACKOFF_MS, 163 | multiplier=MULTIPLIER), 164 | status_for_retry=(grpc.StatusCode.UNAVAILABLE,), 165 | ), 166 | ) 167 | 168 | 169 | def url_to_channel(stac_service_url): 170 | if stac_service_url.startswith("localhost") or IP_REGEX.match(stac_service_url) or \ 171 | "." not in stac_service_url or stac_service_url.startswith("http://") or INSECURE: 172 | stac_service_url = stac_service_url.strip("http://") 173 | channel = grpc.insecure_channel(stac_service_url, options=GRPC_CHANNEL_OPTIONS) 174 | else: 175 | stac_service_url = stac_service_url.strip("https://") 176 | channel_credentials = grpc.ssl_channel_credentials() 177 | channel = grpc.secure_channel(stac_service_url, 178 | credentials=channel_credentials, 179 | options=GRPC_CHANNEL_OPTIONS) 180 | 181 | return grpc.intercept_channel(channel, *interceptors) 182 | 183 | 184 | class __GCSStorageClient: 185 | _client = None 186 | 187 | @property 188 | def client(self): 189 | if self._client is not None: 190 | return self._client 191 | 192 | if SERVICE_ACCOUNT_DETAILS: 193 | details = json.loads(SERVICE_ACCOUNT_DETAILS) 194 | creds = service_account.Credentials.from_service_account_info(details) 195 | client = gcp_storage.Client(project=CLOUD_PROJECT, credentials=creds) 196 | elif GOOGLE_APPLICATION_CREDENTIALS: 197 | creds = service_account.Credentials.from_service_account_file(GOOGLE_APPLICATION_CREDENTIALS) 198 | client = gcp_storage.Client(project=CLOUD_PROJECT, credentials=creds) 199 | else: 200 | try: 201 | # https://github.com/googleapis/google-auth-library-python/issues/271#issuecomment-400186626 202 | warnings.filterwarnings("ignore", "Your application has authenticated using end user credentials") 203 | client = gcp_storage.Client(project="") 204 | except DefaultCredentialsError: 205 | client = None 206 | self._client = client 207 | return self._client 208 | 209 | 210 | def _generate_grpc_channel(stac_service_url=None): 211 | # TODO host env should include http:// so we can just see if it's https or http 212 | 213 | if stac_service_url is None: 214 | stac_service_url = STAC_SERVICE 215 | 216 | channel = url_to_channel(stac_service_url) 217 | 218 | print("nsl client connecting to stac service at: {}\n".format(stac_service_url)) 219 | 220 | return channel, stac_service_pb2_grpc.StacServiceStub(channel) 221 | 222 | 223 | class __StacServiceStub(object): 224 | def __init__(self): 225 | channel, stub = _generate_grpc_channel() 226 | self._channel = channel 227 | self._stub = stub 228 | 229 | @property 230 | def channel(self): 231 | return self._channel 232 | 233 | @property 234 | def stub(self): 235 | return self._stub 236 | 237 | def set_channel(self, channel): 238 | """ 239 | This allows you to override the channel created on init, with another channel. This might be needed if multiple 240 | libraries are using the same channel, or if multi-threading. 241 | :param channel: 242 | :return: 243 | """ 244 | self._stub = stac_service_pb2_grpc.StacServiceStub(channel) 245 | self._channel = channel 246 | 247 | def update_service_url(self, stac_service_url): 248 | """allows you to update your stac service address""" 249 | self._channel, self._stub = _generate_grpc_channel(stac_service_url) 250 | 251 | 252 | @dataclass 253 | class Contract: 254 | balance: int 255 | region: int 256 | type: str 257 | 258 | @staticmethod 259 | def from_jwt(token: str): 260 | payload = json.loads(base64.b64decode(token.split('.')[1] + '==')) 261 | contract = payload[f'{API_AUDIENCE}/contract'] 262 | return Contract(balance=contract['balance'], region=contract['region'], type=contract['type']) 263 | 264 | def is_valid_for(self, region: str) -> bool: 265 | if self.region == 1 or region == 'REGION_0' or region == 'SAMPLES': 266 | return True 267 | 268 | if region == "REGION_1": 269 | masked = self.region & 2 270 | elif region == "REGION_2": 271 | masked = self.region & 4 272 | elif region == "REGION_3": 273 | masked = self.region & 8 274 | elif region == "REGION_4": 275 | masked = self.region & 16 276 | elif region == "REGION_5": 277 | masked = self.region & 32 278 | elif region == "REGION_6": 279 | masked = self.region & 64 280 | elif region == "REGION_7": 281 | masked = self.region & 128 282 | else: 283 | return False 284 | return masked != 0 and masked <= self.region 285 | 286 | 287 | class AuthInfo: 288 | nsl_id: str = None 289 | nsl_secret: str = None 290 | token: str = None 291 | expiry: float = 0 292 | skip_authorization: bool = False 293 | contract: Contract 294 | 295 | def __init__(self, nsl_id: str, nsl_secret: str): 296 | if not nsl_id or not nsl_secret: 297 | raise ValueError("nsl_id and nsl_secret must be non-zero length strings") 298 | self.nsl_id = nsl_id 299 | self.nsl_secret = nsl_secret 300 | 301 | # this only retries if there's a timeout error 302 | @retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5)) 303 | def authorize(self): 304 | if self.skip_authorization: 305 | return 306 | 307 | expiry, token = AuthInfo.get_token_client_credentials(self.nsl_id, self.nsl_secret) 308 | self.expiry = expiry 309 | self.token = token 310 | self.contract = Contract.from_jwt(token) 311 | 312 | @property 313 | def permissions(self) -> Set[str]: 314 | _, payload, _ = self.token.split('.') 315 | payload = json.loads(base64.b64decode(payload + '===')) 316 | return {permission for permission in payload.get('permissions', set())} 317 | 318 | @staticmethod 319 | def get_token_client_credentials(nsl_id: str, nsl_secret: str, 320 | auth_url=f"{AUTH0_TENANT}/oauth/token", 321 | grant_type: str = 'client_credentials', 322 | additional_headers: dict = None): 323 | print(f"attempting NSL authentication against {auth_url}...") 324 | now = time.time() 325 | 326 | if additional_headers is None: 327 | additional_headers = dict() 328 | 329 | headers = {'content-type': 'application/json', **additional_headers} 330 | post_body = { 331 | 'client_id': nsl_id, 332 | 'client_secret': nsl_secret, 333 | 'audience': API_AUDIENCE, 334 | 'grant_type': grant_type, 335 | } 336 | 337 | res = requests.post(auth_url, json=post_body, headers=headers) 338 | 339 | if res.status_code != 200 and res.status_code != 201: 340 | # evaluate codes first. 341 | message = f"authentication failed with code '{res.status_code}' and reason '{res.reason}'" 342 | raise requests.exceptions.RequestException(message) 343 | elif len(res.content) == 0: 344 | # then if response is empty, HTTPResponse method for read returns b"" which will be zero in length 345 | raise requests.exceptions.RequestException("empty authentication return. notify nsl of error") 346 | 347 | print(f"successfully authenticated with NSL_ID: `{nsl_id}`") 348 | res_json = res.json() 349 | expiry = now + int(res_json['expires_in']) 350 | token = res_json['access_token'] 351 | return expiry, token 352 | 353 | 354 | class __BearerAuth: 355 | _auth_info_map: Dict[str, AuthInfo] = {} 356 | _profile_map: Dict[str, str] = {} 357 | _default_nsl_id = None 358 | 359 | def __init__(self, init=False): 360 | if (not NSL_ID or not NSL_SECRET) and not NSL_CREDENTIALS.exists(): 361 | warnings.warn(f"NSL_ID and NSL_SECRET environment variables not set, and {NSL_CREDENTIALS} does not exist") 362 | return 363 | 364 | # if credentials exist, add them to our auth store 365 | if NSL_CREDENTIALS and NSL_CREDENTIALS.exists(): 366 | for profile_name, auth_info in self.loads().items(): 367 | self._auth_info_map[auth_info.nsl_id] = auth_info 368 | if profile_name == 'default': 369 | self._default_nsl_id = auth_info.nsl_id 370 | self._profile_map[profile_name] = auth_info.nsl_id 371 | print(f"found NSL_ID {auth_info.nsl_id} under profile name `{profile_name}`") 372 | 373 | # if env vars were specified, add them as well and set them to the default 374 | if NSL_ID and NSL_SECRET: 375 | print(f"using NSL_ID {NSL_ID} specified in env var") 376 | self._auth_info_map[NSL_ID] = AuthInfo(nsl_id=NSL_ID, nsl_secret=NSL_SECRET) 377 | self._default_nsl_id = NSL_ID 378 | 379 | # if env vars are unset and no NSL_ID was tagged as default, use the first one available 380 | if self.default_nsl_id is None: 381 | self._default_nsl_id = list(key for key in self._auth_info_map.keys())[0] 382 | print(f"using NSL_ID {self.default_nsl_id}") 383 | 384 | if init: 385 | self._auth_info_map[self._default_nsl_id].authorize() 386 | 387 | @property 388 | def default_nsl_id(self): 389 | return self._default_nsl_id 390 | 391 | def auth_header(self, nsl_id: str = None, profile_name: str = None) -> str: 392 | auth_info = self._get_auth_info(nsl_id, profile_name) 393 | if not auth_info.skip_authorization and (auth_info.expiry - time.time()) < TOKEN_REFRESH_THRESHOLD: 394 | print(f'authorizing NSL_ID: `{auth_info.nsl_id}`') 395 | auth_info.authorize() 396 | diff_seconds = auth_info.expiry - time.time() 397 | ttl = round(int(math.ceil(float(diff_seconds / 60) / 10) * 10)) 398 | print(f"will attempt re-authorization in {ttl} minutes") 399 | return f"Bearer {auth_info.token}" 400 | 401 | def get_credentials(self, nsl_id: str = None, profile_name: str = None) -> Optional[AuthInfo]: 402 | if profile_name is not None: 403 | nsl_id = self._profile_map.get(profile_name, None) 404 | return self._auth_info_map.get(nsl_id if nsl_id is not None else self.default_nsl_id, None) 405 | 406 | def set_credentials(self, nsl_id: str, nsl_secret: str, profile_name: str = None): 407 | if len(self._auth_info_map) == 0: 408 | self._default_nsl_id = nsl_id 409 | 410 | self._auth_info_map[nsl_id] = AuthInfo(nsl_id=nsl_id, nsl_secret=nsl_secret) 411 | self._auth_info_map[nsl_id].authorize() 412 | if profile_name is not None: 413 | self._profile_map[profile_name] = nsl_id 414 | 415 | def unset_credentials(self, profile_name: str): 416 | nsl_id = self._profile_map.pop(profile_name) 417 | delattr(self._auth_info_map, nsl_id) 418 | if self._default_nsl_id == nsl_id: 419 | if len(self._auth_info_map) == 0: 420 | self._default_nsl_id = None 421 | else: 422 | self._default_nsl_id = list(key for key in self._auth_info_map.keys())[0] 423 | print(f"using NSL_ID {self.default_nsl_id}") 424 | 425 | def is_valid_for(self, region: str, nsl_id: str = None, profile_name: str = None) -> bool: 426 | auth_info = self._get_auth_info(nsl_id=nsl_id, profile_name=profile_name) 427 | return auth_info.contract.is_valid_for(region) 428 | 429 | def loads(self) -> Dict[str, AuthInfo]: 430 | output = dict() 431 | with NSL_CREDENTIALS.open('r') as file_obj: 432 | lines = file_obj.readlines() 433 | for i, line in enumerate(lines): 434 | if line.startswith('['): 435 | if not lines[i + 1].startswith('NSL_ID') or not lines[i + 2].startswith('NSL_SECRET'): 436 | raise ValueError("credentials should be of the format:\n[named profile]\nNSL_ID={your " 437 | "nsl id}\nNSL_SECRET={your nsl secret}") 438 | # for id like 'NSL_ID = all_the_id_text\n', first strip remove front whitespace and newline, and optionally the leading quote 439 | # .strip(), now we now [6:] starts after 'NSL_ID' .strip()[6:], strip potential whitespace 440 | # between NSL_ID and '=' with .strip()[6:].strip(), start one after equal 441 | # .strip()[6:].strip()[1:], strip potential whitespace 442 | # after equal .strip()[6:].strip()[1:].strip() 443 | profile_name = line.strip().lstrip('[').rstrip(']') 444 | nsl_id = lines[i + 1].strip()[6:].strip().strip('"')[1:].strip().strip('"') 445 | nsl_secret = lines[i + 2].strip()[10:].strip().strip('"')[1:].strip().strip('"') 446 | 447 | output[profile_name] = AuthInfo(nsl_id=nsl_id, nsl_secret=nsl_secret) 448 | return output 449 | 450 | def dumps(self): 451 | with NSL_CREDENTIALS.open('w') as file_obj: 452 | for profile_name, nsl_id in self._profile_map.items(): 453 | creds = self.get_credentials(nsl_id) 454 | file_obj.write(f'[{profile_name}]\n') 455 | file_obj.write(f'NSL_ID="{creds.nsl_id}"\n') 456 | file_obj.write(f'NSL_SECRET="{creds.nsl_secret}"\n') 457 | file_obj.write('\n') 458 | file_obj.close() 459 | 460 | def _get_auth_info(self, nsl_id: str = None, profile_name: str = None) -> AuthInfo: 461 | if nsl_id is None and profile_name is None: 462 | nsl_id = self._default_nsl_id 463 | 464 | if nsl_id not in self._auth_info_map and profile_name not in self._profile_map: 465 | raise ValueError("credentials must be set by environment variables NSL_ID & NSL_SECRET, by setting a " 466 | "credentials file at ~/.nsl/credentials, or by using the set_credentials method") 467 | 468 | if profile_name is not None: 469 | nsl_id = self._profile_map[profile_name] 470 | return self._auth_info_map[nsl_id] 471 | 472 | 473 | time.sleep(NSL_NETWORK_DELAY) 474 | bearer_auth = __BearerAuth() 475 | stac_service = __StacServiceStub() 476 | gcs_storage_client = __GCSStorageClient() 477 | -------------------------------------------------------------------------------- /nsl/stac/client.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | import uuid 18 | 19 | import requests 20 | 21 | from typing import Iterator, List, Optional, Tuple 22 | from warnings import warn 23 | 24 | from epl.protobuf.v1 import stac_pb2 25 | 26 | from nsl.stac import AUTH0_TENANT, bearer_auth, stac_service as stac_singleton, utils, TimestampFilter 27 | from nsl.stac.destinations import BaseDestination, MemoryDestination 28 | from nsl.stac.subscription import Subscription 29 | from nsl.stac.utils import item_region 30 | 31 | 32 | class NSLClient: 33 | def __init__(self, nsl_only=True, nsl_id=None, profile_name=None): 34 | """ 35 | Create a client connection to a gRPC STAC service. nsl_only limits all queries to only return data from Near 36 | Space Labs. 37 | :param nsl_only: 38 | """ 39 | self._stac_service = stac_singleton 40 | self._nsl_only = nsl_only 41 | if profile_name: 42 | nsl_id = bearer_auth._get_auth_info(profile_name=profile_name).nsl_id 43 | if nsl_id: 44 | bearer_auth._default_nsl_id = nsl_id 45 | 46 | @property 47 | def default_nsl_id(self): 48 | """ 49 | if you don't set the nsl_id for each stac request, then this nsl_id is the default choice. 50 | if you set this default value you must make sure that the nsl_id has already been 'set' by calling `set_credentials` 51 | :return: 52 | """ 53 | return bearer_auth.default_nsl_id 54 | 55 | def set_credentials(self, nsl_id: str, nsl_secret: str): 56 | """ 57 | Set nsl_id and secret for use in querying metadata and downloading imagery 58 | :param nsl_id: 59 | :param nsl_secret: 60 | """ 61 | bearer_auth.set_credentials(nsl_id=nsl_id, nsl_secret=nsl_secret) 62 | 63 | def update_service_url(self, stac_service_url): 64 | """ 65 | update the stac service address 66 | :param stac_service_url: localhost:8080, 34.34.34.34:9000, http://api.nearspacelabs.net:9090, etc 67 | :return: 68 | """ 69 | self._stac_service.update_service_url(stac_service_url=stac_service_url) 70 | 71 | def search_one(self, 72 | stac_request: stac_pb2.StacRequest, 73 | timeout=15, 74 | nsl_id: str = None, 75 | profile_name: str = None, 76 | correlation_id: str = None) -> stac_pb2.StacItem: 77 | """ 78 | search for one item from the db that matches the stac request 79 | :param timeout: timeout for request 80 | :param stac_request: StacRequest of query parameters to filter by 81 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one nsl_id and nsl_secret have been defined with 82 | set_credentials method. Specify nsl_id to use. if NSL_ID and NSL_SECRET environment variables not set must use 83 | NSLClient object's set_credentials to set credentials 84 | :param profile_name: if a ~/.nsl/credentials file exists, you can override the [default] credential usage, by 85 | using a different profile name 86 | :param correlation_id: is a unique identifier that is added to the very first interaction (incoming request) 87 | to identify the context and is passed to all components that are involved in the transaction flow 88 | :return: StacItem 89 | """ 90 | # limit to only search Near Space Labs SWIFT data 91 | if self._nsl_only: 92 | stac_request.mission_enum = stac_pb2.SWIFT 93 | 94 | metadata = self._grpc_headers(nsl_id, profile_name, correlation_id) 95 | return self._stac_service.stub.SearchOneItem(stac_request, timeout=timeout, metadata=metadata) 96 | 97 | def count(self, 98 | stac_request: stac_pb2.StacRequest, 99 | timeout=15, 100 | nsl_id: str = None, 101 | profile_name: str = None, 102 | correlation_id: str = None) -> int: 103 | """ 104 | count all the items in the database that match the stac request 105 | :param timeout: timeout for request 106 | :param stac_request: StacRequest query parameters to apply to count method (limit ignored) 107 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one nsl_id and nsl_secret have been defined with 108 | set_credentials method. Specify nsl_id to use. if NSL_ID and NSL_SECRET environment variables not set must use 109 | NSLClient object's set_credentials to set credentials 110 | :param profile_name: if a ~/.nsl/credentials file exists, you can override the [default] credential usage, by 111 | using a different profile name 112 | :param correlation_id: is a unique identifier that is added to the very first interaction (incoming request) 113 | to identify the context and is passed to all components that are involved in the transaction flow 114 | :return: int 115 | """ 116 | # limit to only search Near Space Labs SWIFT data 117 | if self._nsl_only: 118 | stac_request.mission_enum = stac_pb2.SWIFT 119 | 120 | metadata = self._grpc_headers(nsl_id, profile_name, correlation_id) 121 | db_result = self._stac_service.stub.CountItems(stac_request, timeout=timeout, metadata=metadata) 122 | if db_result.status: 123 | # print db_result 124 | print(db_result.status) 125 | return db_result.count 126 | 127 | def search(self, 128 | stac_request: stac_pb2.StacRequest, 129 | timeout=15, 130 | nsl_id: str = None, 131 | profile_name: str = None, 132 | auto_paginate: bool = False, 133 | only_accessible: bool = False, 134 | page_size: int = 50, 135 | correlation_id: str = None) -> Iterator[stac_pb2.StacItem]: 136 | """ 137 | search for stac items by using StacRequest. return a stream of StacItems 138 | :param timeout: timeout for request 139 | :param stac_request: StacRequest of query parameters to filter by 140 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one nsl_id and nsl_secret have been defined with 141 | set_credentials method. Specify nsl_id to use. if NSL_ID and NSL_SECRET environment variables not set must use 142 | NSLClient object's set_credentials to set credentials 143 | :param profile_name: if a ~/.nsl/credentials file exists, you can override the [default] credential usage, by 144 | using a different profile name 145 | :param auto_paginate: 146 | - if specified, this will automatically paginate and yield all received StacItems. 147 | - If `stac_request.limit` is specified, only the that amount of StacItems will be yielded. 148 | - If `stac_request.offset` is specified, pagination will begin at that `offset`. 149 | - If set to `False` (the default), `stac_request.limit` and `stac_request.offset` can be used to manually 150 | page through StacItems. 151 | :param only_accessible: limits results to only StacItems downloadable by your level of sample/paid access 152 | :param page_size: how many results to page at a time 153 | :return: stream of StacItems 154 | """ 155 | for item in self._search_all(stac_request, 156 | timeout, 157 | nsl_id=nsl_id, 158 | profile_name=profile_name, 159 | auto_paginate=auto_paginate, 160 | page_size=page_size, 161 | correlation_id=correlation_id): 162 | if not only_accessible or \ 163 | bearer_auth.is_valid_for(item_region(item), nsl_id=nsl_id, profile_name=profile_name): 164 | yield item 165 | 166 | def search_collections(self, 167 | collection_request: stac_pb2.CollectionRequest, 168 | timeout=15, 169 | nsl_id: str = None, 170 | profile_name: str = None, 171 | correlation_id: str = None) -> Iterator[stac_pb2.Collection]: 172 | 173 | metadata = self._grpc_headers(nsl_id, profile_name, correlation_id) 174 | for item in self._stac_service.stub.SearchCollections(collection_request, timeout=timeout, metadata=metadata): 175 | yield item 176 | 177 | def subscribe(self, 178 | stac_request: stac_pb2.StacRequest, 179 | destination: BaseDestination, 180 | nsl_id: str = None, 181 | profile_name: str = None, 182 | is_active=True) -> str: 183 | """ 184 | Creates a subscription to a `StacRequest`, to deliver matching `StacItem`s to a `BaseDestination`. 185 | """ 186 | assert stac_request.updated == TimestampFilter(), \ 187 | "cannot subscribe to StacRequests with a set `updated` timestamp filter" 188 | assert not (isinstance(destination, MemoryDestination) or destination.__class__ == BaseDestination), \ 189 | "cannot create subscriptions that deliver to `BaseDestination`s or `MemoryDestination`s" 190 | 191 | if self._nsl_only: 192 | stac_request.mission_enum = stac_pb2.SWIFT 193 | res = requests.post(f'{AUTH0_TENANT}/subscription', 194 | headers=self._json_headers(nsl_id, profile_name), 195 | json=dict(stac_request=utils.stac_request_to_b64(stac_request), 196 | destination=destination.to_json_str(), 197 | is_active=is_active)) 198 | 199 | NSLClient._handle_json_response(res, 201) 200 | sub_id = res.json()['sub_id'] 201 | print(f'created subscription with id: {sub_id}') 202 | return sub_id 203 | 204 | def resubscribe(self, sub_id: str, nsl_id: str = None, profile_name: str = None): 205 | """Reactivates a subscription with the given `sub_id`.""" 206 | res = requests.put(f'{AUTH0_TENANT}/subscription/{sub_id}', 207 | headers=self._json_headers(nsl_id, profile_name)) 208 | 209 | NSLClient._handle_json_response(res, 200) 210 | print(f'reactivated subscription with id: {sub_id}') 211 | return 212 | 213 | def unsubscribe(self, sub_id: str, nsl_id: str = None, profile_name: str = None): 214 | """Deactivates a subscription with the given `sub_id`.""" 215 | res = requests.delete(f'{AUTH0_TENANT}/subscription/{sub_id}', 216 | headers=self._json_headers(nsl_id, profile_name)) 217 | 218 | NSLClient._handle_json_response(res, 202) 219 | print(f'deactivated subscription with id: {sub_id}') 220 | return 221 | 222 | def subscriptions(self, nsl_id: str = None, profile_name: str = None) -> List[Subscription]: 223 | """Fetches all subscriptions.""" 224 | res = requests.get(f'{AUTH0_TENANT}/subscription', 225 | headers=self._json_headers(nsl_id, profile_name)) 226 | 227 | NSLClient._handle_json_response(res, 200) 228 | return list(Subscription(response_dict) for response_dict in res.json()['results']) 229 | 230 | def _search_all(self, 231 | stac_request: stac_pb2.StacRequest, 232 | timeout=15, 233 | nsl_id: str = None, 234 | profile_name: str = None, 235 | auto_paginate: bool = False, 236 | page_size: int = 50, 237 | correlation_id: str = None) -> Iterator[stac_pb2.StacItem]: 238 | # limit to only search Near Space Labs SWIFT data 239 | if self._nsl_only: 240 | stac_request.mission_enum = stac_pb2.SWIFT 241 | 242 | if not auto_paginate: 243 | metadata = self._grpc_headers(nsl_id, profile_name, correlation_id) 244 | for item in self._stac_service.stub.SearchItems(stac_request, timeout=timeout, metadata=metadata): 245 | if not item.id: 246 | warn(f"STAC item missing STAC id: \n{item};\n ending search") 247 | return 248 | else: 249 | yield item 250 | else: 251 | original_limit = stac_request.limit if stac_request.limit > 0 else None 252 | offset = stac_request.offset 253 | count = 0 254 | 255 | stac_request.limit = page_size if original_limit is None else max(original_limit, page_size) 256 | items = list(self._search_all(stac_request, timeout=timeout, 257 | nsl_id=nsl_id, profile_name=profile_name, 258 | page_size=page_size, correlation_id=correlation_id)) 259 | while len(items) > 0: 260 | for item in items: 261 | if original_limit is None or (original_limit is not None and count < original_limit): 262 | yield item 263 | count += 1 264 | if original_limit is not None and count >= original_limit: 265 | break 266 | 267 | if original_limit is not None and count >= original_limit: 268 | break 269 | 270 | stac_request.offset += len(items) 271 | items = list(self._search_all(stac_request, timeout=timeout, 272 | nsl_id=nsl_id, profile_name=profile_name, 273 | page_size=page_size, correlation_id=correlation_id)) 274 | 275 | stac_request.offset = offset 276 | stac_request.limit = original_limit if original_limit is not None else 0 277 | 278 | def _json_headers(self, 279 | nsl_id: str = None, 280 | profile_name: str = None, 281 | correlation_id: str = None) -> dict: 282 | headers = {k: v for (k, v) in self._grpc_headers(nsl_id, profile_name, correlation_id)} 283 | return {'content-type': 'application/json', **headers} 284 | 285 | def _grpc_headers(self, 286 | nsl_id: str = None, 287 | profile_name: str = None, 288 | correlation_id: str = None) -> Tuple[Tuple[str, str], ...]: 289 | correlation_id = str(uuid.uuid4()) if correlation_id is None else correlation_id 290 | return (('x-correlation-id', correlation_id), 291 | ('authorization', bearer_auth.auth_header(nsl_id=nsl_id, profile_name=profile_name))) 292 | 293 | @staticmethod 294 | def _handle_json_response(res, status_code: int): 295 | if res.status_code != status_code: 296 | raise requests.exceptions.RequestException(f'non-nominal status code: {res.status_code}') 297 | elif len(res.content) == 0: 298 | # then if response is empty, HTTPResponse method for read returns b"" which will be zero in length 299 | raise requests.exceptions.RequestException("empty authentication return. notify nsl of error") 300 | -------------------------------------------------------------------------------- /nsl/stac/destinations/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import BaseDestination, DestinationDecoder 2 | from .aws import AWSDestination 3 | from .gcp import GCPDestination 4 | from .memory import MemoryDestination 5 | 6 | __all__ = ['BaseDestination', 'DestinationDecoder', 7 | 'AWSDestination', 'GCPDestination', 'MemoryDestination'] 8 | -------------------------------------------------------------------------------- /nsl/stac/destinations/aws.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from pathlib import Path 4 | from typing import Optional, Union 5 | 6 | import boto3 7 | 8 | from epl.protobuf.v1 import stac_pb2 9 | from nsl.stac.enum import AssetType 10 | from nsl.stac.destinations.base import BaseDestination 11 | 12 | AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') 13 | AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') 14 | 15 | 16 | class AWSDestination(BaseDestination): 17 | type = 'aws' 18 | 19 | _client = None 20 | save_directory: Path 21 | role_arn: str 22 | bucket: str 23 | region: str 24 | 25 | def __init__(self, 26 | role_arn: str, 27 | bucket: str, 28 | region: str, 29 | asset_type: AssetType = AssetType.GEOTIFF, 30 | save_directory: Union[Path, str] = '/'): 31 | super().__init__(asset_type=asset_type) 32 | self.save_directory = Path(save_directory) 33 | self.role_arn = role_arn 34 | self.bucket = bucket 35 | self.region = region 36 | 37 | def deliver(self, nsl_id: str, sub_id: str, stac_item: stac_pb2.StacItem): 38 | try: 39 | # TODO: in the future, check a local cache for this asset to avoid multiple downloads 40 | self.target_obj(stac_item).upload_fileobj(self.src_blob(stac_item).open('rb')) 41 | return None 42 | except BaseException as err: 43 | print(f'ERROR: failed to transfer asset {stac_item.id}:\n{err}') 44 | raise err 45 | 46 | def __json__(self) -> dict: 47 | return dict(**super().__json__(), 48 | role_arn=self.role_arn, 49 | bucket=self.bucket, 50 | region=self.region, 51 | save_directory=str(self.save_directory)) 52 | 53 | def target_obj(self, stac_item: stac_pb2.StacItem) -> Optional[object]: 54 | return self.s3.Object(self.bucket, self.blob_path(stac_item, self.save_directory)) 55 | 56 | @property 57 | def s3(self): 58 | if self._client is None: 59 | client = boto3\ 60 | .Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\ 61 | .client('sts') 62 | assumed_role = client.assume_role(RoleArn=self.role_arn, RoleSessionName='nearspacelabs') 63 | credentials = assumed_role['Credentials'] 64 | self._client = boto3.resource('s3', 65 | aws_access_key_id=credentials['AccessKeyId'], 66 | aws_secret_access_key=credentials['SecretAccessKey'], 67 | aws_session_token=credentials['SessionToken']) 68 | return self._client 69 | -------------------------------------------------------------------------------- /nsl/stac/destinations/base.py: -------------------------------------------------------------------------------- 1 | import json 2 | from pathlib import Path 3 | from typing import Iterator, Optional 4 | 5 | from epl.protobuf.v1 import stac_pb2 6 | from nsl.stac import Asset 7 | from nsl.stac.enum import AssetType 8 | from nsl.stac.utils import get_asset, get_blob_metadata 9 | 10 | 11 | class BaseDestination(dict): 12 | type: str 13 | # TODO: make plural? 14 | asset_type: AssetType 15 | 16 | def __init__(self, asset_type: AssetType = AssetType.GEOTIFF): 17 | super().__init__(self) 18 | # FIXME: only allow co_geotiff, tiff and jpeg2000 19 | self.asset_type = asset_type 20 | 21 | @property 22 | def asset_type_str(self) -> str: return stac_pb2.AssetType.Name(self.asset_type) 23 | 24 | def deliver(self, nsl_id: str, sub_id: str, stac_item: stac_pb2.StacItem): pass 25 | 26 | def deliver_batch(self, nsl_id, sub_id: str, stac_items: Iterator[stac_pb2.StacItem]): pass 27 | 28 | def to_json_str(self) -> str: return json.dumps(self.__json__(), sort_keys=True) 29 | 30 | def __json__(self) -> dict: return dict(type=self.type, asset_type=self.asset_type_str) 31 | 32 | def file_name(self, stac_item: stac_pb2.StacItem) -> str: 33 | if self.asset_type == AssetType.TIFF or self.asset_type == AssetType.GEOTIFF: 34 | return f'{stac_item.id}.tif' 35 | elif self.asset_type == AssetType.THUMBNAIL: 36 | return Path(self.asset(stac_item).object_path).name 37 | elif self.asset_type == AssetType.JPEG: 38 | return f'{stac_item.id}.jpg' 39 | elif self.asset_type == AssetType.PNG: 40 | return f'{stac_item.id}.png' 41 | elif self.asset_type == AssetType.JPEG_2000: 42 | return f'{stac_item.id}.jp2' 43 | 44 | return stac_item.id 45 | 46 | def asset(self, stac_item: stac_pb2.StacItem) -> Optional[Asset]: 47 | return get_asset(stac_item=stac_item, asset_type=self.asset_type, b_relaxed_types=True) 48 | 49 | def src_blob(self, stac_item: stac_pb2.StacItem): 50 | asset = self.asset(stac_item) 51 | return get_blob_metadata(asset.bucket, asset.object_path) 52 | 53 | def blob_path(self, stac_item: stac_pb2.StacItem, root_dir=Path('/')) -> str: 54 | return str(root_dir.joinpath(self.file_name(stac_item))) 55 | 56 | 57 | class DestinationDecoder(json.JSONDecoder): 58 | def __init__(self, *args, **kwargs): 59 | json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) 60 | 61 | def object_hook(self, dct: dict) -> Optional[BaseDestination]: 62 | from nsl.stac.destinations.aws import AWSDestination 63 | from nsl.stac.destinations.gcp import GCPDestination 64 | from nsl.stac.destinations.memory import MemoryDestination 65 | 66 | destination_type = dct.get('type', '') 67 | asset_type = DestinationDecoder.asset_type_from_str(dct.get('asset_type', self.default_asset_type_str)) 68 | 69 | dct = {k: dct[k] for k in dct if k not in {'type', 'asset_type'}} 70 | if destination_type == AWSDestination.type: 71 | return AWSDestination(asset_type=asset_type, **dct) 72 | if destination_type == GCPDestination.type: 73 | return GCPDestination(asset_type=asset_type, **dct) 74 | if destination_type == MemoryDestination.type: 75 | return MemoryDestination(asset_type=asset_type, **dct) 76 | return None 77 | 78 | @staticmethod 79 | def asset_type_from_str(s: str) -> AssetType: return AssetType(stac_pb2.AssetType.Value(s)) 80 | 81 | @property 82 | def default_asset_type_str(self) -> str: return stac_pb2.AssetType.Name(stac_pb2.GEOTIFF) 83 | -------------------------------------------------------------------------------- /nsl/stac/destinations/gcp.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import Union 3 | 4 | from google.cloud.storage import Blob, Bucket 5 | 6 | from epl.protobuf.v1 import stac_pb2 7 | from nsl.stac import gcs_storage_client 8 | from nsl.stac.enum import AssetType 9 | from nsl.stac.destinations.base import BaseDestination 10 | 11 | 12 | class GCPDestination(BaseDestination): 13 | # TODO: GKE access to a bucket w/in the same region is Free 14 | # TODO: "transfer" between buckets w/in the same region is Free 15 | type = 'gcp' 16 | 17 | save_directory: Path 18 | bucket: str 19 | region: str 20 | 21 | def __init__(self, 22 | bucket: str, 23 | region: str, 24 | asset_type: AssetType = AssetType.GEOTIFF, 25 | save_directory: Union[Path, str] = '/'): 26 | super().__init__(asset_type=asset_type) 27 | self.save_directory = Path(save_directory) 28 | self.bucket = bucket 29 | self.region = region 30 | 31 | def deliver(self, nsl_id: str, sub_id: str, stac_item: stac_pb2.StacItem): 32 | try: 33 | # TODO: in the future, check a local cache for this asset to avoid multiple downloads 34 | self.target_blob(stac_item)\ 35 | .upload_from_file(self.src_blob(stac_item).open('rb'), client=gcs_storage_client.client) 36 | return None 37 | except BaseException as err: 38 | print(f'ERROR: failed to transfer asset {stac_item.id}:\n{err}') 39 | raise err 40 | 41 | def __json__(self) -> dict: 42 | return dict(**super().__json__(), 43 | bucket=self.bucket, 44 | region=self.region, 45 | save_directory=str(self.save_directory)) 46 | 47 | def target_blob(self, stac_item: stac_pb2.StacItem) -> Blob: 48 | return Blob(name=self.blob_path(stac_item, self.save_directory), 49 | bucket=Bucket(client=gcs_storage_client.client, name=self.bucket)) 50 | -------------------------------------------------------------------------------- /nsl/stac/destinations/memory.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import Union 3 | 4 | from epl.protobuf.v1 import stac_pb2 5 | from nsl.stac.destinations.base import BaseDestination 6 | from nsl.stac.enum import AssetType 7 | from nsl.stac.utils import download_asset 8 | 9 | 10 | class MemoryDestination(BaseDestination): 11 | type = 'memory' 12 | save_directory: Path 13 | 14 | def __init__(self, asset_type: AssetType = AssetType.GEOTIFF, save_directory: Union[Path, str] = '/'): 15 | super().__init__(asset_type=asset_type) 16 | self.save_directory = Path(save_directory) 17 | 18 | def deliver(self, nsl_id: str, sub_id: str, stac_item: stac_pb2.StacItem): 19 | try: 20 | file_path = self.save_directory.joinpath(self.file_name(stac_item)) 21 | download_asset(asset=self.asset(stac_item), 22 | from_bucket=True, 23 | save_filename=str(file_path)) 24 | return None 25 | except BaseException as err: 26 | print(f'ERROR: failed downloading asset for {stac_item.id}:\n{err}') 27 | raise err 28 | 29 | def __json__(self) -> dict: 30 | return dict(**super().__json__(), save_directory=str(self.save_directory)) 31 | -------------------------------------------------------------------------------- /nsl/stac/enum.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | 18 | import sys 19 | from epl.protobuf.v1.stac_pb2 import AssetType as _AssetType 20 | from epl.protobuf.v1.stac_pb2 import CloudPlatform as _CloudPlatform 21 | from epl.protobuf.v1.query_pb2 import FilterRelationship as _FilterRelationship 22 | from epl.protobuf.v1.query_pb2 import SortDirection as _SortDirection 23 | from epl.protobuf.v1.stac_pb2 import Constellation as _Constellation 24 | from epl.protobuf.v1.stac_pb2 import Mission as _Mission 25 | from epl.protobuf.v1.stac_pb2 import Instrument as _Instrument 26 | from epl.protobuf.v1.stac_pb2 import Platform as _Platform 27 | from epl.protobuf.v1.stac_pb2 import Eo as _Eo 28 | 29 | from enum import IntFlag 30 | 31 | __all__ = ['AssetType', 'Band', 'CloudPlatform', 'Constellation', 'Mission', 'Instrument', 'Platform', 32 | 'FilterRelationship', 'SortDirection'] 33 | 34 | 35 | class AssetType(IntFlag): 36 | UNKNOWN_ASSET = _AssetType.UNKNOWN_ASSET 37 | JPEG = _AssetType.JPEG 38 | GEOTIFF = _AssetType.GEOTIFF 39 | LERC = _AssetType.LERC 40 | MRF = _AssetType.MRF 41 | MRF_IDX = _AssetType.MRF_IDX 42 | MRF_XML = _AssetType.MRF_XML 43 | CO_GEOTIFF = _AssetType.CO_GEOTIFF 44 | RAW = _AssetType.RAW 45 | THUMBNAIL = _AssetType.THUMBNAIL 46 | TIFF = _AssetType.TIFF 47 | JPEG_2000 = _AssetType.JPEG_2000 48 | XML = _AssetType.XML 49 | TXT = _AssetType.TXT 50 | PNG = _AssetType.PNG 51 | OVERVIEW = _AssetType.OVERVIEW 52 | JSON = _AssetType.JSON 53 | HTML = _AssetType.HTML 54 | WEBP = _AssetType.WEBP 55 | 56 | 57 | class Band(IntFlag): 58 | UNKNOWN_BAND = _Eo.UNKNOWN_BAND 59 | COASTAL = _Eo.COASTAL 60 | BLUE = _Eo.BLUE 61 | GREEN = _Eo.GREEN 62 | RED = _Eo.RED 63 | RGB = _Eo.RGB 64 | NIR = _Eo.NIR 65 | # special case for landsat 1 - 3 66 | NIR_2 = _Eo.NIR_2 67 | RGBIR = _Eo.RGBIR 68 | SWIR_1 = _Eo.SWIR_1 69 | SWIR_2 = _Eo.SWIR_2 70 | PAN = _Eo.PAN 71 | CIRRUS = _Eo.CIRRUS 72 | LWIR_1 = _Eo.LWIR_1 73 | LWIR_2 = _Eo.LWIR_2 74 | 75 | 76 | class CloudPlatform(IntFlag): 77 | UNKNOWN_CLOUD_PLATFORM = _CloudPlatform.UNKNOWN_CLOUD_PLATFORM 78 | AWS = _CloudPlatform.AWS 79 | GCP = _CloudPlatform.GCP 80 | AZURE = _CloudPlatform.AZURE 81 | IBM = _CloudPlatform.IBM 82 | 83 | 84 | class Constellation(IntFlag): 85 | UNKNOWN_PLATFORM = _Constellation.UNKNOWN_CONSTELLATION 86 | 87 | 88 | class Mission(IntFlag): 89 | UNKNOWN_MISSION = _Mission.UNKNOWN_MISSION 90 | LANDSAT = _Mission.LANDSAT 91 | NAIP = _Mission.NAIP 92 | SWIFT = _Mission.SWIFT 93 | PNOA = _Mission.PNOA 94 | 95 | 96 | class Instrument(IntFlag): 97 | UNKNOWN_INSTRUMENT = _Instrument.UNKNOWN_INSTRUMENT 98 | OLI = _Instrument.OLI 99 | TIRS = _Instrument.TIRS 100 | OLI_TIRS = _Instrument.OLI_TIRS 101 | POM_1 = _Instrument.POM_1 102 | TM = _Instrument.TM 103 | ETM = _Instrument.ETM 104 | MSS = _Instrument.MSS 105 | POM_2 = _Instrument.POM_2 106 | 107 | 108 | class Platform(IntFlag): 109 | UNKNOWN_PLATFORM = _Platform.UNKNOWN_PLATFORM 110 | LANDSAT_1 = _Platform.LANDSAT_1 111 | LANDSAT_2 = _Platform.LANDSAT_2 112 | LANDSAT_3 = _Platform.LANDSAT_3 113 | LANDSAT_123 = _Platform.LANDSAT_123 114 | LANDSAT_4 = _Platform.LANDSAT_4 115 | LANDSAT_5 = _Platform.LANDSAT_5 116 | LANDSAT_45 = _Platform.LANDSAT_45 117 | LANDSAT_7 = _Platform.LANDSAT_7 118 | LANDSAT_8 = _Platform.LANDSAT_8 119 | SWIFT_2 = _Platform.SWIFT_2 120 | SWIFT_3 = _Platform.SWIFT_3 121 | 122 | 123 | class SortDirection(IntFlag): 124 | NOT_SORTED = _SortDirection.NOT_SORTED 125 | DESC = _SortDirection.DESC 126 | ASC = _SortDirection.ASC 127 | 128 | 129 | class FilterRelationship(IntFlag): 130 | EQ = _FilterRelationship.EQ 131 | LTE = _FilterRelationship.LTE 132 | GTE = _FilterRelationship.GTE 133 | LT = _FilterRelationship.LT 134 | GT = _FilterRelationship.GT 135 | BETWEEN = _FilterRelationship.BETWEEN 136 | NOT_BETWEEN = _FilterRelationship.NOT_BETWEEN 137 | NEQ = _FilterRelationship.NEQ 138 | IN = _FilterRelationship.IN 139 | NOT_IN = _FilterRelationship.NOT_IN 140 | LIKE = _FilterRelationship.LIKE 141 | NOT_LIKE = _FilterRelationship.NOT_LIKE 142 | 143 | 144 | # Final check to make sure that all enums have complete definitions for the associated protobufs 145 | for enum_class_name in __all__: 146 | nsl_enum = getattr(sys.modules[__name__], enum_class_name) 147 | if enum_class_name in ['Band']: 148 | eo_class = getattr(sys.modules[__name__], '_Eo') 149 | epl_pb_enum_wrapper = getattr(eo_class, enum_class_name) 150 | else: 151 | epl_pb_enum_wrapper = getattr(sys.modules[__name__], '_' + enum_class_name) 152 | 153 | for enum_key_name, num in epl_pb_enum_wrapper.items(): 154 | enum_values = [member[1].value for member in nsl_enum.__members__.items()] 155 | if num not in enum_values: 156 | raise Exception("protobuf enum_class_name {} not accounted for in enum {}. the stac client hasn't been " 157 | "updated for this version of the protobuf definition".format(enum_key_name, 158 | enum_class_name)) 159 | -------------------------------------------------------------------------------- /nsl/stac/subscription.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from base64 import b64decode 4 | from datetime import datetime, timezone 5 | 6 | from epl.protobuf.v1 import stac_pb2 7 | 8 | from nsl.stac.destinations import BaseDestination, DestinationDecoder 9 | from nsl.stac.utils import stac_request_from_b64 10 | 11 | 12 | class Subscription: 13 | id: str 14 | nsl_id: str 15 | is_active: bool 16 | created_at: datetime 17 | stac_request: stac_pb2.StacRequest 18 | destination: BaseDestination 19 | 20 | def __init__(self, response_dict: dict): 21 | self.id = response_dict['sub_id'] 22 | self.nsl_id = response_dict['nsl_id'] 23 | self.is_active = response_dict['is_active'] 24 | self.created_at = datetime.utcfromtimestamp(response_dict['created_at']).replace(tzinfo=timezone.utc) 25 | self.stac_request = stac_request_from_b64(response_dict['stac_request']) 26 | self.destination = json.loads(response_dict['destination_json'], cls=DestinationDecoder) 27 | -------------------------------------------------------------------------------- /nsl/stac/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | 18 | import base64 19 | import os 20 | import datetime 21 | import http.client 22 | import re 23 | from urllib.parse import urlparse 24 | from typing import List, IO, Union, Dict, Any, Optional 25 | from warnings import warn 26 | 27 | import boto3 28 | import botocore 29 | import botocore.exceptions 30 | import botocore.client 31 | from google.cloud import storage 32 | from google.protobuf import timestamp_pb2, duration_pb2 33 | from tenacity import retry, stop_after_delay, wait_fixed 34 | 35 | from epl.protobuf.v1.stac_pb2 import epl_dot_protobuf_dot_v1_dot_query__pb2 as query 36 | from nsl.stac import gcs_storage_client, bearer_auth, \ 37 | StacItem, StacRequest, Asset, TimestampFilter, DatetimeRange, Eo, FloatFilter, enum 38 | from nsl.stac.enum import Band, CloudPlatform, FilterRelationship, SortDirection, AssetType 39 | 40 | DEFAULT_RGB = [Band.RED, Band.GREEN, Band.BLUE, Band.NIR] 41 | RASTER_TYPES = [AssetType.CO_GEOTIFF, AssetType.GEOTIFF, AssetType.MRF] 42 | UNSUPPORTED_TIME_FILTERS = [FilterRelationship.IN, 43 | FilterRelationship.NOT_IN, 44 | FilterRelationship.LIKE, 45 | FilterRelationship.NOT_LIKE] 46 | 47 | 48 | def get_blob_metadata(bucket: str, blob_name: str) -> storage.Blob: 49 | """ 50 | get metadata/interface for one asset in google cloud storage 51 | :param bucket: bucket name 52 | :param blob_name: complete blob name of item (doesn't include bucket name) 53 | :return: Blob interface item 54 | """ 55 | if gcs_storage_client.client is None: 56 | raise ValueError("GOOGLE_APPLICATION_CREDENTIALS environment variable not set") 57 | 58 | bucket = gcs_storage_client.client.get_bucket(bucket) 59 | return bucket.get_blob(blob_name=blob_name.strip('/')) 60 | 61 | 62 | @retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5)) 63 | def download_gcs_object(bucket: str, 64 | blob_name: str, 65 | file_obj: IO[bytes] = None, 66 | save_filename: str = "", 67 | make_dir=True) -> str: 68 | """ 69 | download a specific blob from Google Cloud Storage (GCS) to a file object handle 70 | :param make_dir: if directory doesn't exist create 71 | :param bucket: bucket name 72 | :param blob_name: the full prefix to a specific asset in GCS. Does not include bucket name 73 | :param file_obj: file object (or BytesIO string_buffer) where data should be written 74 | :param save_filename: the filename to save the file to 75 | :return: returns path to downloaded file if applicable 76 | """ 77 | if make_dir and save_filename != "": 78 | path_to_create = os.path.split(save_filename)[0] 79 | if not os.path.exists(path_to_create): 80 | os.makedirs(path_to_create, exist_ok=True) 81 | 82 | blob = get_blob_metadata(bucket=bucket, blob_name=blob_name) 83 | 84 | if file_obj is not None: 85 | blob.download_to_file(file_obj=file_obj, client=gcs_storage_client.client) 86 | if "name" in file_obj.__dict__: 87 | save_filename = file_obj.name 88 | else: 89 | save_filename = "" 90 | try: 91 | file_obj.seek(0) 92 | except: 93 | pass 94 | 95 | return save_filename 96 | elif len(save_filename) > 0: 97 | with open(save_filename, "w+b") as file_obj: 98 | download_gcs_object(bucket, blob_name, file_obj=file_obj) 99 | return save_filename 100 | else: 101 | raise ValueError("must provide filename or file_obj") 102 | 103 | 104 | def download_s3_object(bucket: str, 105 | blob_name: str, 106 | file_obj: IO = None, 107 | save_filename: str = "", 108 | requester_pays: bool = False) -> str: 109 | extra_args = None 110 | if requester_pays: 111 | extra_args = {'RequestPayer': 'requester'} 112 | 113 | s3 = boto3.client('s3') 114 | try: 115 | if file_obj is not None: 116 | s3.download_fileobj(Bucket=bucket, Key=blob_name, Fileobj=file_obj, ExtraArgs=extra_args) 117 | if "name" in file_obj.__dict__: 118 | save_filename = file_obj.name 119 | else: 120 | save_filename = "" 121 | file_obj.seek(0) 122 | 123 | return save_filename 124 | elif len(save_filename) > 0: 125 | s3.download_file(Bucket=bucket, Key=blob_name, Filename=save_filename, ExtraArgs=extra_args) 126 | return save_filename 127 | else: 128 | raise ValueError("must provide filename or file_obj") 129 | except botocore.exceptions.ClientError as e: 130 | if e.response['Error']['Code'] == "404": 131 | print("The object does not exist.") 132 | else: 133 | raise 134 | 135 | 136 | def download_href_object(asset: Asset, 137 | file_obj: IO = None, 138 | save_filename: str = "", 139 | nsl_id: str = None, 140 | profile_name: str = None) -> str: 141 | """ 142 | download the href of an asset 143 | :param asset: The asset to download 144 | :param file_obj: BinaryIO file object to download data into. If file_obj and save_filename and/or save_directory 145 | are set, then only file_obj is used 146 | :param save_filename: absolute or relative path filename to save asset to (must have write permissions) 147 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one NSL_ID and NSL_SECRET have been defined with 148 | set_credentials method. Specify NSL_ID to use for downloading. If NSL_ID and NSL_SECRET environment variables 149 | are not set, you must use `NSLClient.set_credentials` to add at least one set of credentials. 150 | :param profile_name: ADVANCED ONLY. Only necessary if more than one NSL profile has been defined with the 151 | `set_credentials` method. Specifies which NSL profile to use for downloading. 152 | :return: returns the save_filename. if BinaryIO is not a FileIO object type, save_filename returned is an 153 | empty string 154 | """ 155 | if not asset.href: 156 | raise ValueError("no href on asset") 157 | 158 | host = urlparse(asset.href) 159 | conn = http.client.HTTPConnection(host.netloc) 160 | 161 | headers = {} 162 | asset_url = host.path 163 | if asset.bucket_manager == "Near Space Labs": 164 | headers = {"authorization": bearer_auth.auth_header(nsl_id=nsl_id, profile_name=profile_name)} 165 | asset_url = "/download/{object}".format(object=asset.object_path) 166 | 167 | if len(asset.type) > 0: 168 | headers["content-type"] = asset.type 169 | conn.request(method="GET", url=asset_url, headers=headers) 170 | 171 | res = conn.getresponse() 172 | if res.status == 404: 173 | raise ValueError("not found error for {path}".format(path=asset.href)) 174 | elif res.status == 403: 175 | raise ValueError("auth error for asset {asset}".format(asset=asset.href)) 176 | elif res.status == 402: 177 | raise ValueError("not enough credits for downloading asset {asset}".format(asset=asset.href)) 178 | elif res.status != 200: 179 | raise ValueError("error code {code} for asset: {asset}".format(code=res.status, asset=asset.href)) 180 | 181 | if len(save_filename) > 0: 182 | with open(save_filename, mode='wb') as f: 183 | f.write(res.read()) 184 | elif file_obj is not None: 185 | file_obj.write(res.read()) 186 | if "name" in file_obj.__dict__: 187 | save_filename = file_obj.name 188 | else: 189 | save_filename = "" 190 | file_obj.seek(0) 191 | else: 192 | raise ValueError("must provide filename or file_obj") 193 | 194 | return save_filename 195 | 196 | 197 | def download_asset(asset: Asset, 198 | from_bucket: bool = False, 199 | file_obj: IO[Union[Union[str, bytes], Any]] = None, 200 | save_filename: str = "", 201 | save_directory: str = "", 202 | requester_pays: bool = False, 203 | nsl_id: str = None, 204 | profile_name: str = None) -> str: 205 | """ 206 | download an asset. Defaults to downloading from cloud storage. save the data to a BinaryIO file object, a filename 207 | on your filesystem, or to a directory on your filesystem (the filename will be chosen from the basename of the 208 | object). 209 | :param requester_pays: authorize a requester pays download. this can be costly, 210 | so only enable it if you understand the implications. 211 | :param asset: The asset to download 212 | :param from_bucket: force the download to occur from cloud storage instead of href endpoint 213 | :param file_obj: BinaryIO file object to download data into. If file_obj and save_filename and/or save_directory are 214 | set, then only file_obj is used 215 | :param save_filename: absolute or relative path filename to save asset to (must have write permissions) 216 | :param save_directory: absolute or relative directory path to save asset in (must have write permissions). Filename 217 | is derived from the basename of the object_path or the href 218 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one NSL_ID and NSL_SECRET have been defined with 219 | set_credentials method. Specify NSL_ID to use for downloading. If NSL_ID and NSL_SECRET environment variables 220 | are not set, you must use `NSLClient.set_credentials` to add at least one set of credentials. 221 | :param profile_name: ADVANCED ONLY. Only necessary if more than one NSL profile has been defined with the 222 | `set_credentials` method. Specifies which NSL profile to use for downloading. 223 | :return: 224 | """ 225 | if len(save_directory) > 0 and file_obj is None and len(save_filename) == 0: 226 | if os.path.exists(save_directory): 227 | save_filename = os.path.join(save_directory, os.path.basename(asset.object_path)) 228 | else: 229 | raise ValueError("directory 'save_directory' doesn't exist") 230 | 231 | if from_bucket and asset.cloud_platform == CloudPlatform.GCP: 232 | return download_gcs_object(bucket=asset.bucket, 233 | blob_name=asset.object_path, 234 | file_obj=file_obj, 235 | save_filename=save_filename) 236 | elif from_bucket and asset.cloud_platform == CloudPlatform.AWS: 237 | return download_s3_object(bucket=asset.bucket, 238 | blob_name=asset.object_path, 239 | file_obj=file_obj, 240 | save_filename=save_filename, 241 | requester_pays=requester_pays) 242 | else: 243 | return download_href_object(asset=asset, 244 | file_obj=file_obj, 245 | save_filename=save_filename, 246 | nsl_id=nsl_id, 247 | profile_name=profile_name) 248 | 249 | 250 | def download_assets(stac_item: StacItem, 251 | save_directory: str, 252 | from_bucket: bool = False, 253 | nsl_id: str = None) -> List[str]: 254 | """ 255 | Download all the assets for a StacItem into a directory 256 | :param nsl_id: ADVANCED ONLY. Only necessary if more than one nsl_id and nsl_secret have been defined with 257 | set_credentials method. Specify nsl_id to use. if NSL_ID and NSL_SECRET environment variables not set must use 258 | NSLClient object's set_credentials to set credentials 259 | :param stac_item: StacItem containing assets to download 260 | :param save_directory: the directory where the files should be downloaded 261 | :param from_bucket: force download from bucket. if set to false downloads happen from href. defaults to False 262 | :return: 263 | """ 264 | filenames = [] 265 | for asset_key in stac_item.assets: 266 | asset = stac_item.assets[asset_key] 267 | filenames.append(download_asset(asset=asset, 268 | from_bucket=from_bucket, 269 | save_directory=save_directory, 270 | nsl_id=nsl_id)) 271 | return filenames 272 | 273 | 274 | # TODO https://pypi.org/project/Deprecated/ 275 | def get_asset(stac_item: StacItem, 276 | asset_type: AssetType = None, 277 | cloud_platform: CloudPlatform = CloudPlatform.UNKNOWN_CLOUD_PLATFORM, 278 | eo_bands: Eo.Band = Eo.UNKNOWN_BAND, 279 | asset_regex: Dict = None, 280 | asset_key: str = None, 281 | b_relaxed_types: bool = False) -> Optional[Asset]: 282 | """ 283 | get a protobuf object(pb) asset from a stac item pb. If your parameters are broad (say, if you used all defaults) 284 | this function would only return you the first asset that matches the parameters. use 285 | :func:`get_assets ` to return more than one asset from a request. 286 | :param stac_item: stac item whose assets we want to search by parameters 287 | :param asset_type: an asset_type enum to return. if not defined then it is assumed to search all asset types 288 | :param cloud_platform: only return assets that are hosted on the cloud platform described in the cloud_platform 289 | field of the item. default grabs the first asset that meets all the other parameters. 290 | :param band: if the data has electro-optical spectrum data, define the band you want to retrieve. if the data is 291 | not electro-optical then don't define this parameter (defaults to UNKNOWN_BAND) 292 | :param asset_basename: only return asset if the basename of the object path matches this value 293 | :return: asset pb object 294 | """ 295 | results = get_assets(stac_item, asset_type, cloud_platform, eo_bands, asset_regex, asset_key, b_relaxed_types) 296 | if len(results) > 1: 297 | raise ValueError("must be more specific in selecting your asset. if all enums are used, try using " 298 | "asset_key_regex") 299 | elif len(results) == 1: 300 | return results[0] 301 | return None 302 | 303 | 304 | def _asset_types_match(desired_type: enum.AssetType, 305 | asset_type: enum.AssetType, 306 | b_relaxed_types: bool = False) -> bool: 307 | if not b_relaxed_types: 308 | return desired_type == asset_type 309 | elif desired_type == enum.AssetType.TIFF: 310 | return asset_type == desired_type or \ 311 | asset_type == enum.AssetType.GEOTIFF or \ 312 | asset_type == enum.AssetType.CO_GEOTIFF 313 | elif desired_type == enum.AssetType.GEOTIFF: 314 | return asset_type == desired_type or asset_type == enum.AssetType.CO_GEOTIFF 315 | return asset_type == desired_type 316 | 317 | 318 | def equals_pb(left: Asset, right: Asset): 319 | """ 320 | does the AssetWrap equal a protobuf Asset 321 | :param other: 322 | :return: 323 | """ 324 | return left.SerializeToString() == right.SerializeToString() 325 | 326 | 327 | # TODO https://pypi.org/project/Deprecated/ 328 | def get_assets(stac_item: StacItem, 329 | asset_type: enum.AssetType = None, 330 | cloud_platform: CloudPlatform = CloudPlatform.UNKNOWN_CLOUD_PLATFORM, 331 | eo_bands: Eo.Band = Eo.UNKNOWN_BAND, 332 | asset_regex: Dict = None, 333 | asset_key: str = None, 334 | b_relaxed_types: bool = False) -> List[Asset]: 335 | """ 336 | get a generator of assets from a stac item, filtered by the parameters. 337 | :param stac_item: stac item whose assets we want to search by parameters 338 | :param band: if the data has electro optical spectrum data, define the band you want to retrieve. if the data is not 339 | electro optical then don't define this parameter (defaults to UNKNOWN_BAND) 340 | :param asset_types: a list of asset_types to seach. if not defined then it is assumed to search all asset types 341 | :param cloud_platform: only return assets that are hosted on the cloud platform described in the cloud_platform 342 | field of the item. default grabs the first asset that meets all the other parameters. 343 | :param asset_basename: only return asset if the basename of the object path matches this value 344 | :return: asset pb object 345 | """ 346 | if asset_key is not None and asset_key in stac_item.assets: 347 | return [stac_item.assets[asset_key]] 348 | elif asset_key is not None and asset_key and asset_key not in stac_item.assets: 349 | raise ValueError("asset_key {} not found".format(asset_key)) 350 | 351 | results = [] 352 | for asset_key in stac_item.assets: 353 | current = stac_item.assets[asset_key] 354 | b_asset_type_match = _asset_types_match(desired_type=asset_type, 355 | asset_type=current.asset_type, 356 | b_relaxed_types=b_relaxed_types) 357 | if (eo_bands is not None and eo_bands != enum.Band.UNKNOWN_BAND) and \ 358 | current.eo_bands != eo_bands: 359 | continue 360 | if (cloud_platform is not None and cloud_platform != enum.CloudPlatform.UNKNOWN_CLOUD_PLATFORM) and \ 361 | current.cloud_platform != cloud_platform: 362 | continue 363 | if (asset_type is not None and asset_type != enum.AssetType.UNKNOWN_ASSET) and \ 364 | not b_asset_type_match: 365 | continue 366 | if asset_regex is not None and len(asset_regex) > 0: 367 | b_continue = False 368 | for key, regex_value in asset_regex.items(): 369 | if key == 'asset_key': 370 | if not re.match(regex_value, asset_key): 371 | b_continue = True 372 | break 373 | else: 374 | if not hasattr(current, key): 375 | raise AttributeError("no key {0} in asset {1}".format(key, current)) 376 | elif not re.match(regex_value, getattr(current, key)): 377 | b_continue = True 378 | break 379 | 380 | if b_continue: 381 | continue 382 | 383 | # check that asset hasn't changed between protobuf and asset_map 384 | pb_asset = stac_item.assets[asset_key] 385 | if not equals_pb(current, pb_asset): 386 | raise ValueError("corrupted protobuf. Asset and AssetWrap have differing underlying protobuf") 387 | 388 | results.append(current) 389 | return results 390 | 391 | 392 | def _asset_has_filename(asset: Asset, asset_basename): 393 | if os.path.basename(asset.object_path).lower() == os.path.basename(asset_basename).lower(): 394 | return True 395 | return False 396 | 397 | 398 | # TODO https://pypi.org/project/Deprecated/ 399 | def has_asset_type(stac_item: StacItem, asset_type: AssetType): 400 | """ 401 | does the stac item contain the asset 402 | :param stac_item: 403 | :param asset_type: 404 | :return: 405 | """ 406 | for asset in stac_item.assets.values(): 407 | if asset.asset_type == asset_type: 408 | return True 409 | return False 410 | 411 | 412 | # TODO https://pypi.org/project/Deprecated/ 413 | def has_asset(stac_item: StacItem, asset: Asset): 414 | """ 415 | check whether a stac_item has a perfect match to the provided asset 416 | :param stac_item: stac item whose assets we're checking against asset 417 | :param asset: asset we're looking for in stac_item 418 | :return: 419 | """ 420 | for test_asset in stac_item.assets.values(): 421 | b_matches = True 422 | for field in test_asset.DESCRIPTOR.fields: 423 | if getattr(test_asset, field.name) != getattr(asset, field.name): 424 | b_matches = False 425 | break 426 | if b_matches: 427 | return b_matches 428 | return False 429 | 430 | 431 | def item_region(stac_item: StacItem) -> str: 432 | for asset_key in stac_item.assets: 433 | return stac_item.assets[asset_key].object_path.split('/')[2] 434 | warn(f"failed to find STAC item's region: {stac_item.id}") 435 | return "" 436 | 437 | 438 | def get_uri(asset: Asset, b_vsi_uri=True, prefix: str = "") -> str: 439 | """ 440 | construct the uri for the resource in the asset. 441 | :param asset: 442 | :param b_vsi_uri: 443 | :param prefix: 444 | :return: 445 | """ 446 | 447 | if not asset.bucket or not asset.object_path: 448 | if not b_vsi_uri: 449 | raise FileNotFoundError("The bucket ref is not AWS or Google:\nhref : {0}".format(asset.href)) 450 | return '/vsicurl_streaming/{}'.format(asset.href) 451 | elif not prefix: 452 | prefix = "{0}://" 453 | if b_vsi_uri: 454 | prefix = "/vsi{0}_streaming" 455 | 456 | if asset.cloud_platform == CloudPlatform.GCP: 457 | prefix = prefix.format("gs") 458 | elif asset.cloud_platform == CloudPlatform.AWS: 459 | prefix = prefix.format("s3") 460 | else: 461 | raise ValueError("The only current cloud platforms are GCP and AWS. This asset doesn't have the " 462 | "'cloud_platform' field defined") 463 | 464 | return "{0}/{1}/{2}".format(prefix, asset.bucket, asset.object_path) 465 | 466 | 467 | def pb_timestampfield(rel_type: FilterRelationship, 468 | value: Union[datetime.datetime, datetime.date] = None, 469 | start: Union[datetime.datetime, datetime.date] = None, 470 | end: Union[datetime.datetime, datetime.date] = None, 471 | sort_direction: SortDirection = SortDirection.NOT_SORTED, 472 | tzinfo: datetime.timezone = datetime.timezone.utc) -> TimestampFilter: 473 | """ 474 | Create a protobuf query filter for a timestamp or a range of timestamps. If you use a datetime.date as 475 | the value combined with a rel_type of EQ then you will be creating a query filter for the 476 | 24 period of that date. 477 | :param rel_type: the relationship type to query more 478 | [here](https://geo-grpc.github.io/api/#epl.protobuf.FieldRelationship) 479 | :param value: time to search by using >, >=, <, <=, etc. cannot be used with start or end 480 | :param start: start time for between/not between query. cannot be used with value 481 | :param end: end time for between/not between query. cannot be used with value 482 | :param sort_direction: sort direction for results. Defaults to not sorting by this field 483 | :param tzinfo: timezone info, defaults to UTC 484 | :return: TimestampFilter 485 | """ 486 | if rel_type in UNSUPPORTED_TIME_FILTERS: 487 | raise ValueError("unsupported relationship type: {}".format(rel_type.name)) 488 | 489 | if value is not None and rel_type != FilterRelationship.EQ and rel_type != FilterRelationship.NEQ: 490 | if not isinstance(value, datetime.datetime): 491 | if rel_type == FilterRelationship.GTE or rel_type == FilterRelationship.LT: 492 | return TimestampFilter(value=pb_timestamp(value, tzinfo, b_force_min=True), 493 | rel_type=rel_type, 494 | sort_direction=sort_direction) 495 | elif rel_type == FilterRelationship.LTE or rel_type == FilterRelationship.GT: 496 | return TimestampFilter(value=pb_timestamp(value, tzinfo, b_force_min=False), 497 | rel_type=rel_type, 498 | sort_direction=sort_direction) 499 | return TimestampFilter(value=pb_timestamp(value, tzinfo), rel_type=rel_type, sort_direction=sort_direction) 500 | elif value is not None and not isinstance(value, datetime.datetime) and \ 501 | (rel_type == FilterRelationship.EQ or rel_type == FilterRelationship.NEQ): 502 | start = datetime.datetime.combine(value, datetime.datetime.min.time(), tzinfo=tzinfo) 503 | end = datetime.datetime.combine(value, datetime.datetime.max.time(), tzinfo=tzinfo) 504 | if rel_type == FilterRelationship.EQ: 505 | rel_type = FilterRelationship.BETWEEN 506 | else: 507 | rel_type = FilterRelationship.NOT_BETWEEN 508 | 509 | return TimestampFilter(start=pb_timestamp(start, tzinfo), 510 | end=pb_timestamp(end, tzinfo), 511 | rel_type=rel_type, 512 | sort_direction=sort_direction) 513 | 514 | 515 | def pb_timestamp(d_utc: Union[datetime.datetime, datetime.date], 516 | tzinfo: datetime.timezone = datetime.timezone.utc, 517 | b_force_min=True) -> timestamp_pb2.Timestamp: 518 | """ 519 | create a google.protobuf.Timestamp from a python datetime 520 | :param d_utc: python datetime or date 521 | :param tzinfo: 522 | :return: 523 | """ 524 | ts = timestamp_pb2.Timestamp() 525 | ts.FromDatetime(timezoned(d_utc, tzinfo, b_force_min)) 526 | return ts 527 | 528 | 529 | def datetime_from_pb_timestamp(ts: timestamp_pb2.Timestamp) -> datetime: 530 | return datetime.datetime.utcfromtimestamp(ts.seconds + ts.nanos/1e9) 531 | 532 | 533 | def timezoned(d_utc: Union[datetime.datetime, datetime.date], 534 | tzinfo: datetime.timezone = datetime.timezone.utc, 535 | b_force_min=True) -> datetime.datetime: 536 | # datetime is child to datetime.date, so if we reverse the order of this instance of we fail 537 | if isinstance(d_utc, datetime.datetime) and d_utc.tzinfo is None: 538 | # TODO add warning here: 539 | # print("warning, no timezone provided with datetime, so UTC is assumed") 540 | d_utc = datetime.datetime(d_utc.year, 541 | d_utc.month, 542 | d_utc.day, 543 | d_utc.hour, 544 | d_utc.minute, 545 | d_utc.second, 546 | d_utc.microsecond, 547 | tzinfo=tzinfo) 548 | elif not isinstance(d_utc, datetime.datetime): 549 | # print("warning, no timezone provided with date, so UTC is assumed") 550 | if b_force_min: 551 | d_utc = datetime.datetime.combine(d_utc, datetime.datetime.min.time(), tzinfo=tzinfo) 552 | else: 553 | d_utc = datetime.datetime.combine(d_utc, datetime.datetime.max.time(), tzinfo=tzinfo) 554 | return d_utc 555 | 556 | 557 | # TODO https://pypi.org/project/Deprecated/ 558 | def duration(d_start: Union[datetime.datetime, datetime.date], d_end: Union[datetime.datetime, datetime.date]): 559 | d = duration_pb2.Duration() 560 | d.FromTimedelta(timezoned(d_end) - timezoned(d_start)) 561 | return d 562 | 563 | 564 | # TODO https://pypi.org/project/Deprecated/ 565 | def datetime_range(d_start: Union[datetime.datetime, datetime.date], 566 | d_end: Union[datetime.datetime, datetime.date]) -> DatetimeRange: 567 | """ 568 | for datetime range definitions for Mosaic objects. 569 | :param d_start: start datetime or date 570 | :param d_end: end datetime or date 571 | :return: DatetimeRange object 572 | """ 573 | return DatetimeRange(start=pb_timestamp(d_start), end=pb_timestamp(d_end)) 574 | 575 | 576 | def stac_request_to_b64(req: StacRequest) -> str: 577 | return str(base64.b64encode(req.SerializeToString()), encoding='ascii') 578 | 579 | 580 | def stac_request_from_b64(encoded: str) -> StacRequest: 581 | req = StacRequest() 582 | req.ParseFromString(base64.b64decode(bytes(encoded, encoding='ascii'))) 583 | return req 584 | 585 | 586 | def stac_item_to_b64(item: StacItem) -> str: 587 | return str(base64.b64encode(item.SerializeToString()), encoding='ascii') 588 | 589 | 590 | def stac_item_from_b64(encoded: str) -> StacItem: 591 | item = StacItem() 592 | item.ParseFromString(base64.b64decode(bytes(encoded, encoding='ascii'))) 593 | return item 594 | 595 | 596 | def eval_float_filter(float_filter: FloatFilter, val: float) -> bool: 597 | rel = float_filter.rel_type 598 | 599 | if rel == enum.FilterRelationship.EQ: 600 | return val == float_filter.value 601 | elif rel == enum.FilterRelationship.NEQ: 602 | return val != float_filter.value 603 | elif rel == enum.FilterRelationship.BETWEEN: 604 | return float_filter.start < val < float_filter.end 605 | elif rel == enum.FilterRelationship.NOT_BETWEEN: 606 | return val < float_filter.start or val > float_filter.end 607 | elif rel == enum.FilterRelationship.GTE: 608 | return val >= float_filter.value 609 | elif rel == enum.FilterRelationship.GT: 610 | return val > float_filter.value 611 | elif rel == enum.FilterRelationship.LTE: 612 | return val <= float_filter.value 613 | elif rel == enum.FilterRelationship.LT: 614 | return val < float_filter.value 615 | else: 616 | raise ValueError(f"not currently evaluating float filters of type: {query.FilterRelationship.Name(rel)}") 617 | -------------------------------------------------------------------------------- /requirements-demo.txt: -------------------------------------------------------------------------------- 1 | epl.geometry==1.0.3 2 | 3 | ipykernel 4 | jupyter 5 | jupyter_contrib_nbextensions 6 | matplotlib 7 | requests 8 | shapely 9 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | epl.geometry==1.0.3 2 | 3 | numpy 4 | pytest 5 | pytest-flake8 6 | requests 7 | treon 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.16.10 2 | epl.protobuf.v1==1.0.4 3 | google-cloud-storage>=1.14.0 4 | grpcio-tools~=1.33.0 5 | protobuf~=3.19.0 6 | requests 7 | shapely==1.8.5.post1 8 | tenacity==8.0.1 9 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | # content of setup.cfg 2 | [tool:pytest] 3 | flake8-max-line-length = 120 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | 18 | import sys 19 | import os 20 | 21 | from setuptools import setup 22 | 23 | src_path = os.path.dirname(os.path.abspath(sys.argv[0])) 24 | old_path = os.getcwd() 25 | os.chdir(src_path) 26 | sys.path.insert(0, src_path) 27 | 28 | package_name = 'nsl.stac' 29 | kwargs = { 30 | 'name': package_name, 31 | 'description': 'gRPC Spatio Temporal Asset Catalog library', 32 | 'url': 'https://github.com/nearspacelabs/stac-client-python', 33 | 'long_description': "gRPC Spatio Temporal Asset Catalog library provided by Near Space Labs", 34 | 'author': 'David Raleigh', 35 | 'author_email': 'david@nearspacelabs.com', 36 | 'license': 'Apache 2.0', 37 | 'version': '1.2.7', 38 | 'python_requires': '>3.6.0', 39 | 'packages': ['nsl.stac', 'nsl.stac.destinations'], 40 | 'install_requires': [ 41 | # local 42 | 'epl.protobuf.v1', 43 | 'epl.geometry', 44 | # third-party 45 | 'boto3', 46 | 'google-cloud-storage', 47 | 'grpcio-tools==1.33.*', 48 | 'protobuf~=3.19.0', 49 | 'requests', 50 | 'shapely', 51 | 'tenacity', 52 | ], 53 | 'zip_safe': False 54 | } 55 | 56 | clssfrs = [ 57 | 'Programming Language :: Python', 58 | 'Programming Language :: Python :: 3', 59 | 'Programming Language :: Python :: 3.7', 60 | 'Programming Language :: Python :: 3.8', 61 | 'Programming Language :: Python :: 3.9', 62 | ] 63 | kwargs['classifiers'] = clssfrs 64 | 65 | setup(**kwargs) 66 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com -------------------------------------------------------------------------------- /test/test_client.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-20 Near Space Labs 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | # for additional information, contact: 16 | # info@nearspacelabs.com 17 | import pathlib 18 | import tempfile 19 | import unittest 20 | import io 21 | import os 22 | import pickle 23 | 24 | from epl import geometry as epl_geometry 25 | from epl.geometry import Polygon 26 | from epl.protobuf.v1.geometry_pb2 import EnvelopeData 27 | from google.protobuf import timestamp_pb2 28 | from datetime import datetime, timezone, date, timedelta 29 | 30 | from nsl.stac import StacRequest, LandsatRequest, MosaicRequest 31 | from nsl.stac import StacItem, Asset, TimestampFilter, GeometryData, ProjectionData, Mosaic 32 | from nsl.stac import utils, enum 33 | from nsl.stac.enum import AssetType, Band, CloudPlatform, Mission, FilterRelationship 34 | from nsl.stac.client import NSLClient 35 | from nsl.stac.experimental import StacRequestWrap, NSLClientEx, AssetWrap, StacItemWrap 36 | 37 | client = NSLClient(nsl_only=False) 38 | client_ex = NSLClientEx(nsl_only=False) 39 | 40 | 41 | class TestProtobufs(unittest.TestCase): 42 | def test_mosaic_parts(self): 43 | mosaic = Mosaic(name="bananas", quad_key="stuff", provenance_ids=["no one", "wants", "potato", "waffles"]) 44 | 45 | self.assertEqual(mosaic.name, "bananas") 46 | mosaic.observation_range.CopyFrom(utils.datetime_range(date(2016, 1, 1), date(2018, 1, 1))) 47 | d_compare = utils.timezoned(date(2019, 1, 1)) 48 | self.assertGreater(d_compare.timestamp(), mosaic.observation_range.start.seconds) 49 | self.assertGreater(d_compare.timestamp(), mosaic.observation_range.end.seconds) 50 | 51 | self.assertEqual(mosaic.provenance_ids[0], "no one") 52 | self.assertEqual(4, len(mosaic.provenance_ids)) 53 | mosaic.provenance_ids.append("and boiled chicken") 54 | self.assertEqual(5, len(mosaic.provenance_ids)) 55 | mosaic_request = MosaicRequest(name="bananas", quad_key="stuffly") 56 | self.assertEqual(mosaic_request.name, mosaic.name) 57 | stac_item = StacItem(mosaic=mosaic) 58 | self.assertEqual(stac_item.mosaic.name, mosaic.name) 59 | 60 | stac_request = StacRequest(mosaic=mosaic_request) 61 | self.assertEqual(stac_request.mosaic.name, mosaic.name) 62 | 63 | def test_durations(self): 64 | d = utils.duration(datetime(2016, 1, 1), datetime(2017, 1, 1)) 65 | self.assertEquals(d.seconds, 31622400) 66 | d = utils.duration(date(2016, 1, 1), datetime(2017, 1, 1)) 67 | self.assertEquals(d.seconds, 31622400) 68 | d = utils.duration(date(2016, 1, 1), date(2017, 1, 1)) 69 | self.assertEquals(d.seconds, 31622400) 70 | d = utils.duration(datetime(2016, 1, 1), date(2017, 1, 1)) 71 | self.assertEquals(d.seconds, 31622400) 72 | 73 | td = timedelta(seconds=d.seconds) 74 | d_end = datetime(2016, 1, 1) + td 75 | self.assertEquals(d_end.year, 2017) 76 | self.assertEquals(d_end.day, 1) 77 | self.assertEquals(d_end.month, 1) 78 | 79 | # FromDatetime for protobuf 3.6.1 throws "TypeError: can't subtract offset-naive and offset-aware datetimes" 80 | ts = utils.pb_timestamp(datetime(2016, 1, 1, tzinfo=timezone.utc)) 81 | self.assertIsNotNone(ts) 82 | 83 | d = utils.duration(datetime(2017, 1, 1), datetime(2017, 1, 1, 0, 0, 59)) 84 | self.assertEquals(d.seconds, 59) 85 | 86 | now_local = datetime.now().astimezone() 87 | now_utc = datetime.now(tz=timezone.utc) 88 | d = utils.duration(now_local, now_utc) 89 | self.assertLess(d.seconds, 1) 90 | 91 | ts = utils.pb_timestamp(now_local) 92 | ts2 = timestamp_pb2.Timestamp() 93 | ts2.FromDatetime(now_local) 94 | self.assertEquals(ts.seconds, ts2.seconds) 95 | 96 | d = utils.duration(datetime(2016, 1, 1, 0, 0, 59, tzinfo=timezone.utc), 97 | datetime(2016, 1, 1, 0, 1, 59, tzinfo=timezone.utc)) 98 | self.assertEquals(d.seconds, 60) 99 | 100 | utc_now = now_local.astimezone(tz=timezone.utc) 101 | later_now = utc_now + timedelta(seconds=33) 102 | 103 | d = utils.duration(now_local, later_now) 104 | self.assertEquals(d.seconds, 33) 105 | 106 | 107 | class TestAssetMatching(unittest.TestCase): 108 | def test_asset_match(self): 109 | asset_1 = Asset(href="pecans") 110 | asset_2 = Asset(href="walnuts") 111 | stac_item = StacItem() 112 | stac_item.assets["test_key"].CopyFrom(asset_1) 113 | self.assertFalse(utils.has_asset(stac_item, asset_2)) 114 | 115 | 116 | class TestLandsat(unittest.TestCase): 117 | def test_product_id(self): 118 | product_id = "LC08_L1TP_027039_20150226_20170228_01_T1" 119 | stac_request = StacRequest(landsat=LandsatRequest(product_id=product_id)) 120 | stac_item = client.search_one(stac_request) 121 | self.assertIsNotNone(stac_item) 122 | self.assertEquals("LC80270392015057LGN01", stac_item.id) 123 | 124 | def test_wrs_row_path(self): 125 | wrs_path = 27 126 | wrs_row = 38 127 | 128 | stac_request = StacRequest(landsat=LandsatRequest(wrs_path=wrs_path, wrs_row=wrs_row)) 129 | stac_item = client.search_one(stac_request) 130 | self.assertNotEqual(len(stac_item.id), 0) 131 | 132 | def test_OLI(self): 133 | stac_id = "LO81120152015061LGN00" 134 | stac_request = StacRequest(id=stac_id) 135 | stac_item = client.search_one(stac_request) 136 | asset = utils.get_asset(stac_item, eo_bands=Band.BLUE, cloud_platform=CloudPlatform.GCP) 137 | self.assertIsNotNone(asset) 138 | asset = utils.get_asset(stac_item, 139 | eo_bands=Band.BLUE, 140 | asset_type=enum.AssetType.GEOTIFF, 141 | cloud_platform=CloudPlatform.AWS) 142 | self.assertIsNotNone(asset) 143 | 144 | asset = utils.get_asset(stac_item, eo_bands=Band.LWIR_1, cloud_platform=CloudPlatform.GCP) 145 | self.assertIsNone(asset) 146 | asset = utils.get_asset(stac_item, eo_bands=Band.LWIR_1, cloud_platform=CloudPlatform.AWS) 147 | self.assertIsNone(asset) 148 | 149 | asset = utils.get_asset(stac_item, eo_bands=Band.CIRRUS, cloud_platform=CloudPlatform.GCP) 150 | self.assertIsNotNone(asset) 151 | asset = utils.get_asset(stac_item, eo_bands=Band.CIRRUS, cloud_platform=CloudPlatform.AWS, 152 | asset_type=enum.AssetType.GEOTIFF) 153 | self.assertIsNotNone(asset) 154 | 155 | aws_count, gcp_count = 0, 0 156 | for key, asset in stac_item.assets.items(): 157 | if asset.cloud_platform == CloudPlatform.AWS: 158 | print(asset.object_path) 159 | aws_count += 1 160 | else: 161 | # print(asset.object_path) 162 | gcp_count += 1 163 | self.assertEquals(25, aws_count) 164 | self.assertEquals(12, gcp_count) 165 | 166 | def test_basename(self): 167 | asset_name = r'.*LO81120152015061LGN00_B2\.TIF$' 168 | stac_id = "LO81120152015061LGN00" 169 | stac_request = StacRequest(id=stac_id) 170 | stac_item = client.search_one(stac_request) 171 | asset = utils.get_asset(stac_item, asset_regex={'object_path': asset_name}, cloud_platform=CloudPlatform.AWS) 172 | self.assertIsNotNone(asset) 173 | 174 | def test_thumbnail(self): 175 | stac_id = 'LO81120152015061LGN00' 176 | stac_request = StacRequest(id=stac_id) 177 | stac_item = client.search_one(stac_request) 178 | asset = utils.get_asset(stac_item, 179 | asset_type=AssetType.THUMBNAIL, 180 | cloud_platform=CloudPlatform.AWS, 181 | asset_regex={"asset_key": ".*_2$"}) 182 | self.assertIsNotNone(asset) 183 | 184 | def test_aws(self): 185 | stac_id = "LC80270392015025LGN00" 186 | stac_request = StacRequest(id=stac_id) 187 | stac_item = client.search_one(stac_request) 188 | self.assertIsNotNone(stac_item) 189 | count = 0 190 | for key, asset in stac_item.assets.items(): 191 | if asset.cloud_platform == CloudPlatform.AWS: 192 | print(asset.object_path) 193 | count += 1 194 | self.assertEquals(29, count) 195 | 196 | def test_L1TP(self): 197 | stac_id = "LT51560171989121KIS00" 198 | stac_request = StacRequest(id=stac_id) 199 | stac_item = client.search_one(stac_request) 200 | self.assertIsNotNone(stac_item) 201 | aws_count, gcp_count = 0, 0 202 | for key, asset in stac_item.assets.items(): 203 | if asset.cloud_platform == CloudPlatform.AWS: 204 | aws_count += 1 205 | else: 206 | print(asset.object_path) 207 | gcp_count += 1 208 | self.assertEquals(0, aws_count) 209 | self.assertEquals(20, gcp_count) 210 | 211 | def test_L1G(self): 212 | stac_id = "LT51560202010035IKR02" 213 | stac_request = StacRequest(id=stac_id) 214 | stac_item = client.search_one(stac_request) 215 | self.assertIsNotNone(stac_item) 216 | aws_count, gcp_count = 0, 0 217 | for key, asset in stac_item.assets.items(): 218 | if asset.cloud_platform == CloudPlatform.AWS: 219 | aws_count += 1 220 | else: 221 | print(asset.object_path) 222 | gcp_count += 1 223 | self.assertEquals(0, aws_count) 224 | self.assertEquals(20, gcp_count) 225 | 226 | def test_L1t(self): 227 | stac_id = "LT50590132011238PAC00" 228 | stac_request = StacRequest(id=stac_id) 229 | stac_item = client.search_one(stac_request) 230 | self.assertIsNotNone(stac_item) 231 | aws_count, gcp_count = 0, 0 232 | for key, asset in stac_item.assets.items(): 233 | if asset.cloud_platform == CloudPlatform.AWS: 234 | aws_count += 1 235 | else: 236 | print(asset.object_path) 237 | gcp_count += 1 238 | self.assertEquals(0, aws_count) 239 | self.assertEquals(20, gcp_count) 240 | 241 | def test_L1GT(self): 242 | stac_id = "LE70080622016239EDC00" 243 | stac_request = StacRequest(id=stac_id) 244 | stac_item = client.search_one(stac_request) 245 | self.assertIsNotNone(stac_item) 246 | aws_count, gcp_count = 0, 0 247 | for key, asset in stac_item.assets.items(): 248 | if asset.cloud_platform == CloudPlatform.AWS: 249 | aws_count += 1 250 | else: 251 | print(asset.object_path) 252 | gcp_count += 1 253 | self.assertEquals(0, aws_count) 254 | self.assertEquals(22, gcp_count) 255 | 256 | def test_L8_processed_id(self): 257 | stac_id = "LC81262052018263LGN00" 258 | stac_request = StacRequest(id=stac_id) 259 | stac_item = client.search_one(stac_request) 260 | self.assertIsNotNone(stac_item) 261 | aws_count, gcp_count = 0, 0 262 | for key, asset in stac_item.assets.items(): 263 | if asset.cloud_platform == CloudPlatform.AWS: 264 | aws_count += 1 265 | else: 266 | print(asset.object_path) 267 | gcp_count += 1 268 | self.assertEquals(42, aws_count) 269 | self.assertEquals(14, gcp_count) 270 | 271 | def test_L8_processed_id_2(self): 272 | stac_id = "LC81262052018263LGN00" 273 | stac_request = StacRequest(id=stac_id) 274 | stac_item = client.search_one(stac_request) 275 | self.assertIsNotNone(stac_item) 276 | aws_count, gcp_count = 0, 0 277 | for key, asset in stac_item.assets.items(): 278 | if asset.cloud_platform == CloudPlatform.AWS: 279 | aws_count += 1 280 | print(asset.object_path) 281 | else: 282 | gcp_count += 1 283 | self.assertEquals(42, aws_count) 284 | self.assertEquals(14, gcp_count) 285 | 286 | def test_count(self): 287 | stac_id = "LC81262052018263LGN00" 288 | stac_request = StacRequest(id=stac_id) 289 | number = client.count(stac_request) 290 | self.assertEquals(1, number) 291 | 292 | def test_2000(self): 293 | start = datetime(1999, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 294 | end = datetime(1999, 4, 6, 12, 52, 59, tzinfo=timezone.utc) 295 | observed_range = utils.pb_timestampfield(rel_type=FilterRelationship.BETWEEN, start=start, end=end) 296 | 297 | stac_request = StacRequest(observed=observed_range, limit=20, landsat=LandsatRequest()) 298 | for stac_item in client.search(stac_request): 299 | self.assertEqual(Mission.LANDSAT, stac_item.mission_enum) 300 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 301 | self.assertGreaterEqual(utils.pb_timestamp(end).seconds, stac_item.datetime.seconds) 302 | self.assertLessEqual(utils.pb_timestamp(start).seconds, stac_item.datetime.seconds) 303 | 304 | self.assertEquals(2728, client.count(stac_request)) 305 | 306 | def test_count_more(self): 307 | start = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 308 | end = datetime(2014, 4, 1, 12, 52, 59, tzinfo=timezone.utc) 309 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 310 | end=utils.pb_timestamp(end), 311 | rel_type=FilterRelationship.BETWEEN) 312 | 313 | stac_request = StacRequest(observed=observed_range, limit=40, landsat=LandsatRequest()) 314 | for stac_item in client.search(stac_request): 315 | self.assertEquals(Mission.LANDSAT, stac_item.mission_enum) 316 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 317 | self.assertGreaterEqual(utils.pb_timestamp(end).seconds, stac_item.datetime.seconds) 318 | self.assertLessEqual(utils.pb_timestamp(start).seconds, stac_item.datetime.seconds) 319 | 320 | self.assertEquals(12, client.count(stac_request)) 321 | 322 | 323 | class TestDatetimeQueries(unittest.TestCase): 324 | def test_date_LT_OR_EQ(self): 325 | bd = date(2014, 11, 3) 326 | observed_range = utils.pb_timestampfield(rel_type=FilterRelationship.LTE, value=bd) 327 | stac_request = StacRequest(observed=observed_range, mission_enum=enum.Mission.NAIP) 328 | stac_item = client.search_one(stac_request) 329 | self.assertIsNotNone(stac_item) 330 | self.assertLessEqual(utils.pb_timestamp(bd).seconds, stac_item.datetime.seconds) 331 | 332 | def test_date_GT_OR_EQ(self): 333 | bd = date(2015, 11, 3) 334 | observed_range = TimestampFilter(value=utils.pb_timestamp(bd, tzinfo=timezone.utc), 335 | rel_type=FilterRelationship.GTE) 336 | stac_request = StacRequest(observed=observed_range) 337 | stac_item = client.search_one(stac_request) 338 | self.assertIsNotNone(stac_item) 339 | self.assertLessEqual(utils.pb_timestamp(bd, tzinfo=timezone.utc).seconds, stac_item.observed.seconds) 340 | 341 | def test_date_GT_OR_EQ_datetime(self): 342 | bd = date(2015, 11, 3) 343 | observed_range = TimestampFilter(value=utils.pb_timestamp(bd, tzinfo=timezone.utc), 344 | rel_type=FilterRelationship.GTE) 345 | stac_request = StacRequest(observed=observed_range) 346 | stac_item = client.search_one(stac_request) 347 | self.assertIsNotNone(stac_item) 348 | self.assertLessEqual(utils.pb_timestamp(bd, tzinfo=timezone.utc).seconds, stac_item.datetime.seconds) 349 | 350 | def test_observed_GT(self): 351 | bdt = datetime(2015, 11, 3, 1, 1, 1, tzinfo=timezone.utc) 352 | observed_range = TimestampFilter(value=utils.pb_timestamp(bdt), 353 | rel_type=FilterRelationship.GT) 354 | stac_request = StacRequest(observed=observed_range) 355 | stac_item = client.search_one(stac_request) 356 | self.assertIsNotNone(stac_item) 357 | self.assertLessEqual(utils.pb_timestamp(bdt).seconds, stac_item.observed.seconds) 358 | 359 | def test_datetime_GT(self): 360 | bdt = datetime(2015, 11, 3, 1, 1, 1, tzinfo=timezone.utc) 361 | observed_range = TimestampFilter(value=utils.pb_timestamp(bdt), 362 | rel_type=FilterRelationship.GT) 363 | stac_request = StacRequest(observed=observed_range) 364 | stac_item = client.search_one(stac_request) 365 | self.assertIsNotNone(stac_item) 366 | self.assertLessEqual(utils.pb_timestamp(bdt).seconds, stac_item.datetime.seconds) 367 | 368 | def test_datetime_range(self): 369 | start = datetime(2013, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 370 | end = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 371 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 372 | end=utils.pb_timestamp(end), 373 | rel_type=FilterRelationship.BETWEEN) 374 | stac_request = StacRequest(observed=observed_range, limit=5) 375 | for stac_item in client.search(stac_request): 376 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 377 | self.assertGreaterEqual(utils.pb_timestamp(end).seconds, stac_item.datetime.seconds) 378 | self.assertLessEqual(utils.pb_timestamp(start).seconds, stac_item.datetime.seconds) 379 | 380 | def test_datetime_not_range(self): 381 | start = datetime(2013, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 382 | end = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 383 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 384 | end=utils.pb_timestamp(end), 385 | rel_type=FilterRelationship.NOT_BETWEEN) 386 | stac_request = StacRequest(observed=observed_range, limit=5) 387 | for stac_item in client.search(stac_request): 388 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 389 | self.assertTrue(utils.pb_timestamp(end).seconds < stac_item.datetime.seconds or 390 | utils.pb_timestamp(start).seconds > stac_item.datetime.seconds) 391 | 392 | def test_datetime_not_range_asc(self): 393 | start = datetime(2013, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 394 | end = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 395 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 396 | end=utils.pb_timestamp(end), 397 | rel_type=FilterRelationship.NOT_BETWEEN, 398 | sort_direction=enum.SortDirection.ASC) 399 | stac_request = StacRequest(observed=observed_range, limit=5) 400 | count = 0 401 | for stac_item in client.search(stac_request): 402 | count += 1 403 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 404 | self.assertTrue(utils.pb_timestamp(end).seconds > stac_item.datetime.seconds or 405 | utils.pb_timestamp(start).seconds < stac_item.datetime.seconds) 406 | self.assertEqual(count, 5) 407 | 408 | def test_datetime_not_range_desc(self): 409 | start = datetime(2013, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 410 | end = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 411 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 412 | end=utils.pb_timestamp(end), 413 | rel_type=FilterRelationship.NOT_BETWEEN, 414 | sort_direction=enum.SortDirection.DESC) 415 | stac_request = StacRequest(observed=observed_range, limit=5) 416 | count = 0 417 | for stac_item in client.search(stac_request): 418 | count += 1 419 | print(datetime.fromtimestamp(stac_item.datetime.seconds, tz=timezone.utc)) 420 | self.assertTrue(utils.pb_timestamp(end).seconds < stac_item.datetime.seconds) 421 | self.assertEqual(count, 5) 422 | 423 | def test_observed_not_range_desc(self): 424 | start = datetime(2013, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 425 | end = datetime(2014, 4, 1, 12, 45, 59, tzinfo=timezone.utc) 426 | observed_range = TimestampFilter(start=utils.pb_timestamp(start), 427 | end=utils.pb_timestamp(end), 428 | rel_type=FilterRelationship.NOT_BETWEEN, 429 | sort_direction=enum.SortDirection.DESC) 430 | stac_request = StacRequest(observed=observed_range, limit=5) 431 | count = 0 432 | for stac_item in client.search(stac_request): 433 | count += 1 434 | print(datetime.fromtimestamp(stac_item.observed.seconds, tz=timezone.utc)) 435 | self.assertTrue(utils.pb_timestamp(end).seconds < stac_item.observed.seconds) 436 | self.assertEqual(count, 5) 437 | 438 | def test_date_utc_eq(self): 439 | value = date(2019, 8, 6) 440 | texas_utc_offset = timezone(timedelta(hours=-6)) 441 | time_filter = utils.pb_timestampfield(rel_type=enum.FilterRelationship.EQ, 442 | value=value, 443 | tzinfo=texas_utc_offset) 444 | 445 | stac_request = StacRequest(datetime=time_filter, limit=2) 446 | 447 | # get a client interface to the gRPC channel 448 | for stac_item in client.search(stac_request): 449 | print("STAC item date, {0}, is before {1}: {2}".format( 450 | datetime.fromtimestamp(stac_item.observed.seconds, tz=timezone.utc).isoformat(), 451 | datetime.fromtimestamp(time_filter.end.seconds, tz=texas_utc_offset).isoformat(), 452 | stac_item.observed.seconds < time_filter.end.seconds)) 453 | 454 | start = date(2019, 8, 6) 455 | time_filter = utils.pb_timestampfield(rel_type=FilterRelationship.EQ, 456 | value=start, 457 | tzinfo=timezone(timedelta(hours=-6))) 458 | stac_request = StacRequest(datetime=time_filter, limit=2) 459 | count = 0 460 | for _ in client.search(stac_request): 461 | count += 1 462 | 463 | self.assertEqual(2, count) 464 | 465 | 466 | class TestHelpers(unittest.TestCase): 467 | def test_has_asset(self): 468 | stac_id = "LO81120152015061LGN00" 469 | stac_request = StacRequest(id=stac_id) 470 | stac_item = client.search_one(stac_request=stac_request) 471 | for key in stac_item.assets: 472 | asset = stac_item.assets[key] 473 | self.assertTrue(utils.has_asset(stac_item, asset)) 474 | garbage = Asset(href="pie") 475 | self.assertFalse(utils.has_asset(stac_item, garbage)) 476 | garbage.asset_type = asset.asset_type 477 | self.assertFalse(utils.has_asset(stac_item, garbage)) 478 | garbage.href = asset.href 479 | garbage.bucket = asset.bucket 480 | garbage.type = asset.type 481 | garbage.eo_bands = asset.eo_bands 482 | garbage.cloud_platform = asset.cloud_platform 483 | garbage.bucket_manager = asset.bucket_manager 484 | garbage.bucket_region = asset.bucket_region 485 | garbage.object_path = asset.object_path 486 | self.assertTrue(utils.has_asset(stac_item, garbage)) 487 | 488 | def test_download_gcp(self): 489 | stac_id = "LO81120152015061LGN00" 490 | stac_item = client.search_one(stac_request=StacRequest(id=stac_id)) 491 | asset = utils.get_asset(stac_item, 492 | asset_type=AssetType.TXT, 493 | cloud_platform=CloudPlatform.GCP, 494 | asset_regex={'href': r'.*LO81120152015061LGN00_MTL\.txt$'}) 495 | self.assertIsNotNone(asset) 496 | with tempfile.TemporaryDirectory() as d: 497 | print(d) 498 | file_path = utils.download_asset(asset=asset, from_bucket=True, save_directory=d) 499 | with open(file_path) as f: 500 | data1 = f.read() 501 | 502 | file_path = utils.download_asset(asset=asset, from_bucket=True, save_filename=file_path) 503 | with open(file_path) as f: 504 | data2 = f.read() 505 | 506 | self.assertMultiLineEqual(data1, data2) 507 | 508 | with tempfile.NamedTemporaryFile('w+b', delete=False) as f_obj: 509 | utils.download_asset(asset=asset, from_bucket=True, file_obj=f_obj) 510 | data3 = f_obj.read().decode('ascii') 511 | self.assertMultiLineEqual(data1, data3) 512 | 513 | def test_download_aws(self): 514 | stac_id = "LC80270392015025LGN00" 515 | stac_item = client.search_one(stac_request=StacRequest(id=stac_id)) 516 | asset = utils.get_asset(stac_item, 517 | asset_type=AssetType.TXT, 518 | cloud_platform=CloudPlatform.AWS) 519 | self.assertIsNotNone(asset) 520 | with tempfile.TemporaryDirectory() as d: 521 | print(d) 522 | file_path = utils.download_asset(asset=asset, from_bucket=True, save_directory=d) 523 | with open(file_path) as f: 524 | data1 = f.read() 525 | 526 | file_path = utils.download_asset(asset=asset, from_bucket=True, save_filename=file_path) 527 | with open(file_path) as f: 528 | data2 = f.read() 529 | 530 | self.assertMultiLineEqual(data1, data2) 531 | 532 | with tempfile.NamedTemporaryFile('w+b', delete=False) as f_obj: 533 | utils.download_asset(asset=asset, from_bucket=True, file_obj=f_obj) 534 | data3 = f_obj.read().decode('ascii') 535 | self.assertMultiLineEqual(data1, data3) 536 | 537 | def test_download_geotiff(self): 538 | stac_request = StacRequest(id='20190822T183518Z_746_POM1_ST2_P') 539 | 540 | stac_item = client.search_one(stac_request) 541 | 542 | # get the Geotiff asset from the assets map 543 | asset = utils.get_asset(stac_item, asset_type=enum.AssetType.GEOTIFF) 544 | 545 | with tempfile.TemporaryDirectory() as d: 546 | file_path = utils.download_asset(asset=asset, save_directory=d) 547 | print("{0} has {1} bytes".format(os.path.basename(file_path), os.path.getsize(file_path))) 548 | 549 | def test_download_href(self): 550 | stac_id = "20190829T173549Z_1799_POM1_ST2_P" 551 | stac_item = client.search_one(stac_request=StacRequest(id=stac_id)) 552 | asset = utils.get_asset(stac_item, asset_type=AssetType.THUMBNAIL) 553 | 554 | self.assertIsNotNone(asset) 555 | 556 | with tempfile.TemporaryDirectory() as d: 557 | file_path = utils.download_asset(asset=asset, save_directory=d) 558 | with open(file_path, 'rb') as f: 559 | data1 = f.read() 560 | 561 | file_path = utils.download_asset(asset=asset, save_filename=file_path) 562 | with open(file_path, 'rb') as f: 563 | data2 = f.read() 564 | 565 | self.assertEqual(data1, data2) 566 | 567 | with tempfile.NamedTemporaryFile('w+b', delete=False) as file_obj: 568 | utils.download_asset(asset=asset, file_obj=file_obj) 569 | data3 = file_obj.read() 570 | self.assertEqual(data1, data3) 571 | 572 | b = io.BytesIO() 573 | utils.download_asset(asset=asset, file_obj=b) 574 | data4 = b.read() 575 | self.assertEqual(data2, data4) 576 | 577 | def test_download_aws_href(self): 578 | stac_id = 'LC80270392015025LGN00' 579 | stac_item = client.search_one(stac_request=StacRequest(id=stac_id)) 580 | asset = utils.get_asset(stac_item, 581 | asset_type=AssetType.THUMBNAIL, 582 | asset_regex={"asset_key": ".*_2$"}, 583 | cloud_platform=enum.CloudPlatform.AWS) 584 | self.assertIsNotNone(asset) 585 | 586 | with tempfile.TemporaryDirectory() as d: 587 | file_path = utils.download_asset(asset=asset, save_directory=d) 588 | with open(file_path, 'rb') as f: 589 | data1 = f.read() 590 | 591 | file_path = utils.download_asset(asset=asset, save_filename=file_path) 592 | with open(file_path, 'rb') as f: 593 | data2 = f.read() 594 | 595 | self.assertEqual(data1, data2) 596 | 597 | 598 | class TestPerf(unittest.TestCase): 599 | def test_query_limits(self): 600 | # Same geometry as above, but a wkt geometry instead of a geojson 601 | travis_wkt = "POLYGON((-97.9736 30.6251, -97.9188 30.6032, -97.9243 30.5703, -97.8695 30.5484, -97.8476 " \ 602 | "30.4717, -97.7764 30.4279, -97.5793 30.4991, -97.3711 30.4170, -97.4916 30.2089, " \ 603 | "-97.6505 30.0719, -97.6669 30.0665, -97.7107 30.0226, -98.1708 30.3567, -98.1270 30.4279, " \ 604 | "-98.0503 30.6251)) " 605 | geometry_data = GeometryData(wkt=travis_wkt, 606 | proj=ProjectionData(epsg=4326)) 607 | 608 | limit = 200 609 | offset = 0 610 | total = 0 611 | while total < 1000: 612 | # make our request 613 | stac_request = StacRequest(intersects=geometry_data, limit=limit, offset=offset) 614 | # prepare request for next 615 | offset += limit 616 | for stac_item in client.search(stac_request): 617 | total += 1 618 | # do cool things with data here 619 | if total % limit == 0: 620 | print("stac item id: {0} at {1} index in request".format(stac_item.id, total)) 621 | self.assertEqual(total, 1000) 622 | 623 | 624 | class TestWrap(unittest.TestCase): 625 | def test_landsat(self): 626 | stac_id = 'LO81120152015061LGN00' 627 | request_wrapped = StacRequestWrap(id=stac_id) 628 | for stac_wrapped in client_ex.search_ex(stac_request_wrapped=request_wrapped): 629 | self.assertEqual(stac_wrapped.mission, enum.Mission.LANDSAT) 630 | self.assertEqual(stac_wrapped.mission.name, enum.Mission.LANDSAT.name) 631 | self.assertEqual(stac_wrapped.stac_item.mission, enum.Mission.LANDSAT.name) 632 | self.assertEqual(stac_wrapped.platform, enum.Platform.LANDSAT_8) 633 | self.assertEqual(stac_wrapped.platform.name, enum.Platform.LANDSAT_8.name) 634 | self.assertEqual(stac_wrapped.stac_item.platform, enum.Platform.LANDSAT_8.name) 635 | self.assertEqual(stac_wrapped.instrument, enum.Instrument.OLI) 636 | self.assertEqual(stac_wrapped.instrument.name, enum.Instrument.OLI.name) 637 | self.assertEqual(stac_wrapped.stac_item.instrument, enum.Instrument.OLI.name) 638 | self.assertLessEqual(stac_wrapped.gsd, 60) 639 | self.assertEqual(stac_id, stac_wrapped.stac_item.id) 640 | 641 | asset_wrapped_keys = [] 642 | for asset_wrap in stac_wrapped.get_assets(): 643 | asset_wrapped_keys.append(asset_wrap.asset_key) 644 | for asset_key in stac_wrapped.stac_item.assets: 645 | self.assertTrue(asset_key in asset_wrapped_keys) 646 | 647 | self.assertEqual(1, client_ex.count_ex(request_wrapped)) 648 | 649 | def test_constructor(self): 650 | asset_wrap = AssetWrap(bucket='bucky', 651 | object_path="jebidiah/springfield.tif", 652 | asset_type=enum.AssetType.GEOTIFF, 653 | href='https://bubbles.monkey.io/jebidiah/springfield.tif', 654 | cloud_platform=enum.CloudPlatform.AZURE, 655 | bucket_manager='Smithers', 656 | bucket_region='azores') 657 | 658 | asset_clone = AssetWrap(bucket=asset_wrap.bucket, 659 | object_path=str(pathlib.Path(asset_wrap.object_path).with_suffix('.jpg')), 660 | asset_type=enum.AssetType.THUMBNAIL, 661 | href=str(pathlib.Path(asset_wrap.href).with_suffix('.jpg')), 662 | cloud_platform=asset_wrap.cloud_platform, 663 | bucket_manager=asset_wrap.bucket_manager, 664 | bucket_region=asset_wrap.bucket_region) 665 | 666 | self.assertEqual(asset_wrap.bucket_region, asset_clone.bucket_region) 667 | self.assertEqual(asset_clone.ext, '.jpg') 668 | 669 | def test_deep_copy(self): 670 | asset_wrap = AssetWrap() 671 | 672 | asset_wrap.cloud_platform = enum.CloudPlatform.GCP 673 | pickled = pickle.dumps(asset_wrap) 674 | asset_wrap_deep = pickle.loads(pickled) 675 | self.assertEqual(asset_wrap.cloud_platform, asset_wrap_deep.cloud_platform) 676 | self.assertEqual(asset_wrap, asset_wrap_deep) 677 | asset_wrap_shallow = asset_wrap 678 | self.assertEqual(asset_wrap.cloud_platform, asset_wrap_shallow.cloud_platform) 679 | self.assertEqual(asset_wrap, asset_wrap_shallow) 680 | asset_wrap.cloud_platform = enum.CloudPlatform.AWS 681 | self.assertEqual(asset_wrap.cloud_platform, asset_wrap_shallow.cloud_platform) 682 | self.assertNotEqual(asset_wrap.cloud_platform, asset_wrap_deep.cloud_platform) 683 | 684 | stac_item = StacItemWrap() 685 | print(stac_item.stac_item.ListFields()) 686 | stac_item.id = "pancakes" 687 | pickled = pickle.dumps(stac_item) 688 | stac_item_deep = pickle.loads(pickled) 689 | self.assertEqual(stac_item.id, stac_item_deep.id) 690 | self.assertEqual("pancakes", stac_item.id) 691 | self.assertEqual(stac_item, stac_item_deep) 692 | stac_item_shallow = stac_item 693 | self.assertEqual(stac_item.id, stac_item_shallow.id) 694 | stac_item_deep.id = 'waffles' 695 | self.assertNotEqual(stac_item_deep.id, stac_item.id) 696 | self.assertEqual("waffles", stac_item_deep.id) 697 | 698 | def test_platform_landsat(self): 699 | request_wrap = StacRequestWrap() 700 | 701 | request_wrap.mission = enum.Mission.LANDSAT 702 | request_wrap.platform = enum.Platform.LANDSAT_8 703 | request_wrap.set_cloud_cover(rel_type=enum.FilterRelationship.GTE, value=50) 704 | 705 | item_wrapped = client_ex.search_one_ex(request_wrap) 706 | self.assertEqual(item_wrapped.platform, request_wrap.platform) 707 | self.assertEqual(item_wrapped.mission, request_wrap.mission) 708 | 709 | def test_code_example_ex(self): 710 | # create our request. this interface allows us to set fields in our protobuf object 711 | request = StacRequestWrap() 712 | 713 | # our area of interest will be the coordinates of the UT Stadium in Austin Texas 714 | # the order of coordinates here is longitude then latitude (x, y). The results of our query 715 | # will be returned only if they intersect this point geometry we've defined (other geometry 716 | # types besides points are supported) 717 | # This string format, POINT(float, float) is the well-known-text geometry format: 718 | # https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry 719 | # the epsg # defines the WGS-84 elispsoid (`epsg=4326`) spatial reference 720 | # (the latitude longitude spatial reference most commonly used) 721 | # the epl.geometry Polygon class is an extension of shapely's Polygon class that supports 722 | # the protobuf definitions we use with STAC 723 | request.intersects = Polygon.import_wkt(wkt="POINT(-97.7323317 30.2830764)", epsg=4326) 724 | 725 | # `set_observed` allows for making sql-like queries for information 726 | # LTE is an enum that means less than or equal to the value in the query field 727 | # Query data from August 25, 2019 728 | request.set_observed(rel_type=enum.FilterRelationship.LTE, value=date(2019, 8, 25)) 729 | 730 | request.instrument = enum.Instrument.OLI 731 | # search_one_ex method requests only one item be returned that meets the query filters in the StacRequest 732 | # the item returned is a wrapper of the protobuf message; StacItemWrap. search_one_ex, will only return the most 733 | # recently observed results that matches the time filter and spatial filter 734 | stac_item = client_ex.search_one_ex(request) 735 | 736 | # get the thumbnail asset from the assets map. The other option would be a Geotiff, 737 | # with asset key 'GEOTIFF_RGB' 738 | asset = stac_item.get_asset(asset_type=enum.AssetType.GEOTIFF, 739 | eo_bands=enum.Band.SWIR_1, 740 | cloud_platform=enum.CloudPlatform.GCP) 741 | self.assertIsNotNone(asset) 742 | 743 | self.assertEqual(asset.asset_key, "GEOTIFF_GCP_SWIR_1") 744 | asset.asset_key_suffix = "PANCAKES" 745 | self.assertEqual(asset.asset_key, "GEOTIFF_GCP_SWIR_1") 746 | 747 | self.assertTrue(asset.exists()) 748 | 749 | def test_3744_bounds(self): 750 | # request wrapper 751 | request = StacRequestWrap() 752 | request.mission_enum = enum.Mission.SWIFT 753 | 754 | # HARN UTM 755 | neighborhood_box = (621636.1875228449, 3349964.520449501, 623157.4212553708, 3351095.8075163467) 756 | # setting the bounds tests for intersection (not contains) 757 | request.set_bounds(neighborhood_box, epsg=3744) 758 | request.limit = 3 759 | found = 0 760 | # Search for data that intersects the bounding box 761 | for stac_item in client_ex.search_ex(request): 762 | found += 1 763 | self.assertEqual(3, found) 764 | 765 | def test_set_intersects_without_proj(self): 766 | neighborhood_box = (-97.7352547645, 30.27526474757116, -97.7195692, 30.28532) 767 | envelope_data = EnvelopeData(xmin=neighborhood_box[0], 768 | ymin=neighborhood_box[1], 769 | xmax=neighborhood_box[2], 770 | ymax=neighborhood_box[3], 771 | proj=ProjectionData(epsg=0)) 772 | r = StacRequestWrap() 773 | b_hit = False 774 | try: 775 | r.bbox = envelope_data 776 | except BaseException: 777 | b_hit = True 778 | self.assertTrue(b_hit) 779 | 780 | b_hit = False 781 | try: 782 | r.set_bounds(bounds=neighborhood_box, epsg=0) 783 | except BaseException: 784 | b_hit = True 785 | self.assertTrue(b_hit) 786 | 787 | b_hit = False 788 | try: 789 | r.set_bounds(bounds=neighborhood_box, epsg=4326) 790 | except BaseException: 791 | b_hit = True 792 | 793 | self.assertFalse(b_hit) 794 | 795 | def test_projection_error(self): 796 | # request wrapper 797 | request = StacRequestWrap() 798 | 799 | # define our area of interest bounds using the xmin, ymin, xmax, ymax coordinates of an area on 800 | # the WGS-84 ellipsoid 801 | neighborhood_box = (-97.7352547645, 30.27526474757116, -97.7195692, 30.28532) 802 | # setting the bounds tests for intersection (not contains) 803 | request.set_bounds(neighborhood_box, epsg=4326) 804 | 805 | self.assertEquals(request.bbox.xmin, neighborhood_box[0]) 806 | self.assertEquals(request.intersects.proj.epsg, 4326) 807 | 808 | def test_date_vs_datetime(self): 809 | r = StacRequestWrap() 810 | 811 | d = date(2010, 1, 1) 812 | d_min = datetime.combine(d, time=datetime.min.time(), tzinfo=timezone.utc) 813 | r.set_observed(rel_type=enum.FilterRelationship.GTE, value=d) 814 | time_stamp = r.stac_request.observed.value.seconds + r.stac_request.observed.value.nanos / 1000000000.0 815 | self.assertEquals(datetime.fromtimestamp(time_stamp, tz=timezone.utc), d_min) 816 | 817 | r.set_observed(rel_type=enum.FilterRelationship.LT, value=d) 818 | time_stamp = r.stac_request.observed.value.seconds + r.stac_request.observed.value.nanos / 1000000000.0 819 | self.assertEquals(datetime.fromtimestamp(time_stamp, tz=timezone.utc), d_min) 820 | 821 | d_max = datetime.combine(d, time=datetime.max.time(), tzinfo=timezone.utc) 822 | r.set_observed(rel_type=enum.FilterRelationship.GT, value=d) 823 | time_stamp = r.stac_request.observed.value.seconds + r.stac_request.observed.value.nanos / 1000000000.0 824 | self.assertEquals(datetime.fromtimestamp(time_stamp, tz=timezone.utc), d_max) 825 | 826 | r.set_observed(rel_type=enum.FilterRelationship.LTE, value=d) 827 | time_stamp = r.stac_request.observed.value.seconds + r.stac_request.observed.value.nanos / 1000000000.0 828 | self.assertEquals(datetime.fromtimestamp(time_stamp, tz=timezone.utc), d_max) 829 | 830 | d2 = date(2010, 1, 3) 831 | d_max = datetime.combine(d2, time=datetime.max.time(), tzinfo=timezone.utc) 832 | r.set_observed(rel_type=enum.FilterRelationship.BETWEEN, start=d_min, end=d_max) 833 | time_stamp_start = r.stac_request.observed.start.seconds + r.stac_request.observed.start.nanos / 1000000000.0 834 | time_stamp_end = r.stac_request.observed.end.seconds + r.stac_request.observed.end.nanos / 1000000000.0 835 | self.assertEquals(datetime.fromtimestamp(time_stamp_start, tz=timezone.utc), d_min) 836 | self.assertEquals(datetime.fromtimestamp(time_stamp_end, tz=timezone.utc), d_max) 837 | 838 | r.set_observed(rel_type=enum.FilterRelationship.NOT_BETWEEN, start=d_min, end=d_max) 839 | time_stamp_start = r.stac_request.observed.start.seconds + r.stac_request.observed.start.nanos / 1000000000.0 840 | time_stamp_end = r.stac_request.observed.end.seconds + r.stac_request.observed.end.nanos / 1000000000.0 841 | self.assertEquals(datetime.fromtimestamp(time_stamp_start, tz=timezone.utc), d_min) 842 | self.assertEquals(datetime.fromtimestamp(time_stamp_end, tz=timezone.utc), d_max) 843 | 844 | def test_update_asset(self): 845 | r = StacRequestWrap() 846 | r.mission = enum.Mission.LANDSAT 847 | r.platform = enum.Platform.LANDSAT_8 848 | r.set_observed(rel_type=enum.FilterRelationship.GTE, value=date(2016, 1, 1)) 849 | 850 | item = StacItemWrap(client_ex.search_one_ex(r).stac_item) 851 | 852 | asset_key = 'THUMBNAIL_AWS' 853 | asset_wrap = item.get_asset(asset_key=asset_key) 854 | self.assertEqual(asset_wrap.cloud_platform, enum.CloudPlatform.AWS) 855 | self.assertEqual(asset_wrap.cloud_platform, item.stac_item.assets[asset_key].cloud_platform) 856 | 857 | self.assertEqual(enum.CloudPlatform.AWS, item.stac_item.assets[asset_key].cloud_platform) 858 | asset_wrap.cloud_platform = enum.CloudPlatform.GCP 859 | self.assertEqual(asset_wrap.cloud_platform.value, item.stac_item.assets[asset_key].cloud_platform) 860 | self.assertEqual(asset_wrap.cloud_platform, enum.CloudPlatform.GCP) 861 | self.assertEqual(enum.CloudPlatform.GCP.value, item.stac_item.assets[asset_key].cloud_platform) 862 | 863 | def test_feature_collection(self): 864 | r = StacRequestWrap() 865 | r.mission = enum.Mission.NAIP 866 | r.limit = 3 867 | travis_wkt = "POLYGON((-97.9736 30.6251, -97.9188 30.6032, -97.9243 30.5703, -97.8695 30.5484, -97.8476 " \ 868 | "30.4717, -97.7764 30.4279, -97.5793 30.4991, -97.3711 30.4170, -97.4916 30.2089, " \ 869 | "-97.6505 30.0719, -97.6669 30.0665, -97.7107 30.0226, -98.1708 30.3567, -98.1270 30.4279, " \ 870 | "-98.0503 30.6251, -97.9736 30.6251)) " 871 | r.intersects = Polygon.import_wkt(wkt=travis_wkt, epsg=4326) 872 | feature_collection = client_ex.feature_collection_ex(r) 873 | items = list(client_ex.search_ex(r)) 874 | r.offset = 3 875 | feature_collection = client_ex.feature_collection_ex(r, feature_collection=feature_collection) 876 | self.assertEqual(len(feature_collection['features']), 6) 877 | items.extend(list(client_ex.search_ex(r))) 878 | r.limit = 6 879 | r.offset = 0 880 | 881 | id_list = [item.id for item in items] 882 | features = feature_collection['features'] 883 | for feature in features: 884 | self.assertTrue(feature['id'] in id_list) 885 | self.assertEquals(6, len(items)) 886 | union1 = Polygon.s_cascaded_union([item.geometry for item in items]) 887 | union2 = Polygon.s_cascaded_union([epl_geometry.shape(feature['geometry'], epsg=4326) for feature in features]) 888 | diff = union1.s_difference(union2) 889 | self.assertTrue(union1.s_equals(union2), diff) 890 | --------------------------------------------------------------------------------