Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

demo/sverigekartan/app.py

"""Sverigekartan: the korp-map server's Sweden map in a Streamlit page.

The map is the facett-map viewer: a wasm bundle that fetches every viewport from
the map server itself, so the server URL it gets must be one the BROWSER reaches
(the page's own https origin; see origin.py). Address search and reverse lookup run here in Python
through korp-map-client, against SVERIGEKARTAN_MAP_SERVER_INTERNAL (same host, no
hairpin through the router).

The same page serves a v1.2 server (lod) and a v3 server (contract korp-map-v3.0,
res): the examples and the file list follow the server's contract. A v3 cut without
an address index answers geocode with korp-map-116; with
SVERIGEKARTAN_ADDRESS_FALLBACK set, addresses then come from that server instead
(and the examples name SVERIGEKARTAN_ADDRESS_FALLBACK_PUBLIC).

    streamlit run app.py
"""

from __future__ import annotations

import logging
import os

import facett_map
import httpx
import korp_map_client
import streamlit as st

import data_files
import origin

# The browser's map server: the page's own public origin (see origin.py).
PUBLIC_HOSTS = origin.public_hosts(os.environ.get("SVERIGEKARTAN_PUBLIC_HOSTS"))
MAP_SERVER = origin.map_server_for(
    st.context.headers.get("Host"), os.environ.get("SVERIGEKARTAN_MAP_SERVER"), PUBLIC_HOSTS
)
MAP_SERVER_INTERNAL = os.environ.get("SVERIGEKARTAN_MAP_SERVER_INTERNAL", "http://127.0.0.1:8765").rstrip("/")
REGION = "sweden"
MAP_HEIGHT = 560
# Half-size of the view opened around an address, in degrees (about 600 m x 450 m).
HALF_LON = 0.006
HALF_LAT = 0.002
# Where the 3D view opens before any address is picked (Sergels torg).
STOCKHOLM = (18.0686, 59.3324)
# Below this zoom a camera is a country/region view, too far out to open the 3D city on.
CITY_ZOOM = 11.0
# A click farther than this from any address says so instead of naming a far one.
NEAR_M = 1000.0
# Where addresses come from while the map server's cut has no address index (unset:
# nowhere else), and that server's public name for the examples.
ADDRESS_FALLBACK = (os.environ.get("SVERIGEKARTAN_ADDRESS_FALLBACK") or "").rstrip("/") or None
ADDRESS_FALLBACK_PUBLIC = (
    os.environ.get("SVERIGEKARTAN_ADDRESS_FALLBACK_PUBLIC") or "https://karta.gunnar.rs"
).rstrip("/")
# The region's file index: read here (internal), linked for the browser (public).
FILES_INDEX = os.environ.get("SVERIGEKARTAN_FILES_INDEX", f"{MAP_SERVER_INTERNAL}/v1/files/{REGION}/")
FILES_PUBLIC = f"{MAP_SERVER}/v1/files/{REGION}/"
# The snippets' example bbox: central Stockholm (minlon, minlat, maxlon, maxlat).
SNIPPET_BBOX = (17.98, 59.30, 18.12, 59.35)
# The native Rust viewer (crates/sverigekartan, egui + wgpu): install and run. None hides
# the block.
EGUI_HOWTO: str | None = "cargo install sverigekartan\nsverigekartan"
# The offline wheel set: pyarrow >= 23 (korp-map-client) ships manylinux_2_28 wheels only.
WHEEL_PLATFORMS = "--platform manylinux2014_x86_64 --platform manylinux_2_28_x86_64"

log = logging.getLogger("sverigekartan")


@st.cache_resource
def client() -> korp_map_client.Client:
    return korp_map_client.Client(MAP_SERVER_INTERNAL, region=REGION, timeout=15.0)


@st.cache_resource
def fallback_client() -> korp_map_client.Client | None:
    if not ADDRESS_FALLBACK:
        return None
    return korp_map_client.Client(ADDRESS_FALLBACK, region=REGION, timeout=15.0)


@st.cache_data(ttl=300, show_spinner=False)
def contract_v3() -> bool:
    """True when the map server speaks contract korp-map-v3.0 (map queries take res)."""
    try:
        r = httpx.get(f"{MAP_SERVER_INTERNAL}/openapi.json", timeout=10.0)
        version = str(r.json().get("info", {}).get("version", ""))
        return int(version.split(".")[0]) >= 3
    except (httpx.HTTPError, ValueError, AttributeError):
        return data_version().startswith("v3-")


@st.cache_data(ttl=300, show_spinner=False)
def own_addresses() -> bool:
    """False while the map server's cut has no address index (korp-map-116)."""
    try:
        client().revgeocode(*STOCKHOLM)
    except korp_map_client.KorpMapError as e:
        return getattr(e, "code", None) != "korp-map-116"
    return True


def address_client() -> korp_map_client.Client:
    fb = fallback_client()
    return fb if fb is not None and not own_addresses() else client()


def address_public() -> str:
    return ADDRESS_FALLBACK_PUBLIC if fallback_client() is not None and not own_addresses() else MAP_SERVER


@st.cache_data(ttl=300, show_spinner=False)
def data_version() -> str:
    try:
        for r in client().regions():
            if r.get("name") == REGION:
                return str(r.get("data_version") or "?")
    except korp_map_client.KorpMapError:
        pass
    return "?"


@st.cache_data(ttl=600, show_spinner=False)
def geocode(q: str) -> list[dict]:
    # One row per address as shown: the same address from two sources is one hit
    # (two equal labels would also make the radio below select the wrong one).
    out, seen = [], set()
    for h in address_client().geocode(q, max=8):
        if label(h) not in seen:
            seen.add(label(h))
            out.append(h)
    return out[:5]


@st.cache_data(ttl=120, show_spinner=False)
def file_index(index_url: str, public_base: str) -> list[data_files.DataFile] | None:
    """The region's Parquet files, or None while the server has no file index."""
    try:
        r = httpx.get(index_url, timeout=10.0, follow_redirects=True)
    except httpx.HTTPError:
        return None
    if r.status_code != 200:
        return None
    files = data_files.parse_index(r.text, r.headers.get("content-type", ""), str(r.url), public_base)
    return files or None


def sv_size(n: int | None) -> str:
    return data_files.human_size(n).replace(".", ",")


def label(hit: dict) -> str:
    street = " ".join(str(x) for x in (hit.get("street"), hit.get("housenumber")) if x)
    place = " ".join(str(x) for x in (hit.get("postcode"), hit.get("city")) if x)
    return ", ".join(x for x in (street, place) if x) or f"{hit['lon']:.5f}, {hit['lat']:.5f}"


def bbox_around(lon: float, lat: float) -> tuple[float, float, float, float]:
    return (lon - HALF_LON, lat - HALF_LAT, lon + HALF_LON, lat + HALF_LAT)


def go_to(lon: float, lat: float, what: str) -> None:
    n = st.session_state.get("view_n", 0) + 1
    st.session_state.view = {"bbox": bbox_around(lon, lat), "what": what, "n": n}
    st.session_state.view_n = n
    # The camera reported so far is from before this address: a mode switch before the
    # new viewer has reported opens on the address, not on that older place.
    st.session_state.cam = None


st.set_page_config(page_title="Sverigekartan", page_icon="🗺️", layout="wide")
st.session_state.setdefault("view", None)
st.session_state.setdefault("view_n", 0)
st.session_state.setdefault("hits", None)

st.title("Sverigekartan")
st.caption("Sverige från OpenStreetMap, ritad i webbläsaren med WebGPU.")

# -- address search --------------------------------------------------------------
with st.form("search", border=False, enter_to_submit=True):
    c_q, c_go = st.columns([5, 1], vertical_alignment="bottom")
    q = c_q.text_input(
        "Sök adress",
        placeholder="Drottninggatan 53 Stockholm",
        key="q",
    )
    searched = c_go.form_submit_button("Sök", width="stretch")

if searched:
    if q.strip():
        try:
            st.session_state.hits = geocode(q.strip())
        except korp_map_client.KorpMapError as e:
            st.session_state.hits = None
            log.warning("geocode %r: %s", q, e)
            st.error("Sökningen misslyckades. Försök igen.")
        else:
            hits = st.session_state.hits
            st.session_state.hit_pick = 0
            if hits:
                go_to(hits[0]["lon"], hits[0]["lat"], label(hits[0]))
    else:
        st.session_state.hits = None

hits = st.session_state.hits
if hits is not None:
    if not hits:
        st.info("Ingen träff")
    else:

        def _picked() -> None:
            h = hits[st.session_state.hit_pick]
            go_to(h["lon"], h["lat"], label(h))

        st.radio(
            "Träffar",
            options=range(len(hits)),
            format_func=lambda i: label(hits[i]),
            key="hit_pick",
            on_change=_picked,
        )

# -- the map ---------------------------------------------------------------------
# facett-map returns the viewer's state ({"mode", "bbox", "center", "zoom",
# "clicked": {"lon", "lat", "seq"} | None}, None until it has drawn) and opens on
# bbox= or center=/zoom=.
mode = st.segmented_control("Vy", options=["2D", "3D"], default="2D", key="mode") or "2D"
m = mode.lower()
# One mount per (mode, picked address): a new mount gets a new key, so the component
# starts a fresh viewer on what it is opened with; reruns of the same mount pass the
# same payload, so the live viewer is never pulled back to where it opened.
mount = st.session_state.get("mount")
if mount is None or mount["mode"] != m or mount["view_n"] != st.session_state.view_n:
    cam = st.session_state.get("cam")
    view = st.session_state.view
    new_address = view is not None and (mount is None or mount["view_n"] != st.session_state.view_n)
    first_3d_far = m == "3d" and not st.session_state.get("opened_3d") and (cam is None or cam["zoom"] < CITY_ZOOM)
    if new_address:
        o = {"bbox": view["bbox"], "what": view["what"]}
    elif cam is not None and not (first_3d_far and view is None):
        # Switching 2D <-> 3D: open where the other viewer was.
        o = {"center": cam["center"], "zoom": cam["zoom"], "what": None}
    elif view is not None:
        o = {"bbox": view["bbox"], "what": view["what"]}
    elif m == "3d":
        # The 3D city opened on the middle of Sweden is forest; open it on Stockholm.
        o = {"bbox": bbox_around(*STOCKHOLM), "what": "Stockholm, Sergels torg"}
    else:
        o = {"what": None}
    n = mount["n"] + 1 if mount else 0
    mount = {"n": n, "mode": m, "view_n": st.session_state.view_n, "open": o}
    st.session_state.mount = mount
if m == "3d":
    st.session_state.opened_3d = True
key = f"map-{m}-{mount['n']}"
o = mount["open"]
if o.get("what"):
    st.caption(f"Visar: {o['what']}")
state = facett_map.map(
    server=MAP_SERVER,
    region=REGION,
    mode=m,
    bbox=o.get("bbox"),
    center=o.get("center"),
    zoom=o.get("zoom"),
    height=MAP_HEIGHT,
    key=key,
)

if isinstance(state, dict):
    c, z = state.get("center"), state.get("zoom")
    if c is not None and z is not None:
        st.session_state.cam = {"center": (float(c[0]), float(c[1])), "zoom": float(z), "mode": state.get("mode", m)}
    clicked = state.get("clicked")
    # seq counts clicks per viewer: a new mount (key) starts again at 1.
    click_id = (key, clicked.get("seq")) if clicked else None
    if clicked and click_id != st.session_state.get("click_id"):
        st.session_state.click_id = click_id
        try:
            hit = address_client().revgeocode(float(clicked["lon"]), float(clicked["lat"]))
        except korp_map_client.KorpMapError as e:
            log.warning("revgeocode %s: %s", clicked, e)
            st.session_state.click_result = {"error": str(e)}
        else:
            st.session_state.click_result = {"hit": hit, "at": (float(clicked["lon"]), float(clicked["lat"]))}

r = st.session_state.get("click_result")
if r is None:
    st.caption("Klicka på kartan för närmaste adress")
elif "error" in r:
    st.error("Uppslaget misslyckades. Försök igen.")
elif r["hit"] is None:
    st.info("Ingen adress i närheten")
else:
    hit = r["hit"]
    dist = hit.get("distance_m")
    if dist is not None and dist > NEAR_M:
        st.info(f"Ingen adress inom {NEAR_M / 1000:.0f} km (närmast: {label(hit)}, {dist / 1000:.1f} km)")
    else:
        st.success(
            "Närmaste adress: "
            + (f"{label(hit)} ({dist:.0f} m)" if dist is not None else label(hit))
        )

# -- show the map yourself -------------------------------------------------------
x0, y0, x1, y1 = SNIPPET_BBOX
bbox = f"({x0}, {y0}, {x1}, {y1})"
V3 = contract_v3()
AREAS_REL = "v3/areas.parquet" if V3 else "geoparquet2/areas.parquet"
ADDR_PUBLIC = address_public()
st.header("Visa kartan")
st.markdown("**Streamlit**")
st.code("pip install facett-map", language="bash")
st.code(
    f"""# app.py
import facett_map
import streamlit as st

st.title("Sverigekartan")
facett_map.map("{MAP_SERVER}", region="{REGION}", mode="2d")""",
    language="python",
)
st.code("streamlit run app.py", language="bash")
st.caption("Installera på en airgappad dator: hämta alla wheels för Python 3.11 på en dator med nät, installera sedan från dem.")
st.code(
    f"""pip download facett-map --python-version 3.11 --only-binary=:all: \\
  {WHEEL_PLATFORMS} -d wheels/
pip install --no-index --find-links wheels/ facett-map""",
    language="bash",
)
st.caption(
    "Kartdatan kommer fortfarande från servern: en airgappad miljö behöver en egen korp-map-server, "
    f"med data från [/v1/files]({FILES_PUBLIC})."
)
if EGUI_HOWTO:
    st.markdown("**Rust (egui)**")
    st.code(EGUI_HOWTO, language="bash")
    st.caption(
        "Samma karta i ett eget fönster: 2D, 3D, sök på adress, klick ger närmaste adress. "
        "Kräver [Rust](https://rustup.rs) och ett grafikkort med Vulkan, Metal eller DX12. "
        "Egen korp-map-server: `sverigekartan --server URL`."
    )

# -- geo examples ----------------------------------------------------------------
st.header("Geoexempel i Python")
st.code('pip install "korp-map-client>=0.3"' if V3 else "pip install korp-map-client", language="bash")
st.caption("Airgappad dator: samma pip download som ovan, med korp-map-client i stället för facett-map.")
st.caption("Adress till plats:")
st.code(
    f"""from korp_map_client import Client
c = Client("{ADDR_PUBLIC}", region="{REGION}")
c.geocode("Drottninggatan 53 Stockholm", max=1)""",
    language="python",
)
st.caption("Plats till närmaste adress:")
st.code(f"c.revgeocode({STOCKHOLM[0]}, {STOCKHOLM[1]})", language="python")
# The map and file examples need a client on the map server: the address one when
# it is the same server, else a second one.
mc = "c" if ADDR_PUBLIC == MAP_SERVER else "m"
mc_line = "" if mc == "c" else f'm = Client("{MAP_SERVER}", region="{REGION}")\n'
st.caption("Kartdata till GeoPandas:")
if V3:
    # Contract korp-map-v3.0: a continuous scale, res = ground metres per pixel.
    map_call = f'gdf = {mc}.map_view("areas", bbox={bbox}, res=10.0).to_geodataframe()'
else:
    map_call = f'gdf = {mc}.map_gdf("areas", bbox={bbox}, lod=16)'
st.code(
    f"""# pip install 'korp-map-client[geo]'
{mc_line}{map_call}
gdf.head()""",
    language="python",
)
st.caption("Läs Parquet-filen remote, bara delarna inom bbox:")
st.code(f'areas = {mc}.read_parquet("{AREAS_REL}", bbox={bbox})', language="python")
st.caption("Samma fil i DuckDB:")
st.code(
    f"""import duckdb
duckdb.sql("INSTALL httpfs; LOAD httpfs")
duckdb.sql(\"\"\"SELECT count(*) FROM '{FILES_PUBLIC}{AREAS_REL}'
  WHERE bbox.xmin <= {x1} AND bbox.xmax >= {x0} AND bbox.ymin <= {y1} AND bbox.ymax >= {y0}\"\"\").show()""",
    language="python",
)

# -- data ------------------------------------------------------------------------
st.header("Data")
st.caption("Sveriges OSM-data som Parquet-filer, samma data som kartan ritar.")
files = file_index(FILES_INDEX, FILES_PUBLIC)
if files is None:
    st.info("Filerna kommer snart.")
else:
    groups = data_files.by_group(files)
    gp2_total = data_files.total_size(groups[data_files.GP2])
    native_total = data_files.total_size(groups[data_files.NATIVE])
    v3_total = data_files.total_size(groups[data_files.V3])
    if gp2_total and native_total:
        st.caption(
            "Varje fil är ett lager för hela Sverige. Samma innehåll i två format: "
            f"GeoParquet 2.0 ≈{sv_size(gp2_total)} och native ≈{sv_size(native_total)} totalt."
        )
    elif v3_total:
        st.caption(f"Varje fil är ett lager för hela Sverige, ≈{sv_size(v3_total)} totalt.")
    sets = (
        (data_files.GP2, "GeoParquet 2.0", "För DuckDB, GDAL, GeoPandas och QGIS."),
        (data_files.NATIVE, "Native", "Det kartan ritar: GeoParquet 1.1, separated layout."),
        (data_files.V3, "Kartdata v3", "Det kartan ritar: alla skalor i samma fil, format korp-map-v3.0."),
        (data_files.OTHER, "Övrigt", ""),
    )
    for key, title, note in sets:
        if not groups[key]:
            continue
        st.subheader(title)
        if note:
            st.caption(note)
        rows = ["| Fil | Innehåll | Storlek | |", "|---|---|---:|---|"]
        rows += [
            f"| `{f.path}` | {f.holds} | {sv_size(f.size)} | [Ladda ner]({f.url}) |" for f in groups[key]
        ]
        st.markdown("\n".join(rows))

# -- footer ----------------------------------------------------------------------
st.divider()
st.markdown(
    "[facett-map](https://pypi.org/project/facett-map/) · "
    "[korp-map-client](https://pypi.org/project/korp-map-client/) · "
    "[korp-map](https://www.gunnar.rs/nordisk/korp-map)"
)
st.caption(
    f"Kartdata © OpenStreetMap-bidragsgivare, ODbL · dataversion `{data_version()}` · "
    "Kartan kräver WebGPU (Chrome, Edge, Safari 26)."
)