"""Enseignes des stations : enrichissement OpenStreetMap/Nominatim, best-effort. Le flux officiel des prix ne contient aucune enseigne. On interroge donc Nominatim (recherche de catégorie `amenity=fuel` dans la zone, avec `extratags=1`) et on associe une station à l'établissement OSM le plus proche. Une seule requête par lieu, mise en cache : aucune enseigne inventée, et l'absence de réponse n'empêche rien. """ from __future__ import annotations import json import math import os import sqlite3 import time import urllib.parse import urllib.request from pathlib import Path DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3" NOMINATIM = os.environ.get("FUEL_NOMINATIM_URL", "https://nominatim.openstreetmap.org/search") USER_AGENT = os.environ.get("FUEL_HTTP_USER_AGENT", "CortexFuelAdvisor/0.3 (+internal homelab)") CACHE_TTL = int(os.environ.get("FUEL_BRAND_TTL", str(30 * 86400))) MATCH_KM = 0.12 MAX_BRAND_LENGTH = 40 def connect(): DB_PATH.parent.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(DB_PATH, timeout=20) db.row_factory = sqlite3.Row db.execute( "CREATE TABLE IF NOT EXISTS brand_cache (key TEXT PRIMARY KEY, payload TEXT NOT NULL, ts INTEGER NOT NULL)" ) return db def key_for(lat, lon, radius_km): return f"{round(float(lat), 2)}:{round(float(lon), 2)}:{round(float(radius_km), 1)}" def cache_get(key, ttl=CACHE_TTL): try: with connect() as db: row = db.execute("SELECT payload,ts FROM brand_cache WHERE key=?", (key,)).fetchone() except sqlite3.Error: return None if not row or time.time() - row["ts"] > ttl: return None try: return json.loads(row["payload"]) except ValueError: return None def cache_set(key, payload): try: with connect() as db: db.execute( "REPLACE INTO brand_cache VALUES(?,?,?)", (key, json.dumps(payload, ensure_ascii=False), int(time.time())), ) except sqlite3.Error: pass def label_from_tags(tags): for field in ("brand", "operator", "name"): value = str(tags.get(field) or "").strip() if value: return value[:MAX_BRAND_LENGTH] return None def parse_results(rows): out = [] for row in rows: try: lat, lon = float(row["lat"]), float(row["lon"]) except (KeyError, TypeError, ValueError): continue tags = row.get("extratags") or {} if not isinstance(tags, dict): tags = {} label = label_from_tags(tags) or label_from_tags({"name": row.get("name")}) if label: out.append({"lat": lat, "lon": lon, "name": row.get("name") or label, "brand": label}) return out def fetch_candidates(lat, lon, radius_km): """Une requête Nominatim bornée ; lève en cas d'échec réseau.""" span = min(0.35, max(0.02, float(radius_km) / 111.0)) params = urllib.parse.urlencode( { "amenity": "fuel", "format": "jsonv2", "extratags": 1, "limit": 50, "viewbox": f"{lon - span},{lat + span},{lon + span},{lat - span}", "bounded": 1, "addressdetails": 0, } ) request = urllib.request.Request( f"{NOMINATIM}?{params}", headers={"User-Agent": USER_AGENT, "Accept-Language": "fr"} ) with urllib.request.urlopen(request, timeout=20) as response: rows = json.loads(response.read(2_000_000).decode("utf-8", "replace")) if not isinstance(rows, list): raise ValueError("réponse Nominatim inattendue") return parse_results(rows) def candidates(lat, lon, radius_km, source=None): """Résultats OSM pour la zone, mis en cache. Un échec n'est pas mis en cache.""" key = key_for(lat, lon, radius_km) cached = cache_get(key) if isinstance(cached, list): return cached try: rows = (source or fetch_candidates)(lat, lon, radius_km) except Exception: return [] if rows: cache_set(key, rows) return rows def distance_km(lat, lon, other_lat, other_lon): p1, p2 = math.radians(lat), math.radians(other_lat) dlat, dlon = p2 - p1, math.radians(other_lon - lon) a = math.sin(dlat / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlon / 2) ** 2 return 6371 * 2 * math.asin(math.sqrt(min(1, max(0, a)))) def match(station, candidates_rows, max_km=MATCH_KM): best, best_distance = None, max_km for row in candidates_rows or []: try: away = distance_km(row["lat"], row["lon"], station["lat"], station["lon"]) except (KeyError, TypeError): continue if away <= best_distance: best, best_distance = row.get("brand"), away return best def attach(stations, candidates_rows, max_km=MATCH_KM): """Ajoute ``brand`` (ou None) à chaque station, sans jamais en inventer.""" out = [] for station in stations: item = dict(station) item["brand"] = match(station, candidates_rows, max_km) out.append(item) return out def enrich(lat, lon, radius_km, stations): """Raccourci : récupère les enseignes de la zone puis les associe aux stations.""" return attach(stations, candidates(lat, lon, radius_km))