Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/commerces.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2313# 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# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# commerces.py : grands commerces à proximité — API Mapbox Search Box91#92# Pour chaque grande bannière (Costco, Metro, IGA, Walmart…), on interroge93# l'API Search Box de Mapbox (jeton PUBLIC pk.… lu dans94# variable MAPBOX_TOKEN du .env) avec la95# position de l'annonce en `proximity`, et on retient le point de vente le96# plus proche. Cache par cellule d'environ 1 km (data/commerces.db,97# TTL 30 jours) : les fiches d'un même secteur ne recoûtent rien.98# -----------------------------------------------------------------------------99from __future__ import annotations100101import json102import math103import re104import sqlite3105import time106import urllib.parse107import urllib.request108from concurrent.futures import ThreadPoolExecutor109from pathlib import Path110111ROOT = Path(__file__).resolve().parent.parent112DB_PATH = ROOT / "data" / "commerces.db"113UA = "ImmoKaBot/1.0 (+https://www.immo-ka.com; contact@spboucher.ai)"114TTL = 30 * 86400115API = "https://api.mapbox.com/search/searchbox/v1/forward"116117# id, libellé, requête Mapbox, mot-clé de validation (le nom du POI doit le118# contenir, sans accents ni casse — écarte « Station Métro », « Super Qualité »…)119BRANDS = [120 ("costco", "Costco", "Costco Wholesale", "costco"),121 ("walmart", "Walmart", "Walmart Supercentre", "walmart"),122 ("metro", "Metro", "Metro", "metro"),123 ("iga", "IGA", "IGA", "iga"),124 ("maxi", "Maxi", "Maxi", "maxi"),125 ("superc", "Super C", "Super C", "super c"),126 ("provigo", "Provigo", "Provigo", "provigo"),127 ("canadiantire", "Canadian Tire", "Canadian Tire", "canadian tire"),128 ("dollarama", "Dollarama", "Dollarama", "dollarama"),129 ("saq", "SAQ", "SAQ", "saq"),130 ("pharmaprix", "Pharmaprix", "Pharmaprix", "pharmaprix"),131 ("jeancoutu", "Jean Coutu", "Jean Coutu pharmacie", "jean coutu"),132 ("homedepot", "Home Depot", "Home Depot", "home depot"),133 ("rona", "RONA", "RONA", "rona"),134]135136_BAN = ("station", "stationnement")137138139def _norm(s: str) -> str:140 import unicodedata141 s = unicodedata.normalize("NFD", s or "")142 return "".join(c for c in s if unicodedata.category(c) != "Mn").lower()143144_token_cache: list[str] = []145146147def _token() -> str:148 if not _token_cache:149 import os150 tok = os.environ.get("MAPBOX_TOKEN", "").strip()151 if not tok: # ancien emplacement (frontend v1), s'il existe encore152 cfg_path = ROOT / "frontend" / "src" / "kamaps" / "config.ts"153 m = (re.search(r'"(pk\.[A-Za-z0-9._-]+)"', cfg_path.read_text())154 if cfg_path.exists() else None)155 tok = m.group(1) if m else ""156 if not tok:157 raise RuntimeError("jeton Mapbox absent (MAPBOX_TOKEN dans .env)")158 _token_cache.append(tok)159 return _token_cache[0]160161162def _connect() -> sqlite3.Connection:163 DB_PATH.parent.mkdir(parents=True, exist_ok=True)164 con = sqlite3.connect(DB_PATH, timeout=15)165 con.row_factory = sqlite3.Row166 con.execute("""CREATE TABLE IF NOT EXISTS commerces_cache (167 cellule TEXT, brand TEXT, nom TEXT, adresse TEXT,168 lat REAL, lng REAL, fetched_at REAL,169 PRIMARY KEY (cellule, brand))""")170 return con171172173def _dist_m(lat1, lng1, lat2, lng2) -> float:174 dlat = math.radians(lat2 - lat1)175 dlng = math.radians(lng2 - lng1)176 a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1))177 * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2)178 return 6371000 * 2 * math.asin(math.sqrt(a))179180181def _fetch_brand(brand_q: str, lat: float, lng: float,182 match: str = "") -> dict | None:183 params = urllib.parse.urlencode({184 "q": brand_q, "proximity": f"{lng},{lat}", "limit": 5,185 "types": "poi", "language": "fr", "country": "CA",186 "access_token": _token()})187 req = urllib.request.Request(f"{API}?{params}",188 headers={"User-Agent": UA})189 try:190 with urllib.request.urlopen(req, timeout=12) as r:191 feats = json.load(r).get("features") or []192 except Exception:193 return None194 for f in feats:195 p = f.get("properties") or {}196 nom = _norm(p.get("name") or "")197 if match and match not in nom:198 continue199 if any(b in nom for b in _BAN):200 continue201 lng2, lat2 = f["geometry"]["coordinates"][:2]202 return {"nom": p.get("name") or brand_q,203 "adresse": p.get("full_address")204 or p.get("place_formatted") or "",205 "lat": lat2, "lng": lng2}206 return None207208209OVERPASS = ["https://overpass.kumi.systems/api/interpreter",210 "https://overpass-api.de/api/interpreter"]211212213def _fetch_transit(lat: float, lng: float) -> list[tuple[str, dict]]:214 """Station de métro et arrêt de bus les plus proches (OpenStreetMap)."""215 q = f"""[out:json][timeout:20];216(217 node["railway"="station"]["station"="subway"](around:3000,{lat},{lng});218 node["highway"="bus_stop"](around:1000,{lat},{lng});219);220out body;"""221 data = None222 for url in OVERPASS:223 try:224 req = urllib.request.Request(225 url, data=urllib.parse.urlencode({"data": q}).encode(),226 headers={"User-Agent": UA})227 with urllib.request.urlopen(req, timeout=25) as r:228 data = json.load(r)229 break230 except Exception:231 continue232 if not data:233 return []234 best: dict[str, tuple[float, dict]] = {}235 for el in data.get("elements", []):236 tags = el.get("tags") or {}237 kind = ("metro_station" if tags.get("railway") == "station"238 else "arret_bus")239 d = _dist_m(lat, lng, el["lat"], el["lon"])240 if kind not in best or d < best[kind][0]:241 best[kind] = (d, {"nom": tags.get("name")242 or ("Station de métro" if kind == "metro_station"243 else "Arrêt de bus"),244 "adresse": "", "lat": el["lat"],245 "lng": el["lon"]})246 return [(k, v[1]) for k, v in best.items()]247248249TRANSIT = [("metro_station", "Station de métro"),250 ("rem_station", "Station REM"),251 ("arret_bus", "Arrêt de bus"),252 ("gare_train", "Gare de train")]253254_DB_GENRE = {"metro": "metro_station", "rem": "rem_station",255 "bus": "arret_bus", "train": "gare_train"}256257258def _transit_from_db(lat: float, lng: float) -> list[tuple[str, dict]]:259 """Arrêts/stations depuis data/transit.db (extrait OpenStreetMap260 pré-calculé : ~37 000 arrêts de bus, métro, REM, gares du Québec)."""261 db = ROOT / "data" / "transit.db"262 if not db.exists():263 return []264 con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)265 con.row_factory = sqlite3.Row266 out = []267 for genre, rayon in (("metro", 6000), ("rem", 6000), ("bus", 1500),268 ("train", 8000)):269 d = rayon / 111320.0270 rows = con.execute(271 "SELECT nom, lat, lng FROM arrets WHERE genre=? AND lat BETWEEN "272 "? AND ? AND lng BETWEEN ? AND ?",273 (genre, lat - d, lat + d, lng - d, lng + d)).fetchall()274 best = None275 for r in rows:276 dd = _dist_m(lat, lng, r["lat"], r["lng"])277 if dd <= rayon and (best is None or dd < best[0]):278 best = (dd, r)279 if best:280 out.append((_DB_GENRE[genre],281 {"nom": best[1]["nom"] or "", "adresse": "",282 "lat": best[1]["lat"], "lng": best[1]["lng"]}))283 con.close()284 return out285286_POI_CAT = {"metro": "metro_station", "bus": "arret_bus"}287288289def _transit_from_poi(lat: float, lng: float) -> list[tuple[str, dict]]:290 """Métro/bus depuis le cache POI du projet (louka.db, déjà calculé par291 immeuble) — la fiche interroge avec les mêmes coordonnées que poi.py."""292 db_main = ROOT / "data" / next(293 (n for n in ("louka.db", "immoka.db", "immo.db")294 if (ROOT / "data" / n).exists()), "louka.db")295 if not db_main.exists():296 return []297 try:298 con = sqlite3.connect(f"file:{db_main}?mode=ro", uri=True)299 con.row_factory = sqlite3.Row300 d = 300 / 111320.0301 row = con.execute(302 "SELECT pois, lat, lng FROM poi_cache WHERE lat BETWEEN ? AND ? "303 "AND lng BETWEEN ? AND ? ORDER BY (lat-?)*(lat-?)+(lng-?)*(lng-?) "304 "LIMIT 1", (lat - d, lat + d, lng - d, lng + d,305 lat, lat, lng, lng)).fetchone()306 con.close()307 except sqlite3.Error:308 return []309 if row is None:310 return []311 out = []312 for e in json.loads(row["pois"] or "[]"):313 k = _POI_CAT.get(e.get("cat"))314 if k:315 out.append((k, {"nom": e.get("name") or "", "adresse": "",316 "lat": lat, "lng": lng,317 "_dist": e.get("dist_m")}))318 return out319320321def nearby(lat: float, lng: float) -> dict:322 """Grand commerce le plus proche par bannière (cache ~1 km, TTL 30 j)."""323 cell = f"{round(lat, 2)},{round(lng, 2)}"324 con = _connect()325 now = time.time()326 cached = {r["brand"]: r for r in con.execute(327 "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?",328 (cell, now - TTL))}329 manquants = [(bid, q, m) for bid, _, q, m in BRANDS330 if bid not in cached]331 transit_manquant = any(k not in cached for k, _ in TRANSIT)332 if manquants or transit_manquant:333 res: list[tuple[str, dict | None]] = []334 if manquants:335 with ThreadPoolExecutor(max_workers=6) as ex:336 res = list(ex.map(337 lambda b: (b[0], _fetch_brand(b[1], lat, lng, b[2])),338 manquants))339 if transit_manquant:340 tr = (_transit_from_db(lat, lng)341 or _transit_from_poi(lat, lng) or _fetch_transit(lat, lng))342 res.extend(tr)343 with con:344 for bid, hit in res:345 if hit is None:346 continue347 con.execute(348 "INSERT OR REPLACE INTO commerces_cache VALUES "349 "(?,?,?,?,?,?,?)",350 (cell, bid, hit["nom"],351 hit.get("adresse") or (str(hit["_dist"])352 if hit.get("_dist") is not None353 else ""),354 hit["lat"], hit["lng"], now))355 cached = {r["brand"]: r for r in con.execute(356 "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?",357 (cell, now - TTL))}358 con.close()359360 items = []361 transit = []362 for bid, label in TRANSIT:363 r = cached.get(bid)364 if r is not None:365 # distance : celle du cache POI si disponible (adresse numérique)366 d = (float(r["adresse"]) if (r["adresse"] or "").replace(367 ".", "").isdigit() else _dist_m(lat, lng, r["lat"], r["lng"]))368 if d <= 5000:369 transit.append({"id": bid, "commerce": label,370 "nom": r["nom"], "adresse": "",371 "dist_m": round(d),372 "lat": r["lat"], "lng": r["lng"]})373 for bid, label, _q, _m in BRANDS:374 r = cached.get(bid)375 if r is None:376 continue377 d = _dist_m(lat, lng, r["lat"], r["lng"])378 if d > 40000: # au-delà de 40 km : non pertinent379 continue380 items.append({"id": bid, "commerce": label, "nom": r["nom"],381 "adresse": r["adresse"], "dist_m": round(d),382 "lat": r["lat"], "lng": r["lng"]})383 items.sort(key=lambda x: x["dist_m"])384 transit.sort(key=lambda x: x["dist_m"])385 return {"n": len(items), "commerces": items, "transit": transit}386