egms-client 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- egms_client-0.1.0/LICENSE +202 -0
- egms_client-0.1.0/PKG-INFO +141 -0
- egms_client-0.1.0/README.md +111 -0
- egms_client-0.1.0/pyproject.toml +118 -0
- egms_client-0.1.0/pyproject.toml.orig +86 -0
- egms_client-0.1.0/src/egms_client/__init__.py +62 -0
- egms_client-0.1.0/src/egms_client/archive.py +187 -0
- egms_client-0.1.0/src/egms_client/auth.py +116 -0
- egms_client-0.1.0/src/egms_client/client.py +119 -0
- egms_client-0.1.0/src/egms_client/errors.py +6 -0
- egms_client-0.1.0/src/egms_client/mosaic.py +83 -0
- egms_client-0.1.0/src/egms_client/py.typed +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
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.
|
|
202
|
+
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: egms-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the EGMS archive: CLMS service-key auth, tile search and download, Ortho L3 mosaics
|
|
5
|
+
Keywords: egms,copernicus,insar,ground motion,sentinel-1,subsidence,landslide,clms
|
|
6
|
+
Author: Giuseppe Zileni
|
|
7
|
+
Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Dist: cryptography>=43
|
|
20
|
+
Requires-Dist: httpx>=0.27
|
|
21
|
+
Requires-Dist: numpy>=2.0 ; extra == 'raster'
|
|
22
|
+
Requires-Dist: pyproj>=3.6 ; extra == 'raster'
|
|
23
|
+
Requires-Dist: rasterio>=1.4 ; extra == 'raster'
|
|
24
|
+
Requires-Python: >=3.12
|
|
25
|
+
Project-URL: Homepage, https://github.com/agent-engineering-studio/egms-client
|
|
26
|
+
Project-URL: Issues, https://github.com/agent-engineering-studio/egms-client/issues
|
|
27
|
+
Project-URL: Changelog, https://github.com/agent-engineering-studio/egms-client/blob/main/CHANGELOG.md
|
|
28
|
+
Provides-Extra: raster
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# egms-client
|
|
32
|
+
|
|
33
|
+
Async Python client for the archive of [EGMS](https://egms.land.copernicus.eu/),
|
|
34
|
+
the European Ground Motion Service (Copernicus Land Monitoring Service):
|
|
35
|
+
ground velocity from Sentinel-1 InSAR over all of Europe.
|
|
36
|
+
|
|
37
|
+
- **Authentication with a CLMS service key**: no browser, no copied links.
|
|
38
|
+
- **Search and download of Ortho L3 tiles** (100 m, vertical and east-west),
|
|
39
|
+
keeping only the mean-velocity GeoTIFF, cached on disk.
|
|
40
|
+
- **Mosaics** of tiles over any rectangle, with no resampling (extra `raster`).
|
|
41
|
+
|
|
42
|
+
[](https://github.com/agent-engineering-studio/egms-client/actions/workflows/ci.yml)
|
|
43
|
+
[](https://pypi.org/project/egms-client/)
|
|
44
|
+
|
|
45
|
+
## Why a library
|
|
46
|
+
|
|
47
|
+
The EGMS Explorer is built for clicking. The archive behind it has an API,
|
|
48
|
+
but the parts that matter are undocumented, and each one fails quietly:
|
|
49
|
+
|
|
50
|
+
| You try | What happens |
|
|
51
|
+
|---|---|
|
|
52
|
+
| any call without a login | HTTP **200** with `{"status": false, "message": "Please log in…"}` |
|
|
53
|
+
| the `id` in a download link as a credential | it is the id of a **search**, and it expires: HTTP 401 |
|
|
54
|
+
| a tile at sea | `status: false` and `Invalid tile ID`, not an empty search |
|
|
55
|
+
| building the file name yourself | the trailing `_1` is a sub-release: read it from the hit |
|
|
56
|
+
| a malformed token assertion | HTTP **500** `DecodeError`, not 401: retries won't help |
|
|
57
|
+
| comparing CRS by name | four tiles of 2020-2025 say `IGNF:ETRS89LAEA`, not `EPSG:3035` |
|
|
58
|
+
| expecting 2021-2025 after 2020-2024 | the next release was 2020-2025: windows grow |
|
|
59
|
+
|
|
60
|
+
All checked against the live archive on 3 November 2026.
|
|
61
|
+
|
|
62
|
+
## Install
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pip install egms-client # auth, search, download
|
|
66
|
+
pip install "egms-client[raster]" # + mosaics (numpy, rasterio, pyproj)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Credentials
|
|
70
|
+
|
|
71
|
+
Create a service key at [land.copernicus.eu](https://land.copernicus.eu/):
|
|
72
|
+
EU Login, profile, **API Tokens**, *Create new token*. You get a JSON file
|
|
73
|
+
with `client_id`, `user_id`, `private_key` and `token_uri`. It does not
|
|
74
|
+
expire; keep it out of your repository.
|
|
75
|
+
|
|
76
|
+
## Use
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import asyncio
|
|
80
|
+
from pathlib import Path
|
|
81
|
+
|
|
82
|
+
import httpx
|
|
83
|
+
|
|
84
|
+
from egms_client import EgmsArchive, ServiceKey, tiles_for_bounds
|
|
85
|
+
from egms_client.mosaic import mosaic
|
|
86
|
+
|
|
87
|
+
key = ServiceKey.from_json(Path("clms-service-key.json").read_text())
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def main() -> None:
|
|
91
|
+
async with httpx.AsyncClient(timeout=120) as client:
|
|
92
|
+
archive = EgmsArchive(client, key)
|
|
93
|
+
print(await archive.releases()) # ['2020-2024', '2020-2025']
|
|
94
|
+
|
|
95
|
+
# Rectangle in EPSG:3035 metres
|
|
96
|
+
bounds = dict(minx=4_700_000, miny=1_900_000, maxx=4_799_999, maxy=1_999_999)
|
|
97
|
+
tiffs = []
|
|
98
|
+
for tile in tiles_for_bounds(*bounds.values()):
|
|
99
|
+
path = await archive.fetch_tile(tile, "U", "2020-2025", Path("egms"))
|
|
100
|
+
if path is not None: # None: the tile is at sea or not covered
|
|
101
|
+
tiffs.append(path)
|
|
102
|
+
|
|
103
|
+
vertical = mosaic(tiffs, **bounds)
|
|
104
|
+
print(vertical.values.shape, vertical.left, vertical.top) # (1000, 1000) 4700000.0 2000000.0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
asyncio.run(main())
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`fetch_tile` keeps the GeoTIFF (~4 MB) and drops the ~60 MB ZIP. It
|
|
111
|
+
remembers both outcomes in the directory (the file, or an `…absent`
|
|
112
|
+
marker), so running it again for a whole country sends no request. The
|
|
113
|
+
token is renewed five minutes before its hour runs out.
|
|
114
|
+
|
|
115
|
+
### Bring your own HTTP
|
|
116
|
+
|
|
117
|
+
Everything `EgmsArchive` does is also exposed as pure functions, for
|
|
118
|
+
callers with their own HTTP and retry layer: `token_request` /
|
|
119
|
+
`parse_token`, `search_body` / `parse_search` / `latest_hit`,
|
|
120
|
+
`parse_releases`, `download_url` / `check_download` / `extract_tiff`.
|
|
121
|
+
|
|
122
|
+
## Data licence
|
|
123
|
+
|
|
124
|
+
EGMS is © European Union, Copernicus Land Monitoring Service, free and
|
|
125
|
+
open under the [Copernicus data policy](https://land.copernicus.eu/en/data-policy):
|
|
126
|
+
anything you publish from it must credit the source.
|
|
127
|
+
|
|
128
|
+
Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
|
|
129
|
+
which uses the vertical and east-west velocities per 1 km cell as ground
|
|
130
|
+
motion features for landslide risk.
|
|
131
|
+
|
|
132
|
+
## Development
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
uv sync
|
|
136
|
+
make check
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## License
|
|
140
|
+
|
|
141
|
+
Code: [Apache-2.0](./LICENSE).
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# egms-client
|
|
2
|
+
|
|
3
|
+
Async Python client for the archive of [EGMS](https://egms.land.copernicus.eu/),
|
|
4
|
+
the European Ground Motion Service (Copernicus Land Monitoring Service):
|
|
5
|
+
ground velocity from Sentinel-1 InSAR over all of Europe.
|
|
6
|
+
|
|
7
|
+
- **Authentication with a CLMS service key**: no browser, no copied links.
|
|
8
|
+
- **Search and download of Ortho L3 tiles** (100 m, vertical and east-west),
|
|
9
|
+
keeping only the mean-velocity GeoTIFF, cached on disk.
|
|
10
|
+
- **Mosaics** of tiles over any rectangle, with no resampling (extra `raster`).
|
|
11
|
+
|
|
12
|
+
[](https://github.com/agent-engineering-studio/egms-client/actions/workflows/ci.yml)
|
|
13
|
+
[](https://pypi.org/project/egms-client/)
|
|
14
|
+
|
|
15
|
+
## Why a library
|
|
16
|
+
|
|
17
|
+
The EGMS Explorer is built for clicking. The archive behind it has an API,
|
|
18
|
+
but the parts that matter are undocumented, and each one fails quietly:
|
|
19
|
+
|
|
20
|
+
| You try | What happens |
|
|
21
|
+
|---|---|
|
|
22
|
+
| any call without a login | HTTP **200** with `{"status": false, "message": "Please log in…"}` |
|
|
23
|
+
| the `id` in a download link as a credential | it is the id of a **search**, and it expires: HTTP 401 |
|
|
24
|
+
| a tile at sea | `status: false` and `Invalid tile ID`, not an empty search |
|
|
25
|
+
| building the file name yourself | the trailing `_1` is a sub-release: read it from the hit |
|
|
26
|
+
| a malformed token assertion | HTTP **500** `DecodeError`, not 401: retries won't help |
|
|
27
|
+
| comparing CRS by name | four tiles of 2020-2025 say `IGNF:ETRS89LAEA`, not `EPSG:3035` |
|
|
28
|
+
| expecting 2021-2025 after 2020-2024 | the next release was 2020-2025: windows grow |
|
|
29
|
+
|
|
30
|
+
All checked against the live archive on 3 November 2026.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install egms-client # auth, search, download
|
|
36
|
+
pip install "egms-client[raster]" # + mosaics (numpy, rasterio, pyproj)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Credentials
|
|
40
|
+
|
|
41
|
+
Create a service key at [land.copernicus.eu](https://land.copernicus.eu/):
|
|
42
|
+
EU Login, profile, **API Tokens**, *Create new token*. You get a JSON file
|
|
43
|
+
with `client_id`, `user_id`, `private_key` and `token_uri`. It does not
|
|
44
|
+
expire; keep it out of your repository.
|
|
45
|
+
|
|
46
|
+
## Use
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import asyncio
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
|
|
52
|
+
import httpx
|
|
53
|
+
|
|
54
|
+
from egms_client import EgmsArchive, ServiceKey, tiles_for_bounds
|
|
55
|
+
from egms_client.mosaic import mosaic
|
|
56
|
+
|
|
57
|
+
key = ServiceKey.from_json(Path("clms-service-key.json").read_text())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def main() -> None:
|
|
61
|
+
async with httpx.AsyncClient(timeout=120) as client:
|
|
62
|
+
archive = EgmsArchive(client, key)
|
|
63
|
+
print(await archive.releases()) # ['2020-2024', '2020-2025']
|
|
64
|
+
|
|
65
|
+
# Rectangle in EPSG:3035 metres
|
|
66
|
+
bounds = dict(minx=4_700_000, miny=1_900_000, maxx=4_799_999, maxy=1_999_999)
|
|
67
|
+
tiffs = []
|
|
68
|
+
for tile in tiles_for_bounds(*bounds.values()):
|
|
69
|
+
path = await archive.fetch_tile(tile, "U", "2020-2025", Path("egms"))
|
|
70
|
+
if path is not None: # None: the tile is at sea or not covered
|
|
71
|
+
tiffs.append(path)
|
|
72
|
+
|
|
73
|
+
vertical = mosaic(tiffs, **bounds)
|
|
74
|
+
print(vertical.values.shape, vertical.left, vertical.top) # (1000, 1000) 4700000.0 2000000.0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
asyncio.run(main())
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`fetch_tile` keeps the GeoTIFF (~4 MB) and drops the ~60 MB ZIP. It
|
|
81
|
+
remembers both outcomes in the directory (the file, or an `…absent`
|
|
82
|
+
marker), so running it again for a whole country sends no request. The
|
|
83
|
+
token is renewed five minutes before its hour runs out.
|
|
84
|
+
|
|
85
|
+
### Bring your own HTTP
|
|
86
|
+
|
|
87
|
+
Everything `EgmsArchive` does is also exposed as pure functions, for
|
|
88
|
+
callers with their own HTTP and retry layer: `token_request` /
|
|
89
|
+
`parse_token`, `search_body` / `parse_search` / `latest_hit`,
|
|
90
|
+
`parse_releases`, `download_url` / `check_download` / `extract_tiff`.
|
|
91
|
+
|
|
92
|
+
## Data licence
|
|
93
|
+
|
|
94
|
+
EGMS is © European Union, Copernicus Land Monitoring Service, free and
|
|
95
|
+
open under the [Copernicus data policy](https://land.copernicus.eu/en/data-policy):
|
|
96
|
+
anything you publish from it must credit the source.
|
|
97
|
+
|
|
98
|
+
Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
|
|
99
|
+
which uses the vertical and east-west velocities per 1 km cell as ground
|
|
100
|
+
motion features for landslide risk.
|
|
101
|
+
|
|
102
|
+
## Development
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
uv sync
|
|
106
|
+
make check
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Code: [Apache-2.0](./LICENSE).
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "egms-client"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Client for the EGMS archive: CLMS service-key auth, tile search and download, Ortho L3 mosaics"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
keywords = [
|
|
7
|
+
"egms",
|
|
8
|
+
"copernicus",
|
|
9
|
+
"insar",
|
|
10
|
+
"ground motion",
|
|
11
|
+
"sentinel-1",
|
|
12
|
+
"subsidence",
|
|
13
|
+
"landslide",
|
|
14
|
+
"clms",
|
|
15
|
+
]
|
|
16
|
+
requires-python = ">=3.12"
|
|
17
|
+
license = "Apache-2.0"
|
|
18
|
+
license-files = ["LICENSE"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 4 - Beta",
|
|
21
|
+
"Intended Audience :: Science/Research",
|
|
22
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
23
|
+
"Framework :: AsyncIO",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
dependencies = [
|
|
31
|
+
"cryptography>=43",
|
|
32
|
+
"httpx>=0.27",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[[project.authors]]
|
|
36
|
+
name = "Giuseppe Zileni"
|
|
37
|
+
email = "giuseppe.zileni@gmail.com"
|
|
38
|
+
|
|
39
|
+
[project.optional-dependencies]
|
|
40
|
+
raster = [
|
|
41
|
+
"numpy>=2.0",
|
|
42
|
+
"pyproj>=3.6",
|
|
43
|
+
"rasterio>=1.4",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[project.urls]
|
|
47
|
+
Homepage = "https://github.com/agent-engineering-studio/egms-client"
|
|
48
|
+
Issues = "https://github.com/agent-engineering-studio/egms-client/issues"
|
|
49
|
+
Changelog = "https://github.com/agent-engineering-studio/egms-client/blob/main/CHANGELOG.md"
|
|
50
|
+
|
|
51
|
+
[build-system]
|
|
52
|
+
requires = ["uv_build>=0.13.6,<0.14"]
|
|
53
|
+
build-backend = "uv_build"
|
|
54
|
+
|
|
55
|
+
[dependency-groups]
|
|
56
|
+
dev = [
|
|
57
|
+
"mypy>=1.13",
|
|
58
|
+
"numpy>=2.0",
|
|
59
|
+
"pyproj>=3.6",
|
|
60
|
+
"rasterio>=1.4",
|
|
61
|
+
"pytest>=8.3",
|
|
62
|
+
"pytest-cov>=6.0",
|
|
63
|
+
"ruff>=0.8",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
[tool.ruff]
|
|
67
|
+
line-length = 100
|
|
68
|
+
target-version = "py312"
|
|
69
|
+
|
|
70
|
+
[tool.ruff.lint]
|
|
71
|
+
select = [
|
|
72
|
+
"E",
|
|
73
|
+
"F",
|
|
74
|
+
"W",
|
|
75
|
+
"I",
|
|
76
|
+
"N",
|
|
77
|
+
"UP",
|
|
78
|
+
"B",
|
|
79
|
+
"C4",
|
|
80
|
+
"SIM",
|
|
81
|
+
"ARG",
|
|
82
|
+
"PTH",
|
|
83
|
+
"RUF",
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
[tool.ruff.lint.per-file-ignores]
|
|
87
|
+
"tests/**" = [
|
|
88
|
+
"ARG",
|
|
89
|
+
"B018",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
[tool.mypy]
|
|
93
|
+
strict = true
|
|
94
|
+
python_version = "3.12"
|
|
95
|
+
files = [
|
|
96
|
+
"src",
|
|
97
|
+
"tests",
|
|
98
|
+
]
|
|
99
|
+
warn_unused_ignores = true
|
|
100
|
+
warn_redundant_casts = true
|
|
101
|
+
|
|
102
|
+
[[tool.mypy.overrides]]
|
|
103
|
+
module = [
|
|
104
|
+
"rasterio.*",
|
|
105
|
+
"pyproj.*",
|
|
106
|
+
]
|
|
107
|
+
ignore_missing_imports = true
|
|
108
|
+
|
|
109
|
+
[tool.pytest.ini_options]
|
|
110
|
+
testpaths = ["tests"]
|
|
111
|
+
addopts = "--strict-markers"
|
|
112
|
+
|
|
113
|
+
[tool.coverage.run]
|
|
114
|
+
source = ["egms_client"]
|
|
115
|
+
|
|
116
|
+
[tool.coverage.report]
|
|
117
|
+
fail_under = 90
|
|
118
|
+
show_missing = true
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "egms-client"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Client for the EGMS archive: CLMS service-key auth, tile search and download, Ortho L3 mosaics"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
keywords = ["egms", "copernicus", "insar", "ground motion", "sentinel-1", "subsidence", "landslide", "clms"]
|
|
7
|
+
requires-python = ">=3.12"
|
|
8
|
+
license = "Apache-2.0"
|
|
9
|
+
license-files = ["LICENSE"]
|
|
10
|
+
authors = [
|
|
11
|
+
{ name = "Giuseppe Zileni", email = "giuseppe.zileni@gmail.com" },
|
|
12
|
+
]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Intended Audience :: Science/Research",
|
|
16
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
17
|
+
"Framework :: AsyncIO",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"cryptography>=43",
|
|
26
|
+
"httpx>=0.27",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
raster = [
|
|
31
|
+
"numpy>=2.0",
|
|
32
|
+
"pyproj>=3.6",
|
|
33
|
+
"rasterio>=1.4",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/agent-engineering-studio/egms-client"
|
|
38
|
+
Issues = "https://github.com/agent-engineering-studio/egms-client/issues"
|
|
39
|
+
Changelog = "https://github.com/agent-engineering-studio/egms-client/blob/main/CHANGELOG.md"
|
|
40
|
+
|
|
41
|
+
[build-system]
|
|
42
|
+
requires = ["uv_build>=0.13.6,<0.14"]
|
|
43
|
+
build-backend = "uv_build"
|
|
44
|
+
|
|
45
|
+
[dependency-groups]
|
|
46
|
+
dev = [
|
|
47
|
+
"mypy>=1.13",
|
|
48
|
+
"numpy>=2.0",
|
|
49
|
+
"pyproj>=3.6",
|
|
50
|
+
"rasterio>=1.4",
|
|
51
|
+
"pytest>=8.3",
|
|
52
|
+
"pytest-cov>=6.0",
|
|
53
|
+
"ruff>=0.8",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
[tool.ruff]
|
|
57
|
+
line-length = 100
|
|
58
|
+
target-version = "py312"
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint]
|
|
61
|
+
select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "ARG", "PTH", "RUF"]
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint.per-file-ignores]
|
|
64
|
+
"tests/**" = ["ARG", "B018"]
|
|
65
|
+
|
|
66
|
+
[tool.mypy]
|
|
67
|
+
strict = true
|
|
68
|
+
python_version = "3.12"
|
|
69
|
+
files = ["src", "tests"]
|
|
70
|
+
warn_unused_ignores = true
|
|
71
|
+
warn_redundant_casts = true
|
|
72
|
+
|
|
73
|
+
[[tool.mypy.overrides]]
|
|
74
|
+
module = ["rasterio.*", "pyproj.*"]
|
|
75
|
+
ignore_missing_imports = true
|
|
76
|
+
|
|
77
|
+
[tool.pytest.ini_options]
|
|
78
|
+
testpaths = ["tests"]
|
|
79
|
+
addopts = "--strict-markers"
|
|
80
|
+
|
|
81
|
+
[tool.coverage.run]
|
|
82
|
+
source = ["egms_client"]
|
|
83
|
+
|
|
84
|
+
[tool.coverage.report]
|
|
85
|
+
fail_under = 90
|
|
86
|
+
show_missing = true
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Client for the EGMS archive (European Ground Motion Service)."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from egms_client.archive import (
|
|
6
|
+
ARCHIVE_URL,
|
|
7
|
+
COMPONENTS,
|
|
8
|
+
PRODUCT_TYPES,
|
|
9
|
+
TILE_SIZE_M,
|
|
10
|
+
Component,
|
|
11
|
+
Hit,
|
|
12
|
+
Search,
|
|
13
|
+
Tile,
|
|
14
|
+
api_release,
|
|
15
|
+
check_download,
|
|
16
|
+
download_url,
|
|
17
|
+
extract_tiff,
|
|
18
|
+
file_release,
|
|
19
|
+
latest_hit,
|
|
20
|
+
parse_releases,
|
|
21
|
+
parse_search,
|
|
22
|
+
search_body,
|
|
23
|
+
tile_id,
|
|
24
|
+
tile_prefix,
|
|
25
|
+
tiles_for_bounds,
|
|
26
|
+
)
|
|
27
|
+
from egms_client.auth import ServiceKey, Token, assertion, parse_token, token_request
|
|
28
|
+
from egms_client.client import EgmsArchive
|
|
29
|
+
from egms_client.errors import EgmsError
|
|
30
|
+
|
|
31
|
+
__version__ = version("egms-client")
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ARCHIVE_URL",
|
|
35
|
+
"COMPONENTS",
|
|
36
|
+
"PRODUCT_TYPES",
|
|
37
|
+
"TILE_SIZE_M",
|
|
38
|
+
"Component",
|
|
39
|
+
"EgmsArchive",
|
|
40
|
+
"EgmsError",
|
|
41
|
+
"Hit",
|
|
42
|
+
"Search",
|
|
43
|
+
"ServiceKey",
|
|
44
|
+
"Tile",
|
|
45
|
+
"Token",
|
|
46
|
+
"__version__",
|
|
47
|
+
"api_release",
|
|
48
|
+
"assertion",
|
|
49
|
+
"check_download",
|
|
50
|
+
"download_url",
|
|
51
|
+
"extract_tiff",
|
|
52
|
+
"file_release",
|
|
53
|
+
"latest_hit",
|
|
54
|
+
"parse_releases",
|
|
55
|
+
"parse_search",
|
|
56
|
+
"parse_token",
|
|
57
|
+
"search_body",
|
|
58
|
+
"tile_id",
|
|
59
|
+
"tile_prefix",
|
|
60
|
+
"tiles_for_bounds",
|
|
61
|
+
"token_request",
|
|
62
|
+
]
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Searching and downloading Ortho L3 tiles from the EGMS archive.
|
|
2
|
+
|
|
3
|
+
The Ortho L3 product is the ground velocity resampled on a 100 m grid in
|
|
4
|
+
EPSG:3035 (LAEA Europe), in 100 km tiles, one per component: ``U``
|
|
5
|
+
(vertical) and ``E`` (east-west). A tile is named by its lower-left corner
|
|
6
|
+
in hundreds of kilometres: E47N19 covers 4,700,000-4,800,000 m east and
|
|
7
|
+
1,900,000-2,000,000 m north. Each ZIP (~60 MB) holds a CSV of time series
|
|
8
|
+
(~245 MB once unpacked) and a GeoTIFF of the mean velocity (~4 MB).
|
|
9
|
+
|
|
10
|
+
Downloading needs the ``id`` of a **search**, not the bearer token: the
|
|
11
|
+
download URL carries ``?id=<search id>``, and that id expires. An expired or
|
|
12
|
+
unknown id is answered with HTTP 401 and a plain-text message.
|
|
13
|
+
|
|
14
|
+
Verified against the live archive on 2026-11-03:
|
|
15
|
+
|
|
16
|
+
* releases are named ``2020-2025`` in the API and ``2020_2025`` in file
|
|
17
|
+
names; a release is a window of years, and a new one may extend the window
|
|
18
|
+
rather than slide it (2020-2024 was followed by 2020-2025, not 2021-2025);
|
|
19
|
+
* a tile at sea or outside coverage is answered with ``status: false`` and
|
|
20
|
+
``Invalid tile ID: 'E40N15'``, not with an empty search;
|
|
21
|
+
* each hit carries its own ``filename`` and ``version`` (``2020_2025_1``):
|
|
22
|
+
the trailing number is a sub-release, so read the name from the hit
|
|
23
|
+
instead of building it.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import io
|
|
29
|
+
import json
|
|
30
|
+
import math
|
|
31
|
+
import zipfile
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import Any, Literal
|
|
34
|
+
|
|
35
|
+
from egms_client.errors import EgmsError
|
|
36
|
+
|
|
37
|
+
ARCHIVE_URL = "https://egms.land.copernicus.eu/insar-api/archive"
|
|
38
|
+
|
|
39
|
+
Component = Literal["U", "E"]
|
|
40
|
+
COMPONENTS: tuple[Component, ...] = ("U", "E")
|
|
41
|
+
PRODUCT_TYPES: dict[Component, str] = {"U": "ORTHO-UP", "E": "ORTHO-EAST"}
|
|
42
|
+
|
|
43
|
+
#: Side of an Ortho L3 tile, in EPSG:3035 metres.
|
|
44
|
+
TILE_SIZE_M = 100_000
|
|
45
|
+
|
|
46
|
+
#: (E, N): the lower-left corner in hundreds of kilometres.
|
|
47
|
+
Tile = tuple[int, int]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class Hit:
|
|
52
|
+
"""One downloadable file of a search."""
|
|
53
|
+
|
|
54
|
+
filename: str
|
|
55
|
+
filesize: int
|
|
56
|
+
tile_id: str
|
|
57
|
+
release: str
|
|
58
|
+
version: str
|
|
59
|
+
product_type: str
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def stem(self) -> str:
|
|
63
|
+
"""The file name without ``.zip``: also the name of the GeoTIFF inside."""
|
|
64
|
+
return self.filename.removesuffix(".zip")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, slots=True)
|
|
68
|
+
class Search:
|
|
69
|
+
"""A search id and its hits. The id is what the download URL needs."""
|
|
70
|
+
|
|
71
|
+
id: str
|
|
72
|
+
hits: list[Hit]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def tile_id(tile: Tile) -> str:
|
|
76
|
+
"""``(47, 19)`` → ``"E47N19"``."""
|
|
77
|
+
e, n = tile
|
|
78
|
+
return f"E{e}N{n}"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def tiles_for_bounds(minx: float, miny: float, maxx: float, maxy: float) -> list[Tile]:
|
|
82
|
+
"""The tiles covering a rectangle in EPSG:3035 metres."""
|
|
83
|
+
e0, e1 = math.floor(minx / TILE_SIZE_M), math.floor(maxx / TILE_SIZE_M)
|
|
84
|
+
n0, n1 = math.floor(miny / TILE_SIZE_M), math.floor(maxy / TILE_SIZE_M)
|
|
85
|
+
return [(e, n) for e in range(e0, e1 + 1) for n in range(n0, n1 + 1)]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def api_release(release: str) -> str:
|
|
89
|
+
"""``2020_2025`` (file names) or ``2020-2025`` → ``2020-2025`` (the API's form)."""
|
|
90
|
+
return release.replace("_", "-")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def file_release(release: str) -> str:
|
|
94
|
+
"""``2020-2025`` or ``2020_2025`` → ``2020_2025`` (the file names' form)."""
|
|
95
|
+
return release.replace("-", "_")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def tile_prefix(tile: Tile, component: Component, release: str) -> str:
|
|
99
|
+
"""The file name up to the sub-release: ``EGMS_L3_E47N19_100km_U_2020_2025_``."""
|
|
100
|
+
return f"EGMS_L3_{tile_id(tile)}_100km_{component}_{file_release(release)}_"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def search_body(tile: Tile, component: Component, release: str) -> dict[str, Any]:
|
|
104
|
+
"""The JSON body of ``POST {archive}/search`` for one Ortho L3 tile."""
|
|
105
|
+
return {
|
|
106
|
+
"tileId": tile_id(tile),
|
|
107
|
+
"releases": [api_release(release)],
|
|
108
|
+
"levels": ["L3"],
|
|
109
|
+
"productType": PRODUCT_TYPES[component],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def parse_releases(body: bytes | str) -> list[str]:
|
|
114
|
+
"""The release names, oldest first. :class:`EgmsError` when not logged in."""
|
|
115
|
+
data = _json(body)
|
|
116
|
+
if not isinstance(data, list):
|
|
117
|
+
raise EgmsError(f"EGMS archive refused the release list: {_message(data)}")
|
|
118
|
+
return sorted(str(r) for r in data)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def parse_search(body: bytes | str) -> Search | None:
|
|
122
|
+
"""The search, or ``None`` when the tile does not exist (sea, no coverage).
|
|
123
|
+
|
|
124
|
+
Raises :class:`EgmsError` for any other refusal, such as a missing login.
|
|
125
|
+
"""
|
|
126
|
+
data = _json(body)
|
|
127
|
+
if not isinstance(data, dict):
|
|
128
|
+
raise EgmsError(f"EGMS archive returned an unexpected search: {str(body)[:200]}")
|
|
129
|
+
if not data.get("status"):
|
|
130
|
+
if str(data.get("message") or "").startswith("Invalid tile ID"):
|
|
131
|
+
return None
|
|
132
|
+
raise EgmsError(f"EGMS archive refused the search: {_message(data)}")
|
|
133
|
+
hits = [
|
|
134
|
+
Hit(
|
|
135
|
+
filename=str(h["filename"]),
|
|
136
|
+
filesize=int(h.get("filesize") or 0),
|
|
137
|
+
tile_id=str(h.get("tileId") or ""),
|
|
138
|
+
release=str(h.get("release") or ""),
|
|
139
|
+
version=str(h.get("version") or ""),
|
|
140
|
+
product_type=str(h.get("productType") or ""),
|
|
141
|
+
)
|
|
142
|
+
for h in data.get("hits") or []
|
|
143
|
+
]
|
|
144
|
+
return Search(id=str(data["id"]), hits=hits)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def latest_hit(search: Search) -> Hit | None:
|
|
148
|
+
"""The hit with the highest sub-release, or ``None`` if there is none."""
|
|
149
|
+
return max(search.hits, key=lambda h: _sub_release(h.version), default=None)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def download_url(archive_url: str, hit: Hit) -> str:
|
|
153
|
+
"""The URL to GET with ``params={"id": search.id}``."""
|
|
154
|
+
return f"{archive_url.rstrip('/')}/download/{hit.filename}"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def check_download(status_code: int, body: bytes) -> bytes:
|
|
158
|
+
"""The ZIP, or :class:`EgmsError` (401 means the search id expired: search again)."""
|
|
159
|
+
if status_code != 200:
|
|
160
|
+
text = body[:200].decode("utf-8", "replace")
|
|
161
|
+
raise EgmsError(f"EGMS download refused (HTTP {status_code}): {text}")
|
|
162
|
+
return body
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def extract_tiff(archive: bytes, hit: Hit) -> bytes:
|
|
166
|
+
"""The mean-velocity GeoTIFF from a tile's ZIP; the CSV is left inside."""
|
|
167
|
+
with zipfile.ZipFile(io.BytesIO(archive)) as z:
|
|
168
|
+
try:
|
|
169
|
+
return z.read(f"{hit.stem}.tiff")
|
|
170
|
+
except KeyError as exc:
|
|
171
|
+
raise EgmsError(f"{hit.filename} has no {hit.stem}.tiff: {z.namelist()}") from exc
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _sub_release(version: str) -> int:
|
|
175
|
+
tail = version.rsplit("_", 1)[-1]
|
|
176
|
+
return int(tail) if tail.isdigit() else 0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _json(body: bytes | str) -> Any:
|
|
180
|
+
try:
|
|
181
|
+
return json.loads(body)
|
|
182
|
+
except ValueError as exc:
|
|
183
|
+
raise EgmsError(f"EGMS archive did not return JSON: {str(body)[:200]!r}") from exc
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _message(data: Any) -> str:
|
|
187
|
+
return str(data.get("message")) if isinstance(data, dict) else str(data)[:200]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Access tokens from a CLMS service key.
|
|
2
|
+
|
|
3
|
+
The EGMS archive answers ``{"status": false, "message": "Please log in to
|
|
4
|
+
perform archive API calls."}`` to every anonymous call, releases included.
|
|
5
|
+
The way in that needs no browser is a **service key** of the Copernicus Land
|
|
6
|
+
Monitoring Service: land.copernicus.eu, EU Login, profile → "API Tokens" →
|
|
7
|
+
"Create new token". It is a JSON document with ``client_id``, ``user_id``,
|
|
8
|
+
``private_key`` (RSA, PEM) and ``token_uri``, and it does not expire.
|
|
9
|
+
|
|
10
|
+
The key signs a short JWT (RS256), which the token endpoint exchanges for a
|
|
11
|
+
bearer token valid one hour (OAuth 2.0 JWT bearer grant, RFC 7523).
|
|
12
|
+
|
|
13
|
+
A malformed assertion is answered with **HTTP 500** and a ``DecodeError``,
|
|
14
|
+
not 401: a retry policy on 5xx will retry it pointlessly.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import base64
|
|
20
|
+
import json
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from egms_client.errors import EgmsError
|
|
25
|
+
|
|
26
|
+
#: Lifetime of the signed assertion, in seconds.
|
|
27
|
+
ASSERTION_LIFETIME = 3600
|
|
28
|
+
GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
|
|
29
|
+
|
|
30
|
+
_FIELDS = ("client_id", "user_id", "private_key", "token_uri")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class ServiceKey:
|
|
35
|
+
"""A CLMS service key, as downloaded from the land.copernicus.eu profile."""
|
|
36
|
+
|
|
37
|
+
client_id: str
|
|
38
|
+
user_id: str
|
|
39
|
+
private_key: str
|
|
40
|
+
token_uri: str
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def from_json(cls, text: str) -> ServiceKey:
|
|
44
|
+
"""Parse the JSON document; raise ``ValueError`` if a field is missing or empty."""
|
|
45
|
+
data = json.loads(text)
|
|
46
|
+
if not isinstance(data, dict):
|
|
47
|
+
raise ValueError("a CLMS service key is a JSON object")
|
|
48
|
+
missing = [f for f in _FIELDS if not data.get(f)]
|
|
49
|
+
if missing:
|
|
50
|
+
raise ValueError(f"CLMS service key without {', '.join(missing)}")
|
|
51
|
+
return cls(**{f: str(data[f]) for f in _FIELDS})
|
|
52
|
+
|
|
53
|
+
def __repr__(self) -> str:
|
|
54
|
+
return f"ServiceKey(client_id={self.client_id!r}, user_id={self.user_id!r}, private_key=…)"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class Token:
|
|
59
|
+
"""A bearer token and the Unix time it expires at."""
|
|
60
|
+
|
|
61
|
+
access_token: str
|
|
62
|
+
expires_at: float
|
|
63
|
+
|
|
64
|
+
def headers(self) -> dict[str, str]:
|
|
65
|
+
return {"Authorization": f"Bearer {self.access_token}", "Accept": "application/json"}
|
|
66
|
+
|
|
67
|
+
def __repr__(self) -> str:
|
|
68
|
+
return f"Token(access_token=…, expires_at={self.expires_at})"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def assertion(key: ServiceKey, *, now: int, lifetime: int = ASSERTION_LIFETIME) -> str:
|
|
72
|
+
"""The RS256 JWT the service key signs to ask for a token."""
|
|
73
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
74
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
75
|
+
|
|
76
|
+
header = _b64(json.dumps({"alg": "RS256", "typ": "JWT"}).encode())
|
|
77
|
+
claims = _b64(
|
|
78
|
+
json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"iss": key.client_id,
|
|
81
|
+
"sub": key.user_id,
|
|
82
|
+
"aud": key.token_uri,
|
|
83
|
+
"iat": now,
|
|
84
|
+
"exp": now + lifetime,
|
|
85
|
+
}
|
|
86
|
+
).encode()
|
|
87
|
+
)
|
|
88
|
+
private = serialization.load_pem_private_key(key.private_key.encode(), password=None)
|
|
89
|
+
if not isinstance(private, rsa.RSAPrivateKey):
|
|
90
|
+
raise ValueError("the CLMS service key is not an RSA key")
|
|
91
|
+
signature = _b64(private.sign(header + b"." + claims, padding.PKCS1v15(), hashes.SHA256()))
|
|
92
|
+
return (header + b"." + claims + b"." + signature).decode()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def token_request(key: ServiceKey, *, now: int) -> dict[str, str]:
|
|
96
|
+
"""The form body to POST to ``key.token_uri``."""
|
|
97
|
+
return {"grant_type": GRANT_TYPE, "assertion": assertion(key, now=now)}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_token(status_code: int, body: bytes | str, *, now: float) -> Token:
|
|
101
|
+
"""The token from the endpoint's answer; :class:`EgmsError` if it was refused."""
|
|
102
|
+
try:
|
|
103
|
+
data: Any = json.loads(body)
|
|
104
|
+
except ValueError:
|
|
105
|
+
data = None
|
|
106
|
+
if status_code != 200 or not isinstance(data, dict) or "access_token" not in data:
|
|
107
|
+
detail = data.get("message") if isinstance(data, dict) else str(body)[:200]
|
|
108
|
+
raise EgmsError(f"CLMS token refused (HTTP {status_code}): {detail}")
|
|
109
|
+
return Token(
|
|
110
|
+
access_token=str(data["access_token"]),
|
|
111
|
+
expires_at=now + float(data.get("expires_in", ASSERTION_LIFETIME)),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _b64(data: bytes) -> bytes:
|
|
116
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""An async client over :mod:`egms_client.auth` and :mod:`egms_client.archive`.
|
|
2
|
+
|
|
3
|
+
It takes your ``httpx.AsyncClient``: timeouts, retries, proxies and pooling
|
|
4
|
+
stay yours. HTTP errors propagate; refusals the archive disguises as a 200
|
|
5
|
+
raise :class:`~egms_client.errors.EgmsError`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from egms_client.archive import (
|
|
16
|
+
ARCHIVE_URL,
|
|
17
|
+
Component,
|
|
18
|
+
Search,
|
|
19
|
+
Tile,
|
|
20
|
+
check_download,
|
|
21
|
+
download_url,
|
|
22
|
+
extract_tiff,
|
|
23
|
+
latest_hit,
|
|
24
|
+
parse_releases,
|
|
25
|
+
parse_search,
|
|
26
|
+
search_body,
|
|
27
|
+
tile_prefix,
|
|
28
|
+
)
|
|
29
|
+
from egms_client.auth import ServiceKey, Token, parse_token, token_request
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
import httpx
|
|
33
|
+
|
|
34
|
+
#: Renew the token this many seconds before it expires: a national download
|
|
35
|
+
#: lasts longer than the token's hour.
|
|
36
|
+
RENEW_MARGIN_S = 300
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class EgmsArchive:
|
|
40
|
+
"""Releases, searches and Ortho L3 tiles, with a token renewed as needed."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
client: httpx.AsyncClient,
|
|
45
|
+
key: ServiceKey,
|
|
46
|
+
*,
|
|
47
|
+
archive_url: str = ARCHIVE_URL,
|
|
48
|
+
clock: Callable[[], float] = time.time,
|
|
49
|
+
) -> None:
|
|
50
|
+
self._client = client
|
|
51
|
+
self._key = key
|
|
52
|
+
self._archive = archive_url.rstrip("/")
|
|
53
|
+
self._clock = clock
|
|
54
|
+
self._token: Token | None = None
|
|
55
|
+
|
|
56
|
+
async def token(self) -> Token:
|
|
57
|
+
"""A valid bearer token, asking for a new one when the current is about to expire."""
|
|
58
|
+
now = self._clock()
|
|
59
|
+
if self._token is None or now > self._token.expires_at - RENEW_MARGIN_S:
|
|
60
|
+
response = await self._client.post(
|
|
61
|
+
self._key.token_uri,
|
|
62
|
+
data=token_request(self._key, now=int(now)),
|
|
63
|
+
headers={"Accept": "application/json"},
|
|
64
|
+
)
|
|
65
|
+
self._token = parse_token(response.status_code, response.content, now=now)
|
|
66
|
+
return self._token
|
|
67
|
+
|
|
68
|
+
async def releases(self) -> list[str]:
|
|
69
|
+
"""The published releases, oldest first (``["2020-2024", "2020-2025"]``)."""
|
|
70
|
+
token = await self.token()
|
|
71
|
+
response = await self._client.get(f"{self._archive}/releases", headers=token.headers())
|
|
72
|
+
response.raise_for_status()
|
|
73
|
+
return parse_releases(response.content)
|
|
74
|
+
|
|
75
|
+
async def search(self, tile: Tile, component: Component, release: str) -> Search | None:
|
|
76
|
+
"""Search one Ortho L3 tile; ``None`` if the tile does not exist."""
|
|
77
|
+
token = await self.token()
|
|
78
|
+
response = await self._client.post(
|
|
79
|
+
f"{self._archive}/search",
|
|
80
|
+
headers=token.headers(),
|
|
81
|
+
json=search_body(tile, component, release),
|
|
82
|
+
)
|
|
83
|
+
response.raise_for_status()
|
|
84
|
+
return parse_search(response.content)
|
|
85
|
+
|
|
86
|
+
async def fetch_tile(
|
|
87
|
+
self, tile: Tile, component: Component, release: str, directory: Path
|
|
88
|
+
) -> Path | None:
|
|
89
|
+
"""The tile's mean-velocity GeoTIFF in ``directory``, downloaded if missing.
|
|
90
|
+
|
|
91
|
+
``None`` when the tile does not exist. Both outcomes are remembered in
|
|
92
|
+
``directory`` (the GeoTIFF, or an ``…absent`` marker), so running it
|
|
93
|
+
again for a whole country asks the archive nothing.
|
|
94
|
+
"""
|
|
95
|
+
prefix = tile_prefix(tile, component, release)
|
|
96
|
+
cached = sorted(directory.glob(f"{prefix}*.tiff"))
|
|
97
|
+
if cached:
|
|
98
|
+
return cached[-1]
|
|
99
|
+
marker = directory / f"{prefix}absent"
|
|
100
|
+
if marker.exists():
|
|
101
|
+
return None
|
|
102
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
search = await self.search(tile, component, release)
|
|
104
|
+
hit = latest_hit(search) if search is not None else None
|
|
105
|
+
if search is None or hit is None:
|
|
106
|
+
marker.touch()
|
|
107
|
+
return None
|
|
108
|
+
response = await self._client.get(
|
|
109
|
+
download_url(self._archive, hit), params={"id": search.id}
|
|
110
|
+
)
|
|
111
|
+
if response.status_code == 404:
|
|
112
|
+
marker.touch()
|
|
113
|
+
return None
|
|
114
|
+
tiff = extract_tiff(check_download(response.status_code, response.content), hit)
|
|
115
|
+
path = directory / f"{hit.stem}.tiff"
|
|
116
|
+
partial = path.with_suffix(".part")
|
|
117
|
+
partial.write_bytes(tiff)
|
|
118
|
+
partial.rename(path)
|
|
119
|
+
return path
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Ortho L3 tiles pasted onto one grid. Needs the ``raster`` extra.
|
|
2
|
+
|
|
3
|
+
The tiles sit on a common 100 m grid in EPSG:3035, so a mosaic is a copy of
|
|
4
|
+
each tile into its place, with no resampling.
|
|
5
|
+
|
|
6
|
+
Some tiles declare their CRS as ``IGNF:ETRS89LAEA`` instead of
|
|
7
|
+
``EPSG:3035``: the same projection under the French IGN's name. In the
|
|
8
|
+
2020-2025 release that is E43N26, E44N26, E45N26 and E46N26 (in 2020-2024,
|
|
9
|
+
E42N26 and E43N26). Comparing CRS by name rejects them; :func:`is_laea`
|
|
10
|
+
compares the parameters.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import warnings
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
#: Pixel size of the Ortho L3 product, in metres.
|
|
23
|
+
PIXEL_M = 100.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Mosaic:
|
|
28
|
+
"""A float32 array (NaN where there is no data) and its upper-left corner."""
|
|
29
|
+
|
|
30
|
+
values: Any
|
|
31
|
+
left: float
|
|
32
|
+
top: float
|
|
33
|
+
pixel: float = PIXEL_M
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_laea(crs: Any) -> bool:
|
|
37
|
+
"""True if a rasterio CRS is LAEA Europe (EPSG:3035) by its parameters."""
|
|
38
|
+
from pyproj import CRS
|
|
39
|
+
|
|
40
|
+
with warnings.catch_warnings():
|
|
41
|
+
# pyproj warns that a PROJ string drops information: only the
|
|
42
|
+
# parameters are wanted here.
|
|
43
|
+
warnings.simplefilter("ignore", UserWarning)
|
|
44
|
+
return bool(CRS.from_wkt(crs.to_wkt()).to_proj4() == CRS.from_epsg(3035).to_proj4())
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def mosaic(tiffs: Iterable[Path], *, minx: float, miny: float, maxx: float, maxy: float) -> Mosaic:
|
|
48
|
+
"""Paste the tiles of one component over a rectangle in EPSG:3035 metres.
|
|
49
|
+
|
|
50
|
+
The rectangle widens to the 100 m grid. Pixels no tile covers, and the
|
|
51
|
+
tiles' own nodata, are NaN. A tile in another projection raises
|
|
52
|
+
``ValueError``.
|
|
53
|
+
"""
|
|
54
|
+
import numpy as np
|
|
55
|
+
import rasterio
|
|
56
|
+
|
|
57
|
+
x0 = math.floor(minx / PIXEL_M) * PIXEL_M
|
|
58
|
+
y0 = math.floor(miny / PIXEL_M) * PIXEL_M
|
|
59
|
+
x1 = math.ceil(maxx / PIXEL_M) * PIXEL_M
|
|
60
|
+
y1 = math.ceil(maxy / PIXEL_M) * PIXEL_M
|
|
61
|
+
rows = round((y1 - y0) / PIXEL_M)
|
|
62
|
+
cols = round((x1 - x0) / PIXEL_M)
|
|
63
|
+
out = np.full((rows, cols), np.nan, dtype="float32")
|
|
64
|
+
for path in tiffs:
|
|
65
|
+
with rasterio.open(path) as src:
|
|
66
|
+
if not is_laea(src.crs):
|
|
67
|
+
raise ValueError(f"{path.name}: not LAEA Europe ({src.crs})")
|
|
68
|
+
band = src.read(1).astype("float32")
|
|
69
|
+
if src.nodata is not None:
|
|
70
|
+
band[band == src.nodata] = np.nan
|
|
71
|
+
col = round((src.bounds.left - x0) / PIXEL_M)
|
|
72
|
+
row = round((y1 - src.bounds.top) / PIXEL_M)
|
|
73
|
+
sr, sc = max(0, -row), max(0, -col)
|
|
74
|
+
dr, dc = max(0, row), max(0, col)
|
|
75
|
+
h = min(band.shape[0] - sr, rows - dr)
|
|
76
|
+
w = min(band.shape[1] - sc, cols - dc)
|
|
77
|
+
if h <= 0 or w <= 0:
|
|
78
|
+
continue
|
|
79
|
+
piece = band[sr : sr + h, sc : sc + w]
|
|
80
|
+
target = out[dr : dr + h, dc : dc + w]
|
|
81
|
+
valid = ~np.isnan(piece)
|
|
82
|
+
target[valid] = piece[valid]
|
|
83
|
+
return Mosaic(values=out, left=x0, top=y1)
|
|
File without changes
|