Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/public.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-11-2513# Last Modified : 2026-11-2514#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# public.py : la règle UNIQUE de ce qui est montré au public, le verdict91# « Vrai-Prix » et la normalisation des régions. Tous les endpoints publics92# (recherche, carte, facettes, sources, annuaire, statistiques, SEO) partent93# d'ici : leurs totaux concordent par construction.94# -----------------------------------------------------------------------------95from __future__ import annotations9697import re98import threading99import time100import unicodedata101102# petites annonces généralistes : on n'y retient que les vrais biens immobiliers103CLASSIFIEDS = ("fb_marketplace", "kijiji", "lespac")104105# types de propriété canoniques (normalize.normalize_property_type)106CANON_TYPES = ("Maison", "Condo", "Terrain", "Commercial", "Duplex", "Triplex",107 "Multiplex", "Fermette/Agricole", "Maison de ville", "Jumelé",108 "Maison mobile", "Chalet")109110111def _in(values) -> str:112 return "(" + ",".join("'" + v.replace("'", "''") + "'" for v in values) + ")"113114115# Inscription publique = active, publiée (seuil de qualité), sans doublon, au116# Québec. Les petites annonces dont le « type » n'est pas un type de propriété117# (Marketplace range aussi des véhicules sous « à vendre » : « 2022 ford118# f-150 », « Tracteur john deere »…) sont écartées.119#120# Immo-Ka n'affiche que des biens À VENDRE : les loyers que certaines sources121# mêlent à leurs inscriptions (« 13 000$ par mois », baux commerciaux, « à122# louer 925 $ ») sont écartés par leur libellé de prix ou un montant trop bas123# pour une vente. (`details.transaction` n'est pas fiable sous 25 000 $ : un124# terrain à 19 900 $ y est marqué « location ».)125#126# Le « + » devant dup_of empêche SQLite de choisir l'index idx_listings_dupof127# (presque toutes les lignes ont dup_of NULL) : avec une ville, il prend128# idx_listings_city et répond 7 fois plus vite.129PUBLIC = ("active=1 AND published=1 AND dup_hidden=0 AND +dup_of IS NULL"130 " AND COALESCE(region,'')<>'Ontario'"131 " AND COALESCE(region,'') NOT LIKE 'Autres pays%'"132 " AND COALESCE(city,'') NOT LIKE '%Autres pays%'"133 f" AND (source NOT IN {_in(CLASSIFIEDS)}"134 f" OR property_type IN {_in(CANON_TYPES)})"135 " AND (price IS NULL OR price>=5000)"136 " AND COALESCE(price_label,'') NOT LIKE '%mois%'"137 " AND COALESCE(price_label,'') NOT LIKE '%month%'"138 " AND COALESCE(price_label,'') NOT LIKE '%/mth%'")139140# Même règle sans la condition « active » : pour les statistiques qui comptent141# aussi les inscriptions RETIRÉES (retraits, délais avant retrait, reconstitution142# de l'inventaire jour par jour).143PUBLIC_EVER = PUBLIC.replace("active=1 AND ", "", 1)144assert "active=1" not in PUBLIC_EVER145146# emprise du Québec habité : écarte les coordonnées aberrantes147QC_BOUNDS = "lat BETWEEN 44.9 AND 62.6 AND lng BETWEEN -80.0 AND -57.0"148149# bornes de plausibilité d'un prix de vente (statistiques, médianes)150PRICE_MIN, PRICE_MAX = 25_000, 50_000_000151PRICE_OK = f"price BETWEEN {PRICE_MIN} AND {PRICE_MAX}"152153# --- Verdict Vrai-Prix ---------------------------------------------------------154# UNE seule règle pour toute l'application (recherche, carte, fiche, pages par155# ville, statistiques, rapports et fiche PDF). Les clients lisent les seuils156# dans /api/version et /api/facets (`verdict_thresholds`) au lieu de les recoder.157#158# écart = (prix demandé − estimation) / estimation × 100159# « sous » si écart <= VP_SOUS (−8 %)160# « sur » si écart >= VP_SUR (+8 %)161# « marche » entre les deux162# aucun verdict si : pas d'estimation ; écart hors de VP_BOUNDS (−50 % …163# +100 %, presque toujours un mauvais appariement) ; ou estimation située164# HORS de sa propre fourchette [low, high] — une estimation incohérente avec165# elle-même (≈ 10 700 inscriptions) ne sert pas à juger un prix.166VP_SOUS, VP_SUR = -8.0, 8.0167VP_BOUNDS = (-50.0, 100.0)168VP_VALUE_SQL = "CAST(json_extract(vraiprix,'$.value') AS REAL)"169VP_LOW_SQL = "CAST(json_extract(vraiprix,'$.low') AS REAL)"170VP_HIGH_SQL = "CAST(json_extract(vraiprix,'$.high') AS REAL)"171VP_CODES = {"sous": "s", "marche": "m", "sur": "o"}172173174def verdict_thresholds() -> dict:175 """Seuils du verdict, tels qu'exposés aux clients."""176 return {177 "sous_max_pct": VP_SOUS, "sur_min_pct": VP_SUR,178 "ecart_min_pct": VP_BOUNDS[0], "ecart_max_pct": VP_BOUNDS[1],179 "estimation_dans_sa_fourchette": True,180 "codes": dict(VP_CODES),181 "formule": "(price - vp_value) / vp_value * 100",182 }183184185def estimate_ok(value, low=None, high=None) -> bool:186 """L'estimation est exploitable : positive et dans sa propre fourchette."""187 if not value or value <= 0:188 return False189 if low is not None and high is not None and low > 0 and high > 0:190 return min(low, high) <= value <= max(low, high)191 return True192193194def deviation(price, value, low=None, high=None) -> float | None:195 """Écart (%) prix demandé vs estimation, ou None si incalculable/aberrant."""196 if not price or price <= 0 or not estimate_ok(value, low, high):197 return None198 dev = (price - value) * 100.0 / value199 if not (VP_BOUNDS[0] <= dev <= VP_BOUNDS[1]):200 return None201 return round(dev, 1)202203204def verdict_of(dev: float | None) -> str | None:205 if dev is None:206 return None207 if dev <= VP_SOUS:208 return "sous"209 if dev >= VP_SUR:210 return "sur"211 return "marche"212213214def verdict(price, value, low=None, high=None) -> tuple[float | None, str | None]:215 dev = deviation(price, value, low, high)216 return dev, verdict_of(dev)217218219# --- Régions administratives ---------------------------------------------------220# Les sources nomment la région chacune à leur façon (« 15 », « Laurentides »,221# « The Laurentians », « Laval Rive Nord »…) et la moitié des inscriptions n'en222# ont pas. `region_name()` ramène tout aux 17 régions administratives ; pour une223# inscription sans région exploitable, la région majoritaire de sa ville sert.224REGIONS = {225 "01": "Bas-Saint-Laurent", "02": "Saguenay–Lac-Saint-Jean",226 "03": "Capitale-Nationale", "04": "Mauricie", "05": "Estrie",227 "06": "Montréal", "07": "Outaouais", "08": "Abitibi-Témiscamingue",228 "09": "Côte-Nord", "10": "Nord-du-Québec",229 "11": "Gaspésie–Îles-de-la-Madeleine", "12": "Chaudière-Appalaches",230 "13": "Laval", "14": "Lanaudière", "15": "Laurentides", "16": "Montérégie",231 "17": "Centre-du-Québec",232}233234235def _key(s: str) -> str:236 # les tirets longs (« Saguenay–Lac-Saint-Jean ») ne survivent pas à l'ASCII237 s = (s or "").replace("–", " ").replace("—", " ")238 s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()239 return re.sub(r"[^a-z0-9]+", " ", s.lower()).strip()240241242_ALIASES = {_key(v): v for v in REGIONS.values()}243_ALIASES.update({244 "region de quebec": "Capitale-Nationale", "quebec rive nord": "Capitale-Nationale",245 "portneuf": "Capitale-Nationale", "charlevoix": "Capitale-Nationale",246 "quebec city": "Capitale-Nationale",247 "quebec rive sud": "Chaudière-Appalaches",248 "rive sud de montreal": "Montérégie", "monteregie rive sud montreal": "Montérégie",249 "monteregie ouest": "Montérégie", "monteregie est": "Montérégie",250 "south shore": "Montérégie",251 "eastern townships": "Estrie", "cantons de l est": "Estrie", "the estrie": "Estrie",252 "the laurentians": "Laurentides", "the mauricie": "Mauricie",253 "bas st laurent": "Bas-Saint-Laurent",254 "saguenay lac st jean": "Saguenay–Lac-Saint-Jean",255 "gaspesie iles de la madeleine": "Gaspésie–Îles-de-la-Madeleine",256 "gaspesie": "Gaspésie–Îles-de-la-Madeleine",257 "iles de la madeleine": "Gaspésie–Îles-de-la-Madeleine",258 "island of montreal": "Montréal", "ile de montreal": "Montréal",259})260# libellés qui couvrent plusieurs régions ou la province entière : la ville tranche261_AMBIGUOUS = {"quebec", "laval rive nord", "province de quebec", "qc"}262263264def region_name(raw: str | None) -> str | None:265 """Libellé de région d'une source → région administrative, ou None."""266 if not raw:267 return None268 raw = raw.strip()269 if raw in REGIONS:270 return REGIONS[raw]271 k = _key(raw)272 if k in _AMBIGUOUS:273 return None274 return _ALIASES.get(k)275276277_REG_TTL = 900278_REG_CACHE: dict = {"ts": 0.0, "data": None}279_REG_LOCK = threading.Lock()280281282def _build_region_index() -> dict:283 from . import db284 con = db.connect()285 try:286 rows = con.execute(287 f"SELECT COALESCE(region,'') region, city, COUNT(*) n FROM listings"288 f" WHERE {PUBLIC} GROUP BY region, city").fetchall()289 finally:290 con.close()291 cells: dict[tuple, dict[str, int]] = {}292 con = db.connect()293 try:294 for r in con.execute(295 f"SELECT ROUND(lat,1) y, ROUND(lng,1) x, region, COUNT(*) n FROM listings"296 f" WHERE {PUBLIC} AND lat IS NOT NULL AND COALESCE(region,'')<>''"297 " GROUP BY y, x, region"):298 name = region_name(r["region"])299 if name:300 c = cells.setdefault((r["y"], r["x"]), {})301 c[name] = c.get(name, 0) + r["n"]302 finally:303 con.close()304 raw_to_name: dict[str, str | None] = {}305 votes: dict[str, dict[str, int]] = {}306 for r in rows:307 raw = r["region"]308 if raw not in raw_to_name:309 raw_to_name[raw] = region_name(raw)310 name = raw_to_name[raw]311 if name and r["city"]:312 v = votes.setdefault(r["city"], {})313 v[name] = v.get(name, 0) + r["n"]314 # région d'une ville = majorité nette (>= 60 %) des inscriptions qui en ont une315 city_region: dict[str, str] = {}316 for city, v in votes.items():317 name, n = max(v.items(), key=lambda kv: kv[1])318 if n >= 0.6 * sum(v.values()):319 city_region[city] = name320 counts: dict[str, int] = {}321 for r in rows:322 name = raw_to_name[r["region"]] or city_region.get(r["city"] or "")323 if name:324 counts[name] = counts.get(name, 0) + r["n"]325 by_name: dict[str, dict] = {}326 for raw, name in raw_to_name.items():327 if name:328 by_name.setdefault(name, {"raw": [], "cities": []})["raw"].append(raw)329 for city, name in city_region.items():330 by_name.setdefault(name, {"raw": [], "cities": []})["cities"].append(city)331 return {"cells": cells, "raw_to_name": raw_to_name, "city_region": city_region,332 "by_name": by_name, "counts": counts,333 "unmapped_raw": [raw for raw, name in raw_to_name.items() if not name]}334335336def region_index() -> dict:337 """Index des régions (cache 15 min, recalcul à un seul fil)."""338 cached = _REG_CACHE["data"]339 if cached is not None and time.time() - _REG_CACHE["ts"] < _REG_TTL:340 return cached341 if not _REG_LOCK.acquire(blocking=cached is None):342 return cached343 try:344 cached = _REG_CACHE["data"]345 if cached is not None and time.time() - _REG_CACHE["ts"] < _REG_TTL:346 return cached347 data = _build_region_index()348 _REG_CACHE.update(ts=time.time(), data=data)349 return data350 finally:351 _REG_LOCK.release()352353354def region_of(raw: str | None, city: str | None) -> str | None:355 """Région administrative d'une inscription (libellé source, sinon ville)."""356 idx = region_index()357 return region_name(raw) or idx["city_region"].get(city or "")358359360def region_clause(name: str) -> tuple[str, list]:361 """Clause SQL (et arguments) des inscriptions d'une région administrative."""362 idx = region_index()363 canon = region_name(name) or name364 entry = idx["by_name"].get(canon)365 if not entry:366 return " AND 0", []367 raws, cities = entry["raw"], entry["cities"]368 parts, args = [], []369 if raws:370 parts.append(f"COALESCE(region,'') IN ({','.join('?' * len(raws))})")371 args += raws372 if cities:373 unm = idx["unmapped_raw"]374 parts.append(f"(COALESCE(region,'') IN ({','.join('?' * len(unm))})"375 f" AND city IN ({','.join('?' * len(cities))}))")376 args += unm + cities377 return " AND (" + " OR ".join(parts) + ")", args378379380def region_at(lat, lng, min_share: float = 0.7) -> str | None:381 """Région administrative d'un point : majorité nette (>= 70 %) des382 inscriptions à région connue de la cellule de 0,1° (≈ 10 km), sinon de la383 cellule et de ses huit voisines. None si rien de net."""384 if lat is None or lng is None:385 return None386 cells = region_index()["cells"]387 y, x = round(lat, 1), round(lng, 1)388 for ring in (0, 1):389 votes: dict[str, int] = {}390 for dy in range(-ring, ring + 1):391 for dx in range(-ring, ring + 1):392 for name, n in cells.get((round(y + dy * 0.1, 1), round(x + dx * 0.1, 1)), {}).items():393 votes[name] = votes.get(name, 0) + n394 if votes:395 name, n = max(votes.items(), key=lambda kv: kv[1])396 if n >= min_share * sum(votes.values()) and n >= 3:397 return name398 return None399