SPB Git

Repository Public

commerces.py 15.1 KB 383 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/commerces.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-2313# Last Modified    : 2026-08-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# Lou-Ka — Agrégateur de logements à louer (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#   frontend/src/kamaps/config.ts — source de vérité du projet) 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 = "LouKaBot/1.0 (+https://www.lou-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        cfg = (ROOT / "frontend" / "src" / "kamaps" / "config.ts").read_text()150        m = re.search(r'"(pk\.[A-Za-z0-9._-]+)"', cfg)151        if not m:152            raise RuntimeError("jeton Mapbox introuvable (kamaps/config.ts)")153        _token_cache.append(m.group(1))154    return _token_cache[0]155156157def _connect() -> sqlite3.Connection:158    DB_PATH.parent.mkdir(parents=True, exist_ok=True)159    con = sqlite3.connect(DB_PATH, timeout=15)160    con.row_factory = sqlite3.Row161    con.execute("""CREATE TABLE IF NOT EXISTS commerces_cache (162        cellule TEXT, brand TEXT, nom TEXT, adresse TEXT,163        lat REAL, lng REAL, fetched_at REAL,164        PRIMARY KEY (cellule, brand))""")165    return con166167168def _dist_m(lat1, lng1, lat2, lng2) -> float:169    dlat = math.radians(lat2 - lat1)170    dlng = math.radians(lng2 - lng1)171    a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1))172         * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2)173    return 6371000 * 2 * math.asin(math.sqrt(a))174175176def _fetch_brand(brand_q: str, lat: float, lng: float,177                 match: str = "") -> dict | None:178    params = urllib.parse.urlencode({179        "q": brand_q, "proximity": f"{lng},{lat}", "limit": 5,180        "types": "poi", "language": "fr", "country": "CA",181        "access_token": _token()})182    req = urllib.request.Request(f"{API}?{params}",183                                 headers={"User-Agent": UA})184    try:185        with urllib.request.urlopen(req, timeout=12) as r:186            feats = json.load(r).get("features") or []187    except Exception:188        return None189    for f in feats:190        p = f.get("properties") or {}191        nom = _norm(p.get("name") or "")192        if match and match not in nom:193            continue194        if any(b in nom for b in _BAN):195            continue196        lng2, lat2 = f["geometry"]["coordinates"][:2]197        return {"nom": p.get("name") or brand_q,198                "adresse": p.get("full_address")199                           or p.get("place_formatted") or "",200                "lat": lat2, "lng": lng2}201    return None202203204OVERPASS = ["https://overpass.kumi.systems/api/interpreter",205            "https://overpass-api.de/api/interpreter",206            "https://maps.mail.ru/osm/tools/overpass/api/interpreter",207            "https://overpass.openstreetmap.fr/api/interpreter"]208209210def _fetch_transit(lat: float, lng: float) -> list[tuple[str, dict]]:211    """Station de métro et arrêt de bus les plus proches (OpenStreetMap)."""212    q = f"""[out:json][timeout:20];213(214  node["railway"="station"]["station"="subway"](around:3000,{lat},{lng});215  node["highway"="bus_stop"](around:1000,{lat},{lng});216);217out body;"""218    data = None219    for url in OVERPASS:220        try:221            req = urllib.request.Request(222                url, data=urllib.parse.urlencode({"data": q}).encode(),223                headers={"User-Agent": UA})224            with urllib.request.urlopen(req, timeout=25) as r:225                data = json.load(r)226            break227        except Exception:228            continue229    if not data:230        return []231    best: dict[str, tuple[float, dict]] = {}232    for el in data.get("elements", []):233        tags = el.get("tags") or {}234        kind = ("metro_station" if tags.get("railway") == "station"235                else "arret_bus")236        d = _dist_m(lat, lng, el["lat"], el["lon"])237        if kind not in best or d < best[kind][0]:238            best[kind] = (d, {"nom": tags.get("name")239                              or ("Station de métro" if kind == "metro_station"240                                  else "Arrêt de bus"),241                              "adresse": "", "lat": el["lat"],242                              "lng": el["lon"]})243    return [(k, v[1]) for k, v in best.items()]244245246TRANSIT = [("metro_station", "Station de métro"),247           ("rem_station", "Station REM"),248           ("arret_bus", "Arrêt de bus"),249           ("gare_train", "Gare de train")]250251_DB_GENRE = {"metro": "metro_station", "rem": "rem_station",252             "bus": "arret_bus", "train": "gare_train"}253254255def _transit_from_db(lat: float, lng: float) -> list[tuple[str, dict]]:256    """Arrêts/stations depuis data/transit.db (extrait OpenStreetMap257    pré-calculé : ~37 000 arrêts de bus, métro, REM, gares du Québec)."""258    db = ROOT / "data" / "transit.db"259    if not db.exists():260        return []261    con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)262    con.row_factory = sqlite3.Row263    out = []264    for genre, rayon in (("metro", 6000), ("rem", 6000), ("bus", 1500),265                         ("train", 8000)):266        d = rayon / 111320.0267        rows = con.execute(268            "SELECT nom, lat, lng FROM arrets WHERE genre=? AND lat BETWEEN "269            "? AND ? AND lng BETWEEN ? AND ?",270            (genre, lat - d, lat + d, lng - d, lng + d)).fetchall()271        best = None272        for r in rows:273            dd = _dist_m(lat, lng, r["lat"], r["lng"])274            if dd <= rayon and (best is None or dd < best[0]):275                best = (dd, r)276        if best:277            out.append((_DB_GENRE[genre],278                        {"nom": best[1]["nom"] or "", "adresse": "",279                         "lat": best[1]["lat"], "lng": best[1]["lng"]}))280    con.close()281    return out282283_POI_CAT = {"metro": "metro_station", "bus": "arret_bus"}284285286def _transit_from_poi(lat: float, lng: float) -> list[tuple[str, dict]]:287    """Métro/bus depuis le cache POI du projet (louka.db, déjà calculé par288    immeuble) — la fiche interroge avec les mêmes coordonnées que poi.py."""289    db_main = ROOT / "data" / next(290        (n for n in ("louka.db", "immoka.db", "immo.db")291         if (ROOT / "data" / n).exists()), "louka.db")292    if not db_main.exists():293        return []294    try:295        con = sqlite3.connect(f"file:{db_main}?mode=ro", uri=True)296        con.row_factory = sqlite3.Row297        d = 300 / 111320.0298        row = con.execute(299            "SELECT pois, lat, lng FROM poi_cache WHERE lat BETWEEN ? AND ? "300            "AND lng BETWEEN ? AND ? ORDER BY (lat-?)*(lat-?)+(lng-?)*(lng-?) "301            "LIMIT 1", (lat - d, lat + d, lng - d, lng + d,302                        lat, lat, lng, lng)).fetchone()303        con.close()304    except sqlite3.Error:305        return []306    if row is None:307        return []308    out = []309    for e in json.loads(row["pois"] or "[]"):310        k = _POI_CAT.get(e.get("cat"))311        if k:312            out.append((k, {"nom": e.get("name") or "", "adresse": "",313                            "lat": lat, "lng": lng,314                            "_dist": e.get("dist_m")}))315    return out316317318def nearby(lat: float, lng: float) -> dict:319    """Grand commerce le plus proche par bannière (cache ~1 km, TTL 30 j)."""320    cell = f"{round(lat, 2)},{round(lng, 2)}"321    con = _connect()322    now = time.time()323    cached = {r["brand"]: r for r in con.execute(324        "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?",325        (cell, now - TTL))}326    manquants = [(bid, q, m) for bid, _, q, m in BRANDS327                 if bid not in cached]328    transit_manquant = any(k not in cached for k, _ in TRANSIT)329    if manquants or transit_manquant:330        res: list[tuple[str, dict | None]] = []331        if manquants:332            with ThreadPoolExecutor(max_workers=6) as ex:333                res = list(ex.map(334                    lambda b: (b[0], _fetch_brand(b[1], lat, lng, b[2])),335                    manquants))336        if transit_manquant:337            tr = (_transit_from_db(lat, lng)338                  or _transit_from_poi(lat, lng) or _fetch_transit(lat, lng))339            res.extend(tr)340        with con:341            for bid, hit in res:342                if hit is None:343                    continue344                con.execute(345                    "INSERT OR REPLACE INTO commerces_cache VALUES "346                    "(?,?,?,?,?,?,?)",347                    (cell, bid, hit["nom"],348                     hit.get("adresse") or (str(hit["_dist"])349                                            if hit.get("_dist") is not None350                                            else ""),351                     hit["lat"], hit["lng"], now))352        cached = {r["brand"]: r for r in con.execute(353            "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?",354            (cell, now - TTL))}355    con.close()356357    items = []358    transit = []359    for bid, label in TRANSIT:360        r = cached.get(bid)361        if r is not None:362            # distance : celle du cache POI si disponible (adresse numérique)363            d = (float(r["adresse"]) if (r["adresse"] or "").replace(364                 ".", "").isdigit() else _dist_m(lat, lng, r["lat"], r["lng"]))365            if d <= 5000:366                transit.append({"id": bid, "commerce": label,367                                "nom": r["nom"], "adresse": "",368                                "dist_m": round(d),369                                "lat": r["lat"], "lng": r["lng"]})370    for bid, label, _q, _m in BRANDS:371        r = cached.get(bid)372        if r is None:373            continue374        d = _dist_m(lat, lng, r["lat"], r["lng"])375        if d > 40000:                 # au-delà de 40 km : non pertinent376            continue377        items.append({"id": bid, "commerce": label, "nom": r["nom"],378                      "adresse": r["adresse"], "dist_m": round(d),379                      "lat": r["lat"], "lng": r["lng"]})380    items.sort(key=lambda x: x["dist_m"])381    transit.sort(key=lambda x: x["dist_m"])382    return {"n": len(items), "commerces": items, "transit": transit}383
Files main
Menu

Theme