|
1 |
+# ----------------------------------------------------------------------------- |
|
2 |
+# Lou-Ka — Agrégateur de logements à louer (province de Québec) |
|
3 |
+# Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
|
4 |
+# commerces.py : grands commerces à proximité — API Mapbox Search Box |
|
5 |
+# |
|
6 |
+# Pour chaque grande bannière (Costco, Metro, IGA, Walmart…), on interroge |
|
7 |
+# l'API Search Box de Mapbox (jeton PUBLIC pk.… lu dans |
|
8 |
+# frontend/src/kamaps/config.ts — source de vérité du projet) avec la |
|
9 |
+# position de l'annonce en `proximity`, et on retient le point de vente le |
|
10 |
+# plus proche. Cache par cellule d'environ 1 km (data/commerces.db, |
|
11 |
+# TTL 30 jours) : les fiches d'un même secteur ne recoûtent rien. |
|
12 |
+# ----------------------------------------------------------------------------- |
|
13 |
+from __future__ import annotations |
|
14 |
+ |
|
15 |
+import json |
|
16 |
+import math |
|
17 |
+import re |
|
18 |
+import sqlite3 |
|
19 |
+import time |
|
20 |
+import urllib.parse |
|
21 |
+import urllib.request |
|
22 |
+from concurrent.futures import ThreadPoolExecutor |
|
23 |
+from pathlib import Path |
|
24 |
+ |
|
25 |
+ROOT = Path(__file__).resolve().parent.parent |
|
26 |
+DB_PATH = ROOT / "data" / "commerces.db" |
|
27 |
+UA = "LouKaBot/1.0 (+https://www.lou-ka.com; contact@spboucher.ai)" |
|
28 |
+TTL = 30 * 86400 |
|
29 |
+API = "https://api.mapbox.com/search/searchbox/v1/forward" |
|
30 |
+ |
|
31 |
+# id, libellé, requête Mapbox, mot-clé de validation (le nom du POI doit le |
|
32 |
+# contenir, sans accents ni casse — écarte « Station Métro », « Super Qualité »…) |
|
33 |
+BRANDS = [ |
|
34 |
+ ("costco", "Costco", "Costco Wholesale", "costco"), |
|
35 |
+ ("walmart", "Walmart", "Walmart Supercentre", "walmart"), |
|
36 |
+ ("metro", "Metro", "Metro", "metro"), |
|
37 |
+ ("iga", "IGA", "IGA", "iga"), |
|
38 |
+ ("maxi", "Maxi", "Maxi", "maxi"), |
|
39 |
+ ("superc", "Super C", "Super C", "super c"), |
|
40 |
+ ("provigo", "Provigo", "Provigo", "provigo"), |
|
41 |
+ ("canadiantire", "Canadian Tire", "Canadian Tire", "canadian tire"), |
|
42 |
+ ("dollarama", "Dollarama", "Dollarama", "dollarama"), |
|
43 |
+ ("saq", "SAQ", "SAQ", "saq"), |
|
44 |
+ ("pharmaprix", "Pharmaprix", "Pharmaprix", "pharmaprix"), |
|
45 |
+ ("jeancoutu", "Jean Coutu", "Jean Coutu pharmacie", "jean coutu"), |
|
46 |
+ ("homedepot", "Home Depot", "Home Depot", "home depot"), |
|
47 |
+ ("rona", "RONA", "RONA", "rona"), |
|
48 |
+] |
|
49 |
+ |
|
50 |
+_BAN = ("station", "stationnement") |
|
51 |
+ |
|
52 |
+ |
|
53 |
+def _norm(s: str) -> str: |
|
54 |
+ import unicodedata |
|
55 |
+ s = unicodedata.normalize("NFD", s or "") |
|
56 |
+ return "".join(c for c in s if unicodedata.category(c) != "Mn").lower() |
|
57 |
+ |
|
58 |
+_token_cache: list[str] = [] |
|
59 |
+ |
|
60 |
+ |
|
61 |
+def _token() -> str: |
|
62 |
+ if not _token_cache: |
|
63 |
+ cfg = (ROOT / "frontend" / "src" / "kamaps" / "config.ts").read_text() |
|
64 |
+ m = re.search(r'"(pk\.[A-Za-z0-9._-]+)"', cfg) |
|
65 |
+ if not m: |
|
66 |
+ raise RuntimeError("jeton Mapbox introuvable (kamaps/config.ts)") |
|
67 |
+ _token_cache.append(m.group(1)) |
|
68 |
+ return _token_cache[0] |
|
69 |
+ |
|
70 |
+ |
|
71 |
+def _connect() -> sqlite3.Connection: |
|
72 |
+ DB_PATH.parent.mkdir(parents=True, exist_ok=True) |
|
73 |
+ con = sqlite3.connect(DB_PATH, timeout=15) |
|
74 |
+ con.row_factory = sqlite3.Row |
|
75 |
+ con.execute("""CREATE TABLE IF NOT EXISTS commerces_cache ( |
|
76 |
+ cellule TEXT, brand TEXT, nom TEXT, adresse TEXT, |
|
77 |
+ lat REAL, lng REAL, fetched_at REAL, |
|
78 |
+ PRIMARY KEY (cellule, brand))""") |
|
79 |
+ return con |
|
80 |
+ |
|
81 |
+ |
|
82 |
+def _dist_m(lat1, lng1, lat2, lng2) -> float: |
|
83 |
+ dlat = math.radians(lat2 - lat1) |
|
84 |
+ dlng = math.radians(lng2 - lng1) |
|
85 |
+ a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) |
|
86 |
+ * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2) |
|
87 |
+ return 6371000 * 2 * math.asin(math.sqrt(a)) |
|
88 |
+ |
|
89 |
+ |
|
90 |
+def _fetch_brand(brand_q: str, lat: float, lng: float, |
|
91 |
+ match: str = "") -> dict | None: |
|
92 |
+ params = urllib.parse.urlencode({ |
|
93 |
+ "q": brand_q, "proximity": f"{lng},{lat}", "limit": 5, |
|
94 |
+ "types": "poi", "language": "fr", "country": "CA", |
|
95 |
+ "access_token": _token()}) |
|
96 |
+ req = urllib.request.Request(f"{API}?{params}", |
|
97 |
+ headers={"User-Agent": UA}) |
|
98 |
+ try: |
|
99 |
+ with urllib.request.urlopen(req, timeout=12) as r: |
|
100 |
+ feats = json.load(r).get("features") or [] |
|
101 |
+ except Exception: |
|
102 |
+ return None |
|
103 |
+ for f in feats: |
|
104 |
+ p = f.get("properties") or {} |
|
105 |
+ nom = _norm(p.get("name") or "") |
|
106 |
+ if match and match not in nom: |
|
107 |
+ continue |
|
108 |
+ if any(b in nom for b in _BAN): |
|
109 |
+ continue |
|
110 |
+ lng2, lat2 = f["geometry"]["coordinates"][:2] |
|
111 |
+ return {"nom": p.get("name") or brand_q, |
|
112 |
+ "adresse": p.get("full_address") |
|
113 |
+ or p.get("place_formatted") or "", |
|
114 |
+ "lat": lat2, "lng": lng2} |
|
115 |
+ return None |
|
116 |
+ |
|
117 |
+ |
|
118 |
+OVERPASS = ["https://overpass.kumi.systems/api/interpreter", |
|
119 |
+ "https://overpass-api.de/api/interpreter"] |
|
120 |
+ |
|
121 |
+ |
|
122 |
+def _fetch_transit(lat: float, lng: float) -> list[tuple[str, dict]]: |
|
123 |
+ """Station de métro et arrêt de bus les plus proches (OpenStreetMap).""" |
|
124 |
+ q = f"""[out:json][timeout:20]; |
|
125 |
+( |
|
126 |
+ node["railway"="station"]["station"="subway"](around:3000,{lat},{lng}); |
|
127 |
+ node["highway"="bus_stop"](around:1000,{lat},{lng}); |
|
128 |
+); |
|
129 |
+out body;""" |
|
130 |
+ data = None |
|
131 |
+ for url in OVERPASS: |
|
132 |
+ try: |
|
133 |
+ req = urllib.request.Request( |
|
134 |
+ url, data=urllib.parse.urlencode({"data": q}).encode(), |
|
135 |
+ headers={"User-Agent": UA}) |
|
136 |
+ with urllib.request.urlopen(req, timeout=25) as r: |
|
137 |
+ data = json.load(r) |
|
138 |
+ break |
|
139 |
+ except Exception: |
|
140 |
+ continue |
|
141 |
+ if not data: |
|
142 |
+ return [] |
|
143 |
+ best: dict[str, tuple[float, dict]] = {} |
|
144 |
+ for el in data.get("elements", []): |
|
145 |
+ tags = el.get("tags") or {} |
|
146 |
+ kind = ("metro_station" if tags.get("railway") == "station" |
|
147 |
+ else "arret_bus") |
|
148 |
+ d = _dist_m(lat, lng, el["lat"], el["lon"]) |
|
149 |
+ if kind not in best or d < best[kind][0]: |
|
150 |
+ best[kind] = (d, {"nom": tags.get("name") |
|
151 |
+ or ("Station de métro" if kind == "metro_station" |
|
152 |
+ else "Arrêt de bus"), |
|
153 |
+ "adresse": "", "lat": el["lat"], |
|
154 |
+ "lng": el["lon"]}) |
|
155 |
+ return [(k, v[1]) for k, v in best.items()] |
|
156 |
+ |
|
157 |
+ |
|
158 |
+TRANSIT = [("metro_station", "Station de métro"), ("arret_bus", "Arrêt de bus")] |
|
159 |
+ |
|
160 |
+_POI_CAT = {"metro": "metro_station", "bus": "arret_bus"} |
|
161 |
+ |
|
162 |
+ |
|
163 |
+def _transit_from_poi(lat: float, lng: float) -> list[tuple[str, dict]]: |
|
164 |
+ """Métro/bus depuis le cache POI du projet (louka.db, déjà calculé par |
|
165 |
+ immeuble) — la fiche interroge avec les mêmes coordonnées que poi.py.""" |
|
166 |
+ db_main = ROOT / "data" / next( |
|
167 |
+ (n for n in ("louka.db", "immoka.db", "immo.db") |
|
168 |
+ if (ROOT / "data" / n).exists()), "louka.db") |
|
169 |
+ if not db_main.exists(): |
|
170 |
+ return [] |
|
171 |
+ try: |
|
172 |
+ con = sqlite3.connect(f"file:{db_main}?mode=ro", uri=True) |
|
173 |
+ con.row_factory = sqlite3.Row |
|
174 |
+ d = 300 / 111320.0 |
|
175 |
+ row = con.execute( |
|
176 |
+ "SELECT pois, lat, lng FROM poi_cache WHERE lat BETWEEN ? AND ? " |
|
177 |
+ "AND lng BETWEEN ? AND ? ORDER BY (lat-?)*(lat-?)+(lng-?)*(lng-?) " |
|
178 |
+ "LIMIT 1", (lat - d, lat + d, lng - d, lng + d, |
|
179 |
+ lat, lat, lng, lng)).fetchone() |
|
180 |
+ con.close() |
|
181 |
+ except sqlite3.Error: |
|
182 |
+ return [] |
|
183 |
+ if row is None: |
|
184 |
+ return [] |
|
185 |
+ out = [] |
|
186 |
+ for e in json.loads(row["pois"] or "[]"): |
|
187 |
+ k = _POI_CAT.get(e.get("cat")) |
|
188 |
+ if k: |
|
189 |
+ out.append((k, {"nom": e.get("name") or "", "adresse": "", |
|
190 |
+ "lat": lat, "lng": lng, |
|
191 |
+ "_dist": e.get("dist_m")})) |
|
192 |
+ return out |
|
193 |
+ |
|
194 |
+ |
|
195 |
+def nearby(lat: float, lng: float) -> dict: |
|
196 |
+ """Grand commerce le plus proche par bannière (cache ~1 km, TTL 30 j).""" |
|
197 |
+ cell = f"{round(lat, 2)},{round(lng, 2)}" |
|
198 |
+ con = _connect() |
|
199 |
+ now = time.time() |
|
200 |
+ cached = {r["brand"]: r for r in con.execute( |
|
201 |
+ "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?", |
|
202 |
+ (cell, now - TTL))} |
|
203 |
+ manquants = [(bid, q, m) for bid, _, q, m in BRANDS |
|
204 |
+ if bid not in cached] |
|
205 |
+ transit_manquant = any(k not in cached for k, _ in TRANSIT) |
|
206 |
+ if manquants or transit_manquant: |
|
207 |
+ res: list[tuple[str, dict | None]] = [] |
|
208 |
+ if manquants: |
|
209 |
+ with ThreadPoolExecutor(max_workers=6) as ex: |
|
210 |
+ res = list(ex.map( |
|
211 |
+ lambda b: (b[0], _fetch_brand(b[1], lat, lng, b[2])), |
|
212 |
+ manquants)) |
|
213 |
+ if transit_manquant: |
|
214 |
+ tr = _transit_from_poi(lat, lng) or _fetch_transit(lat, lng) |
|
215 |
+ res.extend(tr) |
|
216 |
+ with con: |
|
217 |
+ for bid, hit in res: |
|
218 |
+ if hit is None: |
|
219 |
+ continue |
|
220 |
+ con.execute( |
|
221 |
+ "INSERT OR REPLACE INTO commerces_cache VALUES " |
|
222 |
+ "(?,?,?,?,?,?,?)", |
|
223 |
+ (cell, bid, hit["nom"], |
|
224 |
+ hit.get("adresse") or (str(hit["_dist"]) |
|
225 |
+ if hit.get("_dist") is not None |
|
226 |
+ else ""), |
|
227 |
+ hit["lat"], hit["lng"], now)) |
|
228 |
+ cached = {r["brand"]: r for r in con.execute( |
|
229 |
+ "SELECT * FROM commerces_cache WHERE cellule=? AND fetched_at>?", |
|
230 |
+ (cell, now - TTL))} |
|
231 |
+ con.close() |
|
232 |
+ |
|
233 |
+ items = [] |
|
234 |
+ transit = [] |
|
235 |
+ for bid, label in TRANSIT: |
|
236 |
+ r = cached.get(bid) |
|
237 |
+ if r is not None: |
|
238 |
+ # distance : celle du cache POI si disponible (adresse numérique) |
|
239 |
+ d = (float(r["adresse"]) if (r["adresse"] or "").replace( |
|
240 |
+ ".", "").isdigit() else _dist_m(lat, lng, r["lat"], r["lng"])) |
|
241 |
+ if d <= 5000: |
|
242 |
+ transit.append({"id": bid, "commerce": label, |
|
243 |
+ "nom": r["nom"], "adresse": "", |
|
244 |
+ "dist_m": round(d), |
|
245 |
+ "lat": r["lat"], "lng": r["lng"]}) |
|
246 |
+ for bid, label, _q, _m in BRANDS: |
|
247 |
+ r = cached.get(bid) |
|
248 |
+ if r is None: |
|
249 |
+ continue |
|
250 |
+ d = _dist_m(lat, lng, r["lat"], r["lng"]) |
|
251 |
+ if d > 40000: # au-delà de 40 km : non pertinent |
|
252 |
+ continue |
|
253 |
+ items.append({"id": bid, "commerce": label, "nom": r["nom"], |
|
254 |
+ "adresse": r["adresse"], "dist_m": round(d), |
|
255 |
+ "lat": r["lat"], "lng": r["lng"]}) |
|
256 |
+ items.sort(key=lambda x: x["dist_m"]) |
|
257 |
+ transit.sort(key=lambda x: x["dist_m"]) |
|
258 |
+ return {"n": len(items), "commerces": items, "transit": transit} |