SPB Git

Repository Public

poi.py 14.0 KB 343 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/poi.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0813# Last Modified    : 2026-09-0414#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# 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    # replis vérifiés couvrant le Québec (panne simultanée kumi+officiel114    # constatée le 2026-08-25) ; overpass.osm.ch exclu (extrait suisse)115    "https://maps.mail.ru/osm/tools/overpass/api/interpreter",116    "https://overpass.openstreetmap.fr/api/interpreter",117]118USER_AGENT = "LouKaBot/1.0 (agregateur logements Quebec; +contact@spboucher.ai)"119REQUEST_DELAY = 2.0120REFRESH_AFTER = 90 * 86400      # les POI bougent peu : rafraîchir aux ~3 mois121122# Stratégie « par tuiles » : plutôt qu'une requête par immeuble (l'union123# d'around() est très coûteuse côté Overpass), on télécharge TOUS les POI124# des catégories par tuile de 0,5° couvrant nos immeubles (~10 tuiles pour125# Québec/Lévis + Grand Montréal), puis on calcule les plus proches en local.126TILE = 0.5127TILE_MARGIN = 0.04              # ~4 km > plus grand rayon de catégorie (3 km)128129# Catégories : (clé, libellé FR, sélecteur Overpass, rayon m)130CATEGORIES: list[tuple[str, str, str, int]] = [131    ("epicerie",   "Épicerie",        '["shop"="supermarket"]',                    1500),132    ("depanneur",  "Dépanneur",       '["shop"="convenience"]',                     800),133    ("pharmacie",  "Pharmacie",       '["amenity"="pharmacy"]',                    1500),134    ("ecole",      "École",           '["amenity"="school"]',                      1500),135    ("garderie",   "Garderie",        '["amenity"~"^(kindergarten|childcare)$"]',  1500),136    ("parc",       "Parc",            '["leisure"="park"]',                        1200),137    ("bus",        "Arrêt de bus",    '["highway"="bus_stop"]',                     600),138    ("metro",      "Métro",           '["railway"="station"]["station"="subway"]', 1500),139    ("gym",        "Gym",             '["leisure"="fitness_centre"]',              1500),140    ("cafe",       "Café",            '["amenity"="cafe"]',                        1000),141    ("clinique",   "Clinique / CLSC", '["amenity"~"^(clinic|doctors)$"]',          2000),142    ("hopital",    "Hôpital",         '["amenity"="hospital"]',                    3000),143    ("bibliotheque", "Bibliothèque",  '["amenity"="library"]',                     2000),144]145146LABELS = {cat: label for cat, label, _, _ in CATEGORIES}147148149def coord_key(lat: float, lng: float) -> str:150    return f"{round(lat, 4)},{round(lng, 4)}"151152153def _haversine_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float:154    r = 6371000.0155    p1, p2 = math.radians(lat1), math.radians(lat2)156    dp, dl = math.radians(lat2 - lat1), math.radians(lng2 - lng1)157    a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2158    return 2 * r * math.asin(math.sqrt(a))159160161def _tile_of(lat: float, lng: float) -> tuple[int, int]:162    return (math.floor(lat / TILE), math.floor(lng / TILE))163164165def _build_tile_query(ty: int, tx: int) -> str:166    """Tous les POI des catégories dans la tuile (bbox élargie de la marge)."""167    s = ty * TILE - TILE_MARGIN168    n = (ty + 1) * TILE + TILE_MARGIN169    w = tx * TILE - TILE_MARGIN170    e = (tx + 1) * TILE + TILE_MARGIN171    bbox = f"{s:.4f},{w:.4f},{n:.4f},{e:.4f}"172    parts = [f"nwr{sel}({bbox});" for _c, _l, sel, _r in CATEGORIES]173    return f'[out:json][timeout:180];({"".join(parts)});out center tags;'174175176def _match_category(tags: dict) -> str | None:177    """Retrouve la catégorie Lou-Ka d'un élément OSM retourné."""178    shop = tags.get("shop")179    amenity = tags.get("amenity")180    leisure = tags.get("leisure")181    if shop == "supermarket":182        return "epicerie"183    if shop == "convenience":184        return "depanneur"185    if amenity == "pharmacy":186        return "pharmacie"187    if amenity == "school":188        return "ecole"189    if amenity in ("kindergarten", "childcare"):190        return "garderie"191    if leisure == "park":192        return "parc"193    if tags.get("highway") == "bus_stop":194        return "bus"195    if tags.get("railway") == "station" and tags.get("station") == "subway":196        return "metro"197    if leisure == "fitness_centre":198        return "gym"199    if amenity == "cafe":200        return "cafe"201    if amenity in ("clinic", "doctors"):202        return "clinique"203    if amenity == "hospital":204        return "hopital"205    if amenity == "library":206        return "bibliotheque"207    return None208209210_RADII = {cat: radius for cat, _l, _s, radius in CATEGORIES}211212213class PoiClient:214    def __init__(self) -> None:215        self.session = requests.Session()216        self.session.headers["User-Agent"] = USER_AGENT217        self._last = 0.0218        self._url_idx = 0219220    def _post(self, query: str) -> list | None:221        """POST Overpass avec throttling et rotation de miroir sur erreur."""222        wait = REQUEST_DELAY - (time.time() - self._last)223        if wait > 0:224            time.sleep(wait)225        for essai in range(len(OVERPASS_URLS)):226            url = OVERPASS_URLS[(self._url_idx + essai) % len(OVERPASS_URLS)]227            try:228                resp = self.session.post(url, data={"data": query}, timeout=90)229                self._last = time.time()230                resp.raise_for_status()231                self._url_idx = (self._url_idx + essai) % len(OVERPASS_URLS)232                return resp.json().get("elements") or []233            except Exception:234                self._last = time.time()235                continue236        return None237238    def fetch_tile(self, ty: int, tx: int) -> list[dict] | None:239        """Tous les POI catégorisés d'une tuile : [{cat, name, lat, lng}]."""240        elements = self._post(_build_tile_query(ty, tx))241        if elements is None:242            return None243        pois = []244        for el in elements:245            tags = el.get("tags") or {}246            cat = _match_category(tags)247            if cat is None:248                continue249            elat = el.get("lat") or (el.get("center") or {}).get("lat")250            elng = el.get("lon") or (el.get("center") or {}).get("lon")251            if elat is None or elng is None:252                continue253            pois.append({"cat": cat, "name": (tags.get("name") or LABELS[cat])[:60],254                         "lat": elat, "lng": elng})255        return pois256257258def _nearest_by_cat(lat: float, lng: float, pois_by_cat: dict[str, list[dict]]) -> list[dict]:259    """Plus proche POI de chaque catégorie (dans son rayon), trié par distance."""260    out = []261    for cat, pois in pois_by_cat.items():262        radius = _RADII[cat]263        # préfiltre rectangulaire bon marché avant l'haversine264        dlat_max = radius / 111000.0265        dlng_max = radius / (111000.0 * max(0.2, math.cos(math.radians(lat))))266        best = None267        for p in pois:268            if abs(p["lat"] - lat) > dlat_max or abs(p["lng"] - lng) > dlng_max:269                continue270            d = _haversine_m(lat, lng, p["lat"], p["lng"])271            if d <= radius and (best is None or d < best["dist_m"]):272                # lat/lng conservés (2026-09-04) pour placer le lieu sur la273                # carte de la fiche ; les entrées de cache antérieures n'en ont274                # pas — le frontend tolère leur absence.275                best = {"cat": cat, "name": p["name"], "dist_m": round(d),276                        "lat": round(p["lat"], 6), "lng": round(p["lng"], 6)}277        if best:278            out.append(best)279    return sorted(out, key=lambda p: p["dist_m"])280281282def run(limit: int | None = None) -> dict:283    """Remplit poi_cache pour les immeubles géolocalisés qui n'y sont pas.284285    `limit` borne le nombre de requêtes Overpass de cette exécution286    (les entrées déjà en cache ne coûtent rien).287    """288    con = db.connect()289    client = PoiClient()290    rows = con.execute(291        """SELECT DISTINCT ROUND(lat,4) la, ROUND(lng,4) ln FROM listings292           WHERE active=1 AND lat IS NOT NULL AND lng IS NOT NULL""").fetchall()293294    now = time.time()295    a_faire: list[tuple[float, float]] = []296    skipped = 0297    for r in rows:298        cached = con.execute(299            "SELECT ts FROM poi_cache WHERE coord_key=?",300            (f"{r['la']},{r['ln']}",)).fetchone()301        if cached and now - (cached["ts"] or 0) < REFRESH_AFTER:302            skipped += 1303        else:304            a_faire.append((r["la"], r["ln"]))305    if limit is not None:306        a_faire = a_faire[:limit]307308    # 1) télécharger les POI des tuiles nécessaires (une requête par tuile)309    tuiles = sorted({_tile_of(la, ln) for la, ln in a_faire})310    pois_by_tile: dict[tuple[int, int], dict[str, list[dict]]] = {}311    tile_errors = []312    for t in tuiles:313        res = client.fetch_tile(*t)314        if res is None:315            tile_errors.append(t)316        else:317            by_cat: dict[str, list[dict]] = {}318            for p in res:319                by_cat.setdefault(p["cat"], []).append(p)320            pois_by_tile[t] = by_cat321322    # 2) calcul local du plus proche par catégorie pour chaque immeuble323    done = errors = 0324    for la, ln in a_faire:325        t = _tile_of(la, ln)326        if t not in pois_by_tile:327            errors += 1             # tuile en échec : re-tentée au prochain run328            continue329        pois = _nearest_by_cat(la, ln, pois_by_tile[t])330        con.execute(331            "INSERT INTO poi_cache (coord_key, lat, lng, pois, ts) VALUES (?,?,?,?,?)"332            " ON CONFLICT(coord_key) DO UPDATE SET pois=excluded.pois, ts=excluded.ts",333            (coord_key(la, ln), la, ln, json.dumps(pois, ensure_ascii=False), now))334        done += 1335    con.commit()336337    con.close()338    stats = {"fetched": done, "cached": skipped, "errors": errors,339             "tiles": len(tuiles), "tile_errors": len(tile_errors),340             "total_coords": len(rows)}341    print(f"[lou-ka] poi {stats}")342    return stats343
Files main
Menu

Theme