Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/poi.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-1213# Last Modified : 2026-09-0714#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# poi.py : commodités de proximité par immeuble via Overpass (OpenStreetMap)91# Pour chaque immeuble géolocalisé, une requête Overpass unique récupère92# les points d'intérêt utiles à un locataire (épicerie, pharmacie, école,93# garderie, parc, arrêt de bus, gym, clinique…) ; on retient le PLUS PROCHE94# de chaque catégorie avec sa distance. Cache permanent par coordonnées95# (table poi_cache, clé arrondie à 4 décimales ≈ 11 m : les unités d'un96# même immeuble partagent la même entrée). Politesse : 1 requête/seconde.97# -----------------------------------------------------------------------------98from __future__ import annotations99100import json101import math102import time103104import requests105106from . import db107108# Miroirs Overpass (rotation en cas d'erreur/limitation) — kumi.systems109# tolère mieux les gros volumes que l'instance officielle110OVERPASS_URLS = [111 "https://overpass.kumi.systems/api/interpreter",112 "https://overpass-api.de/api/interpreter",113]114USER_AGENT = "ImmoKaBot/1.0 (agregateur logements Quebec; +contact@spboucher.ai)"115REQUEST_DELAY = 2.0116REFRESH_AFTER = 90 * 86400 # les POI bougent peu : rafraîchir aux ~3 mois117118# Stratégie « par tuiles » : plutôt qu'une requête par immeuble (l'union119# d'around() est très coûteuse côté Overpass), on télécharge TOUS les POI120# des catégories par tuile de 0,5° couvrant nos immeubles (~10 tuiles pour121# Québec/Lévis + Grand Montréal), puis on calcule les plus proches en local.122TILE = 0.5123TILE_MARGIN = 0.04 # ~4 km > plus grand rayon de catégorie (3 km)124125# Catégories : (clé, libellé FR, sélecteur Overpass, rayon m)126CATEGORIES: list[tuple[str, str, str, int]] = [127 ("epicerie", "Épicerie", '["shop"="supermarket"]', 1500),128 ("depanneur", "Dépanneur", '["shop"="convenience"]', 800),129 ("pharmacie", "Pharmacie", '["amenity"="pharmacy"]', 1500),130 ("ecole", "École", '["amenity"="school"]', 1500),131 ("garderie", "Garderie", '["amenity"~"^(kindergarten|childcare)$"]', 1500),132 ("parc", "Parc", '["leisure"="park"]', 1200),133 ("bus", "Arrêt de bus", '["highway"="bus_stop"]', 600),134 ("metro", "Métro", '["railway"="station"]["station"="subway"]', 1500),135 ("gym", "Gym", '["leisure"="fitness_centre"]', 1500),136 ("cafe", "Café", '["amenity"="cafe"]', 1000),137 ("clinique", "Clinique / CLSC", '["amenity"~"^(clinic|doctors)$"]', 2000),138 ("hopital", "Hôpital", '["amenity"="hospital"]', 3000),139 ("bibliotheque", "Bibliothèque", '["amenity"="library"]', 2000),140]141142LABELS = {cat: label for cat, label, _, _ in CATEGORIES}143144145def coord_key(lat: float, lng: float) -> str:146 return f"{round(lat, 4)},{round(lng, 4)}"147148149def _haversine_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float:150 r = 6371000.0151 p1, p2 = math.radians(lat1), math.radians(lat2)152 dp, dl = math.radians(lat2 - lat1), math.radians(lng2 - lng1)153 a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2154 return 2 * r * math.asin(math.sqrt(a))155156157def _tile_of(lat: float, lng: float) -> tuple[int, int]:158 return (math.floor(lat / TILE), math.floor(lng / TILE))159160161def _build_tile_query(ty: int, tx: int) -> str:162 """Tous les POI des catégories dans la tuile (bbox élargie de la marge)."""163 s = ty * TILE - TILE_MARGIN164 n = (ty + 1) * TILE + TILE_MARGIN165 w = tx * TILE - TILE_MARGIN166 e = (tx + 1) * TILE + TILE_MARGIN167 bbox = f"{s:.4f},{w:.4f},{n:.4f},{e:.4f}"168 parts = [f"nwr{sel}({bbox});" for _c, _l, sel, _r in CATEGORIES]169 return f'[out:json][timeout:180];({"".join(parts)});out center tags;'170171172def _match_category(tags: dict) -> str | None:173 """Retrouve la catégorie Lou-Ka d'un élément OSM retourné."""174 shop = tags.get("shop")175 amenity = tags.get("amenity")176 leisure = tags.get("leisure")177 if shop == "supermarket":178 return "epicerie"179 if shop == "convenience":180 return "depanneur"181 if amenity == "pharmacy":182 return "pharmacie"183 if amenity == "school":184 return "ecole"185 if amenity in ("kindergarten", "childcare"):186 return "garderie"187 if leisure == "park":188 return "parc"189 if tags.get("highway") == "bus_stop":190 return "bus"191 if tags.get("railway") == "station" and tags.get("station") == "subway":192 return "metro"193 if leisure == "fitness_centre":194 return "gym"195 if amenity == "cafe":196 return "cafe"197 if amenity in ("clinic", "doctors"):198 return "clinique"199 if amenity == "hospital":200 return "hopital"201 if amenity == "library":202 return "bibliotheque"203 return None204205206_RADII = {cat: radius for cat, _l, _s, radius in CATEGORIES}207208209class PoiClient:210 def __init__(self) -> None:211 self.session = requests.Session()212 self.session.headers["User-Agent"] = USER_AGENT213 self._last = 0.0214 self._url_idx = 0215216 def _post(self, query: str) -> list | None:217 """POST Overpass avec throttling et rotation de miroir sur erreur."""218 wait = REQUEST_DELAY - (time.time() - self._last)219 if wait > 0:220 time.sleep(wait)221 for essai in range(len(OVERPASS_URLS)):222 url = OVERPASS_URLS[(self._url_idx + essai) % len(OVERPASS_URLS)]223 try:224 resp = self.session.post(url, data={"data": query}, timeout=90)225 self._last = time.time()226 resp.raise_for_status()227 self._url_idx = (self._url_idx + essai) % len(OVERPASS_URLS)228 return resp.json().get("elements") or []229 except Exception:230 self._last = time.time()231 continue232 return None233234 def fetch_tile(self, ty: int, tx: int) -> list[dict] | None:235 """Tous les POI catégorisés d'une tuile : [{cat, name, lat, lng}]."""236 elements = self._post(_build_tile_query(ty, tx))237 if elements is None:238 return None239 pois = []240 for el in elements:241 tags = el.get("tags") or {}242 cat = _match_category(tags)243 if cat is None:244 continue245 elat = el.get("lat") or (el.get("center") or {}).get("lat")246 elng = el.get("lon") or (el.get("center") or {}).get("lon")247 if elat is None or elng is None:248 continue249 pois.append({"cat": cat, "name": (tags.get("name") or LABELS[cat])[:60],250 "lat": elat, "lng": elng})251 return pois252253254def _nearest_by_cat(lat: float, lng: float, pois_by_cat: dict[str, list[dict]]) -> list[dict]:255 """Plus proche POI de chaque catégorie (dans son rayon), trié par distance."""256 out = []257 for cat, pois in pois_by_cat.items():258 radius = _RADII[cat]259 # préfiltre rectangulaire bon marché avant l'haversine260 dlat_max = radius / 111000.0261 dlng_max = radius / (111000.0 * max(0.2, math.cos(math.radians(lat))))262 best = None263 for p in pois:264 if abs(p["lat"] - lat) > dlat_max or abs(p["lng"] - lng) > dlng_max:265 continue266 d = _haversine_m(lat, lng, p["lat"], p["lng"])267 if d <= radius and (best is None or d < best["dist_m"]):268 # lat/lng conservés (2026-09-07) pour placer le lieu sur la269 # carte de la fiche ; les entrées de cache antérieures n'en ont270 # pas — le frontend tolère leur absence.271 best = {"cat": cat, "name": p["name"], "dist_m": round(d),272 "lat": round(p["lat"], 6), "lng": round(p["lng"], 6)}273 if best:274 out.append(best)275 return sorted(out, key=lambda p: p["dist_m"])276277278def run(limit: int | None = None) -> dict:279 """Remplit poi_cache pour les immeubles géolocalisés qui n'y sont pas.280281 `limit` borne le nombre de requêtes Overpass de cette exécution282 (les entrées déjà en cache ne coûtent rien).283 """284 con = db.connect()285 client = PoiClient()286 rows = con.execute(287 """SELECT DISTINCT ROUND(lat,4) la, ROUND(lng,4) ln FROM listings288 WHERE active=1 AND lat IS NOT NULL AND lng IS NOT NULL""").fetchall()289290 now = time.time()291 a_faire: list[tuple[float, float]] = []292 skipped = 0293 for r in rows:294 cached = con.execute(295 "SELECT ts FROM poi_cache WHERE coord_key=?",296 (f"{r['la']},{r['ln']}",)).fetchone()297 if cached and now - (cached["ts"] or 0) < REFRESH_AFTER:298 skipped += 1299 else:300 a_faire.append((r["la"], r["ln"]))301 if limit is not None:302 a_faire = a_faire[:limit]303304 # 1) télécharger les POI des tuiles nécessaires (une requête par tuile)305 tuiles = sorted({_tile_of(la, ln) for la, ln in a_faire})306 pois_by_tile: dict[tuple[int, int], dict[str, list[dict]]] = {}307 tile_errors = []308 for t in tuiles:309 res = client.fetch_tile(*t)310 if res is None:311 tile_errors.append(t)312 else:313 by_cat: dict[str, list[dict]] = {}314 for p in res:315 by_cat.setdefault(p["cat"], []).append(p)316 pois_by_tile[t] = by_cat317318 # 2) calcul local du plus proche par catégorie pour chaque immeuble319 done = errors = 0320 for la, ln in a_faire:321 t = _tile_of(la, ln)322 if t not in pois_by_tile:323 errors += 1 # tuile en échec : re-tentée au prochain run324 continue325 pois = _nearest_by_cat(la, ln, pois_by_tile[t])326 con.execute(327 "INSERT INTO poi_cache (coord_key, lat, lng, pois, ts) VALUES (?,?,?,?,?)"328 " ON CONFLICT(coord_key) DO UPDATE SET pois=excluded.pois, ts=excluded.ts",329 (coord_key(la, ln), la, ln, json.dumps(pois, ensure_ascii=False), now))330 done += 1331 con.commit()332333 con.close()334 stats = {"fetched": done, "cached": skipped, "errors": errors,335 "tiles": len(tuiles), "tile_errors": len(tile_errors),336 "total_coords": len(rows)}337 print(f"[immo-ka] poi {stats}")338 return stats339