SPB Git

Repository Public

quartier.py 12.6 KB 316 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/quartier.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-08-2314#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# quartier.py : statistiques de quartier par annonce (à la Centris, en libre)91#   Base statique data/quartier.db construite par scripts/build_*.py :92#     - da_poly / da_stats : aires de diffusion 2021 + profil du recensement93#     - da_pmd : mesures de proximité StatCan (scores 0..1)94#     - da_defav : défavorisation matérielle/sociale INSPQ (quintiles)95#     - heat : classe d'îlot de chaleur/fraîcheur INSPQ par immeuble96#     - crime_mtl / igc : actes criminels SPVM (points) + indice de gravité97#   Jointure : lat/lng -> DAUID par point-dans-polygone local (préfiltre bbox),98#   mémorisée dans listings.dauid à l'enrichissement (boucle watch).99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103import math104import sqlite3105import time106from pathlib import Path107108from . import db109110QUARTIER_DB = Path(__file__).resolve().parent.parent / "data" / "quartier.db"111112# villes couvertes par les points SPVM (agglomération de Montréal)113_VILLES_SPVM = {"montreal", "montreal-est", "montreal-ouest", "westmount",114                "cote saint-luc", "cote-saint-luc", "hampstead", "mont-royal",115                "outremont", "verdun", "lasalle", "lachine", "anjou",116                "saint-leonard", "saint-laurent", "ahuntsic", "dorval",117                "pointe-claire", "kirkland", "beaconsfield", "dollard-des-ormeaux"}118119# correspondance ville -> fragment du nom de service dans la table igc120_IGC_SERVICE = {121    "quebec": "SPVQ", "levis": "Lévis", "montreal": "SPVM",122    "laval": "Laval", "longueuil": "Longueuil",123}124125126def disponible() -> bool:127    return QUARTIER_DB.exists()128129130def _connect() -> sqlite3.Connection:131    con = sqlite3.connect(f"file:{QUARTIER_DB}?mode=ro", uri=True)132    con.row_factory = sqlite3.Row133    return con134135136# ---------------------------------------------------------------------------137# lat/lng -> DAUID (point dans polygone, préfiltre bbox)138# ---------------------------------------------------------------------------139140def _dans_anneau(lat: float, lng: float, anneau: list) -> bool:141    """Lancer de rayon (even-odd). anneau = [[lng, lat], ...]."""142    dedans = False143    n = len(anneau)144    j = n - 1145    for i in range(n):146        xi, yi = anneau[i][0], anneau[i][1]147        xj, yj = anneau[j][0], anneau[j][1]148        if (yi > lat) != (yj > lat) and \149                lng < (xj - xi) * (lat - yi) / (yj - yi + 1e-12) + xi:150            dedans = not dedans151        j = i152    return dedans153154155def dauid_for(qcon: sqlite3.Connection, lat: float, lng: float) -> str | None:156    rows = qcon.execute(157        "SELECT dauid, poly FROM da_poly WHERE lat_min<=? AND lat_max>=?"158        " AND lng_min<=? AND lng_max>=?", (lat, lat, lng, lng)).fetchall()159    for r in rows:160        anneaux = json.loads(r["poly"])161        # even-odd sur tous les anneaux (les trous annulent)162        compte = sum(1 for a in anneaux if _dans_anneau(lat, lng, a))163        if compte % 2 == 1:164            return r["dauid"]165    return None166167168# ---------------------------------------------------------------------------169# Assemblage pour la fiche170# ---------------------------------------------------------------------------171172def _cle_ville(city: str) -> str:173    import unicodedata174    s = "".join(c for c in unicodedata.normalize("NFD", city or "")175                if unicodedata.category(c) != "Mn")176    return s.strip().lower()177178179def _crime_mtl(qcon: sqlite3.Connection, lat: float, lng: float) -> dict | None:180    """Comptage des actes criminels SPVM à < 500 m : 12 mois vs 12 précédents."""181    dlat = 500 / 111000.0182    dlng = 500 / (111000.0 * max(0.2, math.cos(math.radians(lat))))183    now = time.time()184    rows = qcon.execute(185        "SELECT lat, lng, ts, categorie FROM crime_mtl WHERE lat BETWEEN ? AND ?"186        " AND lng BETWEEN ? AND ? AND ts >= ?",187        (lat - dlat, lat + dlat, lng - dlng, lng + dlng, now - 730 * 86400)).fetchall()188    recent = avant = 0189    cats: dict[str, list[int]] = {}          # categorie -> [12 mois, 12 prec.]190    for r in rows:191        # distance exacte (le bbox est un carré)192        d = math.hypot((r["lat"] - lat) * 111000.0,193                       (r["lng"] - lng) * 111000.0 * math.cos(math.radians(lat)))194        if d > 500:195            continue196        c = cats.setdefault(r["categorie"] or "Autre", [0, 0])197        if r["ts"] >= now - 365 * 86400:198            recent += 1199            c[0] += 1200        else:201            avant += 1202            c[1] += 1203    if recent == 0 and avant == 0:204        return None205    categories = [{"nom": k, "n": v[0], "n_prec": v[1]}206                  for k, v in sorted(cats.items(),207                                     key=lambda kv: -(kv[1][0] + kv[1][1]))]208    return {"type": "points", "rayon_m": 500, "douze_mois": recent,209            "douze_mois_precedents": avant, "categories": categories}210211212def _crime_igc(qcon: sqlite3.Connection, city: str) -> dict | None:213    service = _IGC_SERVICE.get(_cle_ville(city))214    if not service:215        return None216    row = qcon.execute(217        "SELECT annee, indice FROM igc WHERE service LIKE '%' || ? || '%'"218        " ORDER BY annee DESC LIMIT 1", (service,)).fetchone()219    if row is None or row["indice"] is None:220        return None221    ref = qcon.execute(222        "SELECT indice FROM igc WHERE service LIKE '%canada%' AND annee=?",223        (row["annee"],)).fetchone()224    return {"type": "igc", "ville": city, "annee": row["annee"],225            "indice": round(row["indice"], 1),226            "indice_canada": round(ref["indice"], 1) if ref and ref["indice"] else None}227228229def fiche_quartier(lat: float | None, lng: float | None, city: str,230                   dauid: str | None = None) -> dict | None:231    """Bloc « Le quartier » d'une fiche. None si données indisponibles."""232    if not disponible() or lat is None or lng is None:233        return None234    qcon = _connect()235    try:236        if not dauid:237            dauid = dauid_for(qcon, lat, lng)238        out: dict = {"dauid": dauid}239240        if dauid:241            r = qcon.execute("SELECT * FROM da_stats WHERE dauid=?", (dauid,)).fetchone()242            if r:243                out["demographie"] = {k: r[k] for k in244                                      ("population", "densite", "age_median",245                                       "revenu_median", "pct_locataires",246                                       "loyer_moyen", "pct_francais", "pct_univ")}247            # rangs centiles québécois (0-100) — voir scripts/merge_quartier.py248            r = qcon.execute("SELECT * FROM da_pmd_pct WHERE dauid=?", (dauid,)).fetchone()249            if r:250                out["proximite"] = {k: r[k] / 100.0 for k in r.keys()251                                    if k != "dauid" and r[k] is not None}252            r = qcon.execute("SELECT quintile_materiel, quintile_social FROM da_defav"253                             " WHERE dauid=?", (dauid,)).fetchone()254            if r:255                out["defavorisation"] = dict(r)256257        # îlot de chaleur : coordonnée exacte, sinon la plus proche (~120 m)258        key = f"{round(lat, 4)},{round(lng, 4)}"259        r = qcon.execute("SELECT classe, ecart FROM heat WHERE coord_key=?",260                         (key,)).fetchone()261        if r is None:262            r = qcon.execute(263                "SELECT classe, ecart FROM heat WHERE coord_key LIKE ?"264                " AND classe IS NOT NULL LIMIT 1",265                (f"{round(lat, 3)}%",)).fetchone()266        if r and r["classe"] is not None:267            out["chaleur"] = {"classe": r["classe"], "ecart": r["ecart"]}268269        # criminalité : points SPVM sur l'île, indice IGC ailleurs270        crime = None271        if _cle_ville(city) in _VILLES_SPVM:272            crime = _crime_mtl(qcon, lat, lng)273        if crime is None:274            crime = _crime_igc(qcon, city)275        if crime:276            out["crime"] = crime277278        return out if len(out) > 1 else None279    except sqlite3.Error:280        return None281    finally:282        qcon.close()283284285# ---------------------------------------------------------------------------286# Enrichissement : mémoriser le DAUID de chaque annonce (boucle watch)287# ---------------------------------------------------------------------------288289def enrich(limit: int | None = None) -> dict:290    """Remplit listings.dauid pour les annonces géolocalisées qui ne l'ont pas."""291    if not disponible():292        print("[lou-ka] quartier: data/quartier.db absent — étape sautée")293        return {"enriched": 0, "missing_db": True}294    con = db.connect()295    qcon = _connect()296    rows = con.execute(297        "SELECT uid, lat, lng FROM listings WHERE active=1 AND lat IS NOT NULL"298        " AND (dauid IS NULL OR dauid='')").fetchall()299    if limit is not None:300        rows = rows[:limit]301    done = introuvable = 0302    for r in rows:303        d = dauid_for(qcon, r["lat"], r["lng"])304        con.execute("UPDATE listings SET dauid=? WHERE uid=?",305                    (d or "hors-zone", r["uid"]))306        if d:307            done += 1308        else:309            introuvable += 1310    con.commit()311    qcon.close()312    con.close()313    stats = {"enriched": done, "hors_zone": introuvable, "candidats": len(rows)}314    print(f"[lou-ka] quartier {stats}")315    return stats316
Files main
Menu

Theme