Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : scripts/merge_quartier.py10# Module : scripts11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0813# Last Modified : 2026-08-0814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# scripts/merge_quartier.py : fusionne les bases de préparation91# data/staging-{recensement,contexte,environnement}.db -> data/quartier.db92# (la base statique servie en production ; voir louka/quartier.py)93# Usage : .venv/bin/python scripts/merge_quartier.py94# -----------------------------------------------------------------------------95from __future__ import annotations9697import sqlite398import sys99from pathlib import Path100101DATA = Path(__file__).resolve().parent.parent / "data"102CIBLE = DATA / "quartier.db"103104# staging -> tables attendues105SOURCES = {106 "staging-recensement.db": ["da_poly", "da_stats"],107 "staging-contexte.db": ["da_pmd", "da_defav", "ecoles"],108 "staging-environnement.db": ["heat", "crime_mtl", "igc"],109}110111112def main() -> None:113 if CIBLE.exists():114 CIBLE.unlink()115 out = sqlite3.connect(CIBLE)116 out.execute("CREATE TABLE meta (cle TEXT PRIMARY KEY, valeur TEXT)")117118 for fichier, tables in SOURCES.items():119 chemin = DATA / fichier120 if not chemin.exists():121 print(f"⚠ {fichier} absent — tables {tables} sautées", file=sys.stderr)122 continue123 out.execute("ATTACH DATABASE ? AS src", (str(chemin),))124 for t in tables:125 existe = out.execute(126 "SELECT name FROM src.sqlite_master WHERE type='table' AND name=?",127 (t,)).fetchone()128 if not existe:129 print(f"⚠ table {t} absente de {fichier}", file=sys.stderr)130 continue131 schema = out.execute(132 "SELECT sql FROM src.sqlite_master WHERE type='table' AND name=?",133 (t,)).fetchone()[0]134 out.execute(schema)135 out.execute(f"INSERT INTO {t} SELECT * FROM src.{t}")136 n = out.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]137 print(f"✓ {t}: {n} lignes (depuis {fichier})")138 # préfixer les métadonnées de provenance139 if out.execute("SELECT name FROM src.sqlite_master WHERE name='meta'").fetchone():140 for cle, val in out.execute("SELECT cle, valeur FROM src.meta"):141 out.execute("INSERT OR REPLACE INTO meta VALUES (?,?)",142 (f"{fichier.replace('.db', '')}:{cle}", val))143 out.commit()144 out.execute("DETACH DATABASE src")145146 # scores PMD -> rangs centiles parmi les AD du Québec (l'échelle brute est147 # normalisée nationalement et écrase les valeurs urbaines : un Saint-Roch148 # très marchable afficherait 17/100 ; son centile québécois le rétablit)149 import bisect150 cols = [r[1] for r in out.execute("PRAGMA table_info(da_pmd)") if r[1] != "dauid"]151 out.execute("DROP TABLE IF EXISTS da_pmd_pct")152 out.execute("CREATE TABLE da_pmd_pct (dauid TEXT PRIMARY KEY, "153 + ", ".join(f"{c} INTEGER" for c in cols) + ")")154 lignes = out.execute(f"SELECT dauid, {', '.join(cols)} FROM da_pmd").fetchall()155 tries = {c: sorted(v for (v,) in156 out.execute(f"SELECT {c} FROM da_pmd WHERE {c} IS NOT NULL"))157 for c in cols}158 q = (f"INSERT INTO da_pmd_pct VALUES (?{',?' * len(cols)})")159 for ligne in lignes:160 vals = [ligne[0]]161 for i, c in enumerate(cols):162 v = ligne[i + 1]163 t = tries[c]164 if v is None or len(t) < 2:165 vals.append(None)166 else: # rang centile parmi les valeurs non nulles du Québec167 vals.append(round(100 * bisect.bisect_left(t, v) / (len(t) - 1)))168 out.execute(q, vals)169 print(f"✓ da_pmd_pct: {len(lignes)} lignes (rangs centiles QC, non-nuls)")170171 # index utiles au runtime172 for idx in [173 "CREATE INDEX IF NOT EXISTS idx_poly_bbox ON da_poly(lat_min, lat_max)",174 "CREATE INDEX IF NOT EXISTS idx_crime_lat2 ON crime_mtl(lat)",175 ]:176 try:177 out.execute(idx)178 except sqlite3.Error as e:179 print(f"⚠ index: {e}", file=sys.stderr)180 out.commit()181 out.execute("VACUUM")182 out.close()183 print(f"→ {CIBLE} : {CIBLE.stat().st_size / 1e6:.1f} Mo")184185186if __name__ == "__main__":187 main()188