SPB Git

Repository Public BSD-3-Clause

inspect-pmtiles.py 8.5 KB 200 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Maps10# File             : scripts/inspect-pmtiles.py11# Description      : Inspect a PMTiles v3 archive of vector tiles: header,12#                    metadata summary, and the layers / attribute keys / `kind`13#                    values found in the tile containing a point at several14#                    zooms.15# Module           : scripts16# Repository       : https://git.spboucher.ai/orix-maps17# Created          : 2026-11-2518# Last Modified    : 2026-11-2519#20# =============================================================================21# AUTHOR & PROFESSIONAL AFFILIATION22# =============================================================================23#24# Author           : Simon-Pierre Boucher25# Position         : Professor of Finance26# Institution      : Université du Québec en Outaouais (UQO)27# Department       : Département des sciences administratives28# Organization     : SP Boucher29#30# Website          : https://spboucher.ai31# Git              : https://git.spboucher.ai32#33# =============================================================================34# OFFICIAL CONTACT DIRECTORY35# =============================================================================36#37# General          : info@spboucher.ai38# Professional     : contact@spboucher.ai39# Direct           : simon@spboucher.ai40# Research         : research@spboucher.ai41# Development      : dev@spboucher.ai42# Support          : support@spboucher.ai43# Security/Admin   : admin@spboucher.ai44# Notifications    : notifications@spboucher.ai45#46# Preferred Contact: support@spboucher.ai47#48# =============================================================================49# COPYRIGHT & INTELLECTUAL PROPERTY50# =============================================================================51#52# Copyright (c) 202653# Simon-Pierre Boucher54#55# All rights reserved where applicable.56#57# This file is governed by the applicable project license,58# copyright notices, institutional agreements and relevant law.59#60# Unless expressly authorized by the applicable license or61# rights holder, copying, redistribution, sublicensing,62# publication and commercial exploitation are not permitted.63#64# Existing third-party rights and notices remain unaffected.65#66# =============================================================================67# CONFIDENTIALITY & SECURITY68# =============================================================================69#70# Classification   : Public71# Distribution     : Public repository; use is governed by the project license72# Security Contact : admin@spboucher.ai73#74# Access to this source does not independently grant permission75# to redistribute or disclose confidential materials.76#77# Do not embed credentials, private keys, access tokens,78# certificates or confidential personal information.79#80# =============================================================================81# LICENSE & MAINTENANCE82# =============================================================================83#84# License          : Proprietary, all rights reserved (see license file)85# License File     : LICENSE86# Maintainer       : Simon-Pierre Boucher87# Technical Contact: dev@spboucher.ai88#89# =============================================================================90# END OF SP BOUCHER SOURCE HEADER91# =============================================================================9293"""Inspect a PMTiles v3 archive of vector tiles: header, metadata summary, and the layers / attribute keys / `kind`94values found in the tile containing a point at several zooms. Standard library only.95usage: inspect-pmtiles.py <file.pmtiles> [lat lon] [zooms…]"""96import gzip, json, math, struct, sys, collections9798def varint(b, i):99    r = s = 0100    while True:101        c = b[i]; i += 1102        r |= (c & 0x7f) << s103        if c < 0x80: return r, i104        s += 7105106def directory(b):107    n, i = varint(b, 0); ids = []; last = 0108    for _ in range(n):109        d, i = varint(b, i); last += d; ids.append(last)110    runs = []; lens = []; offs = []111    for _ in range(n): v, i = varint(b, i); runs.append(v)112    for _ in range(n): v, i = varint(b, i); lens.append(v)113    for k in range(n):114        v, i = varint(b, i)115        offs.append(offs[k-1] + lens[k-1] if v == 0 and k > 0 else v - 1)116    return list(zip(ids, runs, lens, offs))117118def tile_id(z, x, y):119    acc = sum(4 ** i for i in range(z)); n = 1 << z; d = 0; s = n >> 1120    while s > 0:121        rx = 1 if x & s else 0; ry = 1 if y & s else 0122        d += s * s * ((3 * rx) ^ ry)123        if ry == 0:124            if rx == 1: x = s - 1 - x; y = s - 1 - y125            x, y = y, x126        s >>= 1127    return acc + d128129def fields(b):130    i = 0131    while i < len(b):132        k, i = varint(b, i); f, w = k >> 3, k & 7133        if w == 0: v, i = varint(b, i)134        elif w == 2: l, i = varint(b, i); v = b[i:i + l]; i += l135        elif w == 5: v = b[i:i + 4]; i += 4136        elif w == 1: v = b[i:i + 8]; i += 8137        else: raise ValueError(w)138        yield f, w, v139140def value(b):141    for f, w, v in fields(b):142        if f == 1: return v.decode()143        if f == 2: return struct.unpack('<f', v)[0]144        if f == 3: return struct.unpack('<d', v)[0]145        if f in (4, 5): return v146        if f == 6: return (v >> 1) ^ -(v & 1)147        if f == 7: return bool(v)148149def main():150    path = sys.argv[1]; f = open(path, 'rb'); h = f.read(127)151    assert h[:7] == b'PMTiles' and h[7] == 3, 'not PMTiles v3'152    (root_off, root_len, meta_off, meta_len, leaf_off, leaf_len, data_off, data_len, n_addr, n_entries, n_contents) = struct.unpack('<11Q', h[8:96])153    clustered, icomp, tcomp, ttype, minz, maxz = h[96], h[97], h[98], h[99], h[100], h[101]154    b = struct.unpack('<4i', h[102:118])155    print(f'tiles {n_addr} entries {n_entries} contents {n_contents} zoom {minz}-{maxz} type {ttype} tile-compression {tcomp} bounds {[v / 1e7 for v in b]}')156    f.seek(meta_off); meta = json.loads(gzip.decompress(f.read(meta_len)))157    print('metadata keys', sorted(meta)); print({k: meta[k] for k in meta if k not in ('vector_layers', 'tilestats') and len(str(meta[k])) < 300})158    for vl in meta.get('vector_layers', []): print(' layer', vl['id'], vl.get('minzoom'), vl.get('maxzoom'), sorted(vl.get('fields', {})))159    if len(sys.argv) < 4: return160    lat, lon = float(sys.argv[2]), float(sys.argv[3])161    for z in [int(a) for a in sys.argv[4:]] or [maxz]:162        n = 1 << z; x = int((lon + 180) / 360 * n); y = int((1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n)163        tid = tile_id(z, x, y); off, ln = root_off, root_len; found = None164        for _ in range(4):165            f.seek(off); d = directory(gzip.decompress(f.read(ln)))166            e = None167            for ent in d:168                if ent[0] <= tid: e = ent169                else: break170            if e is None: break171            if e[1] > 0:172                if tid < e[0] + e[1]: found = e173                break174            off, ln = leaf_off + e[3], e[2]175        if not found: print(f'z{z} {x}/{y}: no tile'); continue176        f.seek(data_off + found[3]); raw = f.read(found[2]); t = gzip.decompress(raw) if tcomp == 2 else raw177        print(f'z{z} {x}/{y}: {len(raw)} bytes compressed, {len(t)} raw')178        for fl, w, layer in fields(t):179            if fl != 3: continue180            name = None; keys = []; vals = []; feats = []181            for lf, lw, lv in fields(layer):182                if lf == 1: name = lv.decode()183                elif lf == 2: feats.append(lv)184                elif lf == 3: keys.append(lv.decode())185                elif lf == 4: vals.append(value(lv))186            kinds = collections.Counter(); details = collections.Counter()187            for ft in feats:188                for ff, fw, fv in fields(ft):189                    if ff == 2:190                        i = 0; tags = []191                        while i < len(fv): v, i = varint(fv, i); tags.append(v)192                        for k, v in zip(tags[::2], tags[1::2]):193                            if keys[k] == 'kind': kinds[vals[v]] += 1194                            if keys[k] == 'kind_detail': details[vals[v]] += 1195            print(f'  {name}: {len(feats)} features; keys {sorted(keys)}')196            print(f'     kind {dict(kinds.most_common(60))}')197            if details: print(f'     kind_detail {dict(details.most_common(40))}')198199main()200
Files main
Menu

Theme