Metadata-Version: 2.5
Name: korp-map-client
Version: 0.2.1
Summary: Python data client for the korp-map server: OpenStreetMap rows as Arrow tables, geocoding
Project-URL: Source, https://gunnar.rs/nordisk/korp-map
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Keywords: arrow,geocoding,geoparquet,map,openstreetmap
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pyarrow>=23.0.1
Provides-Extra: all
Requires-Dist: brotli>=1.2.1; extra == 'all'
Requires-Dist: geopandas>=1.1.2; extra == 'all'
Requires-Dist: shapely>=2.0; extra == 'all'
Requires-Dist: zstandard>=0.18; extra == 'all'
Provides-Extra: br
Requires-Dist: brotli>=1.2.1; extra == 'br'
Provides-Extra: geo
Requires-Dist: geopandas>=1.1.2; extra == 'geo'
Requires-Dist: shapely>=2.0; extra == 'geo'
Provides-Extra: test
Requires-Dist: pytest>=9.0.3; extra == 'test'
Provides-Extra: zstd
Requires-Dist: zstandard>=0.18; extra == 'zstd'
Description-Content-Type: text/markdown

# korp-map-client (Python)

A Python data client for the **korp-map server**: OpenStreetMap rows for a bounding box
as Arrow tables (or GeoDataFrames), plus address geocoding. For notebooks and analysis;
it speaks the map wire, contract v1.2 (HTTP). Formerly published as `korp-map`
(`import korp_map`); that name is now a deprecated shim that installs this package.

## Try it

The public server is **https://karta.gunnar.rs** (all of Sweden from OpenStreetMap),
and it is the default, so `Client()` needs no URL. Real output:

```python
>>> import korp_map_client
>>> c = korp_map_client.Client()          # https://karta.gunnar.rs
>>> c.regions()
[{'name': 'sweden', 'bbox': [10.59326171875, 55.13720703125, 24.177734375, 69.06005859375], 'data_version': 'files-aff34692ba7c0dd8'}]

>>> res = c.map("lines", bbox=(18.05, 59.32, 18.08, 59.34), lod=14)   # Stockholm, Gamla stan
>>> res.num_rows, res.truncated, res.geometry_source
(3508, False, 'full')
>>> res.table.column_names
['id', 'tags', 'min_zoom', 'geometry']

>>> c.geocode("Drottninggatan 53 Stockholm", max=1)
[{'street': 'Drottninggatan', 'housenumber': '53', 'city': 'Stockholm', 'postcode': '', 'lon': 18.0618896484375, 'lat': 59.3333740234375, 'source': 2453165069, 'score': 110}]

>>> c.revgeocode(18.07, 59.33)
{'street': 'Jakobs Torg', 'housenumber': '4', 'city': 'Stockholm', 'postcode': '', 'lon': 18.0701904296875, 'lat': 59.3299560546875, 'source': 2336793900, 'score': 0, 'distance_m': 11.85489947514537}
```

## Install

```sh
pip install korp-map-client             # pyarrow + httpx
pip install 'korp-map-client[geo]'      # + geopandas, shapely: map_gdf()
pip install 'korp-map-client[zstd,br]'  # + zstd / brotli Content-Encoding
pip install 'korp-map-client[all]'
```

## Use

```python
import korp_map_client

c = korp_map_client.Client("https://karta.gunnar.rs")  # the default; region = the first served one
c.regions()        # [{"name": "sweden", "bbox": [...], "data_version": "files-..."}]

res = c.map("lines", bbox=(17.9, 59.2, 18.2, 59.4), lod=14)
res.table          # pyarrow.Table; schema metadata kept (geo, data_version, ...)
res.truncated, res.data_version, res.geometry_source, res.row_groups_scanned
res.to_pandas()

gdf = c.map_gdf("areas", bbox=(17.9, 59.2, 18.2, 59.4), lod=12)   # GeoDataFrame, EPSG:4326
gdf.attrs["truncated"]

c.geocode("Drottninggatan 53 Stockholm", max=5)   # [{"street", "housenumber", "city", "postcode",
                                                  #   "lon", "lat", "source", "score"}, ...]
c.revgeocode(18.07, 59.33)                        # {..., "distance_m": 11.9} or None
```

* `kind` is `points` (tagged nodes), `lines` or `areas`.
* `bbox` is `(minlon, minlat, maxlon, maxlat)`; `lod` (0 to 20 or so) keeps rows with
  `min_zoom <= lod` and picks the geometry detail (`geometry_source`: z6, z9, z12, full).
* `max=K` caps the rows; the reply then says `truncated=True`.
* `compress="zstd"` asks for zstd Arrow IPC buffers (pyarrow decodes them).
* `tags` is a JSON string per row: `res.to_pandas().tags.map(json.loads)`.
* `MapResult` speaks the Arrow stream protocol: `polars.from_arrow(res)`, `duckdb.sql("from res")`.
* `c.map_table(...)` gives the bare `pyarrow.Table`.
* `korp_map_client.geometry_to_shapely(col)` turns a separated-layout geometry column
  (`struct<x, y>` in lists, GeoParquet 1.1) into shapely geometries, vectorised.

## Files (`/v1/files`)

The server also offers its files for download: the `native` set (the GeoParquet 1.1
files it serves from) and `geoparquet2` (GeoParquet 2.0 points, lines, areas).

```python
c.files()      # [{"name", "set", "format", "size", "sha256", "url", "last_modified"}, ...]
url = c.file_url("geoparquet2/lines.parquet")  # absolute URL; a bare name works when unique
duckdb.sql(f"select count(*) from read_parquet('{url}')")   # DuckDB httpfs
gdal_path = "/vsicurl/" + url                               # GDAL / OGR

c.download("native/ways.multilinestring.parquet", "data/", progress=True)
# streams to data/<name>.part, resumes a broken download with HTTP Range,
# checks size + sha256, then renames into place; an intact file is not fetched again

t = c.read_parquet("native/ways.multilinestring.parquet", bbox=(18.05, 59.32, 18.08, 59.34),
                   columns=["id", "tags", "geometry"])
c.last_read   # {"row_groups_read": 25, "row_groups_total": 443, "bytes_fetched": 15661663, ...}
gdf = c.read_gdf("geoparquet2/lines.parquet", bbox=(18.05, 59.32, 18.08, 59.34))
```

`read_parquet` reads over HTTP Range requests (through the client's own connection,
so `https`, `verify=` and headers apply) and fetches only the footer and the row groups
whose statistics touch `bbox`: the covering `bbox` column (GeoParquet 1.1) or the
geometry column's geospatial statistics (GeoParquet 2.0). Rows are then cut to those
whose bbox touches `bbox` (by the covering column; for 2.0 WKB files by the geometry
bounds when shapely is installed, else whole row groups). `read_gdf` gives a
GeoDataFrame for WKB (2.0) and separated (native) geometry, CRS from the file.

Errors raise `korp_map_client.KorpMapError`; `.code` is the wire code (`korp-map-108` for an
unknown region, ...) and `.status` the HTTP status. Replies compressed with gzip, br or
zstd are decoded transparently; `Accept-Encoding` names what is installed. `https://`
URLs work; extra keyword arguments go to `httpx.Client` (`verify=`, `proxy=`, ...).

## Test

```sh
pip install -e '.[all,test]'
pytest                                          # the fake server
KORP_MAP_URL=https://karta.gunnar.rs pytest -m live   # a running server (Stockholm queries)
# tests/test_live_files.py skips while the server has no /v1/files;
# KORP_MAP_FILES=1 makes that a failure
```

License: MIT OR Apache-2.0.
