Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/vraiprix_local.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-08-1814#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# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# vraiprix_local.py : appariement LOCAL contre la base Vrai-Prix (vraiprix.db,91# 3,7 M unités d'évaluation avec adresse, lat/lng, estimation, fourchette).92# Une jointure d'adresse (FTS) par annonce → remplit d'un coup :93# · lat/lng manquants (géocodage instantané, sans API externe)94# · l'estimation Vrai-Prix (valeur + P10-P90 + lien /estimation/{id})95# Bien plus rapide que l'API vrai-prix (une requête réseau par annonce).96# -----------------------------------------------------------------------------97from __future__ import annotations9899import json100import os101import re102import sqlite3103import time104import unicodedata105106from . import db107108# Emplacement de la base Vrai-Prix (copiée à côté de immoka.db sur le nœud).109VP_DB = os.environ.get(110 "VRAIPRIX_DB",111 str((__import__("pathlib").Path(__file__).resolve().parent.parent112 / "data" / "vraiprix.db")))113SITE = "https://www.vrai-prix.com"114_BBOX = (44.5, 63.0, -80.0, -56.0) # Québec115116117def _norm(s: str) -> str:118 return "".join(c for c in unicodedata.normalize("NFD", (s or "").lower())119 if unicodedata.category(c) != "Mn").strip()120121122# mots de « type de voie » ignorés dans l'appariement (variabilité rue/av/boul…)123_VOIE = {"rue", "av", "ave", "avenue", "boul", "boulevard", "bd", "blvd",124 "ch", "chemin", "place", "pl", "rang", "rangs", "rg", "montee",125 "montée", "mtee", "cote", "côte", "route", "rte", "terrasse", "tsse",126 "ter", "impasse", "imp", "croissant", "crois", "croiss", "cours",127 "allee", "allée", "prom", "promenade", "carre", "aut", "autoroute",128 "de", "du", "des", "la", "le", "les", "l", "d", "et", "sur",129 "est", "ouest", "nord", "sud", "st", "ste", "saint", "sainte"}130131_APP_RE = r"\b(?:app?t?|appartement|unite|suite|local|bureau|#)\s*[\w-]+"132133134def _street_words(norm_addr: str) -> set:135 """Mots significatifs de la rue (sans n° civique, type de voie, n° d'app.)."""136 a = re.sub(_APP_RE, " ", norm_addr.split(",")[0])137 a = re.sub(r"[^a-z0-9 ]+", " ", a)138 a = re.sub(r"^\s*\d+[a-z]{0,2}(?:\s+\d+)?\s+", " ", a) # civique(s) en tête139 toks = [t for t in a.split() if t]140 return {t for t in toks if t not in _VOIE and len(t) > 1}141142143def _addr_parts(address: str) -> tuple[list, list]:144 """→ (civiques candidats, mots de rue). Gère « 822Z » (suffixe de lettre),145 « 102 50 Rue X » (app-civique : les deux nombres sont candidats) et146 conserve les rues numériques (« Route 202 », « 117e Avenue »)."""147 a = _norm(address).split(",")[0]148 a = re.sub(_APP_RE, " ", a)149 a = re.sub(r"[^a-z0-9 ]+", " ", a)150 toks = [t for t in a.split() if t]151 civs = []152 while toks and len(civs) < 2:153 m = re.match(r"^(\d+)[a-z]{0,2}$", toks[0])154 if not m:155 break156 if civs and not toks[0].isdigit(): # ordinal de rue (2e, 3e…) : garder157 break158 civs.append(m.group(1))159 toks = toks[1:]160 words = [t for t in toks if t not in _VOIE and len(t) > 1]161 return civs, words162163164def _fts_query(address: str) -> tuple[str, str]:165 """Requête FTS AND (n° civique + mots significatifs de la rue)."""166 civs, words = _addr_parts(address)167 civ = civs[-1] if civs else ""168 parts = ([civ] if civ else []) + words169 if not parts:170 return "", civ171 return " AND ".join(f'"{p}"' for p in parts), civ172173174def available() -> bool:175 return os.path.exists(VP_DB)176177178def _pack(r) -> dict:179 d = {180 "id": r["id_provinc"], "lat": r["lat"], "lng": r["lng"],181 "value": r["est_hedo"] or r["est_2026"], "low": r["p10"], "high": r["p90"],182 "confidence": None, "confidence_pct": None,183 "url": f"{SITE}/estimation/{r['id_provinc']}",184 }185 d.update(_role_fields(r))186 return d187188189# clés « rôle d'évaluation » ajoutées au JSON vraiprix (valeurs officielles)190ROLE_KEYS = ("valeur_role", "valeur_terrain", "valeur_batiment",191 "annee_construction_role", "superficie_terrain_role_m2",192 "aire_etages_role_m2")193194195def _role_fields(r) -> dict:196 """Champs du rôle d'évaluation foncière de l'unité appariée (officiels) :197 valeurs (rôle/terrain/bâtiment), année de construction et superficies."""198 out = {}199 for src, dst in (("valeur_role", "valeur_role"),200 ("valeur_terrain", "valeur_terrain"),201 ("valeur_batiment", "valeur_batiment"),202 ("annee_construction", "annee_construction_role"),203 ("superficie_terrain_m2", "superficie_terrain_role_m2"),204 ("aire_etages_m2", "aire_etages_role_m2")):205 try:206 v = r[src]207 except (KeyError, IndexError):208 v = None209 if v:210 out[dst] = v211 return out212213214# le terrain du rôle d'une COPROPRIÉTÉ est souvent celui de l'immeuble entier :215# jamais de repli lot_sqft pour ces types216_NO_LOT_TYPES = ("condo", "appartement", "loft", "copropriete")217218219def _apply_role_fallback(con, uid: str, year_built, lot_sqft,220 property_type: str, est: dict) -> tuple[int, int]:221 """Repli des COLONNES depuis le rôle quand la source ne fournit rien :222 year_built ← annee_construction_role, lot_sqft ← superficie_terrain_role_m2223 (sauf copropriétés). Provenance marquée dans details.*_source='role'.224 Retourne (année_remplie, terrain_rempli) ∈ {0,1}²."""225 fy = fl = 0226 y = est.get("annee_construction_role")227 if year_built is None and y and 1600 <= int(y) <= 2049:228 con.execute(229 "UPDATE listings SET year_built=?,"230 " details=json_set(COALESCE(details,'{}'),'$.year_built_source','role')"231 " WHERE uid=? AND year_built IS NULL", (int(y), uid))232 fy = 1233 t = est.get("superficie_terrain_role_m2")234 pt = _norm(property_type or "")235 if (lot_sqft is None and t and float(t) > 0236 and not any(k in pt for k in _NO_LOT_TYPES)):237 con.execute(238 "UPDATE listings SET lot_sqft=?,"239 " details=json_set(COALESCE(details,'{}'),'$.lot_sqft_source','role')"240 " WHERE uid=? AND lot_sqft IS NULL",241 (round(float(t) * 10.7639), uid))242 fl = 1243 return fy, fl244245246def _meters(a1: float, o1: float, a2: float, o2: float) -> float:247 """Distance approx. en mètres (équirectangulaire, ~exact à courte portée)."""248 import math249 dlat = (a2 - a1) * 111_000.0250 dlng = (o2 - o1) * 111_000.0 * math.cos(math.radians(a1))251 return (dlat * dlat + dlng * dlng) ** 0.5252253254# mots génériques ignorés dans la comparaison de municipalités255_MUNI_GEN = {"saint", "sainte", "ville", "de", "du", "des", "la", "le", "les",256 "sur", "au", "aux", "lac", "notre", "dame", "canton", "cantons",257 "municipalite", "paroisse", "village", "mont"}258259260def _muni_norm(s: str) -> str:261 s = re.sub(r"[^a-z0-9 ]+", " ", _norm(s or ""))262 s = re.sub(r"\bst\b", "saint", s)263 s = re.sub(r"\bste\b", "sainte", s)264 return " ".join(s.split())265266267def _muni_one(nc: str, um: str) -> bool:268 if nc in um or um in nc:269 return True270 return bool((set(nc.split()) - _MUNI_GEN) & (set(um.split()) - _MUNI_GEN))271272273def _muni_match(city: str, unit_muni: str, address: str = "") -> bool:274 """Ville de l'annonce vs municipalité du rôle — tolère St/Ste, accents,275 arrondissement (« Gatineau Aylmer ») et la ville glissée dans l'adresse276 (« 1119 Ch. Dunant, Sainte-Anne-des-Lacs » avec city=« Laurentides »)."""277 nc = _muni_norm(city)278 if not nc:279 return True280 um = _muni_norm(unit_muni)281 if not um:282 return False283 cands = [nc] + [_muni_norm(p) for p in _norm(address).split(",")[1:]]284 return any(c and _muni_one(c, um) for c in cands)285286287def _concordance(address: str, city: str, r) -> tuple[bool, bool, bool]:288 """(civique_ok, rue_ok, municipalité_ok) entre l'annonce et l'unité."""289 civs, words = _addr_parts(address)290 ua = _norm(r["adresse"])291 civ_ok = False292 mr = re.match(r"\s*(\d+)\s*-\s*(\d+)", ua)293 ms = re.match(r"\s*(\d+)", ua)294 for c in civs:295 ci = int(c)296 if mr:297 lo, hi = int(mr.group(1)), int(mr.group(2))298 civ_ok = min(lo, hi) <= ci <= max(lo, hi)299 elif ms:300 civ_ok = ms.group(1) == c301 if civ_ok:302 break303 iwords = set(words)304 rue_ok = bool(iwords) and bool(iwords & _street_words(ua))305 muni_ok = _muni_match(city, r["municipalite"] or "", address)306 return civ_ok, rue_ok, muni_ok307308309_COLS = ("id_provinc, adresse, municipalite, lat, lng, est_hedo, est_2026, p10, p90, "310 "annee_construction, aire_etages_m2, superficie_terrain_m2, "311 "valeur_terrain, valeur_batiment, valeur_role")312313314def _match(vp: sqlite3.Connection, address: str, city: str,315 lat: float | None = None, lng: float | None = None) -> dict | None:316 """Apparie une annonce à une unité Vrai-Prix par :317 1) PROXIMITÉ SPATIALE (si lat/lng) — l'unité la plus proche, validée par318 l'adresse (text mining : civique/rue/municipalité) ;319 2) sinon recherche d'adresse FTS stricte.320 Ne retourne un match que s'il est fiable (mieux vaut rien qu'un faux)."""321 # 1) spatial + text-mining : candidats triés par distance322 if lat is not None and lng is not None:323 d = 0.0022 # ~±250 m324 try:325 cands = vp.execute(326 f"SELECT {_COLS} FROM units"327 " WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?",328 (lat - d, lat + d, lng - d, lng + d)).fetchall()329 except sqlite3.OperationalError:330 cands = []331 cands = [r for r in cands if r["lat"] is not None]332 cands.sort(key=lambda r: _meters(lat, lng, r["lat"], r["lng"]))333 has_civ = bool(_addr_parts(address)[0])334 # ≤20 m du plus proche = même propriété (seulement si l'annonce a un335 # n° civique : un terrain géocodé près d'une maison ne doit pas hériter336 # de la valeur du voisin)337 if (cands and has_civ338 and _meters(lat, lng, cands[0]["lat"], cands[0]["lng"]) <= 20):339 return _pack(cands[0])340 for r in cands:341 dm = _meters(lat, lng, r["lat"], r["lng"])342 civ_ok, rue_ok, muni_ok = _concordance(address, city, r)343 # au-delà de 20 m : le CIVIQUE doit concorder (la « même rue » seule344 # apparie l'immeuble d'à côté → mauvais merge)345 if civ_ok and muni_ok and (dm <= 100 or rue_ok):346 return _pack(r)347348 # 2) repli : recherche d'adresse FTS stricte (avec relances)349 civs, words = _addr_parts(address)350 tries = []351 for c in (civs[::-1] or [""]): # civique(s), du plus probable au moins352 parts = ([c] if c else []) + words353 if parts:354 tries.append(" AND ".join(f'"{p}"' for p in parts))355 if civs and words:356 tries.append(" AND ".join(f'"{p}"' for p in words)) # rue seule (dernier recours)357 seen = set()358 for q in tries:359 if q in seen:360 continue361 seen.add(q)362 try:363 rows = vp.execute(364 f"SELECT u.{_COLS.replace(', ', ', u.')} FROM units_fts f"365 " JOIN units u ON u.rowid=f.rowid WHERE units_fts MATCH ? LIMIT 50",366 (q,)).fetchall()367 except sqlite3.OperationalError:368 return None369 for r in rows:370 civ_ok, rue_ok, muni_ok = _concordance(address, city, r)371 if civ_ok and rue_ok and muni_ok:372 return _pack(r)373 return None374375376def run(limit: int | None = None, revalidate: bool = False) -> dict:377 """Apparie les annonces à la base Vrai-Prix : remplit lat/lng (si manquant)378 et l'estimation. `limit` borne le nombre d'annonces traitées.379 `revalidate=True` : re-vérifie AUSSI les annonces déjà appariées (corrige les380 mauvais merges après durcissement du matcher)."""381 if not available():382 print(f"[immo-ka] vraiprix_local: base absente ({VP_DB})")383 return {"error": "vraiprix.db absent"}384 vp = sqlite3.connect(f"file:{VP_DB}?mode=ro", uri=True)385 vp.row_factory = sqlite3.Row386 con = db.connect()387 where = ("active=1 AND dup_hidden=0 AND address<>''" if revalidate388 else "active=1 AND dup_hidden=0 AND address<>''"389 " AND (vraiprix IS NULL OR vraiprix='{}')")390 rows = con.execute(391 f"SELECT uid, address, city, lat, lng, year_built, lot_sqft,"392 f" property_type FROM listings WHERE {where}"393 " ORDER BY first_seen DESC").fetchall()394 if limit is not None:395 rows = rows[:limit]396397 matched = geoloc = miss = 0398 for i, r in enumerate(rows):399 m = _match(vp, r["address"], r["city"], r["lat"], r["lng"])400 try:401 if m and m["value"]:402 est = {k: m[k] for k in ("id", "value", "low", "high",403 "confidence", "confidence_pct", "url")}404 est.update({k: m[k] for k in ROLE_KEYS if m.get(k)})405 con.execute("UPDATE listings SET vraiprix=? WHERE uid=?",406 (json.dumps(est, ensure_ascii=False), r["uid"]))407 # repli des colonnes depuis le rôle (année, terrain)408 _apply_role_fallback(con, r["uid"], r["year_built"],409 r["lot_sqft"], r["property_type"], est)410 # géocodage gratuit : coordonnées de l'unité si l'annonce n'en a pas411 if (r["lat"] is None and m["lat"] is not None412 and _BBOX[0] <= m["lat"] <= _BBOX[1]413 and _BBOX[2] <= m["lng"] <= _BBOX[3]):414 con.execute("UPDATE listings SET lat=?, lng=? WHERE uid=?",415 (m["lat"], m["lng"], r["uid"]))416 geoloc += 1417 matched += 1418 else:419 con.execute("UPDATE listings SET vraiprix='{}' WHERE uid=?", (r["uid"],))420 miss += 1421 if i % 200 == 0:422 con.commit()423 except sqlite3.OperationalError:424 try:425 con.rollback()426 except sqlite3.Error:427 pass428 time.sleep(1.0)429 con.commit()430 con.close()431 vp.close()432 out = {"matched": matched, "geolocated": geoloc, "no_match": miss}433 print(f"[immo-ka] vraiprix_local {out}")434 return out435436437def enrich_role(limit: int | None = None) -> dict:438 """Backfill du rôle d'évaluation pour les annonces DÉJÀ appariées dont le439 JSON vraiprix ne porte pas encore les champs officiels (valeur_role,440 annee_construction_role, superficies…). Aucun ré-appariement : jointure441 directe par id_provinc (clé primaire) — quasi gratuit. Applique aussi les442 replis de colonnes (year_built/lot_sqft) marqués `*_source='role'`."""443 if not available():444 return {"error": "vraiprix.db absent"}445 vp = sqlite3.connect(f"file:{VP_DB}?mode=ro", uri=True)446 vp.row_factory = sqlite3.Row447 con = db.connect()448 rows = con.execute(449 "SELECT uid, vraiprix, year_built, lot_sqft, property_type FROM listings"450 " WHERE active=1 AND vraiprix LIKE '%\"id\"%'"451 " AND vraiprix NOT LIKE '%valeur_role%'"452 " AND vraiprix NOT LIKE '%role_checked%'").fetchall()453 if limit is not None:454 rows = rows[:limit]455 enriched = fallback_y = fallback_l = 0456 for i, r in enumerate(rows):457 try:458 est = json.loads(r["vraiprix"]) or {}459 except (TypeError, ValueError):460 continue461 if not est.get("id"):462 continue463 u = vp.execute(464 "SELECT annee_construction, aire_etages_m2, superficie_terrain_m2,"465 " valeur_terrain, valeur_batiment, valeur_role"466 " FROM units WHERE id_provinc=?", (str(est["id"]),)).fetchone()467 try:468 if u is None:469 est["role_checked"] = 1 # unité disparue : ne pas repasser470 else:471 fields = _role_fields(u)472 if not fields:473 est["role_checked"] = 1 # unité sans données de rôle474 est.update(fields)475 fy, fl = _apply_role_fallback(con, r["uid"], r["year_built"],476 r["lot_sqft"], r["property_type"], est)477 fallback_y += fy478 fallback_l += fl479 con.execute("UPDATE listings SET vraiprix=? WHERE uid=?",480 (json.dumps(est, ensure_ascii=False), r["uid"]))481 enriched += 1482 if i % 500 == 0:483 con.commit()484 except sqlite3.OperationalError:485 try:486 con.rollback()487 except sqlite3.Error:488 pass489 time.sleep(1.0)490 con.commit()491 # réparation set-based (idempotente, instantanée) : ré-applique le repli de492 # colonnes depuis le JSON vraiprix déjà enrichi — filet de sécurité si une493 # mise à jour de source a écrasé year_built/lot_sqft (anciens process sans494 # COALESCE, edge cases de course entre writer et backfill).495 cur = con.execute(496 "UPDATE listings SET"497 " year_built=CAST(json_extract(vraiprix,'$.annee_construction_role') AS INT),"498 " details=json_set(COALESCE(details,'{}'),'$.year_built_source','role')"499 " WHERE active=1 AND year_built IS NULL"500 " AND CAST(json_extract(vraiprix,'$.annee_construction_role') AS INT)"501 " BETWEEN 1600 AND 2049")502 repaired_y = cur.rowcount503 like_condo = ("lower(property_type) LIKE '%condo%'"504 " OR lower(property_type) LIKE '%appartement%'"505 " OR lower(property_type) LIKE '%loft%'"506 " OR lower(property_type) LIKE '%copropri%'")507 cur = con.execute(508 "UPDATE listings SET"509 " lot_sqft=ROUND(CAST(json_extract(vraiprix,'$.superficie_terrain_role_m2')"510 " AS REAL) * 10.7639),"511 " details=json_set(COALESCE(details,'{}'),'$.lot_sqft_source','role')"512 " WHERE active=1 AND lot_sqft IS NULL"513 " AND CAST(json_extract(vraiprix,'$.superficie_terrain_role_m2') AS REAL) > 0"514 f" AND NOT ({like_condo})")515 repaired_l = cur.rowcount516 con.commit()517 con.close()518 vp.close()519 out = {"role_enriched": enriched, "year_built_filled": fallback_y,520 "lot_filled": fallback_l, "repaired_year": repaired_y,521 "repaired_lot": repaired_l}522 print(f"[immo-ka] vraiprix_local.enrich_role {out}")523 return out524