imageserver-export 0.1.0__py3-none-any.whl

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,52 @@
1
+ """Export ArcGIS ImageServer rasters to aligned, atomic GeoTIFF mosaics.
2
+
3
+ Pure pieces (:mod:`~imageserver_export.service`, :mod:`~imageserver_export.grid`,
4
+ :mod:`~imageserver_export.tiles`, :mod:`~imageserver_export.request`), the
5
+ mosaic writer (:mod:`~imageserver_export.mosaic`) and an async client over
6
+ them (:class:`ImageServer`).
7
+ """
8
+
9
+ from importlib.metadata import version
10
+
11
+ from imageserver_export.client import Export, ImageServer, Send, list_services
12
+ from imageserver_export.errors import ImageServerError
13
+ from imageserver_export.grid import Bounds, Grid
14
+ from imageserver_export.mosaic import Mosaic
15
+ from imageserver_export.request import Interpolation, check_image, export_params
16
+ from imageserver_export.service import (
17
+ EEA_FOLDER,
18
+ EEA_URL,
19
+ ServiceInfo,
20
+ eea,
21
+ parse_attribute_table,
22
+ parse_info,
23
+ parse_services,
24
+ )
25
+ from imageserver_export.tiles import DEFAULT_TILE_PX, Tile, plan
26
+
27
+ __version__ = version("imageserver-export")
28
+
29
+ __all__ = [
30
+ "DEFAULT_TILE_PX",
31
+ "EEA_FOLDER",
32
+ "EEA_URL",
33
+ "Bounds",
34
+ "Export",
35
+ "Grid",
36
+ "ImageServer",
37
+ "ImageServerError",
38
+ "Interpolation",
39
+ "Mosaic",
40
+ "Send",
41
+ "ServiceInfo",
42
+ "Tile",
43
+ "__version__",
44
+ "check_image",
45
+ "eea",
46
+ "export_params",
47
+ "list_services",
48
+ "parse_attribute_table",
49
+ "parse_info",
50
+ "parse_services",
51
+ "plan",
52
+ ]
@@ -0,0 +1,195 @@
1
+ """An async client: describe a service, and export an area of it to a GeoTIFF.
2
+
3
+ Give it your ``httpx.AsyncClient`` and timeouts, proxies and pooling stay
4
+ yours; give it none and it opens (and closes) its own. Network errors and
5
+ 429/5xx are retried ``retries`` times with exponential backoff.
6
+
7
+ To route every request through your own HTTP layer (a shared retry policy,
8
+ a cache, a rate limiter), pass ``send``: an ``async (method, url, **kwargs)
9
+ -> httpx.Response``. The client then uses it for every call and does no
10
+ retrying of its own.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ from collections.abc import Awaitable, Callable
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from types import TracebackType
20
+ from typing import Any
21
+
22
+ import httpx
23
+
24
+ from imageserver_export.grid import Grid
25
+ from imageserver_export.mosaic import Mosaic
26
+ from imageserver_export.request import Interpolation, check_image, export_params
27
+ from imageserver_export.service import (
28
+ ServiceInfo,
29
+ parse_attribute_table,
30
+ parse_info,
31
+ parse_services,
32
+ )
33
+ from imageserver_export.tiles import DEFAULT_TILE_PX, Tile, plan
34
+
35
+ Send = Callable[..., Awaitable[httpx.Response]]
36
+ _RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class Export:
41
+ """What an export wrote."""
42
+
43
+ path: Path
44
+ tiles: int
45
+ width: int
46
+ height: int
47
+ valid_px: int
48
+
49
+ @property
50
+ def valid_fraction(self) -> float:
51
+ return self.valid_px / (self.width * self.height) if self.width and self.height else 0.0
52
+
53
+
54
+ class ImageServer:
55
+ """One ImageServer (``https://…/arcgis/rest/services/<name>/ImageServer``)."""
56
+
57
+ def __init__(
58
+ self,
59
+ url: str,
60
+ client: httpx.AsyncClient | None = None,
61
+ *,
62
+ send: Send | None = None,
63
+ retries: int = 3,
64
+ backoff_s: float = 2.0,
65
+ timeout_s: float = 180.0,
66
+ sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep,
67
+ ) -> None:
68
+ self.url = url.rstrip("/")
69
+ self._own = client is None and send is None
70
+ self._client = client or (
71
+ None if send is not None else httpx.AsyncClient(follow_redirects=True)
72
+ )
73
+ self._send_hook = send
74
+ self._retries = retries
75
+ self._backoff_s = backoff_s
76
+ self._timeout_s = timeout_s
77
+ self._sleep = sleep
78
+
79
+ async def __aenter__(self) -> ImageServer:
80
+ return self
81
+
82
+ async def __aexit__(
83
+ self,
84
+ exc_type: type[BaseException] | None,
85
+ exc: BaseException | None,
86
+ tb: TracebackType | None,
87
+ ) -> None:
88
+ await self.aclose()
89
+
90
+ async def aclose(self) -> None:
91
+ """Close the HTTP client if this instance opened it."""
92
+ if self._own and self._client is not None:
93
+ await self._client.aclose()
94
+
95
+ async def info(self) -> ServiceInfo:
96
+ """The service description: pixel type, size, extent, largest image."""
97
+ response = await self._send("GET", self.url, params={"f": "json"})
98
+ return parse_info(response.content)
99
+
100
+ async def attribute_table(self) -> list[dict[str, Any]]:
101
+ """The raster attribute table: what each pixel value means."""
102
+ response = await self._send("GET", f"{self.url}/rasterAttributeTable", params={"f": "json"})
103
+ return parse_attribute_table(response.content)
104
+
105
+ async def export(
106
+ self,
107
+ grid: Grid,
108
+ dest: Path,
109
+ *,
110
+ pixel_type: str = "U8",
111
+ interpolation: Interpolation = "RSP_NearestNeighbor",
112
+ dtype: str = "uint8",
113
+ nodata: float | None = 255,
114
+ valid_range: tuple[float, float] | None = None,
115
+ tile_px: int = DEFAULT_TILE_PX,
116
+ concurrency: int = 3,
117
+ on_tile: Callable[[int, int], None] | None = None,
118
+ ) -> Export:
119
+ """``grid`` of this service as a GeoTIFF at ``dest``, written atomically.
120
+
121
+ Tiles are requested ``concurrency`` at a time and pasted as they
122
+ arrive; ``on_tile(done, total)`` reports progress. ``valid_range``
123
+ counts the valid pixels (e.g. ``(0, 100)`` for a percentage layer
124
+ that uses 254 and 255 as sentinels); without it, every pixel that is
125
+ not ``nodata`` counts.
126
+ """
127
+ tiles = plan(grid, tile_px=tile_px)
128
+ gate = asyncio.Semaphore(concurrency)
129
+
130
+ async def one(tile: Tile) -> tuple[Tile, bytes]:
131
+ params = export_params(
132
+ tile.bounds(grid),
133
+ width=tile.width,
134
+ height=tile.height,
135
+ crs=grid.crs,
136
+ pixel_type=pixel_type,
137
+ interpolation=interpolation,
138
+ )
139
+ async with gate:
140
+ response = await self._send(
141
+ "GET", f"{self.url}/exportImage", params=params, timeout=self._timeout_s
142
+ )
143
+ ctype = response.headers.get("content-type", "")
144
+ return tile, check_image(response.status_code, ctype, response.content)
145
+
146
+ with Mosaic(dest, grid, dtype=dtype, nodata=nodata, valid_range=valid_range) as mosaic:
147
+ pending = [asyncio.ensure_future(one(t)) for t in tiles]
148
+ try:
149
+ for done, future in enumerate(asyncio.as_completed(pending), 1):
150
+ tile, image = await future
151
+ await asyncio.to_thread(mosaic.paste, tile, image)
152
+ if on_tile is not None:
153
+ on_tile(done, len(tiles))
154
+ except BaseException:
155
+ for p in pending:
156
+ p.cancel()
157
+ raise
158
+ return Export(
159
+ path=dest,
160
+ tiles=len(tiles),
161
+ width=grid.width,
162
+ height=grid.height,
163
+ valid_px=mosaic.valid_px,
164
+ )
165
+
166
+ async def _send(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
167
+ if self._send_hook is not None:
168
+ return await self._send_hook(method, url, **kwargs)
169
+ assert self._client is not None
170
+ for attempt in range(self._retries + 1):
171
+ try:
172
+ response = await self._client.request(method, url, **kwargs)
173
+ except httpx.TransportError:
174
+ if attempt == self._retries:
175
+ raise
176
+ else:
177
+ if response.status_code not in _RETRY_STATUS:
178
+ return response
179
+ if attempt == self._retries:
180
+ response.raise_for_status()
181
+ await self._sleep(self._backoff_s * 2**attempt)
182
+ raise AssertionError("unreachable") # pragma: no cover
183
+
184
+
185
+ async def list_services(folder_url: str, client: httpx.AsyncClient | None = None) -> list[str]:
186
+ """The ImageServer names in a folder (``…/rest/services/<folder>``)."""
187
+ own = client is None
188
+ http = client or httpx.AsyncClient(follow_redirects=True)
189
+ try:
190
+ response = await http.get(folder_url.rstrip("/"), params={"f": "json"})
191
+ response.raise_for_status()
192
+ return parse_services(response.content)
193
+ finally:
194
+ if own:
195
+ await http.aclose()
@@ -0,0 +1,7 @@
1
+ """The one exception this package raises for answers it cannot use."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ImageServerError(Exception):
7
+ """The ImageServer answered, but not with what was asked for."""
@@ -0,0 +1,85 @@
1
+ """The target raster: a grid whose edges sit on whole pixels.
2
+
3
+ Every tile of an export is a window of this grid, so its bounds are exact
4
+ multiples of the resolution and the service never has to resample to fit
5
+ the size asked for. Resampling a band that carries sentinels (255 "no data"
6
+ next to 0-100 percentages) can invent valid values exactly where data is
7
+ missing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from dataclasses import dataclass
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ from affine import Affine
18
+
19
+ Bounds = tuple[float, float, float, float]
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class Grid:
24
+ """``width`` x ``height`` pixels of ``res`` units, top-left at ``(left, top)``."""
25
+
26
+ crs: int
27
+ left: float
28
+ top: float
29
+ res: float
30
+ width: int
31
+ height: int
32
+
33
+ @property
34
+ def bounds(self) -> Bounds:
35
+ return (
36
+ self.left,
37
+ self.top - self.height * self.res,
38
+ self.left + self.width * self.res,
39
+ self.top,
40
+ )
41
+
42
+ @property
43
+ def transform(self) -> Affine:
44
+ from rasterio.transform import from_origin
45
+
46
+ transform: Affine = from_origin(self.left, self.top, self.res, self.res)
47
+ return transform
48
+
49
+ @classmethod
50
+ def snap(cls, bounds: Bounds, *, res: float, crs: int) -> Grid:
51
+ """The smallest grid of ``res`` that contains ``bounds`` (in ``crs``).
52
+
53
+ Edges grow outward to the next multiple of ``res``: rounding would
54
+ cut a strip off the area asked for.
55
+ """
56
+ x0, y0, x1, y1 = bounds
57
+ if not (x0 < x1 and y0 < y1):
58
+ raise ValueError(f"bounds are (xmin, ymin, xmax, ymax): {bounds}")
59
+ if res <= 0:
60
+ raise ValueError("res must be positive")
61
+ left = math.floor(x0 / res) * res
62
+ bottom = math.floor(y0 / res) * res
63
+ right = math.ceil(x1 / res) * res
64
+ top = math.ceil(y1 / res) * res
65
+ return cls(
66
+ crs=crs,
67
+ left=left,
68
+ top=top,
69
+ res=res,
70
+ width=round((right - left) / res),
71
+ height=round((top - bottom) / res),
72
+ )
73
+
74
+ @classmethod
75
+ def from_lonlat(cls, bbox: Bounds, *, res: float, crs: int = 3035) -> Grid:
76
+ """The grid covering a longitude/latitude box, in ``crs`` (LAEA Europe by default).
77
+
78
+ The box is reprojected with densified edges, not by its four corners:
79
+ in an equal-area projection the sides of a geographic box curve, and
80
+ the southernmost point is not a corner. Measured on Italy, the corners
81
+ alone cut 6.8 km off the southern edge (Lampedusa outside the raster).
82
+ """
83
+ from rasterio.warp import transform_bounds
84
+
85
+ return cls.snap(transform_bounds(4326, crs, *bbox, densify_pts=101), res=res, crs=crs)
@@ -0,0 +1,103 @@
1
+ """Writing tiles into one GeoTIFF that exists only when it is whole."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from types import TracebackType
7
+ from typing import Any
8
+
9
+ from imageserver_export.errors import ImageServerError
10
+ from imageserver_export.grid import Grid
11
+ from imageserver_export.tiles import Tile
12
+
13
+
14
+ class Mosaic:
15
+ """A tiled, compressed GeoTIFF on ``grid``, written to ``<path>.part``.
16
+
17
+ Used as a context manager: on a clean exit the ``.part`` is renamed to
18
+ ``path``; on an exception it is deleted. A half-written raster that a
19
+ later reader takes for a whole one is worse than no raster.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ path: Path,
25
+ grid: Grid,
26
+ *,
27
+ dtype: str = "uint8",
28
+ nodata: float | None = 255,
29
+ valid_range: tuple[float, float] | None = None,
30
+ ) -> None:
31
+ self.path = path
32
+ self.partial = path.with_name(f"{path.name}.part")
33
+ self.grid = grid
34
+ self.dtype = dtype
35
+ self.nodata = nodata
36
+ self.valid_range = valid_range
37
+ self.valid_px = 0
38
+ self._dst: Any = None
39
+
40
+ def __enter__(self) -> Mosaic:
41
+ import rasterio
42
+
43
+ self.path.parent.mkdir(parents=True, exist_ok=True)
44
+ self._dst = rasterio.open(
45
+ self.partial,
46
+ "w",
47
+ driver="GTiff",
48
+ width=self.grid.width,
49
+ height=self.grid.height,
50
+ count=1,
51
+ dtype=self.dtype,
52
+ crs=f"EPSG:{self.grid.crs}",
53
+ transform=self.grid.transform,
54
+ nodata=self.nodata,
55
+ tiled=True,
56
+ blockxsize=256,
57
+ blockysize=256,
58
+ compress="deflate",
59
+ BIGTIFF="IF_SAFER",
60
+ )
61
+ return self
62
+
63
+ def __exit__(
64
+ self,
65
+ exc_type: type[BaseException] | None,
66
+ exc: BaseException | None,
67
+ tb: TracebackType | None,
68
+ ) -> None:
69
+ if self._dst is not None:
70
+ self._dst.close()
71
+ if exc_type is None:
72
+ self.partial.replace(self.path)
73
+ else:
74
+ self.partial.unlink(missing_ok=True)
75
+
76
+ def paste(self, tile: Tile, image: bytes) -> int:
77
+ """Write one tile into its window; the number of valid pixels in it.
78
+
79
+ A tile whose size differs from the one asked for raises: pasting it
80
+ would shift the data by however many pixels the service got wrong.
81
+ """
82
+ import numpy as np
83
+ from rasterio.io import MemoryFile
84
+ from rasterio.windows import Window
85
+
86
+ with MemoryFile(image) as mem, mem.open() as src:
87
+ band = src.read(1)
88
+ if band.shape != (tile.height, tile.width):
89
+ raise ImageServerError(
90
+ f"the service returned {band.shape[1]}x{band.shape[0]} pixels "
91
+ f"for a {tile.width}x{tile.height} tile"
92
+ )
93
+ band = band.astype(self.dtype, copy=False)
94
+ self._dst.write(band, 1, window=Window(tile.col_off, tile.row_off, tile.width, tile.height))
95
+ if self.valid_range is not None:
96
+ low, high = self.valid_range
97
+ valid = int(np.count_nonzero((band >= low) & (band <= high)))
98
+ elif self.nodata is not None:
99
+ valid = int(np.count_nonzero(band != self.nodata))
100
+ else:
101
+ valid = int(band.size)
102
+ self.valid_px += valid
103
+ return valid
File without changes
@@ -0,0 +1,55 @@
1
+ """``exportImage``: the query and the check of the answer, pure."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from imageserver_export.errors import ImageServerError
8
+ from imageserver_export.grid import Bounds
9
+
10
+ #: ``RSP_NearestNeighbor`` is the only safe choice for thematic or
11
+ #: sentinel-carrying layers; ``RSP_BilinearInterpolation`` only for continuous ones.
12
+ Interpolation = Literal[
13
+ "RSP_NearestNeighbor",
14
+ "RSP_BilinearInterpolation",
15
+ "RSP_CubicConvolution",
16
+ "RSP_Majority",
17
+ ]
18
+
19
+
20
+ def export_params(
21
+ bounds: Bounds,
22
+ *,
23
+ width: int,
24
+ height: int,
25
+ crs: int,
26
+ pixel_type: str = "U8",
27
+ interpolation: Interpolation = "RSP_NearestNeighbor",
28
+ ) -> dict[str, str]:
29
+ """The query string of ``GET <service>/exportImage`` for one tile, as a GeoTIFF."""
30
+ return {
31
+ "bbox": ",".join(f"{v:.6f}" for v in bounds),
32
+ "bboxSR": str(crs),
33
+ "imageSR": str(crs),
34
+ "size": f"{width},{height}",
35
+ "format": "tiff",
36
+ "pixelType": pixel_type,
37
+ "interpolation": interpolation,
38
+ "f": "image",
39
+ }
40
+
41
+
42
+ def check_image(status_code: int, content_type: str, body: bytes) -> bytes:
43
+ """The GeoTIFF bytes, or :class:`ImageServerError` with the service's message.
44
+
45
+ An ImageServer answers a bad request with **HTTP 200 and a JSON error**:
46
+ without this check the JSON would reach the TIFF reader as a corrupt
47
+ file, hiding the message that says what was wrong.
48
+ """
49
+ if status_code != 200:
50
+ raise ImageServerError(f"exportImage failed (HTTP {status_code}): {body[:200]!r}")
51
+ if "json" in content_type or body[:1] == b"{":
52
+ raise ImageServerError(
53
+ f"exportImage refused the request: {body[:300].decode('utf-8', 'replace')}"
54
+ )
55
+ return body
@@ -0,0 +1,101 @@
1
+ """What an ImageServer says about itself: pure parsers of its JSON.
2
+
3
+ ``GET <service>?f=json`` describes the raster (pixel type, bands, pixel
4
+ size, extent, the largest image one request may ask for);
5
+ ``GET <service>/rasterAttributeTable?f=json`` maps the pixel values of a
6
+ thematic layer to their meaning; ``GET <folder>?f=json`` lists the services.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from imageserver_export.errors import ImageServerError
16
+
17
+ #: The European Environment Agency's open ImageServer: the Copernicus Land
18
+ #: Monitoring Service layers (imperviousness, tree cover, grassland, water
19
+ #: and wetness, small woody features...), with no account.
20
+ EEA_URL = "https://image.discomap.eea.europa.eu/arcgis/rest/services"
21
+ EEA_FOLDER = "GioLandPublic"
22
+
23
+
24
+ def eea(name: str) -> str:
25
+ """The URL of one EEA service: ``eea("HRL_ImperviousnessDensity_2018")``."""
26
+ return f"{EEA_URL}/{EEA_FOLDER}/{name}/ImageServer"
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class ServiceInfo:
31
+ """The parts of a service description an export needs."""
32
+
33
+ name: str
34
+ pixel_type: str
35
+ band_count: int
36
+ pixel_size: tuple[float, float]
37
+ #: The largest image one ``exportImage`` may return, in pixels.
38
+ max_width: int
39
+ max_height: int
40
+ #: EPSG code of the service's own CRS.
41
+ crs: int | None
42
+ extent: tuple[float, float, float, float]
43
+ has_attribute_table: bool
44
+ copyright: str
45
+
46
+
47
+ def _json(body: bytes | str) -> Any:
48
+ try:
49
+ data = json.loads(body)
50
+ except ValueError as exc:
51
+ raise ImageServerError(f"the service did not return JSON: {str(body)[:200]!r}") from exc
52
+ if isinstance(data, dict) and "error" in data:
53
+ error = data["error"]
54
+ message = error.get("message") if isinstance(error, dict) else error
55
+ raise ImageServerError(f"the service refused: {message}")
56
+ return data
57
+
58
+
59
+ def parse_info(body: bytes | str) -> ServiceInfo:
60
+ """A :class:`ServiceInfo` from ``<service>?f=json``."""
61
+ data = _json(body)
62
+ try:
63
+ sr = data.get("spatialReference") or {}
64
+ extent = data["extent"]
65
+ return ServiceInfo(
66
+ name=str(data.get("name") or ""),
67
+ pixel_type=str(data["pixelType"]),
68
+ band_count=int(data.get("bandCount") or 1),
69
+ pixel_size=(float(data["pixelSizeX"]), float(data["pixelSizeY"])),
70
+ max_width=int(data.get("maxImageWidth") or 4000),
71
+ max_height=int(data.get("maxImageHeight") or 4000),
72
+ crs=sr.get("latestWkid") or sr.get("wkid"),
73
+ extent=(
74
+ float(extent["xmin"]),
75
+ float(extent["ymin"]),
76
+ float(extent["xmax"]),
77
+ float(extent["ymax"]),
78
+ ),
79
+ has_attribute_table=bool(data.get("hasRasterAttributeTable")),
80
+ copyright=str(data.get("copyrightText") or ""),
81
+ )
82
+ except (KeyError, TypeError, ValueError) as exc:
83
+ raise ImageServerError(f"not an ImageServer description: missing {exc}") from exc
84
+
85
+
86
+ def parse_attribute_table(body: bytes | str) -> list[dict[str, Any]]:
87
+ """The rows of ``<service>/rasterAttributeTable?f=json``, as plain dicts."""
88
+ data = _json(body)
89
+ features = data.get("features") if isinstance(data, dict) else None
90
+ if not isinstance(features, list):
91
+ raise ImageServerError("not a raster attribute table")
92
+ return [dict(f.get("attributes") or {}) for f in features]
93
+
94
+
95
+ def parse_services(body: bytes | str) -> list[str]:
96
+ """The ImageServer names of a folder listing (``<folder>?f=json``)."""
97
+ data = _json(body)
98
+ services = data.get("services") if isinstance(data, dict) else None
99
+ if not isinstance(services, list):
100
+ raise ImageServerError("not a folder listing")
101
+ return [str(s["name"]) for s in services if s.get("type") == "ImageServer"]
@@ -0,0 +1,43 @@
1
+ """Cutting a grid into requests the service accepts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from imageserver_export.grid import Bounds, Grid
8
+
9
+ #: Default tile side: well under the 4,100 px most services allow, so one
10
+ #: failed request costs a few MB, not the whole export.
11
+ DEFAULT_TILE_PX = 2048
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class Tile:
16
+ """A window of the target grid, in pixels."""
17
+
18
+ col_off: int
19
+ row_off: int
20
+ width: int
21
+ height: int
22
+
23
+ def bounds(self, grid: Grid) -> Bounds:
24
+ """The tile's box in the grid's CRS: whole pixels by construction."""
25
+ x0 = grid.left + self.col_off * grid.res
26
+ y1 = grid.top - self.row_off * grid.res
27
+ return (x0, y1 - self.height * grid.res, x0 + self.width * grid.res, y1)
28
+
29
+
30
+ def plan(grid: Grid, *, tile_px: int = DEFAULT_TILE_PX) -> list[Tile]:
31
+ """Tiles that cover the grid exactly once, edge tiles clamped to the grid."""
32
+ if tile_px < 1:
33
+ raise ValueError("tile_px must be ≥ 1")
34
+ return [
35
+ Tile(
36
+ col_off=col,
37
+ row_off=row,
38
+ width=min(tile_px, grid.width - col),
39
+ height=min(tile_px, grid.height - row),
40
+ )
41
+ for row in range(0, grid.height, tile_px)
42
+ for col in range(0, grid.width, tile_px)
43
+ ]
@@ -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).
@@ -0,0 +1,13 @@
1
+ imageserver_export/__init__.py,sha256=_TUv8maB-xQ3Trl7H9WYzU7HOkXiqf7S3hJG1Dt--RI,1364
2
+ imageserver_export/client.py,sha256=2jVzEetiw-q-gaCnDklkmAGL6wFR6Xx9DHfAAOy8_0k,7050
3
+ imageserver_export/errors.py,sha256=jqF61ddCB1PwAdGdQ3I6hvxbbB4NzVK9nIDTSlqXzRA,213
4
+ imageserver_export/grid.py,sha256=GAlHwexVjiYpFwfzIvAvRgdJwVdbSiDFYo692IDqyTc,2792
5
+ imageserver_export/mosaic.py,sha256=H76on1E4wivlHJBQFNlFAiBYAm10Zs-THT7D_MXcKMY,3375
6
+ imageserver_export/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ imageserver_export/request.py,sha256=Kgo9AGXdqkWOIzPf6csnPoD8zM-wMRrUgaSGBltDaCI,1787
8
+ imageserver_export/service.py,sha256=gBzVyM-fBryuqDeiOWoVJMr9vxhpTkDEyTb7KZk6rIY,3865
9
+ imageserver_export/tiles.py,sha256=dNDoXBOSEJbS2APY_7EQqUOt4R63lWc223HKVECthZQ,1317
10
+ imageserver_export-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
11
+ imageserver_export-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
12
+ imageserver_export-0.1.0.dist-info/METADATA,sha256=aYotOckhM8ieHv8ElCPVVpY8Aq5vS5zp7LU-LyJhU4s,15944
13
+ imageserver_export-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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
+