imageserver-export 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.
@@ -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,357 @@
1
+ Metadata-Version: 2.4
2
+ Name: imageserver-export
3
+ Version: 0.1.0
4
+ Summary: Export ArcGIS ImageServer rasters (like the open Copernicus Land layers the EEA serves) to aligned, atomic GeoTIFF mosaics
5
+ Keywords: arcgis,imageserver,geotiff,raster,copernicus,eea,land monitoring,imperviousness,gis
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: httpx>=0.27
20
+ Requires-Dist: numpy>=1.26
21
+ Requires-Dist: rasterio>=1.3
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/agent-engineering-studio/imageserver-export
24
+ Project-URL: Issues, https://github.com/agent-engineering-studio/imageserver-export/issues
25
+ Project-URL: Changelog, https://github.com/agent-engineering-studio/imageserver-export/blob/main/CHANGELOG.md
26
+ Description-Content-Type: text/markdown
27
+
28
+ <p align="center">
29
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/imageserver-export/main/docs/images/banner.svg" alt="imageserver-export: open land-cover maps of Europe, as clean GeoTIFFs, in a few lines of Python" width="100%">
30
+ </p>
31
+
32
+ <p align="center">
33
+ <a href="https://github.com/agent-engineering-studio/imageserver-export/actions/workflows/ci.yml"><img src="https://github.com/agent-engineering-studio/imageserver-export/actions/workflows/ci.yml/badge.svg" alt="ci"></a>
34
+ <a href="https://pypi.org/project/imageserver-export/"><img src="https://img.shields.io/pypi/v/imageserver-export" alt="PyPI"></a>
35
+ <a href="https://agentengineering.it/imageserver-export/"><img src="https://img.shields.io/badge/docs-site-informational" alt="docs"></a>
36
+ <img src="https://img.shields.io/badge/python-3.12%20%7C%203.13-blue" alt="Python 3.12 | 3.13">
37
+ <img src="https://img.shields.io/badge/typing-mypy%20strict-informational" alt="mypy strict">
38
+ <img src="https://img.shields.io/badge/coverage-100%25-brightgreen" alt="coverage 100%">
39
+ <a href="https://github.com/agent-engineering-studio/imageserver-export/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="Apache-2.0"></a>
40
+ </p>
41
+
42
+ **imageserver-export** is a small, typed, async Python library that turns an
43
+ area of any **ArcGIS ImageServer** into one clean **GeoTIFF**. Its first use
44
+ is the open server of the European Environment Agency, which publishes the
45
+ **Copernicus Land Monitoring Service** maps of all of Europe, at 10 m:
46
+ how much of the ground is sealed by concrete and asphalt, how dense the
47
+ trees are, where the grassland, the water and the wetlands are. No account,
48
+ no key, no manual download.
49
+
50
+ ```python
51
+ async with ImageServer(eea("HRL_ImperviousnessDensity_2018")) as server:
52
+ await server.export(Grid.from_lonlat((8.95, 45.33, 9.45, 45.62), res=100), Path("milan.tif"))
53
+ ```
54
+
55
+ Three dependencies: `httpx`, `numpy`, `rasterio`.
56
+
57
+ <p align="center">
58
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/imageserver-export/main/docs/images/map-milan.png" alt="Map of Milan and its belt: the share of sealed soil in each 100 m pixel, from bare fields in light beige to the fully sealed centre in dark brown" width="85%">
59
+ </p>
60
+
61
+ ---
62
+
63
+ ## Contents
64
+
65
+ - [What is an ImageServer, in 30 seconds](#what-is-an-imageserver-in-30-seconds)
66
+ - [What this library does](#what-this-library-does)
67
+ - [Who is it for](#who-is-it-for)
68
+ - [Quick start](#quick-start)
69
+ - [The open maps of Europe](#the-open-maps-of-europe)
70
+ - [How it works](#how-it-works)
71
+ - [Why nearest neighbour](#why-nearest-neighbour)
72
+ - [Recipes](#recipes)
73
+ - [The traps we already fell into](#the-traps-we-already-fell-into)
74
+ - [API at a glance](#api-at-a-glance)
75
+ - [Data licence and credits](#data-licence-and-credits)
76
+ - [Contributing](#contributing)
77
+
78
+ ## What is an ImageServer, in 30 seconds
79
+
80
+ Many public agencies publish their maps with **ArcGIS Server**. An
81
+ *ImageServer* is the part of it that serves rasters: grids of numbers, one
82
+ per pixel, like satellite-derived land cover. You give it a box, a size and
83
+ a coordinate system, and its `exportImage` operation sends back a picture of
84
+ that box.
85
+
86
+ That is enough to view a map, but not to *use* it. One request returns at
87
+ most a few thousand pixels a side, so Italy at 10 m takes thousands of them.
88
+ They have to line up exactly, or the pieces shift against each other. And
89
+ when something goes wrong, the server still answers "200 OK", with an error
90
+ message where the image should be.
91
+
92
+ This library does that part for you.
93
+
94
+ ## What this library does
95
+
96
+ | | | |
97
+ |---|---|---|
98
+ | 🗺️ | **One area, one GeoTIFF** | Give it a longitude/latitude box and a resolution; get back one tiled, compressed GeoTIFF, georeferenced in the CRS you chose (LAEA Europe by default). |
99
+ | 📐 | **Pixels that line up** | The grid is snapped to whole pixels, and every request is a window of it: the server never resamples to fit, and tiles never shift. |
100
+ | 🧩 | **Big areas in pieces** | The area is cut into tiles the server accepts, fetched a few at a time, and pasted as they arrive. A whole country is just more tiles. |
101
+ | 🛟 | **A file or nothing** | The mosaic is written to `out.tif.part` and renamed only when every tile is in. A failure leaves nothing a later reader could mistake for a whole map. |
102
+ | 🚨 | **Errors that say why** | A JSON error sent with "200 OK", or a tile of the wrong size, stops the export with the server's own message. |
103
+ | 🏷️ | **What the values mean** | `info()` describes the service (pixel type, size, extent, largest image); `attribute_table()` gives the label of every pixel value. |
104
+ | 🔌 | **Your HTTP, your rules** | Bring your own `httpx.AsyncClient`, or a `send` function: a shared retry policy, a cache or a rate limiter then sees every request. |
105
+
106
+ ## Who is it for
107
+
108
+ - **Researchers and analysts** who need a Copernicus Land layer for a
109
+ region, at the resolution of their own grid, in a script they can run again.
110
+ - **Risk and climate tools** that turn land cover into a factor per cell:
111
+ sealed soil makes rain run off faster, tree cover feeds fires, wetlands
112
+ change how floods spread.
113
+ - **Anyone with an ArcGIS ImageServer to read**, from the EEA or from a
114
+ regional or national agency: the library is not tied to one server.
115
+
116
+ It was written for [Limen](https://github.com/agent-engineering-studio/limen),
117
+ an open early-warning platform for landslides, floods and wildfires in
118
+ Italy, which uses sealed soil to amplify the rain-driven flood trigger.
119
+
120
+ ## Quick start
121
+
122
+ ### 1. Install
123
+
124
+ ```bash
125
+ pip install imageserver-export
126
+ ```
127
+
128
+ ### 2. Export an area
129
+
130
+ ```python
131
+ import asyncio
132
+ from pathlib import Path
133
+
134
+ from imageserver_export import Grid, ImageServer, eea
135
+
136
+
137
+ async def main() -> None:
138
+ async with ImageServer(eea("HRL_ImperviousnessDensity_2018")) as server:
139
+ # Milan and its belt, at 100 m, in LAEA Europe (EPSG:3035).
140
+ grid = Grid.from_lonlat((8.95, 45.33, 9.45, 45.62), res=100)
141
+ result = await server.export(grid, Path("milan.tif"), valid_range=(0, 100))
142
+ print(result.width, "x", result.height, "pixels,", f"{result.valid_fraction:.0%} valid")
143
+
144
+
145
+ asyncio.run(main())
146
+ ```
147
+
148
+ `valid_range=(0, 100)` tells the library which values are real data: this
149
+ layer uses 254 for "unclassifiable" and 255 for "no data" (the sea, or
150
+ outside Europe), and both are kept in the file as they are.
151
+
152
+ ### 3. Read it
153
+
154
+ The result is an ordinary GeoTIFF: open it in QGIS, or read it with
155
+ `rasterio`:
156
+
157
+ ```python
158
+ import rasterio
159
+
160
+ with rasterio.open("milan.tif") as src:
161
+ band = src.read(1)
162
+ sealed = band[band <= 100]
163
+ print(f"mean sealed soil: {sealed.mean():.1f} %") # ~25 % around Milan
164
+ ```
165
+
166
+ ## The open maps of Europe
167
+
168
+ The EEA serves 26 Copernicus Land layers this way (`eea(name)` builds the
169
+ URL, `list_services(f"{EEA_URL}/{EEA_FOLDER}")` lists them). Among them:
170
+
171
+ | Layer (`eea(...)`) | What each pixel says | Native pixel |
172
+ |---|---|---|
173
+ | `HRL_ImperviousnessDensity_2018` | % of the ground sealed by buildings, roads, car parks | 10 m |
174
+ | `HRL_TreeCoverDensity_2018` | % of the ground under tree crowns | 10 m |
175
+ | `HRL_DominantLeafType2018` | broadleaved or coniferous forest | 10 m |
176
+ | `HRL_Grassland_2018` | grassland or not | 10 m |
177
+ | `HRL_WaterWetness_2018` | permanent water, temporary water, wet and dry ground | 10 m |
178
+ | `HRL_SmallWoodyFeatures_2018_005m` | hedges, tree rows, small groves | 5 m |
179
+ | `HRL_ImperviousnessChange_15_18` | how sealed soil changed, 2015 to 2018 | 20 m |
180
+
181
+ Each layer has a raster attribute table: `await server.attribute_table()`
182
+ returns, for the imperviousness layer, 102 rows such as
183
+ `{"Value": 1, "Class_name": "1% imperviousness value", "Area_km2": 222.19}`.
184
+
185
+ ## How it works
186
+
187
+ <p align="center">
188
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/imageserver-export/main/docs/images/tiles.svg" alt="How an export works: an area becomes a grid on whole pixels, the grid is cut into tiles that are requested with exportImage, and the tiles become one GeoTIFF that is renamed from .part only when whole" width="100%">
189
+ </p>
190
+
191
+ ```mermaid
192
+ flowchart LR
193
+ A["Grid.from_lonlat(box, res)"] --> B["plan(grid, tile_px)"]
194
+ B --> C{{"exportImage<br/>per tile, 3 at a time"}}
195
+ C -->|"GeoTIFF bytes"| D["check_image()"]
196
+ C -->|"200 + JSON error"| X["ImageServerError"]
197
+ D --> E["Mosaic.paste()<br/>size checked"]
198
+ E --> F["out.tif.part"]
199
+ F -->|"all tiles in"| G["out.tif"]
200
+ F -->|"any failure"| H["deleted"]
201
+ ```
202
+
203
+ 1. **The grid.** `Grid.from_lonlat` reprojects the box with densified edges
204
+ (in an equal-area projection the sides of a geographic box curve, and its
205
+ southern point is not a corner), then grows it outward to whole pixels.
206
+ 2. **The tiles.** `plan()` covers the grid exactly once, edge tiles clamped
207
+ to it. Every tile's box is a multiple of the resolution, so the server
208
+ returns exactly the size asked for, with no resampling.
209
+ 3. **The requests.** `export_params()` builds each `exportImage` query in the
210
+ grid's own CRS, nearest neighbour by default. `check_image()` turns a JSON
211
+ answer into an error with the server's message.
212
+ 4. **The mosaic.** `Mosaic` writes a tiled, deflate-compressed GeoTIFF to
213
+ `.part`, refuses a tile whose size differs from the one asked for, counts
214
+ the valid pixels, and renames the file only on success.
215
+
216
+ Every step is a plain function or class you can use alone; `ImageServer`
217
+ just puts them together.
218
+
219
+ ## Why nearest neighbour
220
+
221
+ <p align="center">
222
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/imageserver-export/main/docs/images/sentinel.svg" alt="Between a 0 percent pixel and a 255 no-data pixel, bilinear resampling invents a believable 64 percent; nearest neighbour keeps the two real values" width="100%">
223
+ </p>
224
+
225
+ Many land-cover layers keep their "no data" marker in the same band as the
226
+ data: 0 to 100 are percentages, 255 is "nothing here". Bilinear or cubic
227
+ resampling averages neighbours, so between a 0 % field and a 255 sea pixel
228
+ it can produce 64: a believable "64 % sealed", exactly where nothing was
229
+ measured. Nothing downstream can tell it from a real value.
230
+
231
+ So the default is `RSP_NearestNeighbor`: every output pixel is one the
232
+ server really has. Pass `interpolation="RSP_BilinearInterpolation"` only for
233
+ continuous layers with no sentinel values.
234
+
235
+ ## Recipes
236
+
237
+ ### Tree cover of a region, at 20 m
238
+
239
+ ```python
240
+ grid = Grid.from_lonlat((15.3, 39.9, 16.9, 41.2), res=20) # Basilicata
241
+ async with ImageServer(eea("HRL_TreeCoverDensity_2018")) as server:
242
+ await server.export(
243
+ grid,
244
+ Path("basilicata_trees.tif"),
245
+ valid_range=(0, 100),
246
+ on_tile=lambda done, total: print(f"{done}/{total}"),
247
+ )
248
+ ```
249
+
250
+ ### Your own grid, in your CRS
251
+
252
+ ```python
253
+ # Snap to an existing 1 km grid in UTM 32N.
254
+ grid = Grid.snap((500_000, 4_500_000, 560_000, 4_560_000), res=1000, crs=32632)
255
+ ```
256
+
257
+ ### Label the classes
258
+
259
+ ```python
260
+ async with ImageServer(eea("HRL_WaterWetness_2018")) as server:
261
+ rows = await server.attribute_table()
262
+
263
+
264
+ # The label field is `Class_name` in some layers and `class_name` in others.
265
+ def label(row: dict) -> str | None:
266
+ return next((v for k, v in row.items() if k.lower() == "class_name"), None)
267
+
268
+
269
+ labels = {row["Value"]: label(row) for row in rows}
270
+ # {0: 'Dry', 1: 'Permanent water', 2: 'Temporary water', 3: 'Permanent wet', ...}
271
+ ```
272
+
273
+ ### Any other ImageServer
274
+
275
+ ```python
276
+ server = ImageServer("https://example.org/arcgis/rest/services/Elevation/ImageServer")
277
+ info = await server.info() # pixel type, size, extent, largest image
278
+ await server.export(
279
+ Grid.snap(box, res=info.pixel_size[0], crs=3857),
280
+ Path("dem.tif"),
281
+ pixel_type="F32",
282
+ dtype="float32",
283
+ nodata=None,
284
+ )
285
+ ```
286
+
287
+ ### Bring your own HTTP
288
+
289
+ ```python
290
+ import httpx
291
+
292
+ async with httpx.AsyncClient(timeout=120) as client: # your timeouts, proxies
293
+ server = ImageServer(url, client, retries=5)
294
+
295
+
296
+ async def send(method: str, url: str, **kw) -> httpx.Response:
297
+ return await my_retrying_client.request(method, url, **kw) # your policy
298
+
299
+
300
+ server = ImageServer(url, send=send) # every request goes through `send`
301
+ ```
302
+
303
+ ## The traps we already fell into
304
+
305
+ - **"200 OK" is not success.** An ImageServer answers a bad request with
306
+ HTTP 200 and a JSON error. Read as a TIFF, it is just "a corrupt file".
307
+ - **Four corners are not a box.** Reprojecting only the corners of Italy's
308
+ longitude/latitude box to LAEA cut 6.8 km off the south: Lampedusa ended
309
+ outside the raster, and 28 grid cells had no data.
310
+ - **Rounding a box cuts it.** Edges are grown to the next pixel, never
311
+ rounded, or a strip of the area asked for goes missing.
312
+ - **A tile of the wrong size shifts everything.** It is refused, not pasted.
313
+ - **A half-written file looks whole.** Hence `.part` and the rename.
314
+ - **Field names are not consistent.** The label column of the attribute
315
+ table is `Class_name` in the imperviousness layer and `class_name` in the
316
+ water and wetness one: compare names case-insensitively.
317
+
318
+ ## API at a glance
319
+
320
+ | | |
321
+ |---|---|
322
+ | `ImageServer(url, client=None, *, send=None, retries=3)` | the async client |
323
+ | `await server.info()` | `ServiceInfo`: pixel type, size, extent, largest image, CRS |
324
+ | `await server.attribute_table()` | the raster attribute table, as dicts |
325
+ | `await server.export(grid, dest, ...)` | `Export(path, tiles, width, height, valid_px)` |
326
+ | `await list_services(folder_url)` | the ImageServer names of a folder |
327
+ | `Grid.from_lonlat(box, res, crs=3035)`, `Grid.snap(bounds, res, crs)` | the target grid |
328
+ | `plan(grid, tile_px=2048)`, `Tile.bounds(grid)` | the tiles |
329
+ | `export_params(...)`, `check_image(...)` | one request, pure |
330
+ | `Mosaic(path, grid, ...)` | the atomic GeoTIFF writer |
331
+ | `eea(name)`, `EEA_URL`, `EEA_FOLDER` | the European Environment Agency's server |
332
+
333
+ Full reference: [agentengineering.it/imageserver-export](https://agentengineering.it/imageserver-export/).
334
+
335
+ ## Data licence and credits
336
+
337
+ The library is Apache-2.0. The data are not part of it: each server sets its
338
+ own terms. The Copernicus Land Monitoring Service layers the EEA serves are
339
+ free and open; credit them as *© European Union, Copernicus Land Monitoring
340
+ Service, European Environment Agency (EEA)* when you publish anything made
341
+ from them.
342
+
343
+ ## Contributing
344
+
345
+ ```bash
346
+ uv sync
347
+ make check # ruff, mypy --strict, pytest (100 % coverage)
348
+ uv run --group docs python docs/make_images.py # redraw the README images from live data
349
+ uv run --group docs mkdocs serve # the documentation site, locally
350
+ ```
351
+
352
+ Ideas: a command-line `imageserver-export` entry point; a `bbox` given in
353
+ any CRS; multi-band exports.
354
+
355
+ ## License
356
+
357
+ [Apache-2.0](./LICENSE).