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

nordisk/korp-map

crates/korp-map-quality/browser/render.py

"""korp-map-quality browser glue: render every reference view in a WebGPU Chrome (over
CDP) through side_app.py, save the canvas and the viewer's own numbers, then run a
scripted pan (fps) and a scripted wheel zoom (rubber band: the camera zoom must move
one way only).

    python render.py --dir RUN --app http://localhost:8595 --cdp http://127.0.0.1:9335 \
        [--server https://karta.gunnar.rs] [--only stockholm,sarek-16m] [--settle 3000] [--no-motion]

Writes RUN/shots/<view>.png and RUN/render/<view>.json. The metrics are computed by
`korp-map-quality pixels` / `report` (Rust); this file only drives the browser.
"""
import argparse
import base64
import io
import json
import math
import statistics
import time
from pathlib import Path
from urllib.parse import urlencode

from PIL import Image
from playwright.sync_api import sync_playwright

#: The viewer's title strip sits above its map area on the same canvas. The page makes
#: the component this much taller than the view, and the map area (measured from the
#: viewer's own viewport box) is cropped out, so a shot is exactly the view's grid.
TITLE_STRIP = 23


def merc_y(lat):
    p = math.radians(lat)
    return (1 - math.log(math.tan(p) + 1 / math.cos(p)) / math.pi) / 2

KEEP = ("zoom", "fps", "ways", "visible_ways", "filled_ways", "labels", "visible_labels", "way_kinds",
        "lod_sizes", "way_vertices", "viewport", "center", "gpu_enabled", "way_lane", "night", "palette",
        "points", "visible_points")


def map_frame(pg):
    for f in pg.frames:
        if f == pg.main_frame:
            continue
        try:
            if f.evaluate("() => window.facet_mounted ? window.facet_mounted() : ''"):
                return f
        except Exception:
            pass
    return None


def state(f):
    return json.loads(f.evaluate("() => window.facet_state()"))


def wait_drawn(pg, timeout, settle):
    """Until the viewer says ready with a scene swapped in and nothing in flight."""
    t0, last = time.time(), None
    while time.time() - t0 < timeout:
        f = map_frame(pg)
        if f is not None:
            try:
                err = f.evaluate("() => window.facet_error()")
                if err:
                    return f, {"error": err}, None
                s = state(f)
                last = s
                srv = s.get("server") or {}
                if srv.get("status") == "ready" and (s.get("swap") or {}).get("swaps", 0) > 0 and not srv.get("in_flight"):
                    ready_ms = (time.time() - t0) * 1000
                    pg.wait_for_timeout(settle)
                    return f, state(f), ready_ms
            except Exception as e:  # the frame may be mid-reload
                last = {"exc": str(e)[:200]}
        pg.wait_for_timeout(250)
    return map_frame(pg), {"timeout": True, "last": last}, None


REC_START = """(withZoom) => {
  window.__kmq = {t: [], z: [], on: true};
  const tick = (ts) => {
    if (!window.__kmq.on) return;
    window.__kmq.t.push(ts);
    if (withZoom) { try { window.__kmq.z.push(JSON.parse(window.facet_state()).zoom); } catch (e) {} }
    requestAnimationFrame(tick);
  };
  requestAnimationFrame(tick);
}"""
REC_STOP = "() => { window.__kmq.on = false; return {t: window.__kmq.t, z: window.__kmq.z}; }"


def frame_stats(ts):
    d = [b - a for a, b in zip(ts, ts[1:]) if b > a]
    if len(d) < 5:
        return {"frames": len(ts), "note": "too few frames"}
    ds = sorted(d)
    p95 = ds[min(len(ds) - 1, int(0.95 * len(ds)))]
    med = statistics.median(ds)
    return {"frames": len(ts), "seconds": round((ts[-1] - ts[0]) / 1000, 3), "median_fps": round(1000 / med, 1),
            "p5_fps": round(1000 / p95, 1), "mean_fps": round(1000 * len(d) / sum(d), 1),
            "max_frame_ms": round(ds[-1], 1), "long_frames": sum(1 for x in d if x > 50)}


def canvas_centre(f):
    b = f.locator("#facet_canvas").bounding_box()
    return b["x"] + b["width"] / 2, b["y"] + b["height"] / 2


def pan(pg, f):
    """A 1.6 s drag: 480 px right and back, 40 steps each way."""
    x, y = canvas_centre(f)
    f.evaluate(REC_START, False)
    pg.mouse.move(x, y)
    pg.mouse.down()
    for dx in list(range(12, 481, 12)) + list(range(468, -1, -12)):
        pg.mouse.move(x + dx, y + dx * 0.25)
        pg.wait_for_timeout(20)
    pg.mouse.up()
    pg.wait_for_timeout(300)
    r = f.evaluate(REC_STOP)
    return frame_stats(r["t"])


def wheel_zoom(pg, f, settle_ms=1500):
    """Five wheel notches in, sampled every frame: zoom must never step back."""
    x, y = canvas_centre(f)
    pg.mouse.move(x, y)
    z0 = state(f).get("zoom")
    f.evaluate(REC_START, True)
    for _ in range(5):
        pg.mouse.wheel(0, -120)
        pg.wait_for_timeout(80)
    pg.wait_for_timeout(settle_ms)
    r = f.evaluate(REC_STOP)
    z = [v for v in r["z"] if isinstance(v, (int, float))]
    back, top = 0.0, float("-inf")
    for v in z:
        top = max(top, v)
        back = max(back, top - v)
    out = {"samples": len(z), "zoom_before": z0, "zoom_after": z[-1] if z else None,
           "max_backstep": round(back, 4), "overshoot": round(max(z) - z[-1], 4) if z else None,
           "monotonic": back < 0.01, "frames": frame_stats(r["t"])}
    # And back out, so the next view starts clean (not measured).
    for _ in range(5):
        pg.mouse.wheel(0, 120)
        pg.wait_for_timeout(80)
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dir", required=True)
    ap.add_argument("--app", default="http://localhost:8595")
    ap.add_argument("--cdp", default="http://127.0.0.1:9335")
    ap.add_argument("--server", default="https://karta.gunnar.rs")
    ap.add_argument("--only")
    ap.add_argument("--settle", type=int, default=3000)
    ap.add_argument("--timeout", type=int, default=180)
    ap.add_argument("--no-motion", action="store_true")
    a = ap.parse_args()
    run = Path(a.dir)
    views = json.loads((run / "views.json").read_text())
    if a.only:
        want = a.only.split(",")
        views = [v for v in views if v["name"] in want or v["place"] in want]
    (run / "shots").mkdir(parents=True, exist_ok=True)
    (run / "render").mkdir(parents=True, exist_ok=True)
    with sync_playwright() as p:
        b = p.chromium.connect_over_cdp(a.cdp)
        for v in views:
            w, h = v["width"], v["height"]
            ctx = b.new_context(viewport={"width": w, "height": h + 200}, device_scale_factor=1)
            pg = ctx.new_page()
            q = urlencode({"lon": v["lon"], "lat": v["lat"], "zoom": v["zoom"], "h": h + TITLE_STRIP, "server": a.server})
            info = {"name": v["name"], "url": f"{a.app}/?{q}"}
            try:  # the box is shared: fps is read against its load
                info["loadavg"] = [float(x) for x in Path("/proc/loadavg").read_text().split()[:3]]
            except OSError:
                pass
            t0 = time.time()
            pg.goto(info["url"], wait_until="load", timeout=60000)
            f, st, ready_ms = wait_drawn(pg, a.timeout, a.settle)
            info["first_draw_ms"] = round((time.time() - t0) * 1000 - a.settle) if ready_ms else None
            if f is not None and "error" not in st and "timeout" not in st:
                png = f.evaluate("() => document.getElementById('facet_canvas').toDataURL('image/png')")
                img = Image.open(io.BytesIO(base64.b64decode(png.split(",", 1)[1]))).convert("RGB")
                info["canvas"] = [img.width, img.height]
                # The map area: the viewer's viewport box at its zoom, in canvas pixels.
                vb = (st.get("viewport") or {}).get("bbox")
                map_h = (merc_y(vb[1]) - merc_y(vb[3])) * 256 * 2 ** st["zoom"] if vb else None
                top = round(img.height - map_h) if map_h else TITLE_STRIP
                info["map_area"] = {"top": top, "height": round(map_h, 2) if map_h else None,
                                    "centre_err_px": None}
                if map_h and abs(map_h - h) > 0.6:
                    info["map_area"]["mismatch"] = f"map area {map_h:.1f} px tall, view {h}"
                c = st.get("center") or [v["lon"], v["lat"]]
                info["map_area"]["centre_err_px"] = round(math.hypot(
                    (c[0] - v["lon"]) / 360 * 256 * 2 ** st["zoom"],
                    (merc_y(c[1]) - merc_y(v["lat"])) * 256 * 2 ** st["zoom"]), 3)
                img.crop((0, top, w, top + h)).save(run / "shots" / f"{v['name']}.png")
                info["adapter"] = json.loads(f.evaluate("() => window.facet_adapter()"))
                info["server_last"] = (st.get("server") or {}).get("last")
                info["state"] = {k: st.get(k) for k in KEEP if k in st}
                lab = st.get("labels") or {}
                info["labels"] = st.get("visible_labels", lab.get("placed"))
                if not a.no_motion:
                    try:
                        info["fps"] = {"pan": pan(pg, f)}
                        info["rubber"] = wheel_zoom(pg, f)
                    except Exception as e:
                        info["motion_error"] = str(e)[:300]
            else:
                info["problem"] = st
                pg.screenshot(path=str(run / "render" / f"{v['name']}-page.png"))
            (run / "render" / f"{v['name']}.json").write_text(json.dumps(info, indent=1, default=str))
            last = info.get("server_last") or {}
            print(json.dumps({"view": v["name"], "canvas": info.get("canvas"), "zoom": (info.get("state") or {}).get("zoom"),
                              "lod": last.get("lod"), "bytes": last.get("bytes"), "first_draw_ms": info.get("first_draw_ms"),
                              "pan": (info.get("fps") or {}).get("pan", {}).get("median_fps"),
                              "monotonic": (info.get("rubber") or {}).get("monotonic"),
                              "problem": str(info.get("problem"))[:200] if "problem" in info else None}), flush=True)
            ctx.close()
        b.close()


if __name__ == "__main__":
    main()