Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : KA Maps Engine10# File : server/pipeline/05-validate.py11# Description : Valide le schéma `osm_next` avant bascule.12# Module : server13# Repository : https://git.spboucher.ai/ka-maps-engine14# Created : 2026-12-0115# Last Modified : 2026-12-0116#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: support@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Valide le schéma `osm_next` avant bascule. Code de sortie non nul = bascule interdite.9091Contrôles : seuils absolus (un import tronqué ne passe pas), comparaison à la version en service92(chute > 5 % des routes ou des bâtiments, > 10 % des autres tables), validité des géométries (échantillon),93présence de repères connus, emprise, valeurs d'énumération du schéma ka1, tuiles témoins générées par94km-tiler depuis `osm_next`. Le rapport est écrit dans meta.version.validation.95"""96import json97import os98import subprocess99import sys100101import psycopg2102103VERSION = sys.argv[1] if len(sys.argv) > 1 else None104DB = os.environ["KM_DB_URL"]105TILER = os.environ.get("KM_TILER", "/usr/local/bin/km-tiler")106NEW, CUR = "osm_next", "osm"107108# table → (minimum absolu, chute maximale tolérée par rapport à la version en service)109TABLES = {110 "road": (1_000_000, 0.05),111 "building": (1_000_000, 0.05),112 "water": (500_000, 0.10),113 "waterway": (300_000, 0.10),114 "landcover": (300_000, 0.10),115 "landuse": (80_000, 0.10),116 "boundary": (5_000, 0.10),117 "place": (2_000, 0.10),118 "poi": (10_000, 0.10),119 "housenum": (300_000, 0.10),120 "transit_line": (500, 0.20),121 "transit_point": (150, 0.20),122 "admin_area": (1_000, 0.10),123}124GENERALIZED = (["road_z6", "road_z7", "road_z9", "waterway_z8", "waterway_z9", "waterway_z11", "boundary_z7",125 "transit_z10", "place_gen"]126 + ["water_base"] + [f"water_z{z}" for z in range(3, 13)] + [f"landcover_z{z}" for z in range(4, 13)] + ["housenum_all"]127 + [f"landuse_z{z}" for z in range(9, 13)])128ENUMS = {129 "road": {"motorway", "trunk", "primary", "secondary", "tertiary", "minor", "service", "path", "cycleway", "track", "rail", "ferry"},130 "water": {"lake", "river", "reservoir", "basin"},131 "waterway": {"river", "stream", "canal", "drain"},132 "landcover": {"forest", "grass", "farmland", "wetland", "rock", "sand", "scrub", "glacier"},133 "landuse": {"residential", "commercial", "industrial", "park", "cemetery", "school", "university", "hospital", "pitch", "golf", "parking", "airport", "military", "quarry"},134 "place": {"country", "province", "city", "town", "village", "suburb", "neighbourhood", "hamlet"},135 "poi": {"university", "college", "school", "hospital", "clinic", "grocery", "pharmacy", "park", "library", "station", "airport", "mall"},136 "transit_line": {"subway", "light_rail", "tram", "train"},137 "transit_point": {"metro", "rem", "train", "bus_terminal"},138}139# tuiles témoins : (z, x, y, couches attendues)140PROBES = [141 (14, 4843, 5861, {"road", "building", "housenum"}), # Montréal centre142 (14, 4955, 5777, {"road", "building"}), # Québec, Vieux-Québec143 (12, 1210, 1465, {"road", "water", "landuse"}), # Montréal144 (10, 302, 366, {"road", "water", "place", "transit"}),145 (8, 75, 91, {"road", "water", "boundary", "place"}),146 (6, 18, 22, {"water", "boundary", "place", "road"}),147]148149errors, warnings, report = [], [], {"tables": {}, "probes": []}150conn = psycopg2.connect(DB)151conn.autocommit = True152cur = conn.cursor()153154155def one(sql, args=None):156 cur.execute(sql, args)157 return cur.fetchone()[0]158159160def exists(schema, table):161 return one("SELECT to_regclass(%s) IS NOT NULL", (f"{schema}.{table}",))162163164have_current = exists(CUR, "road")165for t, (minimum, max_drop) in TABLES.items():166 if not exists(NEW, t):167 errors.append(f"table {NEW}.{t} absente")168 continue169 n = one(f"SELECT count(*) FROM {NEW}.{t}")170 entry = {"count": n, "minimum": minimum}171 if n < minimum:172 errors.append(f"{t} : {n} objets < minimum {minimum}")173 if have_current and exists(CUR, t):174 p = one(f"SELECT count(*) FROM {CUR}.{t}")175 entry["previous"] = p176 if p > 0:177 change = (n - p) / p178 entry["change"] = round(change, 4)179 if change < -max_drop:180 errors.append(f"{t} : chute de {-change:.1%} ({p} → {n}), seuil {max_drop:.0%}")181 elif change > 0.25:182 warnings.append(f"{t} : hausse de {change:.1%} ({p} → {n})")183 report["tables"][t] = entry184185for t in GENERALIZED:186 if not exists(NEW, t):187 errors.append(f"table généralisée {NEW}.{t} absente")188 else:189 n = one(f"SELECT count(*) FROM {NEW}.{t}")190 report["tables"][t] = {"count": n}191 if n == 0:192 errors.append(f"table généralisée {t} vide")193194# longueur du réseau routier principal (km Mercator) : une chute signale un extrait amputé195if exists(NEW, "road"):196 km = one(f"SELECT coalesce(sum(ST_Length(geom)),0)/1000 FROM {NEW}.road WHERE kind IN ('motorway','trunk','primary')")197 report["major_road_km_mercator"] = round(km)198 if have_current:199 pk = one(f"SELECT coalesce(sum(ST_Length(geom)),0)/1000 FROM {CUR}.road WHERE kind IN ('motorway','trunk','primary')")200 if pk > 0 and (km - pk) / pk < -0.05:201 errors.append(f"réseau principal : chute de {(pk - km) / pk:.1%} en longueur")202203# validité des géométries (échantillon de 2 %)204for t in ("building", "water", "landuse", "landcover"):205 if exists(NEW, t):206 cur.execute(f"SELECT count(*), count(*) FILTER (WHERE NOT ST_IsValid(geom)) FROM {NEW}.{t} TABLESAMPLE SYSTEM (2)")207 total, bad = cur.fetchone()208 ratio = bad / total if total else 0209 report["tables"].setdefault(t, {})["invalid_sample"] = {"sampled": total, "invalid": bad}210 if ratio > 0.005:211 errors.append(f"{t} : {ratio:.2%} de géométries invalides dans l'échantillon")212213# énumérations du schéma214for t, allowed in ENUMS.items():215 if exists(NEW, t):216 cur.execute(f"SELECT DISTINCT kind FROM {NEW}.{t}")217 extra = {r[0] for r in cur.fetchall()} - allowed218 if extra:219 errors.append(f"{t} : valeurs de kind hors schéma {sorted(extra)}")220if exists(NEW, "building"):221 cur.execute(f"SELECT hs, count(*) FROM {NEW}.building GROUP BY hs ORDER BY hs")222 hs = dict(cur.fetchall())223 report["building_hs"] = {str(k): v for k, v in hs.items()}224 if set(hs) - {1, 2, 3, 4}:225 errors.append(f"building.hs hors {{1,2,3,4}} : {sorted(hs)}")226 if one(f"SELECT count(*) FROM {NEW}.building WHERE h <= 0 OR h > 10000 OR mh < 0 OR mh >= h") > 0:227 errors.append("building : hauteurs incohérentes (h ≤ 0, h > 1 km ou mh ≥ h)")228if exists(NEW, "boundary"):229 cur.execute(f"SELECT DISTINCT level FROM {NEW}.boundary")230 lv = {r[0] for r in cur.fetchall()}231 if lv - {2, 4, 6, 8, 10}:232 errors.append(f"boundary.level hors schéma : {sorted(lv)}")233234# repères et emprise235if exists(NEW, "place"):236 for name in ("Montréal", "Québec", "Gatineau", "Sherbrooke", "Saguenay", "Trois-Rivières", "Laval", "Longueuil"):237 if one(f"SELECT count(*) FROM {NEW}.place WHERE name = %s AND kind IN ('city','town')", (name,)) == 0:238 errors.append(f"lieu repère absent : {name}")239 cur.execute(f"SELECT ST_XMin(e), ST_YMin(e), ST_XMax(e), ST_YMax(e) FROM (SELECT ST_Transform(ST_SetSRID(ST_Extent(geom),3857),4326) e FROM {NEW}.road) q")240 w, s, e, n = cur.fetchone()241 report["road_extent"] = [round(w, 2), round(s, 2), round(e, 2), round(n, 2)]242 if not (w < -79 and e > -58 and s < 45.1 and n > 60):243 errors.append(f"emprise des routes trop petite : {report['road_extent']}")244245# tuiles témoins générées depuis osm_next246if os.path.exists(TILER):247 for z, x, y, expect in PROBES:248 p = subprocess.run([TILER, "--schema", NEW, "--data-version", "validation", "tile", str(z), str(x), str(y)],249 capture_output=True, text=True, env={**os.environ, "KM_LOG": "error"})250 if p.returncode != 0:251 errors.append(f"tuile témoin {z}/{x}/{y} : échec ({p.stderr.strip()[-200:]})")252 continue253 info = json.loads(p.stdout)254 layers = {l["name"]: l["features"] for l in info["layers"]}255 report["probes"].append({"tile": f"{z}/{x}/{y}", "gzip_bytes": info["gzip_bytes"], "millis": info.get("millis"), "layers": layers})256 missing = expect - set(layers)257 if missing:258 errors.append(f"tuile témoin {z}/{x}/{y} : couches absentes {sorted(missing)}")259 if info["gzip_bytes"] > 500 * 1024:260 errors.append(f"tuile témoin {z}/{x}/{y} : {info['gzip_bytes']} octets > 500 Ko")261else:262 warnings.append(f"{TILER} absent : tuiles témoins non vérifiées")263264report["errors"], report["warnings"], report["ok"] = errors, warnings, not errors265if VERSION:266 cur.execute("UPDATE meta.version SET validation = %s, status = %s WHERE version = %s AND status IN ('building','validated','rejected')",267 (json.dumps(report), "validated" if not errors else "rejected", VERSION))268print(json.dumps(report, ensure_ascii=False, indent=1))269sys.exit(1 if errors else 0)270