SPB Git

Repository Public

render.py 14.1 KB 294 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : KA Maps Engine10# File             : themes/tools/render.py11# Description      : Planches de preuve des thèmes KA Maps.12# Module           : themes13# 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"""Planches de preuve des thèmes KA Maps.9091Rend les dix vues de référence d'un thème avec `engine/km-shot` (hors écran, aucune fenêtre),92directement depuis le fichier `themes/<nom>.json` (commande `setThemeDocument` : pas besoin de93recompiler le moteur), puis assemble la planche-contact.9495    themes/tools/render.py signature                 # dix vues + planche dans docs/themes/signature/96    themes/tools/render.py terrain --views mtl-z13   # une seule vue97    themes/tools/render.py signature --out /tmp/x    # ailleurs (itération)98    themes/tools/render.py --brands                  # variantes de marque + couches de démonstration99100Dépendances : Pillow. Les tuiles viennent de https://tiles.spboucher.ai (cache disque local).101"""102import argparse103import json104import os105import subprocess106import sys107import tempfile108109from PIL import Image, ImageDraw, ImageFont110111ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))112SHOT = os.path.join(ROOT, "engine", "target", "release", "km-shot")113TILES = os.environ.get("KM_TILES", "https://tiles.spboucher.ai")114CACHE = os.environ.get("KM_CACHE", os.path.join(tempfile.gettempdir(), "kamaps-shot-cache"))115SIZE = (1200, 750)116SCALE = 1.2117118# (identifiant, légende, lon, lat, zoom, inclinaison, cap)119VIEWS = [120    ("qc-z5", "Québec, province — z5", -70.8, 50.2, 5, 0, 0),121    ("mtl-region-z9", "Région de Montréal — z9", -73.65, 45.55, 9, 0, 0),122    ("mtl-z13", "Montréal, centre — z13", -73.5674, 45.5019, 13, 0, 0),123    ("mtl-z15", "Montréal, centre — z15 (2D)", -73.5674, 45.5019, 15, 0, 0),124    ("mtl-z165-3d", "Montréal, centre — z16,5 incliné 55° (3D)", -73.5690, 45.5005, 16.5, 55, -20),125    ("plateau-z17", "Plateau-Mont-Royal, rues résidentielles — z17", -73.5790, 45.5262, 17, 0, 0),126    ("quebec-z15-3d", "Vieux-Québec — z15 (3D)", -71.2060, 46.8120, 15, 50, 25),127    ("laval-z14", "Laval, banlieue — z14", -73.7480, 45.6030, 14, 0, 0),128    ("lacstjean-z11", "Lac-Saint-Jean, rural — z11", -71.78, 48.50, 11, 0, 0),129    ("cotenord-z8", "Côte-Nord — z8", -66.6, 50.25, 8, 0, 0),130]131132BRANDS = ["louka", "immoka", "vraiprix", "valoplex"]133134135def shoot(theme_path, out, lon, lat, zoom, pitch=0, bearing=0, app=None, layers=None, size=SIZE, mode=None):136    """Un rendu. `layers` : fichier de scène (commandes) joué après le thème."""137    doc = json.load(open(theme_path))138    commands = [{"op": "setThemeDocument", "document": doc}]139    if layers:140        commands += json.load(open(layers)).get("commands", [])141    with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:142        json.dump({"commands": commands}, f)143        scene = f.name144    cmd = [SHOT, "--theme", "signature", "--center", f"{lon},{lat}", "--zoom", str(zoom), "--pitch", str(pitch),145           "--bearing", str(bearing), "--size", f"{size[0]}x{size[1]}", "--scale", str(SCALE), "--tiles", TILES,146           "--cache", CACHE, "--layers", scene, "--timeout", "90", "--out", out]147    if app:148        cmd += ["--app", app]149    if mode or pitch > 0:150        cmd += ["--mode", mode or "3d"]151    else:152        cmd += ["--mode", "2d"]153    r = subprocess.run(cmd, capture_output=True, text=True)154    os.unlink(scene)155    err = [l for l in r.stderr.splitlines() if "km-shot" in l or "erreur" in l.lower() or "warning" in l.lower()]156    if r.returncode != 0 or err:157        print("   ", out, r.returncode, *err[:6], sep="\n      ", file=sys.stderr)158    return r.returncode == 0159160161def compress(path, colors=None):162    """PNG optimisé. La réduction à une palette n'est gardée que si elle est fidèle : une planche de preuve163    ne doit pas changer la teinte d'une pastille ou d'une classe (moins de 0,02 % de pixels à plus de 16/255)."""164    import numpy as np165    im = Image.open(path).convert("RGB")166    if colors:167        src = np.asarray(im, dtype=np.int16)168169        def bad(q):170            return np.abs(np.asarray(q.convert("RGB"), dtype=np.int16) - src).max(axis=2) > 16171172        q = im.quantize(colors=colors, method=Image.Quantize.FASTOCTREE, kmeans=2, dither=Image.Dither.NONE)173        if bad(q).mean() >= 0.0002:174            # Les teintes rares (lignes de métro, pastilles) se perdent : on leur réserve une part de la palette.175            base = im.quantize(colors=colors - 63, method=Image.Quantize.FASTOCTREE, kmeans=2, dither=Image.Dither.NONE)176            m = bad(base)177            rare = Image.fromarray(src[m].astype("uint8").reshape(1, -1, 3), "RGB").quantize(colors=63, method=Image.Quantize.MEDIANCUT, kmeans=3)178            pal = Image.new("P", (1, 1))179            pal.putpalette((base.getpalette()[:(colors - 63) * 3] + rare.getpalette()[:63 * 3] + [0] * 768)[:768])180            q = im.quantize(palette=pal, dither=Image.Dither.NONE)181        if bad(q).mean() < 0.0002:182            im = q183    im.save(path, optimize=True)184185186def font(size, weight="Medium"):187    return ImageFont.truetype(os.path.join(ROOT, "engine", "assets", "fonts", f"Inter-{weight}.ttf"), size)188189190def sheet(title, subtitle, items, out, cols=2, cell_w=800, dark=False):191    """Planche-contact : `items` = [(légende, chemin png)]."""192    bg, fg, soft = ((24, 23, 21), (236, 231, 221), (150, 144, 133)) if dark else ((250, 248, 243), (36, 33, 29), (120, 113, 102))193    pad, cap_h, head_h = 16, 30, 86194    ims = [(c, Image.open(p).convert("RGB")) for c, p in items if os.path.exists(p)]195    if not ims:196        return197    ratio = ims[0][1].height / ims[0][1].width198    cell_h = int(cell_w * ratio)199    rows = (len(ims) + cols - 1) // cols200    W = pad + cols * (cell_w + pad)201    H = head_h + rows * (cell_h + cap_h + pad) + pad202    im = Image.new("RGB", (W, H), bg)203    d = ImageDraw.Draw(im)204    d.text((pad, 18), title, font=font(30, "SemiBold"), fill=fg)205    d.text((pad, 56), subtitle, font=font(14, "Regular"), fill=soft)206    d.line([(pad, head_h - 6), (W - pad, head_h - 6)], fill=fg, width=1)207    for i, (cap, src) in enumerate(ims):208        x = pad + (i % cols) * (cell_w + pad)209        y = head_h + (i // cols) * (cell_h + cap_h + pad) + 6210        im.paste(src.resize((cell_w, cell_h), Image.LANCZOS), (x, y))211        d.rectangle([x, y, x + cell_w - 1, y + cell_h - 1], outline=soft)212        d.text((x, y + cell_h + 7), cap, font=font(13), fill=fg)213    im.save(out, optimize=True)214    compress(out, 255)215216217def render_theme(name, outdir, only=None):218    theme = os.path.join(ROOT, "themes", f"{name}.json")219    os.makedirs(outdir, exist_ok=True)220    items = []221    for vid, cap, lon, lat, zoom, pitch, bearing in VIEWS:222        out = os.path.join(outdir, f"{vid}.png")223        items.append((cap, out))224        if only and vid not in only:225            continue226        if shoot(theme, out, lon, lat, zoom, pitch, bearing):227            compress(out, 255)228    doc = json.load(open(theme))229    dark = name == "midnight"230    if not only:231        sheet(f"KA Maps — {name}", doc.get("_description", ""), items, os.path.join(outdir, "planche.png"), dark=dark)232233234BRAND_DEMO = {235    # marque : (étiquettes de prix, genres propres à la marque)236    "louka": (["1 250 $", "1 480 $", "1 950 $", "1 320 $", "1 690 $", "1 100 $"], ["rented"]),237    "immoka": (["489 k$", "512 k$", "735 k$", "450 k$", "615 k$", "398 k$"], ["featured"]),238    "vraiprix": (["502 k$", "478 k$", "640 k$", "455 k$", "590 k$", "410 k$"], ["sale", "listing"]),239    "valoplex": (["212 k$/p", "184 k$/p", "298 k$/p", "205 k$/p", "240 k$/p", "168 k$/p"], ["subject", "comparable"]),240}241242243def pill_scene(brand, lon=-73.5674, lat=45.5019):244    """Grille de pastilles : colonnes = neutre, bon, élevé, vu, sélectionné, vendu, genres de la marque ;245    rangées (du haut vers le bas) = observé, estimé, hypothèse."""246    labels, kinds = BRAND_DEMO[brand]247    cols = [(None, "default"), ("good", "default"), ("high", "default"), (None, "visited"), (None, "selected"), ("sold", "default")] + [(k, "default") for k in kinds]248    data = []249    for r, nature in enumerate(["observe", "estime", "hypothese"]):250        for c, (kind, state) in enumerate(cols):251            data.append({"id": f"p{r}{c}", "lon": lon + (c - (len(cols) - 1) / 2) * 0.0019, "lat": lat + (1 - r) * 0.0020,252                         "label": labels[c % len(labels)], "value": 1, "kind": kind, "state": state, "nature": nature})253    return {"commands": [{"op": "addLayer", "id": "pastilles", "type": "markers", "options": {}, "data": data}]}254255256def render_brands(outdir):257    scenes = os.path.join(ROOT, "engine", "km-shot", "scenes")258    os.makedirs(outdir, exist_ok=True)259    tmp = tempfile.mkdtemp()260    for b in BRANDS:261        pills = os.path.join(tmp, f"pastilles-{b}.json")262        json.dump(pill_scene(b), open(pills, "w"))263        legend = "neutre, bon, élevé, vu, sélectionné, vendu, genres ; observé / estimé / hypothèse"264        # (thème, scène, nom, légende, lon, lat, zoom, inclinaison, cap)265        plan = [266            ("signature", pills, "pastilles", f"signature — {legend}", -73.5674, 45.5019, 15.2, 0, 0),267            ("midnight", pills, "pastilles", "midnight — mêmes pastilles sur fond sombre", -73.5674, 45.5019, 15.2, 0, 0),268            ("blueprint", pills, "pastilles", "blueprint — mêmes pastilles", -73.5674, 45.5019, 15.2, 0, 0),269            ("signature", os.path.join(scenes, "layers-clusters.json"), "grappes", "signature — grappes (4 000 annonces)", -73.5874, 45.5119, 12.2, 0, 0),270            ("financial", os.path.join(scenes, "layers-analytics.json"), "analyse", "financial — surface, chaleur, colonnes, points", -73.5674, 45.5019, 14.6, 45, -15),271            ("city3d", os.path.join(scenes, "layers-markers-buildings.json"), "batiments", "city3d — valeurs par bâtiment, zones, trajet, pastilles", -73.5674, 45.5019, 15.6, 50, -20),272        ]273        items = []274        for theme, scene, name, cap, lon, lat, zoom, pitch, bearing in plan:275            out = os.path.join(tmp, f"{b}-{theme}-{name}.png")  # seules les planches sont gardées276            if shoot(os.path.join(ROOT, "themes", f"{theme}.json"), out, lon, lat, zoom, pitch, bearing, app=b, layers=scene, size=(1200, 750)):277                compress(out, 255)278                items.append((cap, out))279        desc = json.load(open(os.path.join(ROOT, "themes", "brands", f"{b}.json"))).get("_description", "")280        sheet(f"KA Maps — variante {b}", desc[:150], items, os.path.join(outdir, f"planche-{b}.png"), cols=2, cell_w=680)281282283if __name__ == "__main__":284    ap = argparse.ArgumentParser()285    ap.add_argument("themes", nargs="*")286    ap.add_argument("--views", nargs="*")287    ap.add_argument("--out")288    ap.add_argument("--brands", action="store_true")289    a = ap.parse_args()290    for t in a.themes:291        render_theme(t, os.path.join(a.out or os.path.join(ROOT, "docs", "themes"), t), a.views)292    if a.brands:293        render_brands(a.out or os.path.join(ROOT, "docs", "themes", "marques"))294
Files main
Menu

Theme