From 726bc25fb0e8c2c0f901e227a32ad2d4e239e8b7 Mon Sep 17 00:00:00 2001 From: root Date: Sun, 13 Sep 2026 12:28:41 +0200 Subject: [PATCH] Enseignes normalisees du referentiel data.gouv et pictogrammes locaux Referentiel des noms et enseignes (ODbL, enrichi OpenStreetMap) joint sur l identifiant officiel: 181/213 stations couvertes. Pictogrammes generes localement (monogrammes + pompe Fuel Advisor), aucun logo de marque tierce ni hotlink. Artefacts OSM filtres. --- app.py | 19 ++++++++- brands.svg | 23 +++++++++++ enseignes.py | 114 +++++++++++++++++++++++++++++++++++++++++++++++++++ style.css | 5 +++ ui.js | 10 ++++- 5 files changed, 168 insertions(+), 3 deletions(-) create mode 100644 brands.svg create mode 100644 enseignes.py diff --git a/app.py b/app.py index 89190e3..f424c5a 100755 --- a/app.py +++ b/app.py @@ -22,6 +22,7 @@ from xml.etree import ElementTree as ET import brands import collector +import enseignes import forecast import market import promotions @@ -403,6 +404,17 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None LOG.warning("Complétion des noms de stations ignorée") # Enseignes : enrichissement OpenStreetMap best-effort, sans jamais en inventer. enriched = brands.enrich(lat, lon, radius_km, [s.__dict__ for s in stations]) + # L'enseigne normalisée du référentiel data.gouv (ODbL) prime sur le nom brut du point de + # vente : « S.A. DIS-CAR » devient « Carrefour ». Purement descriptif, aucun effet sur le prix. + enseignes_table = enseignes.load() + for station in enriched: + normalized = enseignes.brand_for( + station.get("id"), fallback=None, mapping=enseignes_table + ) + if normalized: + station["brand"] = normalized + station["brand_source"] = "référentiel data.gouv.fr (ODbL, enrichi OpenStreetMap)" + station["brand_slug"] = enseignes.brand_slug(station.get("brand")) brands_known = [(item["id"], item["brand"]) for item in enriched if item.get("brand")] if brands_known: storage.set_brands(brands_known) @@ -467,7 +479,11 @@ def advice(lat, lon, fuel, radius_km, vehicle=None, remaining_km=None, trip=None stations=enriched[:12], market=market_signal(), ai_used=False, - brands_source="OpenStreetMap via Nominatim" if brands_known else None, + brands_source=( + "référentiel data.gouv.fr (ODbL, enrichi OpenStreetMap) et OpenStreetMap via Nominatim" + if brands_known + else enseignes.LICENCE + ), brands_warning=None if brands_known else "Enseignes indisponibles pour cette zone (source OpenStreetMap muette).", @@ -560,6 +576,7 @@ class Handler(BaseHTTPRequestHandler): "/favicon-32.png": "image/png", "/favicon-16.png": "image/png", "/apple-touch-icon.png": "image/png", + "/brands.svg": "image/svg+xml", } def do_GET(self): diff --git a/brands.svg b/brands.svg new file mode 100644 index 0000000..f69e561 --- /dev/null +++ b/brands.svg @@ -0,0 +1,23 @@ + + diff --git a/enseignes.py b/enseignes.py new file mode 100644 index 0000000..cca898b --- /dev/null +++ b/enseignes.py @@ -0,0 +1,114 @@ +"""Enseignes normalisées des stations-service. + +Source : « Référentiel des noms et enseignes de stations-service (Enrichi par OpenStreetMap) », +data.gouv.fr, licence **ODbL** (© Les contributeurs d'OpenStreetMap, traitement +carburants.chiffrex.fr). La clé `id_station_officiel` est l'identifiant officiel +prix-carburants.gouv.fr, donc directement joignable sur nos relevés. + +Le référentiel ne sert qu'à l'**affichage** : il ne touche ni au prix, ni au conseil. +Une enseigne absente ne doit jamais empêcher l'affichage d'une station. +""" + +from __future__ import annotations + +import csv +import logging +import os +import tempfile +import unicodedata +import urllib.request +from pathlib import Path + +LOG = logging.getLogger("fuel-advisor.enseignes") + +SOURCE_URL = ( + "https://static.data.gouv.fr/resources/referentiel-des-noms-et-enseignes-de-stations-" + "service-enrichi-par-openstreetmap/20260913-100010/referentiel-stations-osm.csv" +) +DATASET_PAGE = ( + "https://www.data.gouv.fr/datasets/referentiel-des-noms-et-enseignes-de-stations-" + "service-enrichi-par-openstreetmap" +) +LICENCE = "ODbL — © les contributeurs d'OpenStreetMap (traitement carburants.chiffrex.fr)" +CACHE = Path(os.environ.get("FUEL_ENSEIGNES_CACHE", "/var/lib/fuel-advisor/enseignes.csv")) +KEY = "id_station_officiel" +VALUE = "nom_normalise" + + +def refresh(url=SOURCE_URL, path=CACHE, timeout=60): + """Télécharge le référentiel et le remplace atomiquement. Renvoie le nombre de lignes.""" + path.parent.mkdir(parents=True, exist_ok=True) + request = urllib.request.Request(url, headers={"User-Agent": "fuel-advisor/1.0"}) + with urllib.request.urlopen(request, timeout=timeout) as response: + payload = response.read() + if len(payload) < 100_000: + raise ValueError(f"référentiel suspect : {len(payload)} octets") + handle, temporary = tempfile.mkstemp(dir=str(path.parent), prefix=".enseignes-") + try: + with os.fdopen(handle, "wb") as stream: + stream.write(payload) + os.replace(temporary, path) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise + return count(path) + + +def count(path=CACHE): + try: + return len(load(path)) + except OSError: + return 0 + + +def load(path=CACHE): + """Table `id_station_officiel` -> enseigne normalisée. Fichier absent = table vide.""" + mapping = {} + try: + with open(path, encoding="utf-8", newline="") as stream: + for row in csv.DictReader(stream): + identifier = (row.get(KEY) or "").strip() + name = (row.get(VALUE) or "").strip() + clean = clean_name(name) + if identifier and clean: + mapping[identifier] = clean + except FileNotFoundError: + LOG.info("référentiel des enseignes absent : %s", path) + except (csv.Error, UnicodeDecodeError) as exc: + LOG.warning("référentiel des enseignes illisible : %s", type(exc).__name__) + return mapping + + +def brand_for(station_id, fallback=None, mapping=None): + """Enseigne normalisée pour un identifiant officiel, sinon la valeur de repli.""" + table = load() if mapping is None else mapping + return table.get(str(station_id or "").strip(), fallback) + + +def clean_name(name): + """Rejette les artefacts du référentiel (balises OSM non résolues, libellés techniques). + + Une enseigne douteuse vaut mieux absente que fausse : on retombe alors sur le pictogramme + générique plutôt que d'afficher « DELETE TAG ... ». + """ + text = (name or "").strip() + if not text or len(text) > 40: + return None + lowered = text.lower() + if lowered.startswith(("delete tag", "fixme", "todo", "?")) or "http" in lowered: + return None + if sum(character.isalpha() for character in text) < 2: + return None + return text + + +def brand_slug(name): + """Slug stable pour choisir un pictogramme local. Enseigne inconnue -> 'inconnue'.""" + if not name: + return "inconnue" + ascii_name = ( + unicodedata.normalize("NFKD", str(name)).encode("ascii", "ignore").decode("ascii") + ) + slug = "".join(character if character.isalnum() else "-" for character in ascii_name.lower()) + slug = "-".join(part for part in slug.split("-") if part) + return slug or "inconnue" diff --git a/style.css b/style.css index 03babd7..644818b 100644 --- a/style.css +++ b/style.css @@ -62,3 +62,8 @@ img.brand-logo{width:40px;height:40px;flex:0 0 auto} .hero{padding-top:.6rem;padding-bottom:.6rem} .top-bar{padding-top:.45rem;padding-bottom:.45rem} } + +/* Pictogrammes d'enseigne locaux (voir brands.svg) */ +.brand-tile{width:26px;height:26px;flex:0 0 auto;border-radius:7px;display:inline-block;vertical-align:middle} +.station-head .brand-tile{width:30px;height:30px;margin-right:.4rem} +.badge.brand{gap:.45rem} diff --git a/ui.js b/ui.js index 3590ee0..85cf7d0 100644 --- a/ui.js +++ b/ui.js @@ -109,6 +109,12 @@ function stationCards(rows){ // jamais d'une prédiction. Tant que le modèle n'est pas validé, aucune ligne ne doit laisser // croire à une prévision. const DECISION_LABELS={refuel:'ACHETER MAINTENANT',topup:'FAIRE UN APPOINT',wait:'ATTENDRE'}; +// Pictogramme local : monogramme d'enseigne ou pompe Fuel Advisor. Jamais un logo de marque +// tierce (licence de marque non détenue) et jamais une image distante. +function brandTile(slug, label){ + const known=/^[a-z0-9-]+$/.test(slug||'')?slug:'inconnue'; + return ``; +} function decisionLabel(action){return DECISION_LABELS[action]||'PAS DE SIGNAL PRÉDICTIF FIABLE';} function heroQuantity(d){ const q=d.quantity||{}; @@ -133,7 +139,7 @@ function topStations(d){ const km=s.route_distance_km; const extra=(km!==null&&km!==undefined&&nearest!==null&&nearest!==undefined)?Math.max(0,Math.round((km-nearest)*10)/10):null; return `
-
${esc(s.brand||s.name)}${num(s.price,3)} €/L
+
${brandTile(s.brand_slug,s.brand||s.name)}${esc(s.brand||s.name)}${num(s.price,3)} €/L

${esc(s.city||'')}${km!==null&&km!==undefined?` · ${num(km,1)} km${extra?` (détour ≈ ${num(extra,1)} km)`:''}`:' · distance inconnue'}

Prix déclaré : ${esc(s.updated)}${index===0?' · meilleur choix':''}

`; @@ -149,7 +155,7 @@ function render(d){ const eta=s.route_eta_min!==null&&s.route_eta_min!==undefined?` · ≈ ${num(s.route_eta_min,0)} min avec trafic (mesuré il y a ${num((s.route_eta_age_seconds||0)/60,0)} min)`:''; const distance=routed?`${num(s.route_distance_km,1)} km en voiture${duree}${eta}`:`${num(s.distance_km,1)} km à vol d’oiseau (routage indisponible)`; const nav=s.navigation?``:''; - return `
${s.brand?`${esc(s.brand)}`:'Enseigne inconnue'}${s.road?`${esc(s.road)}`:''}${esc(s.name)}

${esc(s.city)} · ${distance}

Déclaré : ${esc(s.updated)}

${nav}
${num(s.price,3)} €/L
`;}).join(''); + return `
${s.brand?`${brandTile(s.brand_slug,s.brand)}${esc(s.brand)}`:'Enseigne inconnue'}${s.road?`${esc(s.road)}`:''}${esc(s.name)}

${esc(s.city)} · ${distance}

Déclaré : ${esc(s.updated)}

${nav}
${num(s.price,3)} €/L
`;}).join(''); const reasons=d.reasons.map(r=>`
  • ${esc(r)}
  • `).join(''); const metrics=d.usable_km!==null?`
    ${num(d.usable_km)} kmavant votre marge
    ${d.days_left===null?'Occasionnel':num(d.days_left,1)+' j'}${d.days_left===null?'pas de moyenne imposée':'usage moyen estimé'}
    ${d.topup_liters===null?'—':num(d.topup_liters,1)+' L'}appoint indicatif
    `:''; $('result').innerHTML=`
    Conseil Fuel Advisor · ${esc(d.fuel)}

    ${esc(decisionLabel(d.action))}

    ${esc(heroQuantity(d))}

    ${heroTrend(d)}

    ${esc(d.quantity_headline||d.label)}

    Pourquoi ce conseil ?${quantityBlock(d)}
      ${reasons}
    Sans décision par IAAucun signal prédictif utilisé dans le conseil${fresh}